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