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