ceffcf7d583f956e0b579bb3763c6f655f9a63dc
[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     if (verbose) fprintf (stderr, "Successfully initialized PulseAudio backend.\n");
98
99     return 0;
100 }
101
102 PUBLIC void _pulse_free (audioCtxHandleT *ctx) {
103
104     int num, i;
105
106     client_count--;
107     if (client_count > 0) return;
108
109     for (num = 0; num < (sizeof(dev_ctx_p)/sizeof(dev_ctx_pulse_T)); num++) {
110
111          for (i = 0; num < (sizeof(dev_ctx_p[num]->card_name)/sizeof(char*)); i++) {
112              free (dev_ctx_p[num]->card_name[i]);
113              dev_ctx_p[num]->card_name[i] = NULL;
114          }
115          pa_context_disconnect (dev_ctx_p[num]->pa_context);
116          pa_context_unref (dev_ctx_p[num]->pa_context);
117          pa_mainloop_free (dev_ctx_p[num]->pa_loop);
118          pa_simple_free (dev_ctx_p[num]->pa);
119          free (dev_ctx_p[num]->sink_name);
120          dev_ctx_p[num]->pa_context = NULL;
121          dev_ctx_p[num]->pa_loop = NULL;
122          dev_ctx_p[num]->pa = NULL;
123          dev_ctx_p[num]->sink_name = NULL;
124          free (dev_ctx_p[num]);
125     }
126 }
127
128 PUBLIC void _pulse_play (audioCtxHandleT *ctx) {
129
130     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
131
132     if (!dev_ctx_p_c || dev_ctx_p_c->thr_should_run || access (AUDIO_BUFFER, F_OK) == -1)
133         return;
134
135     dev_ctx_p_c->thr_should_run = 1;
136     dev_ctx_p_c->thr_finished = 0;
137     pthread_create (&dev_ctx_p_c->thr, NULL, _pulse_play_thread_fn, (void*)dev_ctx_p_c);
138 }
139
140 PUBLIC void _pulse_stop (audioCtxHandleT *ctx) {
141
142     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
143
144     if (!dev_ctx_p_c || !dev_ctx_p_c->thr_should_run)
145         return;
146
147     dev_ctx_p_c->thr_should_run = 0;
148     while (!dev_ctx_p_c->thr_finished)
149         usleep(100000);
150     pthread_join (dev_ctx_p_c->thr, NULL);
151 }
152
153 PUBLIC int _pulse_get_volume (audioCtxHandleT *ctx, unsigned int channel) {
154
155     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
156
157     if (!dev_ctx_p_c)
158         return;
159
160     _pulse_refresh_sink (dev_ctx_p_c);
161
162     return (int)dev_ctx_p_c->volume.values[channel];
163 }
164
165 PUBLIC void _pulse_set_volume (audioCtxHandleT *ctx, unsigned int channel, int vol) {
166
167     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
168     struct pa_cvolume volume;
169
170     if (!dev_ctx_p_c)
171         return;
172
173     volume = dev_ctx_p_c->volume;
174     volume.values[channel] = vol;
175
176     pa_context_set_sink_volume_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
177                                         &volume, NULL, NULL);
178     _pulse_refresh_sink (dev_ctx_p_c);
179 }
180
181 PUBLIC void _pulse_set_volume_all (audioCtxHandleT *ctx, int vol) {
182
183     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
184     struct pa_cvolume volume;
185
186     if (!dev_ctx_p_c)
187         return;
188
189     pa_cvolume_init (&volume);
190     pa_cvolume_set (&volume, dev_ctx_p_c->volume.channels, vol);
191
192     pa_context_set_sink_volume_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
193                                         &volume, NULL, NULL);
194     _pulse_refresh_sink (dev_ctx_p_c);
195 }
196
197 PUBLIC unsigned char _pulse_get_mute (audioCtxHandleT *ctx) {
198
199     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
200
201     if (!dev_ctx_p_c)
202         return;
203
204     _pulse_refresh_sink (dev_ctx_p_c);
205
206     return (unsigned char)dev_ctx_p_c->mute;
207 }
208
209 PUBLIC void _pulse_set_mute (audioCtxHandleT *ctx, unsigned char mute) {
210
211     dev_ctx_pulse_T* dev_ctx_p_c = (dev_ctx_pulse_T*)ctx->audio_dev;
212
213     if (!dev_ctx_p_c)
214         return;
215
216     pa_context_set_sink_mute_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
217                                       (int)mute, NULL, NULL);
218     _pulse_refresh_sink (dev_ctx_p_c);
219 }
220
221  /* ---- LOCAL HELPER FUNCTIONS ---- */
222
223 void _pulse_refresh_sink (dev_ctx_pulse_T* dev_ctx_p_c) {
224
225     dev_ctx_p_c->refresh = 1;
226
227     pa_context_get_sink_info_by_name (dev_ctx_p_c->pa_context, dev_ctx_p_c->sink_name,
228                                       _pulse_sink_info_cb, (void*)dev_ctx_p_c);
229
230     while (dev_ctx_p_c->refresh)
231         pa_mainloop_iterate (dev_ctx_p_c->pa_loop, 0, NULL);
232 }
233
234 void _pulse_enumerate_cards () {
235
236     void **cards, **card;
237     char *name, *found, *alsa_name, *card_name;
238     int new_info, i, num = 0;
239
240     /* allocate the global alsa array */
241     alsa_info = (alsa_info_T**) malloc (sizeof(alsa_info_T));
242     alsa_info[0] = (alsa_info_T*) malloc (sizeof(alsa_info_T));
243     alsa_info[0]->device = NULL;
244     alsa_info[0]->synonyms = NULL;
245
246     /* we use ALSA to enumerate cards */
247     snd_device_name_hint (-1, "pcm", &cards);
248     card = cards;
249
250     for (; *card != NULL; card++) {
251         name = snd_device_name_get_hint (*card, "NAME");
252         new_info = 1;
253
254         /* alsa name is before ':' (if ':' misses, then it has no card) */
255         found = strstr (name, ":");
256         if (!found) continue;
257         /* */
258         alsa_name = (char*) malloc (found-name+1);
259         strncpy (alsa_name, name, found-name);
260         alsa_name[found-name] = '\0';
261
262         /* card name is the invariant between "CARD=" and ',' */
263         found = strstr (name, "CARD=");
264         if (!found) continue;
265         /* */
266         found += 5;
267         card_name = strdup (found);
268         found = strstr (card_name, ",");
269         if (found) card_name[found-card_name] = '\0';
270
271         /* was the card name already listed in the global alsa array ? */
272         for (i = 0; i < (sizeof(alsa_info)/sizeof(alsa_info_T)); i++) {
273
274             if (alsa_info[i]->device &&
275                 !strcmp (alsa_info[i]->device, card_name)) {
276                 /* it was ; add the alsa name as a new synonym */
277                 asprintf (&alsa_info[i]->synonyms, "%s:%s", alsa_info[i]->synonyms, alsa_name);
278                 new_info = 0;
279                 break;
280             }            
281         }
282         /* it was not ; create it */
283         if (new_info) {
284             alsa_info = (alsa_info_T**) realloc (alsa_info, (num+1)*sizeof(alsa_info_T));
285             alsa_info[num]->device = strdup (card_name);
286             asprintf (&alsa_info[num]->synonyms, ":%s", alsa_name);
287             num++;
288         }
289         free (alsa_name);
290         free (card_name);
291     }
292 }
293
294 char** _pulse_find_cards (const char *name) {
295
296     char **cards = NULL;
297     char *needle, *found, *next;
298     int num, i = 0;
299
300     if (!alsa_info)
301       _pulse_enumerate_cards ();
302
303     asprintf (&needle, ":%s", name);
304
305     for (num = 0; num < (sizeof(alsa_info)/sizeof(alsa_info_T)); num++) {
306
307         found = strstr (alsa_info[num]->synonyms, needle);
308         while (found) {
309             /* if next character is not ':' or '\0', we are wrong */
310             if ((found[strlen(name)] != ':') && (found[strlen(name)] != '\0')) {
311                 found = strstr (found+1, needle);
312                 continue;
313             }
314             /* found it ; now return all the "synonym" cards */
315             found = strstr (alsa_info[num]->synonyms, ":");
316             while (found) {
317                 next = strstr (found+1, ":");
318                 cards = (char**) realloc (cards, (i+1)*sizeof(char*));
319                 cards[i] = (char*) malloc (next-found+1);
320                 strncpy (cards[i], found+1, next-found);
321                 cards[i][next-found] = '\0';
322                 i++;
323             }
324         }
325     }
326     free (needle);
327
328     return cards;
329 }
330
331  /* ---- LOCAL CALLBACK FUNCTIONS ---- */
332
333 STATIC void _pulse_context_cb (pa_context *context, void *data) {
334
335     pa_context_state_t state = pa_context_get_state (context);
336     dev_ctx_pulse_T *dev_ctx_p_t = (dev_ctx_pulse_T *)data;
337
338     if (state == PA_CONTEXT_FAILED) {
339         fprintf (stderr, "Could not connect to PulseAudio !\n");
340         pa_mainloop_quit (dev_ctx_p_t->pa_loop, -1);
341     }
342
343     if (state == PA_CONTEXT_READY)
344         pa_context_get_sink_info_list (context, _pulse_sink_list_cb, (void*)dev_ctx_p_t);
345 }
346
347 STATIC void _pulse_sink_list_cb (pa_context *context, const pa_sink_info *info,
348                                  int eol, void *data) {
349
350     dev_ctx_pulse_T *dev_ctx_p_t = (dev_ctx_pulse_T *)data;
351     const char *device_string;
352     char **cards;
353     int num, i;
354
355     if (eol != 0)
356         return;
357
358     /* ignore sinks with no cards */
359     if (!pa_proplist_contains (info->proplist, "device.string"))
360         return;
361
362     device_string = pa_proplist_gets (info->proplist, "device.string");
363
364     /* was a sink with similar name already found ? */
365     for (num = 0; num < (sizeof(dev_ctx_p)/sizeof(dev_ctx_pulse_T)); num++) {
366         if (dev_ctx_p[num]->sink_name &&
367            !strcmp (dev_ctx_p[num]->sink_name, info->name)) {
368
369             /* yet it was, did it have the required card ? */
370             cards = dev_ctx_p[num]->card_name;
371             for (i = 0; i < (sizeof(cards)/sizeof(char*)); i++) {
372                 if (!strcmp (cards[i], dev_ctx_p_t->card_name[0])) {
373                     /* it did : stop there and succeed */
374                     if (verbose) fprintf (stderr, "Found matching sink : %s\n", info->name);
375                     pa_mainloop_quit (dev_ctx_p_t->pa_loop, num);
376                 }
377             }
378             /* it did not, ignore and return */
379             return;
380         }
381     }
382     num++;
383
384     /* new sink, find all the cards it manages, fail if none */
385     cards = _pulse_find_cards (device_string);
386     if (!cards) return;
387
388     /* everything is well, register it in global array */
389     dev_ctx_p_t->sink_name = strdup (info->name);
390     dev_ctx_p_t->card_name = cards;
391     dev_ctx_p_t->mute = info->mute;
392     dev_ctx_p_t->volume = info->volume;
393     dev_ctx_p_t->thr_should_run = 0;
394     dev_ctx_p_t->thr_finished = 0;
395     dev_ctx_p[num] = dev_ctx_p_t;
396
397     /* does this new sink have the card we are looking for ? */ /* TODO : factorize this */
398     for (i = 0; i < (sizeof(cards)/sizeof(char*)); i++) {
399         if (!strcmp (cards[i], dev_ctx_p_t->card_name[0])) {
400              /* it did : stop there and succeed */
401              if (verbose) fprintf (stderr, "Found matching sink : %s\n", info->name);
402              pa_mainloop_quit (dev_ctx_p_t->pa_loop, num);
403         }
404     }
405 }
406
407 STATIC void _pulse_sink_info_cb (pa_context *context, const pa_sink_info *info,
408                                  int eol, void *data) {
409
410     dev_ctx_pulse_T *dev_ctx_p_c = (dev_ctx_pulse_T *)data;
411
412     if (eol != 0)
413         return;
414
415     dev_ctx_p_c->refresh = 0;
416     dev_ctx_p_c->mute = info->mute;
417     dev_ctx_p_c->volume = info->volume;
418 }
419
420  /* ---- LOCAL THREADED FUNCTIONS ---- */
421
422 STATIC void* _pulse_play_thread_fn (void *ctx) {
423
424     dev_ctx_pulse_T *dev_ctx_p_c = (dev_ctx_pulse_T *)ctx;
425     FILE *file = NULL;
426     char *buf = NULL;
427     long size;
428     int error;
429
430     file = fopen (AUDIO_BUFFER, "rb");
431
432     while (dev_ctx_p_c->thr_should_run && file && (access (AUDIO_BUFFER, F_OK) != -1) ) {
433         fseek (file, 0, SEEK_END);
434         size = ftell (file);
435         buf = (char*) realloc (buf, size * sizeof(char));
436
437         fseek (file, 0, SEEK_SET);
438         fread (buf, 1, size, file);
439         fflush (file);
440
441         if (pa_simple_write (dev_ctx_p_c->pa, buf, size*2, &error) < 0)
442             fprintf (stderr, "Error writing to PulseAudio : %s\n", pa_strerror (error));
443         /* pa_simple_drain (dev_ctx_p_c->pa); */
444     }
445     if (buf) free(buf);
446     if (file) fclose(file);
447
448     dev_ctx_p_c->thr_finished = 1;
449     return 0;
450 }