Audio Plugin: add PulseAudio support
[src/app-framework-binder.git] / plugins / audio / audio-pulse.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author "Manuel Bachmann"
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "audio-api.h"
20 #include "audio-pulse.h"
21
22 PUBLIC unsigned char _pulse_init (const char *name, audioCtxHandleT *ctx) {
23
24     pa_mainloop *pa_loop;
25     pa_mainloop_api *pa_api;
26     pa_context *pa_context;
27     pa_simple *pa;
28     pa_sample_spec *pa_spec;
29     struct timeval tv_start, tv_now;
30     int ret, error, i;
31
32     pa_loop = pa_mainloop_new ();
33     pa_api = pa_mainloop_get_api (pa_loop);
34     pa_context = pa_context_new (pa_api, "afb-audio-plugin");
35
36     /* allocate the global array if it hasn't been done */
37     if (!dev_ctx_p)
38         dev_ctx_p = (dev_ctx_pulse_T**) malloc (sizeof(dev_ctx_pulse_T));
39
40     /* create a temporary device, to be held until sink gets discovered */
41     dev_ctx_pulse_T *dev_ctx_p_t = (dev_ctx_pulse_T*) malloc (sizeof(dev_ctx_pulse_T));
42     dev_ctx_p_t->sink_name = NULL;
43     dev_ctx_p_t->card_name = (char**) malloc (sizeof(char*));
44     dev_ctx_p_t->card_name[0] = strdup (name);
45     dev_ctx_p_t->pa_loop = pa_loop;
46     dev_ctx_p_t->pa_context = pa_context;
47
48     pa_context_set_state_callback (pa_context, _pulse_context_cb, (void*)dev_ctx_p_t);
49     pa_context_connect (pa_context, NULL, 0, NULL);
50
51     /* 1 second should be sufficient to retrieve sink info */
52     gettimeofday (&tv_start, NULL);
53     gettimeofday (&tv_now, NULL);
54     while (tv_now.tv_sec - tv_start.tv_sec <= 1) {
55         pa_mainloop_iterate (pa_loop, 0, &ret);
56
57         if (ret == -1) {
58             if (verbose) fprintf (stderr, "Stopping PulseAudio backend...\n");
59             return -1;
60         }
61         if (ret >= 0) {
62             /* found a matching sink from callback */
63             if (verbose) fprintf (stderr, "Success : using sink n.%d\n", error);
64             ctx->audio_dev = (void*)dev_ctx_p[ret];
65             break;
66         }
67         gettimeofday (&tv_now, NULL);
68     }
69     /* fail if we found no matching sink */
70     if (!ctx->audio_dev)
71       return -1;
72
73     /* make the client context aware of current card state */
74     ctx->mute = (unsigned char)dev_ctx_p[ret]->mute;
75     ctx->channels = (unsigned int)dev_ctx_p[ret]->volume.channels;
76     for (i = 0; i < ctx->channels; i++)
77         ctx->volume[i] = (int)dev_ctx_p[ret]->volume.values[i];
78     ctx->idx = ret;
79
80     /* open matching sink for playback */
81     pa_spec = (pa_sample_spec*) malloc (sizeof(pa_sample_spec));
82     pa_spec->format = PA_SAMPLE_S16LE;
83     pa_spec->rate = 22050;
84     pa_spec->channels = ctx->channels;
85
86     if (!(pa = pa_simple_new (NULL, "afb-audio-plugin", PA_STREAM_PLAYBACK, dev_ctx_p[ret]->sink_name,
87                               "afb-audio-output", pa_spec, NULL, NULL, &error))) {
88         fprintf (stderr, "Error opening PulseAudio sink %s : %s\n",
89                           dev_ctx_p[ret]->sink_name, pa_strerror(error));
90         return -1;
91     }
92     dev_ctx_p[ret]->pa = pa;
93     free (pa_spec);
94
95     client_count++;
96
97     return 0;
98 }
99
100 PUBLIC void _pulse_free (audioCtxHandleT *ctx) {
101
102     int num, i;
103
104     client_count--;
105     if (client_count > 0) return;
106
107     for (num = 0; num < (sizeof(dev_ctx_p)/sizeof(dev_ctx_pulse_T)); num++) {
108
109          for (i = 0; num < (sizeof(dev_ctx_p[num]->card_name)/sizeof(char*)); i++) {
110              free (dev_ctx_p[num]->card_name[i]);
111              dev_ctx_p[num]->card_name[i] = NULL;
112          }
113          pa_context_disconnect (dev_ctx_p[num]->pa_context);
114          pa_context_unref (dev_ctx_p[num]->pa_context);
115          pa_mainloop_free (dev_ctx_p[num]->pa_loop);
116          pa_simple_free (dev_ctx_p[num]->pa);
117          free (dev_ctx_p[num]->sink_name);
118          dev_ctx_p[num]->pa_context = NULL;
119          dev_ctx_p[num]->pa_loop = NULL;
120          dev_ctx_p[num]->pa = NULL;
121          dev_ctx_p[num]->sink_name = NULL;
122          free (dev_ctx_p[num]);
123     }
124 }
125
126 PUBLIC void _pulse_play (audioCtxHandleT *ctx) {
127
128     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
129
130     if (!dev_ctx_p_c || dev_ctx_p_c->thr_should_run || access (AUDIO_BUFFER, F_OK) == -1)
131         return;
132
133     dev_ctx_p_c->thr_should_run = 1;
134     dev_ctx_p_c->thr_finished = 0;
135     pthread_create (&dev_ctx_p_c->thr, NULL, _pulse_play_thread_fn, (void*)dev_ctx_p_c);
136 }
137
138 PUBLIC void _pulse_stop (audioCtxHandleT *ctx) {
139
140     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
141
142     if (!dev_ctx_p_c || !dev_ctx_p_c->thr_should_run)
143         return;
144
145     dev_ctx_p_c->thr_should_run = 0;
146     while (!dev_ctx_p_c->thr_finished)
147         usleep(100000);
148     pthread_join (dev_ctx_p_c->thr, NULL);
149 }
150
151 PUBLIC int _pulse_get_volume (audioCtxHandleT *ctx, unsigned int channel) {
152
153     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
154
155     if (!dev_ctx_p_c)
156         return;
157
158     _pulse_refresh_sink (dev_ctx_p_c);
159
160     return (int)dev_ctx_p_c->volume.values[channel];
161 }
162
163 PUBLIC void _pulse_set_volume (audioCtxHandleT *ctx, unsigned int channel, int vol) {
164
165     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
166     struct pa_cvolume volume;
167
168     if (!dev_ctx_p_c)
169         return;
170
171     volume = dev_ctx_p_c->volume;
172     volume.values[channel] = vol;
173
174     pa_context_set_sink_volume_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
175                                         &volume, NULL, NULL);
176     _pulse_refresh_sink (dev_ctx_p_c);
177 }
178
179 PUBLIC void _pulse_set_volume_all (audioCtxHandleT *ctx, int vol) {
180
181     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
182     struct pa_cvolume volume;
183
184     if (!dev_ctx_p_c)
185         return;
186
187     pa_cvolume_init (&volume);
188     pa_cvolume_set (&volume, dev_ctx_p_c->volume.channels, vol);
189
190     pa_context_set_sink_volume_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
191                                         &volume, NULL, NULL);
192     _pulse_refresh_sink (dev_ctx_p_c);
193 }
194
195 PUBLIC unsigned char _pulse_get_mute (audioCtxHandleT *ctx) {
196
197     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
198
199     if (!dev_ctx_p_c)
200         return;
201
202     _pulse_refresh_sink (dev_ctx_p_c);
203
204     return (unsigned char)dev_ctx_p_c->mute;
205 }
206
207 PUBLIC void _pulse_set_mute (audioCtxHandleT *ctx, unsigned char mute) {
208
209     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
210
211     if (!dev_ctx_p_c)
212         return;
213
214     pa_context_set_sink_mute_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
215                                       (int)mute, NULL, NULL);
216     _pulse_refresh_sink (dev_ctx_p_c);
217 }
218
219  /* ---- LOCAL HELPER FUNCTIONS ---- */
220
221 void _pulse_refresh_sink (dev_ctx_pulse_T* dev_ctx_p_c) {
222
223     dev_ctx_p_c->refresh = 1;
224
225     pa_context_get_sink_info_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
226                                       _pulse_sink_info_cb, (void*)dev_ctx_p_c);
227
228     while (dev_ctx_p_c->refresh)
229         pa_mainloop_iterate (dev_ctx_p_c->pa_loop, 0, NULL);
230 }
231
232 void _pulse_enumerate_cards () {
233
234     void **cards, **card;
235     char *name, *found, *alsa_name, *card_name;
236     int new_info, i, num = 0;
237
238     /* allocate the global alsa array */
239     alsa_info = (alsa_info_T**) malloc (sizeof(alsa_info_T));
240     alsa_info[0] = (alsa_info_T*) malloc (sizeof(alsa_info_T));
241     alsa_info[0]->device = NULL;
242     alsa_info[0]->synonyms = NULL;
243
244     /* we use ALSA to enumerate cards */
245     snd_device_name_hint (-1, "pcm", &cards);
246     card = cards;
247
248     for (; *card != NULL; card++) {
249         name = snd_device_name_get_hint (*card, "NAME");
250         new_info = 1;
251
252         /* alsa name is before ':' (if ':' misses, then it has no card) */
253         found = strstr (name, ":");
254         if (!found) continue;
255         /* */
256         alsa_name = (char*) malloc (found-name+1);
257         strncpy (alsa_name, name, found-name);
258         alsa_name[found-name] = '\0';
259
260         /* card name is the invariant between "CARD=" and ',' */
261         found = strstr (name, "CARD=");
262         if (!found) continue;
263         /* */
264         found += 5;
265         card_name = strdup (found);
266         found = strstr (card_name, ",");
267         if (found) card_name[found-card_name] = '\0';
268
269         /* was the card name already listed in the global alsa array ? */
270         for (i = 0; i < (sizeof(alsa_info)/sizeof(alsa_info_T)); i++) {
271
272             if (alsa_info[i]->device &&
273                 !strcmp (alsa_info[i]->device, card_name)) {
274                 /* it was ; add the alsa name as a new synonym */
275                 asprintf (&alsa_info[i]->synonyms, "%s:%s", alsa_info[i]->synonyms, alsa_name);
276                 new_info = 0;
277                 break;
278             }            
279         }
280         /* it was not ; create it */
281         if (new_info) {
282             alsa_info = (alsa_info_T**) realloc (alsa_info, (num+1)*sizeof(alsa_info_T));
283             alsa_info[num]->device = strdup (card_name);
284             asprintf (&alsa_info[num]->synonyms, ":%s", alsa_name);
285             num++;
286         }
287         free (alsa_name);
288         free (card_name);
289     }
290 }
291
292 char** _pulse_find_cards (const char *name) {
293
294     char **cards = NULL;
295     char *needle, *found, *next;
296     int num, i = 0;
297
298     if (!alsa_info)
299       _pulse_enumerate_cards ();
300
301     asprintf (&needle, ":%s", name);
302
303     for (num = 0; num < (sizeof(alsa_info)/sizeof(alsa_info_T)); num++) {
304
305         found = strstr (alsa_info[num]->synonyms, needle);
306         while (found) {
307             /* if next character is not ':' or '\0', we are wrong */
308             if ((found[strlen(name)] != ':') && (found[strlen(name)] != '\0')) {
309                 found = strstr (found+1, needle);
310                 continue;
311             }
312             /* found it ; now return all the "synonym" cards */
313             found = strstr (alsa_info[num]->synonyms, ":");
314             while (found) {
315                 next = strstr (found+1, ":");
316                 cards = (char**) realloc (cards, (i+1)*sizeof(char*));
317                 cards[i] = (char*) malloc (next-found+1);
318                 strncpy (cards[i], found+1, next-found);
319                 cards[i][next-found] = '\0';
320                 i++;
321             }
322         }
323     }
324     free (needle);
325
326     return cards;
327 }
328
329  /* ---- LOCAL CALLBACK FUNCTIONS ---- */
330
331 STATIC void _pulse_context_cb (pa_context *context, void *data) {
332
333     pa_context_state_t state = pa_context_get_state (context);
334     dev_ctx_pulse_T *dev_ctx_p_t = (dev_ctx_pulse_T *)data;
335
336     if (state == PA_CONTEXT_FAILED) {
337         fprintf (stderr, "Could not connect to PulseAudio !\n");
338         pa_mainloop_quit (dev_ctx_p_t->pa_loop, -1);
339     }
340
341     if (state == PA_CONTEXT_READY)
342         pa_context_get_sink_info_list (context, _pulse_sink_list_cb, (void*)dev_ctx_p_t);
343 }
344
345 STATIC void _pulse_sink_list_cb (pa_context *context, const pa_sink_info *info,
346                                  int eol, void *data) {
347
348     dev_ctx_pulse_T *dev_ctx_p_t = (dev_ctx_pulse_T *)data;
349     const char *device_string;
350     char **cards;
351     int num, i;
352
353     if (eol != 0)
354         return;
355
356     /* ignore sinks with no cards */
357     if (!pa_proplist_contains (info->proplist, "device.string"))
358         return;
359
360     device_string = pa_proplist_gets (info->proplist, "device.string");
361
362     /* was a sink with similar name already found ? */
363     for (num = 0; num < (sizeof(dev_ctx_p)/sizeof(dev_ctx_pulse_T)); num++) {
364         if (dev_ctx_p[num]->sink_name &&
365            !strcmp (dev_ctx_p[num]->sink_name, info->name)) {
366
367             /* yet it was, did it have the required card ? */
368             cards = dev_ctx_p[num]->card_name;
369             for (i = 0; i < (sizeof(cards)/sizeof(char*)); i++) {
370                 if (!strcmp (cards[i], dev_ctx_p_t->card_name[0])) {
371                     /* it did : stop there and succeed */
372                     if (verbose) fprintf (stderr, "Found matching sink : %s\n", info->name);
373                     pa_mainloop_quit (dev_ctx_p_t->pa_loop, num);
374                 }
375             }
376             /* it did not, ignore and return */
377             return;
378         }
379     }
380     num++;
381
382     /* new sink, find all the cards it manages, fail if none */
383     cards = _pulse_find_cards (device_string);
384     if (!cards) return;
385
386     /* everything is well, register it in global array */
387     dev_ctx_p_t->sink_name = strdup (info->name);
388     dev_ctx_p_t->card_name = cards;
389     dev_ctx_p_t->mute = info->mute;
390     dev_ctx_p_t->volume = info->volume;
391     dev_ctx_p_t->thr_should_run = 0;
392     dev_ctx_p_t->thr_finished = 0;
393     dev_ctx_p[num] = dev_ctx_p_t;
394
395     /* does this new sink have the card we are looking for ? */ /* TODO : factorize this */
396     for (i = 0; i < (sizeof(cards)/sizeof(char*)); i++) {
397         if (!strcmp (cards[i], dev_ctx_p_t->card_name[0])) {
398              /* it did : stop there and succeed */
399              if (verbose) fprintf (stderr, "Found matching sink : %s\n", info->name);
400              pa_mainloop_quit (dev_ctx_p_t->pa_loop, num);
401         }
402     }
403 }
404
405 STATIC void _pulse_sink_info_cb (pa_context *context, const pa_sink_info *info,
406                                  int eol, void *data) {
407
408     dev_ctx_pulse_T *dev_ctx_p_c = (dev_ctx_pulse_T *)data;
409
410     if (eol != 0)
411         return;
412
413     dev_ctx_p_c->refresh = 0;
414     dev_ctx_p_c->mute = info->mute;
415     dev_ctx_p_c->volume = info->volume;
416 }
417
418  /* ---- LOCAL THREADED FUNCTIONS ---- */
419
420 STATIC void* _pulse_play_thread_fn (void *ctx) {
421
422     dev_ctx_pulse_T *dev_ctx_p_c = (dev_ctx_pulse_T *)ctx;
423     FILE *file = NULL;
424     char *buf = NULL;
425     long size;
426     int error;
427
428     file = fopen (AUDIO_BUFFER, "rb");
429
430     while (dev_ctx_p_c->thr_should_run && file && (access (AUDIO_BUFFER, F_OK) != -1) ) {
431         fseek (file, 0, SEEK_END);
432         size = ftell (file);
433         buf = (char*) realloc (buf, size * sizeof(char));
434
435         fseek (file, 0, SEEK_SET);
436         fread (buf, 1, size, file);
437         fflush (file);
438
439         if (pa_simple_write (dev_ctx_p_c->pa, buf, size*2, &error) < 0)
440             fprintf (stderr, "Error writing to PulseAudio : %s\n", pa_strerror (error));
441         /* pa_simple_drain (dev_ctx_p_c->pa); */
442     }
443     if (buf) free(buf);
444     if (file) fclose(file);
445
446     dev_ctx_p_c->thr_finished = 1;
447     return 0;
448 }