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