docs: add yaml book
[AGL/meta-agl-devel.git] / meta-audio-4a-framework / recipes-connectivity / bluez-alsa / bluez-alsa / 0001-Added-a-connection-proxy-plugin.patch
1 From e730ec274c16d5ba390cb1cd29a8ada16204dd44 Mon Sep 17 00:00:00 2001
2 From: Thierry Bultel <thierry.bultel@iot.bzh>
3 Date: Wed, 29 Aug 2018 17:02:52 +0200
4 Subject: [PATCH] Added a connection proxy plugin
5
6 Introduces a new ioplug plugin for alsa.
7 This plugin always keeps the opened PCM in a consitent state
8 for the sound application, despite of bluealsa server or
9 or device disconnection.
10 For now, only playback is supported, and only one PCM per application
11 is allowed.
12 The sound application is in charge of telling the plugin what device
13 to use; the bluealsa_proxy_set_remote_device can be opened through
14 snd_dlopen. Please see the provided README.md for more details.
15
16 Signed-off-by: Stephane Desneux <stephane.desneux@iot.bzh>
17 ---
18  src/asound/20-bluealsa_proxy.conf |  41 ++
19  src/asound/Makefile.am            |  19 +-
20  src/asound/README.md              |  61 +++
21  src/asound/bluealsa-pcm-proxy.c   | 811 ++++++++++++++++++++++++++++++++++++++
22  4 files changed, 931 insertions(+), 1 deletion(-)
23  create mode 100644 src/asound/20-bluealsa_proxy.conf
24  create mode 100644 src/asound/README.md
25  create mode 100644 src/asound/bluealsa-pcm-proxy.c
26
27 diff --git a/src/asound/20-bluealsa_proxy.conf b/src/asound/20-bluealsa_proxy.conf
28 new file mode 100644
29 index 0000000..dec1cd8
30 --- /dev/null
31 +++ b/src/asound/20-bluealsa_proxy.conf
32 @@ -0,0 +1,41 @@
33 +# BlueALSA integration setup
34 +
35 +defaults.bluealsa.interface "hci0"
36 +defaults.bluealsa.profile "a2dp"
37 +defaults.bluealsa.delay 20000
38 +defaults.bluealsa.battery "yes"
39 +
40 +ctl.bluealsa {
41 +       @args [ HCI BAT ]
42 +       @args.HCI {
43 +               type string
44 +               default {
45 +                       @func refer
46 +                       name defaults.bluealsa.interface
47 +               }
48 +       }
49 +       @args.BAT {
50 +               type string
51 +               default {
52 +                       @func refer
53 +                       name defaults.bluealsa.battery
54 +               }
55 +       }
56 +       type bluealsa
57 +       interface $HCI
58 +       battery $BAT
59 +}
60 +
61 +pcm.bluealsa_proxy {
62 +       type plug
63 +       slave.pcm {
64 +               type bluealsa_proxy
65 +       }
66 +       hint {
67 +               show {
68 +                       @func refer
69 +                       name defaults.namehint.extended
70 +               }
71 +               description "Bluetooth Audio Hub Proxy"
72 +       }
73 +}
74 diff --git a/src/asound/Makefile.am b/src/asound/Makefile.am
75 index 75a2dc3..d3b2dfd 100644
76 --- a/src/asound/Makefile.am
77 +++ b/src/asound/Makefile.am
78 @@ -5,22 +5,34 @@ EXTRA_DIST = 20-bluealsa.conf
79  
80  asound_module_ctl_LTLIBRARIES = libasound_module_ctl_bluealsa.la
81  asound_module_pcm_LTLIBRARIES = libasound_module_pcm_bluealsa.la
82 -asound_module_data_DATA = 20-bluealsa.conf
83 +asound_module_pcm_proxy_LTLIBRARIES = libasound_module_pcm_bluealsa_proxy.la
84 +
85 +asound_module_data_DATA = 20-bluealsa.conf 20-bluealsa_proxy.conf
86  
87  libasound_module_ctl_bluealsa_la_SOURCES = \
88         ../shared/ctl-client.c \
89         ../shared/log.c \
90         bluealsa-ctl.c
91 +       
92  libasound_module_pcm_bluealsa_la_SOURCES = \
93         ../shared/ctl-client.c \
94         ../shared/log.c \
95         ../shared/rt.c \
96         bluealsa-pcm.c
97  
98 +libasound_module_pcm_bluealsa_proxy_la_SOURCES = \
99 +       ../shared/ctl-client.c \
100 +       ../shared/log.c \
101 +       ../shared/rt.c \
102 +       bluealsa-pcm-proxy.c
103 +
104 +
105  asound_module_ctldir = @ALSA_PLUGIN_DIR@
106  asound_module_pcmdir = @ALSA_PLUGIN_DIR@
107 +asound_module_pcm_proxydir = @ALSA_PLUGIN_DIR@
108  asound_module_datadir = @ALSA_DATA_DIR@/alsa.conf.d
109  
110 +
111  AM_CFLAGS = \
112         -I$(top_srcdir)/src \
113         @ALSA_CFLAGS@ \
114 @@ -34,3 +46,8 @@ libasound_module_ctl_bluealsa_la_LIBADD = \
115  libasound_module_pcm_bluealsa_la_LIBADD = \
116         @ALSA_LIBS@ \
117         @BLUEZ_LIBS@
118 +libasound_module_pcm_bluealsa_proxy_la_LIBADD = \
119 +       @ALSA_LIBS@ \
120 +       @BLUEZ_LIBS@
121 +
122 +       
123 \ No newline at end of file
124 diff --git a/src/asound/README.md b/src/asound/README.md
125 new file mode 100644
126 index 0000000..8ab52a8
127 --- /dev/null
128 +++ b/src/asound/README.md
129 @@ -0,0 +1,61 @@
130 +# ioplug proxy
131 +
132 +The ioplug proxy maintains a consitent state of the opened PCM.
133 +
134 +The application can call snd_pcm_open giving "bluealsa_proxy" as a card name.
135 +Only one PCM of this type can be opened by the application, and for now the
136 +hci interface is assumed to be hci0.
137 +
138 +To change to another one, just modify this line in 20-blualsa_proxu.conf
139 +defaults.bluealsa.interface "hci0"
140 +
141 +One the PCM is opened, which always succeeds regardless of the fact that there is 
142 +a bluetooth device connected or not, the application can set it dynamically using
143 +the bluealsa_proxy_set_remote_device function, like in this example code:
144 +
145 +```
146 +#define ALSA_BLUEZ_PROXY_LIB "/usr/lib/alsa-lib/libasound_module_pcm_bluealsa_proxy.so"
147 +#define ALSA_BLUEZ_PROXY_SETDEVICE "bluealsa_proxy_set_remote_device"
148 +
149 +typedef        int (*bluealsa_set_remote_device_ptr) (const char * interface, const char * device, const char * profile);
150 +
151 +static bluealsa_set_remote_device_ptr bluealsa_proxy_set_remote_device = NULL;
152 +
153 +void alsa_bluez_init() {
154 +       static bool initialized = false;
155 +       if (initialized)
156 +               goto failed;
157 +
158 +       char errbuf[256];
159 +       void * dl = snd_dlopen(ALSA_BLUEZ_PROXY_LIB, RTLD_NOW, errbuf, 256);
160 +       if (!dl) {
161 +               printf("Failed to open bluealsa proxy plugin\n");
162 +               goto failed;
163 +       }
164 +
165 +       void * func = snd_dlsym(dl, ALSA_BLUEZ_PROXY_SETDEVICE, SND_DLSYM_VERSION(SND_PCM_DLSYM_VERSION));
166 +       if (!func) {
167 +               printf("Unable to find %s symbol\n", ALSA_BLUEZ_PROXY_SETDEVICE);
168 +               goto failed;
169 +       }
170 +
171 +       bluealsa_proxy_set_remote_device = func;
172 +       initialized = true;
173 +
174 +failed:
175 +       return;
176 +}
177 +
178 +int alsa_bluez_set_device(const char * interface, const char * device, const char * profile) {
179 +       if (!bluealsa_proxy_set_remote_device)
180 +               return -1;
181 +
182 +       return bluealsa_proxy_set_remote_device(interface,device,profile);
183 +}
184 +
185 +...
186 +alsa_bluez_set_device("hci0","XX.XX.XX.XX.XX", "a2dp");        
187 +...
188 +
189 +```
190 +
191 diff --git a/src/asound/bluealsa-pcm-proxy.c b/src/asound/bluealsa-pcm-proxy.c
192 new file mode 100644
193 index 0000000..4abab2b
194 --- /dev/null
195 +++ b/src/asound/bluealsa-pcm-proxy.c
196 @@ -0,0 +1,811 @@
197 +/*
198 + * bluealsa-proxy-pcm.c
199 + * Copyright (c) 2018 Thierry Bultel
200 + *
201 + * This file is a part of bluez-alsa.
202 + *
203 + * This project is licensed under the terms of the MIT license.
204 + *
205 + */
206 +
207 +#define _GNU_SOURCE
208 +#include <errno.h>
209 +#include <poll.h>
210 +#include <pthread.h>
211 +#include <signal.h>
212 +#include <stdbool.h>
213 +#include <stdlib.h>
214 +#include <string.h>
215 +#include <unistd.h>
216 +#include <sys/eventfd.h>
217 +#include <sys/ioctl.h>
218 +
219 +#include <alsa/asoundlib.h>
220 +#include <alsa/pcm_external.h>
221 +
222 +#include "shared/ctl-client.h"
223 +#include "shared/ctl-proto.h"
224 +#include "shared/log.h"
225 +#include "shared/rt.h"
226 +
227 +#undef debug
228 +#define debug printf
229 +
230 +#define INTERFACE_STR_MAXLEN   256
231 +#define BDADDR_STR_LEN                 18
232 +#define PROFILE_STR_MAXLEN             16
233 +
234 +struct bluealsa_pcm {
235 +       snd_pcm_ioplug_t io;
236 +
237 +       /* bluealsa socket */
238 +       int fd;
239 +
240 +       /* event file descriptor */
241 +       int event_fd;
242 +
243 +       /* requested transport */
244 +       struct msg_transport * transport;
245 +       size_t pcm_buffer_size;
246 +
247 +       int pcm_fd;
248 +
249 +       /* virtual hardware - ring buffer */
250 +       snd_pcm_uframes_t io_ptr;
251 +       pthread_t io_thread;
252 +       bool io_started;
253 +
254 +       /* communication and encoding/decoding delay */
255 +       snd_pcm_sframes_t delay;
256 +       /* user provided extra delay component */
257 +       snd_pcm_sframes_t delay_ex;
258 +
259 +       /* ALSA operates on frames, we on bytes */
260 +       size_t frame_size;
261 +
262 +       /* In order to see whether the PCM has reached under-run (or over-run), we
263 +        * have to know the exact position of the hardware and software pointers.
264 +        * To do so, we could use the HW pointer provided by the IO plug structure.
265 +        * This pointer is updated by the snd_pcm_hwsync() function, which is not
266 +        * thread-safe (total disaster is guaranteed). Since we can not call this
267 +        * function, we are going to use our own HW pointer, which can be updated
268 +        * safely in our IO thread. */
269 +       snd_pcm_uframes_t io_hw_boundary;
270 +       snd_pcm_uframes_t io_hw_ptr;
271 +
272 +       char interface[INTERFACE_STR_MAXLEN];
273 +       bdaddr_t addr;
274 +       char profile[PROFILE_STR_MAXLEN];
275 +       enum pcm_type type;
276 +       enum pcm_stream stream;
277 +
278 +};
279 +
280 +typedef struct bluealsa_pcm bluealsa_pcm_t;
281 +
282 +static bluealsa_pcm_t * the_pcm = NULL;
283 +
284 +static int close_bluez_connection();
285 +static int open_bluez_connection();
286 +
287 +
288 +/**
289 + * Helper function for closing PCM transport. */
290 +static int close_transport(struct bluealsa_pcm *pcm) {
291 +
292 +       debug("%s ...\n", __func__);
293 +       if (pcm->transport == NULL)
294 +               return 0;
295 +
296 +       int rv = bluealsa_close_transport(pcm->fd, pcm->transport);
297 +       int err = errno;
298 +
299 +       close(pcm->pcm_fd);
300 +       pcm->pcm_fd = -1;
301 +       errno = err;
302 +       return rv;
303 +}
304 +
305 +/**
306 + * IO thread, which facilitates ring buffer. */
307 +static void *io_thread(void *arg) {
308 +       snd_pcm_ioplug_t *io = (snd_pcm_ioplug_t *)arg;
309 +
310 +       struct bluealsa_pcm *pcm = io->private_data;
311 +
312 +       sigset_t sigset;
313 +       sigemptyset(&sigset);
314 +
315 +       /* Block signal, which will be used for pause/resume actions. */
316 +       sigaddset(&sigset, SIGIO);
317 +       /* Block SIGPIPE, so we could receive EPIPE while writing to the pipe
318 +        * whose reading end has been closed. This will allow clean playback
319 +        * termination. */
320 +       sigaddset(&sigset, SIGPIPE);
321 +
322 +       if ((errno = pthread_sigmask(SIG_BLOCK, &sigset, NULL)) != 0) {
323 +               SNDERR("Thread signal mask error: %s", strerror(errno));
324 +               goto final;
325 +       }
326 +
327 +wait_pcm_fd:
328 +
329 +       debug("PLUGIN io-thread: wait for pcm_fd\n");
330 +
331 +       /* In the capture mode, the PCM FIFO is opened in the non-blocking mode.
332 +        * So right now, we have to synchronize write and read sides, otherwise
333 +        * reading might return 0, which will be incorrectly recognized as FIFO
334 +        * close signal, but in fact it means, that it was not opened yet. */
335 +       if (io->stream == SND_PCM_STREAM_CAPTURE) {
336 +
337 +               /* Is the data fd ready ? */
338 +               if (pcm->pcm_fd == -1) {
339 +                       usleep(100*1000);       // TODO This should be replaced by a semaphore
340 +                       goto wait_pcm_fd;
341 +               }
342 +
343 +               /* check both fd status */
344 +
345 +               struct pollfd pfds[2] = {
346 +                               { pcm->pcm_fd, POLLIN, 0 },
347 +                               { pcm->fd,      POLLIN|POLLPRI, 0 }};
348 +
349 +               int ret = poll(pfds, 2, -1);
350 +               if (ret == -1) {
351 +                       SNDERR("PCM FIFO poll error: %s", strerror(errno));
352 +                       goto final;
353 +               }
354 +
355 +               short int evt0 = pfds[0].revents;
356 +               short int evt1 = pfds[1].revents;
357 +
358 +               if (evt1 & POLLHUP) {
359 +                       debug("Server closed the connection\n");
360 +                       close_bluez_connection();
361 +                       open_bluez_connection();
362 +                       usleep(100*1000); /* avoid spinning too fast /*/
363 +                       goto wait_pcm_fd;
364 +               }
365 +
366 +               if (evt0 & POLLHUP) {
367 +                       debug("Remote device disconnected\n");
368 +                       close_bluez_connection();
369 +                       open_bluez_connection();
370 +                       usleep(100*1000);
371 +                       goto wait_pcm_fd;
372 +               }
373 +       }
374 +
375 +       const snd_pcm_channel_area_t *areas = snd_pcm_ioplug_mmap_areas(io);
376 +
377 +       struct asrsync asrs;
378 +       asrsync_init(asrs, io->rate);
379 +
380 +       for (;;) {
381 +
382 +               int tmp;
383 +               switch (io->state) {
384 +               case SND_PCM_STATE_RUNNING:
385 +               case SND_PCM_STATE_DRAINING:
386 +                       break;
387 +               case SND_PCM_STATE_DISCONNECTED:
388 +                       debug("PLUGIN: DISCONNECTED\n");
389 +                       goto final;
390 +               default:
391 +                       sigwait(&sigset, &tmp);
392 +                       asrsync_init(asrs, io->rate);
393 +               }
394 +
395 +               snd_pcm_uframes_t io_ptr = pcm->io_ptr;
396 +               snd_pcm_uframes_t io_buffer_size = io->buffer_size;
397 +               snd_pcm_uframes_t io_hw_ptr = pcm->io_hw_ptr;
398 +               snd_pcm_uframes_t io_hw_boundary = pcm->io_hw_boundary;
399 +               snd_pcm_uframes_t frames = io->period_size;
400 +               char *buffer = areas->addr + (areas->first + areas->step * io_ptr) / 8;
401 +               char *head = buffer;
402 +               ssize_t ret = 0;
403 +               size_t len;
404 +
405 +               /* If the leftover in the buffer is less than a whole period sizes,
406 +                * adjust the number of frames which should be transfered. It has
407 +                * turned out, that the buffer might contain fractional number of
408 +                * periods - it could be an ALSA bug, though, it has to be handled. */
409 +               if (io_buffer_size - io_ptr < frames)
410 +                       frames = io_buffer_size - io_ptr;
411 +
412 +               /* IO operation size in bytes */
413 +               len = frames * pcm->frame_size;
414 +               io_ptr += frames;
415 +
416 +               if (io_ptr >= io_buffer_size)
417 +                       io_ptr -= io_buffer_size;
418 +
419 +               io_hw_ptr += frames;
420 +               if (io_hw_ptr >= io_hw_boundary)
421 +                       io_hw_ptr -= io_hw_boundary;
422 +
423 +               if (io->stream == SND_PCM_STREAM_CAPTURE) {
424 +
425 +                       /* Read the whole period "atomically". This will assure, that frames
426 +                        * are not fragmented, so the pointer can be correctly updated. */
427 +                       while (len != 0 && (ret = read(pcm->pcm_fd, head, len)) != 0) {
428 +                               if (ret == -1) {
429 +                                       if (errno == EINTR)
430 +                                               continue;
431 +
432 +                                       SNDERR("PCM FIFO read error: %s", strerror(errno));
433 +                                       goto final;
434 +                               }
435 +                               head += ret;
436 +                               len -= ret;
437 +                       }
438 +
439 +                       /* something went wrong. this can be a server,
440 +                        * or device disconnection, or a device change request
441 +                        * from the client application */
442 +
443 +                       if (ret == 0)
444 +                               goto wait_pcm_fd;
445 +
446 +               }
447 +               else {
448 +
449 +                       /* check for under-run and act accordingly */
450 +                       if (io_hw_ptr > io->appl_ptr) {
451 +                               io->state = SND_PCM_STATE_XRUN;
452 +                               io_ptr = -1;
453 +                               goto sync;
454 +                       }
455 +
456 +                       /* Perform atomic write - see the explanation above. */
457 +                       do {
458 +                               if ((ret = write(pcm->pcm_fd, head, len)) == -1) {
459 +                                       if (errno == EINTR)
460 +                                               continue;
461 +                                       SNDERR("PCM FIFO write error: %s", strerror(errno));
462 +                                       goto final;
463 +                               }
464 +                               head += ret;
465 +                               len -= ret;
466 +                       }
467 +                       while (len != 0);
468 +
469 +                       /* synchronize playback time */
470 +                       asrsync_sync(&asrs, frames);
471 +               }
472 +
473 +sync:
474 +               pcm->io_ptr = io_ptr;
475 +               pcm->io_hw_ptr = io_hw_ptr;
476 +
477 +               eventfd_write(pcm->event_fd, 1);
478 +       }
479 +
480 +final:
481 +
482 +       debug("PLUGIN: io_thread exiting\n");
483 +
484 +       close_transport(pcm);
485 +       eventfd_write(pcm->event_fd, 0xDEAD0000);
486 +
487 +       return NULL;
488 +}
489 +
490 +static int bluealsa_proxy_start(snd_pcm_ioplug_t *io) {
491 +       struct bluealsa_pcm *pcm = io->private_data;
492 +
493 +       debug("%s ...\n", __func__);
494 +
495 +       /* If the IO thread is already started, skip thread creation. Otherwise,
496 +        * we might end up with a bunch of IO threads reading or writing to the
497 +        * same FIFO simultaneously. Instead, just send resume signal. */
498 +       if (pcm->io_started) {
499 +               io->state = SND_PCM_STATE_RUNNING;
500 +               pthread_kill(pcm->io_thread, SIGIO);
501 +               return 0;
502 +       }
503 +
504 +       /* initialize delay calculation */
505 +       pcm->delay = 0;
506 +
507 +       if (pcm->transport && bluealsa_pause_transport(pcm->fd, pcm->transport, false) == -1) {
508 +               debug("Couldn't start PCM: %s\n", strerror(errno));
509 +               return -errno;
510 +       }
511 +
512 +       /* State has to be updated before the IO thread is created - if the state
513 +        * does not indicate "running", the IO thread will be suspended until the
514 +        * "resume" signal is delivered. This requirement is only (?) theoretical,
515 +        * anyhow forewarned is forearmed. */
516 +       snd_pcm_state_t prev_state = io->state;
517 +       io->state = SND_PCM_STATE_RUNNING;
518 +
519 +       pcm->io_started = true;
520 +
521 +       return 0;
522 +}
523 +
524 +static int bluealsa_proxy_stop(snd_pcm_ioplug_t *io) {
525 +       struct bluealsa_pcm *pcm = io->private_data;
526 +
527 +       debug("Stopping");
528 +       if (pcm->io_started) {
529 +               pcm->io_started = false;
530 +               pthread_cancel(pcm->io_thread);
531 +               pthread_join(pcm->io_thread, NULL);
532 +       }
533 +       return 0;
534 +}
535 +
536 +static snd_pcm_sframes_t bluealsa_proxy_pointer(snd_pcm_ioplug_t *io) {
537 +       struct bluealsa_pcm *pcm = io->private_data;
538 +       if (pcm->pcm_fd == -1)
539 +               return -ENODEV;
540 +
541 +       return pcm->io_ptr;
542 +}
543 +
544 +static int bluealsa_proxy_close(snd_pcm_ioplug_t *io) {
545 +       struct bluealsa_pcm *pcm = io->private_data;
546 +
547 +       debug("Closing plugin\n");
548 +       close(pcm->fd);
549 +       close(pcm->event_fd);
550 +       free(pcm);
551 +
552 +       the_pcm = NULL;
553 +
554 +       return 0;
555 +}
556 +
557 +static int bluealsa_proxy_hw_params(snd_pcm_ioplug_t *io, snd_pcm_hw_params_t *params) {
558 +       struct bluealsa_pcm *pcm = io->private_data;
559 +       (void)params;
560 +
561 +       pcm->frame_size = (snd_pcm_format_physical_width(io->format) * io->channels) / 8;
562 +
563 +       /* Indicate that our PCM is ready for writing, even though is is not 100%
564 +        * true - IO thread is not running yet. Some weird implementations might
565 +        * require PCM to be writable before the snd_pcm_start() call. */
566 +       if (io->stream == SND_PCM_STREAM_PLAYBACK)
567 +               eventfd_write(pcm->event_fd, 1);
568 +
569 +       if (pcm->io.stream == SND_PCM_STREAM_PLAYBACK) {
570 +               /* By default, the size of the pipe buffer is set to a too large value for
571 +                * our purpose. On modern Linux system it is 65536 bytes. Large buffer in
572 +                * the playback mode might contribute to an unnecessary audio delay. Since
573 +                * it is possible to modify the size of this buffer we will set is to some
574 +                * low value, but big enough to prevent audio tearing. Note, that the size
575 +                * will be rounded up to the page size (typically 4096 bytes). */
576 +               pcm->pcm_buffer_size = fcntl(pcm->pcm_fd, F_SETPIPE_SZ, 2048);
577 +               debug("FIFO buffer size: %zd", pcm->pcm_buffer_size);
578 +       }
579 +
580 +       debug("Selected HW buffer: %zd periods x %zd bytes %c= %zd bytes\n",
581 +                       io->buffer_size / io->period_size, pcm->frame_size * io->period_size,
582 +                       io->period_size * (io->buffer_size / io->period_size) == io->buffer_size ? '=' : '<',
583 +                       io->buffer_size * pcm->frame_size);
584 +
585 +       return 0;
586 +}
587 +
588 +static int bluealsa_proxy_hw_free(snd_pcm_ioplug_t *io) {
589 +       struct bluealsa_pcm *pcm = io->private_data;
590 +       debug("Freeing HW");
591 +
592 +       if (close_transport(pcm) == -1)
593 +               return -errno;
594 +       return 0;
595 +}
596 +
597 +static int bluealsa_proxy_sw_params(snd_pcm_ioplug_t *io, snd_pcm_sw_params_t *params) {
598 +       struct bluealsa_pcm *pcm = io->private_data;
599 +       snd_pcm_sw_params_get_boundary(params, &pcm->io_hw_boundary);
600 +       return 0;
601 +}
602 +
603 +static int bluealsa_proxy_prepare(snd_pcm_ioplug_t *io) {
604 +       struct bluealsa_pcm *pcm = io->private_data;
605 +
606 +       /* initialize ring buffer */
607 +       pcm->io_hw_ptr = 0;
608 +       pcm->io_ptr = 0;
609 +
610 +       return 0;
611 +}
612 +
613 +static int bluealsa_proxy_drain(snd_pcm_ioplug_t *io) {
614 +       struct bluealsa_pcm *pcm = io->private_data;
615 +
616 +       if (bluealsa_drain_transport(pcm->fd, pcm->transport) == -1)
617 +               return -errno;
618 +       return 0;
619 +}
620 +
621 +static int bluealsa_proxy_pause(snd_pcm_ioplug_t *io, int enable) {
622 +       struct bluealsa_pcm *pcm = io->private_data;
623 +
624 +       if (bluealsa_pause_transport(pcm->fd, pcm->transport, enable) == -1)
625 +               return -errno;
626 +
627 +       if (enable == 0) {
628 +               io->state = SND_PCM_STATE_RUNNING;
629 +               pthread_kill(pcm->io_thread, SIGIO);
630 +       }
631 +
632 +       /* Even though PCM transport is paused, our IO thread is still running. If
633 +        * the implementer relies on the PCM file descriptor readiness, we have to
634 +        * bump our internal event trigger. Otherwise, client might stuck forever
635 +        * in the poll/select system call. */
636 +       eventfd_write(pcm->event_fd, 1);
637 +
638 +       return 0;
639 +}
640 +
641 +static void bluealsa_proxy_dump(snd_pcm_ioplug_t *io, snd_output_t *out) {
642 +       struct bluealsa_pcm *pcm = io->private_data;
643 +       char addr[18];
644 +
645 +       if (pcm->transport == NULL) {
646 +               snd_output_printf(out, "Bluetooth Proxy: no transport yet\n");
647 +               return;
648 +       }
649 +
650 +       ba2str(&pcm->transport->addr, addr);
651 +       snd_output_printf(out, "Bluetooth Proxy device: %s\n", addr);
652 +       snd_output_printf(out, "Bluetooth Proxy profile: %d\n", pcm->transport->type);
653 +       snd_output_printf(out, "Bluetooth Proxy codec: %d\n", pcm->transport->codec);
654 +
655 +}
656 +
657 +static int bluealsa_proxy_delay(snd_pcm_ioplug_t *io, snd_pcm_sframes_t *delayp) {
658 +       struct bluealsa_pcm *pcm = io->private_data;
659 +
660 +       if (pcm->pcm_fd == -1)
661 +               return -ENODEV;
662 +
663 +       /* Exact calculation of the PCM delay is very hard, if not impossible. For
664 +        * the sake of simplicity we will make few assumptions and approximations.
665 +        * In general, the delay is proportional to the number of bytes queued in
666 +        * the FIFO buffer, the time required to encode data, Bluetooth transfer
667 +        * latency and the time required by the device to decode and play audio. */
668 +
669 +       static int counter = 0;
670 +       snd_pcm_sframes_t delay = 0;
671 +       unsigned int size;
672 +
673 +       /* bytes queued in the PCM ring buffer */
674 +       delay += io->appl_ptr - io->hw_ptr;
675 +
676 +       /* bytes queued in the FIFO buffer */
677 +       if (ioctl(pcm->pcm_fd, FIONREAD, &size) != -1)
678 +               delay += size / pcm->frame_size;
679 +
680 +       /* On the server side, the delay stat will not be available until the PCM
681 +        * data transfer is started. Do not make an unnecessary call then. */
682 +       if ((io->state == SND_PCM_STATE_RUNNING || io->state == SND_PCM_STATE_DRAINING)) {
683 +
684 +               /* data transfer (communication) and encoding/decoding */
685 +               if (io->stream == SND_PCM_STREAM_PLAYBACK &&
686 +                               (pcm->delay == 0 || ++counter % (io->rate / 10) == 0)) {
687 +
688 +                       unsigned int tmp;
689 +                       if ((tmp = bluealsa_get_transport_delay(pcm->fd, pcm->transport)) != -1) {
690 +                               pcm->delay = (io->rate / 100) * tmp / 100;
691 +                               debug("BlueALSA delay: %.1f ms (%ld frames)", (float)tmp / 10, pcm->delay);
692 +                       }
693 +
694 +               }
695 +
696 +       }
697 +
698 +       *delayp = delay + pcm->delay + pcm->delay_ex;
699 +       return 0;
700 +}
701 +
702 +static int bluealsa_proxy_poll_descriptors_count(snd_pcm_ioplug_t *io) {
703 +       (void)io;
704 +       return 1;
705 +}
706 +
707 +static int bluealsa_proxy_poll_descriptors(snd_pcm_ioplug_t *io, struct pollfd *pfd,
708 +               unsigned int space) {
709 +       struct bluealsa_pcm *pcm = io->private_data;
710 +
711 +       if (space != 1)
712 +               return -EINVAL;
713 +
714 +       pfd[0].fd = pcm->event_fd;
715 +       pfd[0].events = POLLIN;
716 +
717 +       return 1;
718 +}
719 +
720 +static int bluealsa_proxy_poll_revents(snd_pcm_ioplug_t *io, struct pollfd *pfd,
721 +               unsigned int nfds, unsigned short *revents) {
722 +       struct bluealsa_pcm *pcm = io->private_data;
723 +
724 +       if (nfds != 1) {
725 +               return -EINVAL;
726 +       }
727 +
728 +       if (pcm->pcm_fd == -1) {
729 +               return -ENODEV;
730 +       }
731 +
732 +       if (pfd[0].revents & POLLIN) {
733 +
734 +               eventfd_t event;
735 +               eventfd_read(pcm->event_fd, &event);
736 +
737 +               if (event & 0xDEAD0000) {
738 +                       goto fail;
739 +               }
740 +
741 +               /* If the event was triggered prematurely, wait for another one.
742 +                * This causes a deadlock if */
743 +               if (!snd_pcm_avail_update(io->pcm)) {
744 +                       return *revents = 0;
745 +               }
746 +
747 +               /* ALSA expects that the event will match stream direction, e.g.
748 +                * playback will not start if the event is for reading. */
749 +               *revents = io->stream == SND_PCM_STREAM_CAPTURE ? POLLIN : POLLOUT;
750 +
751 +       }
752 +       else
753 +               *revents = 0;
754 +
755 +       return 0;
756 +
757 +fail:
758 +       *revents = POLLERR | POLLHUP;
759 +       return -ENODEV;
760 +}
761 +
762 +static const snd_pcm_ioplug_callback_t bluealsa_proxy_callback = {
763 +       .start = bluealsa_proxy_start,
764 +       .stop = bluealsa_proxy_stop,
765 +       .pointer = bluealsa_proxy_pointer,
766 +       .close = bluealsa_proxy_close,
767 +       .hw_params = bluealsa_proxy_hw_params,
768 +       .hw_free = bluealsa_proxy_hw_free,
769 +       .sw_params = bluealsa_proxy_sw_params,
770 +       .prepare = bluealsa_proxy_prepare,
771 +       .drain = bluealsa_proxy_drain,
772 +       .pause = bluealsa_proxy_pause,
773 +       .dump = bluealsa_proxy_dump,
774 +       .delay = bluealsa_proxy_delay,
775 +       .poll_descriptors_count = bluealsa_proxy_poll_descriptors_count,
776 +       .poll_descriptors = bluealsa_proxy_poll_descriptors,
777 +       .poll_revents = bluealsa_proxy_poll_revents,
778 +};
779 +
780 +static enum pcm_type bluealsa_proxy_parse_profile(const char *profile) {
781 +
782 +       if (profile == NULL)
783 +               return PCM_TYPE_NULL;
784 +
785 +       if (strcasecmp(profile, "a2dp") == 0)
786 +               return PCM_TYPE_A2DP;
787 +       else if (strcasecmp(profile, "sco") == 0)
788 +               return PCM_TYPE_SCO;
789 +
790 +       return PCM_TYPE_NULL;
791 +}
792 +
793 +/* This must be called when a transport is available */
794 +
795 +static int bluealsa_proxy_set_hw_constraint(struct bluealsa_pcm *pcm) {
796 +       snd_pcm_ioplug_t *io = &pcm->io;
797 +
798 +       static const snd_pcm_access_t accesses[] = {
799 +               SND_PCM_ACCESS_MMAP_INTERLEAVED,
800 +               SND_PCM_ACCESS_RW_INTERLEAVED,
801 +       };
802 +       static const unsigned int formats[] = {
803 +               SND_PCM_FORMAT_S16_LE,
804 +       };
805 +
806 +       int err;
807 +
808 +       debug("Setting constraints\n");
809 +
810 +       if ((err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_ACCESS,
811 +                                       sizeof(accesses) / sizeof(*accesses), accesses)) < 0)
812 +               return err;
813 +
814 +       if ((err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_FORMAT,
815 +                                       sizeof(formats) / sizeof(*formats), formats)) < 0)
816 +               return err;
817 +
818 +       if ((err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIODS,
819 +                                       2, 1024)) < 0)
820 +               return err;
821 +
822 +       /* In order to prevent audio tearing and minimize CPU utilization, we're
823 +        * going to setup buffer size constraints. These limits are derived from
824 +        * the transport sampling rate and the number of channels, so the buffer
825 +        * "time" size will be constant. The minimal period size and buffer size
826 +        * are respectively 10 ms and 200 ms. Upper limits are not constraint. */
827 +       unsigned int min_p = pcm->transport->sampling * 10 / 1000 * pcm->transport->channels * 2;
828 +       unsigned int min_b = pcm->transport->sampling * 200 / 1000 * pcm->transport->channels * 2;
829 +
830 +       if ((err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIOD_BYTES,
831 +                                       min_p, 1024 * 16)) < 0)
832 +               return err;
833 +
834 +       if ((err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_BUFFER_BYTES,
835 +                                       min_b, 1024 * 1024 * 16)) < 0)
836 +               return err;
837 +
838 +       if ((err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_CHANNELS,
839 +                                       pcm->transport->channels, pcm->transport->channels)) < 0)
840 +               return err;
841 +
842 +       if ((err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_RATE,
843 +                                       pcm->transport->sampling, pcm->transport->sampling)) < 0)
844 +               return err;
845 +
846 +       return 0;
847 +}
848 +
849 +
850 +SND_PCM_PLUGIN_DEFINE_FUNC(bluealsa_proxy) {
851 +       (void)root;
852 +
853 +       struct bluealsa_pcm *pcm;
854 +       long delay = 0;
855 +       int ret;
856 +
857 +       if ((pcm = calloc(1, sizeof(*pcm))) == NULL)
858 +               return -ENOMEM;
859 +
860 +       pcm->fd = -1;
861 +       pcm->event_fd = -1;
862 +       pcm->pcm_fd = -1;
863 +       pcm->delay_ex = delay;
864 +
865 +       if ((pcm->event_fd = eventfd(0, EFD_CLOEXEC)) == -1) {
866 +               ret = -errno;
867 +               goto fail;
868 +       }
869 +
870 +       pcm->io.version = SND_PCM_IOPLUG_VERSION;
871 +       pcm->io.name = "BlueALSA";
872 +       pcm->io.flags = SND_PCM_IOPLUG_FLAG_LISTED;
873 +       pcm->io.mmap_rw = 1;
874 +       pcm->io.callback = &bluealsa_proxy_callback;
875 +       pcm->io.private_data = pcm;
876 +       pcm->transport = NULL;
877 +
878 +       enum pcm_stream _stream = stream == SND_PCM_STREAM_PLAYBACK ?
879 +                       PCM_STREAM_PLAYBACK : PCM_STREAM_CAPTURE;
880 +
881 +       pcm->stream = stream;
882 +
883 +       if ((ret = snd_pcm_ioplug_create(&pcm->io, name, stream, mode)) < 0)
884 +               goto fail;
885 +
886 +       *pcmp = pcm->io.pcm;
887 +
888 +       // Remember PCM
889 +       the_pcm = pcm;
890 +
891 +       if ((errno = pthread_create(&pcm->io_thread, NULL, io_thread, &pcm->io)) != 0) {
892 +               debug("Couldn't create IO thread: %s", strerror(errno));
893 +               pcm->io_started = false;
894 +
895 +               ret = -errno;
896 +               goto fail;
897 +       }
898 +
899 +       pthread_setname_np(pcm->io_thread, "pcm-io");
900 +       return 0;
901 +
902 +fail:
903 +       if (pcm->fd != -1)
904 +               close(pcm->fd);
905 +       if (pcm->event_fd != -1)
906 +               close(pcm->event_fd);
907 +       free(pcm);
908 +       return ret;
909 +}
910 +
911 +SND_PCM_PLUGIN_SYMBOL(bluealsa_proxy);
912 +
913 +static int open_bluez_connection() {
914 +       int ret = 0;
915 +       bluealsa_pcm_t * pcm = the_pcm;
916 +
917 +       char addr[256];
918 +       ba2str(&pcm->addr, addr);
919 +
920 +       debug("%s interface %s addr %s type %d\n", __func__, pcm->interface, addr, pcm->type);
921 +
922 +       if ((pcm->fd = bluealsa_open(pcm->interface)) == -1) {
923 +               SNDERR("BlueALSA connection failed: %s", strerror(errno));
924 +               ret = -errno;
925 +               goto fail;
926 +       }
927 +
928 +       if ((pcm->transport = bluealsa_get_transport(pcm->fd, pcm->addr, pcm->type, pcm->stream)) == NULL) {
929 +               SNDERR("Couldn't get BlueALSA transport: %s", strerror(errno));
930 +               ret = -errno;
931 +               goto fail;
932 +       }
933 +
934 +       if ((ret = bluealsa_proxy_set_hw_constraint(pcm)) < 0) {
935 +               snd_pcm_ioplug_delete(&pcm->io);
936 +               goto fail;
937 +       }
938 +
939 +       pcm->transport->stream = pcm->stream;
940 +
941 +       if ((pcm->pcm_fd = bluealsa_open_transport(pcm->fd, pcm->transport)) == -1) {
942 +               debug("Couldn't open PCM FIFO: %s", strerror(errno));
943 +               return -errno;
944 +       }
945 +
946 +       debug("PLUGIN: starting transport\n");
947 +
948 +       if (bluealsa_pause_transport(pcm->fd, pcm->transport, false) == -1) {
949 +               debug("Couldn't start PCM: %s", strerror(errno));
950 +               return -errno;
951 +       }
952 +
953 +       debug("PLUGIN: connection ready !\n");
954 +
955 +       return 0;
956 +
957 +fail:
958 +       return ret;
959 +}
960 +
961 +static int close_bluez_connection() {
962 +       int ret = 0;
963 +       bluealsa_pcm_t * pcm = the_pcm;
964 +       close_transport(pcm);
965 +       close(pcm->fd);
966 +       return ret;
967 +}
968 +
969 +/* This is an exported function, to be loaded by clients via dlsym */
970 +
971 +int bluealsa_proxy_set_remote_device(const char * interface, const char * device, const char * profile) {
972 +       int ret  = -1;
973 +
974 +       debug("PLUGIN: %s: interface %s device %s profile %s\n", __func__, interface, device, profile);
975 +
976 +       if (the_pcm == NULL) {
977 +               SNDERR("No current opened connection to bluezalsa server\n");
978 +               goto failed;
979 +       }
980 +
981 +       enum pcm_type type;
982 +
983 +       if (device == NULL || str2ba(device, &the_pcm->addr) != 0) {
984 +               SNDERR("Invalid BT device address: %s", device);
985 +               ret = -EINVAL;
986 +               goto failed;
987 +       }
988 +
989 +       if ((type = bluealsa_proxy_parse_profile(profile)) == PCM_TYPE_NULL) {
990 +               SNDERR("Invalid BT profile [a2dp, sco]: %s", profile);
991 +               ret = -EINVAL;
992 +               goto failed;
993 +       }
994 +
995 +       strncpy(the_pcm->profile, profile, PROFILE_STR_MAXLEN);
996 +       strncpy(the_pcm->interface, interface, INTERFACE_STR_MAXLEN);
997 +
998 +       the_pcm->type = type;
999 +
1000 +       close_bluez_connection();
1001 +       ret = open_bluez_connection();
1002 +
1003 +failed:
1004 +       return ret;
1005 +}
1006 +
1007 +SND_DLSYM_BUILD_VERSION(bluealsa_proxy_set_remote_device, SND_PCM_DLSYM_VERSION);
1008 -- 
1009 2.1.4
1010