Debian Codegraph @

utils/aplay/aplay.c

raw
1 /*
2 * BlueALSA - aplay.c
3 * Copyright (c) 2016-2024 Arkadiusz Bokowy
4 *
5 * This file is a part of bluez-alsa.
6 *
7 * This project is licensed under the terms of the MIT license.
8 *
9 */
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include <assert.h>
16 #include <errno.h>
17 #include <getopt.h>
18 #include <libgen.h>
19 #include <math.h>
20 #include <poll.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <stdatomic.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <syslog.h>
29 #include <sys/eventfd.h>
30 #include <sys/param.h>
31 #include <unistd.h>
32
33 #include <alsa/asoundlib.h>
34 #include <bluetooth/bluetooth.h>
35 #include <dbus/dbus.h>
36
37 #include "shared/dbus-client.h"
38 #include "shared/dbus-client-pcm.h"
39 #include "shared/defs.h"
40 #include "shared/ffb.h"
41 #include "shared/log.h"
42 #include "shared/nv.h"
43 #include "alsa-mixer.h"
44 #include "alsa-pcm.h"
45 #include "dbus.h"
46
47 enum volume_type {
48 VOL_TYPE_AUTO,
49 VOL_TYPE_MIXER,
50 VOL_TYPE_SOFTWARE,
51 VOL_TYPE_NONE,
52 };
53
54 struct io_worker {
55 pthread_t thread;
56 /* used BlueALSA PCM device */
57 struct ba_pcm ba_pcm;
58 /* file descriptor of PCM FIFO */
59 int ba_pcm_fd;
60 /* file descriptor of PCM control */
61 int ba_pcm_ctrl_fd;
62 /* opened playback PCM device */
63 snd_pcm_t *snd_pcm;
64 /* mixer for volume control */
65 snd_mixer_t *snd_mixer;
66 snd_mixer_elem_t *snd_mixer_elem;
67 long mixer_volume_db_max_value;
68 bool mixer_has_mute_switch;
69 /* if true, playback is active */
70 atomic_bool active;
71 /* human-readable BT address */
72 char addr[18];
73 };
74
75 static unsigned int verbose = 0;
76 static bool list_bt_devices = false;
77 static bool list_bt_pcms = false;
78 static const char *pcm_device = "default";
79 static enum volume_type volume_type = VOL_TYPE_AUTO;
80 static const char *mixer_device = "default";
81 static const char *mixer_elem_name = "Master";
82 static unsigned int mixer_elem_index = 0;
83 static bool ba_profile_a2dp = true;
84 static bool ba_addr_any = false;
85 static bdaddr_t *ba_addrs = NULL;
86 static size_t ba_addrs_count = 0;
87 static unsigned int pcm_buffer_time = 500000;
88 static unsigned int pcm_period_time = 100000;
89
90 /* local PCM muted state for software mute */
91 static bool pcm_muted = false;
92
93 static struct ba_dbus_ctx dbus_ctx;
94 static char dbus_ba_service[32] = BLUEALSA_SERVICE;
95
96 static struct ba_pcm *ba_pcms = NULL;
97 static size_t ba_pcms_count = 0;
98
99 static pthread_mutex_t single_playback_mutex = PTHREAD_MUTEX_INITIALIZER;
100 static bool force_single_playback = false;
101
102 static pthread_rwlock_t workers_lock = PTHREAD_RWLOCK_INITIALIZER;
103 static struct io_worker *workers = NULL;
104 static size_t workers_count = 0;
105 static size_t workers_size = 0;
106
107 static int main_loop_quit_event_fd = -1;
108 static void main_loop_stop(int sig) {
109 eventfd_write(main_loop_quit_event_fd, sig);
110 }
111
112 static int parse_bt_addresses(char *argv[], size_t count) {
113
114 ba_addrs_count = count;
115 if ((ba_addrs = malloc(sizeof(*ba_addrs) * ba_addrs_count)) == NULL)
116 return -1;
117
118 for (size_t i = 0; i < ba_addrs_count; i++) {
119 if (str2ba(argv[i], &ba_addrs[i]) != 0)
120 return errno = EINVAL, -1;
121 if (bacmp(&ba_addrs[i], BDADDR_ANY) == 0)
122 ba_addr_any = true;
123 }
124
125 return 0;
126 }
127
128 static const char *bluealsa_get_profile(const struct ba_pcm *pcm) {
129 switch (pcm->transport) {
130 case BA_PCM_TRANSPORT_A2DP_SOURCE:
131 case BA_PCM_TRANSPORT_A2DP_SINK:
132 return "A2DP";
133 case BA_PCM_TRANSPORT_HFP_AG:
134 case BA_PCM_TRANSPORT_HFP_HF:
135 case BA_PCM_TRANSPORT_HSP_AG:
136 case BA_PCM_TRANSPORT_HSP_HS:
137 return "SCO";
138 default:
139 error("Unknown transport: %#x", pcm->transport);
140 return "[...]";
141 }
142 }
143
144 static snd_pcm_format_t bluealsa_get_snd_pcm_format(const struct ba_pcm *pcm) {
145 switch (pcm->format) {
146 case 0x0108:
147 return SND_PCM_FORMAT_U8;
148 case 0x8210:
149 return SND_PCM_FORMAT_S16_LE;
150 case 0x8318:
151 return SND_PCM_FORMAT_S24_3LE;
152 case 0x8418:
153 return SND_PCM_FORMAT_S24_LE;
154 case 0x8420:
155 return SND_PCM_FORMAT_S32_LE;
156 default:
157 error("Unknown PCM format: %#x", pcm->format);
158 return SND_PCM_FORMAT_UNKNOWN;
159 }
160 }
161
162 static void print_bt_device_list(void) {
163
164 static const struct {
165 const char *label;
166 unsigned int mode;
167 } section[2] = {
168 { "**** List of PLAYBACK Bluetooth Devices ****", BA_PCM_MODE_SINK },
169 { "**** List of CAPTURE Bluetooth Devices ****", BA_PCM_MODE_SOURCE },
170 };
171
172 const char *tmp;
173 size_t ii;
174
175 for (size_t i = 0; i < ARRAYSIZE(section); i++) {
176 printf("%s\n", section[i].label);
177 for (ii = 0, tmp = ""; ii < ba_pcms_count; ii++) {
178
179 struct ba_pcm *pcm = &ba_pcms[ii];
180 struct bluez_device dev = { 0 };
181
182 if (!(pcm->mode == section[i].mode))
183 continue;
184
185 if (strcmp(pcm->device_path, tmp) != 0) {
186 tmp = ba_pcms[ii].device_path;
187
188 DBusError err = DBUS_ERROR_INIT;
189 if (dbus_bluez_get_device(dbus_ctx.conn, pcm->device_path, &dev, &err) == -1) {
190 warn("Couldn't get BlueZ device properties: %s", err.message);
191 dbus_error_free(&err);
192 }
193
194 char bt_addr[18];
195 ba2str(&dev.bt_addr, bt_addr);
196
197 printf("%s: %s [%s], %s%s\n",
198 dev.hci_name, bt_addr, dev.name,
199 dev.trusted ? "trusted " : "", dev.icon);
200
201 }
202
203 printf(" %s (%s): %s %d channel%s %d Hz\n",
204 bluealsa_get_profile(pcm),
205 pcm->codec.name,
206 snd_pcm_format_name(bluealsa_get_snd_pcm_format(pcm)),
207 pcm->channels, pcm->channels != 1 ? "s" : "",
208 pcm->sampling);
209
210 }
211 }
212
213 }
214
215 static void print_bt_pcm_list(void) {
216
217 DBusError err = DBUS_ERROR_INIT;
218 struct bluez_device dev = { 0 };
219 const char *tmp = "";
220
221 for (size_t i = 0; i < ba_pcms_count; i++) {
222 struct ba_pcm *pcm = &ba_pcms[i];
223
224 if (strcmp(pcm->device_path, tmp) != 0) {
225 tmp = ba_pcms[i].device_path;
226 if (dbus_bluez_get_device(dbus_ctx.conn, pcm->device_path, &dev, &err) == -1) {
227 warn("Couldn't get BlueZ device properties: %s", err.message);
228 dbus_error_free(&err);
229 }
230 }
231
232 char bt_addr[18];
233 ba2str(&dev.bt_addr, bt_addr);
234
235 printf(
236 "bluealsa:DEV=%s,PROFILE=%s,SRV=%s\n"
237 " %s, %s%s, %s\n"
238 " %s (%s): %s %d channel%s %d Hz\n",
239 bt_addr,
240 pcm->transport & BA_PCM_TRANSPORT_MASK_A2DP ? "a2dp" : "sco",
241 dbus_ba_service,
242 dev.name,
243 dev.trusted ? "trusted " : "", dev.icon,
244 pcm->mode == BA_PCM_MODE_SINK ? "playback" : "capture",
245 bluealsa_get_profile(pcm),
246 pcm->codec.name,
247 snd_pcm_format_name(bluealsa_get_snd_pcm_format(pcm)),
248 pcm->channels, pcm->channels != 1 ? "s" : "",
249 pcm->sampling);
250
251 }
252
253 }
254
255 static struct ba_pcm *ba_pcm_add(const struct ba_pcm *pcm) {
256 struct ba_pcm *tmp;
257 if ((tmp = realloc(ba_pcms, (ba_pcms_count + 1) * sizeof(*ba_pcms))) == NULL)
258 return NULL;
259 ba_pcms = tmp;
260 memcpy(&ba_pcms[ba_pcms_count], pcm, sizeof(*ba_pcms));
261 return &ba_pcms[ba_pcms_count++];
262 }
263
264 static struct ba_pcm *ba_pcm_get(const char *path) {
265 for (size_t i = 0; i < ba_pcms_count; i++)
266 if (strcmp(ba_pcms[i].pcm_path, path) == 0)
267 return &ba_pcms[i];
268 return NULL;
269 }
270
271 static void ba_pcm_remove(const char *path) {
272 for (size_t i = 0; i < ba_pcms_count; i++)
273 if (strcmp(ba_pcms[i].pcm_path, path) == 0) {
274 memmove(&ba_pcms[i], &ba_pcms[i + 1],
275 (ba_pcms_count - i - 1) * sizeof(*ba_pcms));
276 ba_pcms_count--;
277 break;
278 }
279 }
280
281 static struct io_worker *get_active_io_worker(void) {
282
283 pthread_rwlock_rdlock(&workers_lock);
284
285 struct io_worker *w = NULL;
286 for (size_t i = 0; i < workers_count; i++)
287 if (workers[i].active) {
288 w = &workers[i];
289 break;
290 }
291
292 pthread_rwlock_unlock(&workers_lock);
293
294 return w;
295 }
296
297 static int pause_device_player(const struct ba_pcm *ba_pcm) {
298
299 DBusMessage *msg = NULL, *rep = NULL;
300 DBusError err = DBUS_ERROR_INIT;
301 char path[160];
302 int ret = 0;
303
304 snprintf(path, sizeof(path), "%s/player0", ba_pcm->device_path);
305 msg = dbus_message_new_method_call("org.bluez", path, "org.bluez.MediaPlayer1", "Pause");
306
307 if ((rep = dbus_connection_send_with_reply_and_block(dbus_ctx.conn, msg,
308 DBUS_TIMEOUT_USE_DEFAULT, &err)) == NULL) {
309 warn("Couldn't pause player: %s", err.message);
310 dbus_error_free(&err);
311 goto fail;
312 }
313
314 debug("Requested playback pause");
315 goto final;
316
317 fail:
318 ret = -1;
319
320 final:
321 if (msg != NULL)
322 dbus_message_unref(msg);
323 if (rep != NULL)
324 dbus_message_unref(rep);
325 return ret;
326 }
327
328 /**
329 * Open ALSA mixer element for volume control. */
330 static int io_worker_mixer_open(
331 struct io_worker *worker,
332 const char *dev_name,
333 const char *elem_name,
334 unsigned int elem_idx) {
335
336 if (dev_name == NULL)
337 return 0;
338
339 debug("Opening ALSA mixer: name=%s elem=%s index=%u",
340 dev_name, elem_name, elem_idx);
341
342 snd_mixer_elem_t *elem;
343 long vmin_db, vmax_db = 0;
344 bool has_mute_switch;
345 char *tmp;
346 int err;
347
348 if (alsa_mixer_open(&worker->snd_mixer, &elem,
349 dev_name, elem_name, elem_idx, &tmp) != 0) {
350 warn("Couldn't open ALSA mixer: %s", tmp);
351 free(tmp);
352 return -1;
353 }
354
355 has_mute_switch = snd_mixer_selem_has_playback_switch(elem);
356
357 if ((err = snd_mixer_selem_get_playback_dB_range(elem, &vmin_db, &vmax_db)) != 0)
358 warn("Couldn't get ALSA mixer playback dB range: %s", snd_strerror(err));
359
360 worker->snd_mixer_elem = elem;
361 worker->mixer_has_mute_switch = has_mute_switch;
362 worker->mixer_volume_db_max_value = vmax_db;
363
364 return 0;
365 }
366
367 /**
368 * Update BlueALSA PCM volume according to ALSA mixer element. */
369 static int io_worker_mixer_volume_sync_ba_pcm(
370 struct io_worker *worker,
371 struct ba_pcm *ba_pcm) {
372
373 snd_mixer_elem_t *elem = worker->snd_mixer_elem;
374 const int vmax = BA_PCM_VOLUME_MAX(ba_pcm);
375 long long volume_db_sum = 0;
376 bool muted = true;
377
378 snd_mixer_selem_channel_id_t ch;
379 for (ch = 0; snd_mixer_selem_has_playback_channel(elem, ch) == 1; ch++) {
380
381 long ch_volume_db;
382 int ch_switch = 1;
383 int err;
384
385 if ((err = snd_mixer_selem_get_playback_dB(elem, ch, &ch_volume_db)) != 0) {
386 error("Couldn't get ALSA mixer playback dB level: %s", snd_strerror(err));
387 return -1;
388 }
389
390 /* Mute switch is an optional feature for a mixer element. */
391 if (worker->mixer_has_mute_switch &&
392 (err = snd_mixer_selem_get_playback_switch(elem, ch, &ch_switch)) != 0) {
393 error("Couldn't get ALSA mixer playback switch: %s", snd_strerror(err));
394 return -1;
395 }
396
397 volume_db_sum += ch_volume_db;
398 /* Normalize volume level so it will not exceed 0.00 dB. */
399 volume_db_sum -= worker->mixer_volume_db_max_value;
400
401 if (ch_switch == 1)
402 muted = false;
403
404 }
405
406 /* Safety check for undefined behavior from
407 * out-of-bounds dB conversion. */
408 assert(volume_db_sum <= 0LL);
409
410 /* Convert dB to loudness using decibel formula and
411 * round to the nearest integer. */
412 int volume = lround(pow(2, (0.01 * volume_db_sum / ch) / 10) * vmax);
413
414 /* If mixer element does not support playback switch,
415 * use our global muted state. */
416 if (!worker->mixer_has_mute_switch)
417 muted = pcm_muted;
418
419 ba_pcm->volume.ch1_muted = muted;
420 ba_pcm->volume.ch1_volume = volume;
421 ba_pcm->volume.ch2_muted = muted;
422 ba_pcm->volume.ch2_volume = volume;
423
424 DBusError err = DBUS_ERROR_INIT;
425 if (!ba_dbus_pcm_update(&dbus_ctx, ba_pcm, BLUEALSA_PCM_VOLUME, &err)) {
426 error("Couldn't update BlueALSA source PCM: %s", err.message);
427 dbus_error_free(&err);
428 return -1;
429 }
430
431 return 0;
432 }
433
434 /**
435 * Update ALSA mixer element according to BlueALSA PCM volume. */
436 static int io_worker_mixer_volume_sync_snd_mixer_elem(
437 struct io_worker *worker,
438 struct ba_pcm *ba_pcm) {
439
440 /* skip update in case of software volume */
441 if (ba_pcm->soft_volume)
442 return 0;
443
444 snd_mixer_elem_t *elem = worker->snd_mixer_elem;
445 if (elem == NULL)
446 return 0;
447
448 /* User can connect BlueALSA PCM to mono, stereo or multi-channel output.
449 * For mono input (audio from BlueALSA PCM), case case is simple: we are
450 * changing all output channels at once. However, for stereo input it is
451 * not possible to know how to control left/right volume unless there is
452 * some kind of channel mapping. In order to simplify things, we will set
453 * all channels to the average left-right volume. */
454
455 const int vmax = BA_PCM_VOLUME_MAX(ba_pcm);
456 int volume = ba_pcm->volume.ch1_volume;
457 int muted = ba_pcm->volume.ch1_muted;
458
459 if (ba_pcm->channels > 1) {
460 volume = (ba_pcm->volume.ch1_volume + ba_pcm->volume.ch2_volume) / 2;
461 muted = ba_pcm->volume.ch1_muted || ba_pcm->volume.ch2_muted;
462 }
463
464 /* keep local muted state up to date */
465 pcm_muted = muted;
466
467 /* convert loudness to dB using decibel formula */
468 long db = 10 * log2(1.0 * volume / vmax) * 100;
469 db += worker->mixer_volume_db_max_value;
470
471 int err;
472 if ((err = snd_mixer_selem_set_playback_dB_all(elem, db, 0)) != 0) {
473 error("Couldn't set ALSA mixer playback dB level: %s", snd_strerror(err));
474 return -1;
475 }
476
477 /* mute switch is an optional feature for a mixer element */
478 if (worker->mixer_has_mute_switch &&
479 (err = snd_mixer_selem_set_playback_switch_all(elem, !muted)) != 0) {
480 error("Couldn't set ALSA mixer playback mute switch: %s", snd_strerror(err));
481 return -1;
482 }
483
484 return 0;
485 }
486
487 static int io_worker_mixer_elem_callback(snd_mixer_elem_t *elem, unsigned int mask) {
488 struct io_worker *worker = snd_mixer_elem_get_callback_private(elem);
489 if (mask & SND_CTL_EVENT_MASK_VALUE)
490 io_worker_mixer_volume_sync_ba_pcm(worker, &worker->ba_pcm);
491 return 0;
492 }
493
494 /**
495 * Setup volume synchronization between ALSA mixer and BlueALSA PCM. */
496 static int io_worker_mixer_volume_sync_setup(
497 struct io_worker *worker) {
498
499 /* skip setup in case of software volume */
500 if (worker->ba_pcm.soft_volume)
501 return 0;
502
503 snd_mixer_elem_t *elem = worker->snd_mixer_elem;
504 if (elem == NULL)
505 return 0;
506
507 debug("Setting up ALSA mixer volume synchronization");
508
509 snd_mixer_elem_set_callback(elem, io_worker_mixer_elem_callback);
510 snd_mixer_elem_set_callback_private(elem, worker);
511
512 /* initial synchronization */
513 io_worker_mixer_volume_sync_ba_pcm(worker, &worker->ba_pcm);
514
515 return 0;
516 }
517
518 static void io_worker_routine_exit(struct io_worker *worker) {
519 if (worker->ba_pcm_fd != -1) {
520 close(worker->ba_pcm_fd);
521 worker->ba_pcm_fd = -1;
522 }
523 if (worker->ba_pcm_ctrl_fd != -1) {
524 close(worker->ba_pcm_ctrl_fd);
525 worker->ba_pcm_ctrl_fd = -1;
526 }
527 if (worker->snd_pcm != NULL) {
528 snd_pcm_close(worker->snd_pcm);
529 worker->snd_pcm = NULL;
530 }
531 if (worker->snd_mixer != NULL) {
532 snd_mixer_close(worker->snd_mixer);
533 worker->snd_mixer_elem = NULL;
534 worker->snd_mixer = NULL;
535 }
536 debug("Exiting IO worker %s", worker->addr);
537 }
538
539 static void *io_worker_routine(struct io_worker *w) {
540
541 snd_pcm_format_t pcm_format = bluealsa_get_snd_pcm_format(&w->ba_pcm);
542 ssize_t pcm_format_size = snd_pcm_format_size(pcm_format, 1);
543 size_t pcm_1s_samples = w->ba_pcm.sampling * w->ba_pcm.channels;
544 ffb_t buffer = { 0 };
545
546 /* Cancellation should be possible only in the carefully selected place
547 * in order to prevent memory leaks and resources not being released. */
548 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
549
550 pthread_cleanup_push(PTHREAD_CLEANUP(io_worker_routine_exit), w);
551 pthread_cleanup_push(PTHREAD_CLEANUP(ffb_free), &buffer);
552
553 /* create buffer big enough to hold 100 ms of PCM data */
554 if (ffb_init(&buffer, pcm_1s_samples / 10, pcm_format_size) == -1) {
555 error("Couldn't create PCM buffer: %s", strerror(errno));
556 goto fail;
557 }
558
559 DBusError err = DBUS_ERROR_INIT;
560
561 /* initialize the PCM soft_volume setting */
562 if (volume_type != VOL_TYPE_AUTO) {
563 bool softvol = (volume_type == VOL_TYPE_SOFTWARE);
564 debug("Setting BlueALSA source PCM volume mode: %s: %s",
565 w->ba_pcm.pcm_path, softvol ? "software" : "pass-through");
566 if (softvol != w->ba_pcm.soft_volume) {
567 w->ba_pcm.soft_volume = softvol;
568 if (!ba_dbus_pcm_update(&dbus_ctx, &w->ba_pcm,
569 BLUEALSA_PCM_SOFT_VOLUME, &err)) {
570 error("Couldn't set BlueALSA source PCM volume mode: %s", err.message);
571 dbus_error_free(&err);
572 goto fail;
573 }
574 }
575 }
576
577 debug("Opening BlueALSA source PCM: %s", w->ba_pcm.pcm_path);
578 if (!ba_dbus_pcm_open(&dbus_ctx, w->ba_pcm.pcm_path,
579 &w->ba_pcm_fd, &w->ba_pcm_ctrl_fd, &err)) {
580 error("Couldn't open BlueALSA source PCM: %s", err.message);
581 dbus_error_free(&err);
582 goto fail;
583 }
584
585 /* Initialize the max read length to 10 ms. Later, when the PCM device
586 * will be opened, this value will be adjusted to one period size. */
587 size_t pcm_max_read_len_init = pcm_1s_samples / 100 * pcm_format_size;
588 size_t pcm_max_read_len = pcm_max_read_len_init;
589
590 /* Track the lock state of the single playback mutex within this thread. */
591 bool single_playback_mutex_locked = false;
592
593 /* Intervals in seconds between consecutive PCM open retry attempts. */
594 const unsigned int pcm_open_retry_intervals[] = { 1, 1, 2, 3, 5 };
595 size_t pcm_open_retry_pcm_samples = 0;
596 size_t pcm_open_retries = 0;
597
598 size_t pause_retry_pcm_samples = pcm_1s_samples;
599 size_t pause_retries = 0;
600
601 int timeout = -1;
602
603 debug("Starting IO loop");
604 for (;;) {
605
606 if (single_playback_mutex_locked) {
607 pthread_mutex_unlock(&single_playback_mutex);
608 single_playback_mutex_locked = false;
609 }
610
611 struct pollfd fds[16] = {
612 { main_loop_quit_event_fd, POLLIN, 0 },
613 { w->ba_pcm_fd, POLLIN, 0 }};
614 nfds_t nfds = 2;
615
616 if (w->snd_mixer != NULL)
617 nfds += snd_mixer_poll_descriptors_count(w->snd_mixer);
618
619 if (nfds > ARRAYSIZE(fds)) {
620 error("Poll FD array size exceeded: %zu > %zu", nfds, ARRAYSIZE(fds));
621 goto fail;
622 }
623
624 if (w->snd_mixer != NULL)
625 snd_mixer_poll_descriptors(w->snd_mixer, fds + 2, nfds - 2);
626
627 /* Reading from the FIFO won't block unless there is an open connection
628 * on the writing side. However, the server does not open PCM FIFO until
629 * a transport is created. With the A2DP, the transport is created when
630 * some clients (BT device) requests audio transfer. */
631
632 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
633 int poll_rv = poll(fds, nfds, timeout);
634 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
635
636 switch (poll_rv) {
637 case -1:
638 if (errno == EINTR)
639 continue;
640 error("IO loop poll error: %s", strerror(errno));
641 goto fail;
642 case 0:
643 debug("BT device marked as inactive: %s", w->addr);
644 pause_retry_pcm_samples = pcm_1s_samples;
645 pause_retries = 0;
646 w->active = false;
647 timeout = -1;
648 goto close_alsa;
649 }
650
651 if (fds[0].revents & POLLIN)
652 break;
653
654 if (w->snd_mixer != NULL)
655 snd_mixer_handle_events(w->snd_mixer);
656
657 size_t read_samples = 0;
658 if (fds[1].revents & POLLIN) {
659
660 ssize_t ret;
661 size_t _in = MIN(pcm_max_read_len, ffb_blen_in(&buffer));
662 if ((ret = read(w->ba_pcm_fd, buffer.tail, _in)) == -1) {
663 if (errno == EINTR)
664 continue;
665 error("BlueALSA source PCM read error: %s", strerror(errno));
666 goto fail;
667 }
668
669 read_samples = ret / pcm_format_size;
670 if (ret % pcm_format_size != 0)
671 warn("Invalid read from BlueALSA source PCM: %zd %% %zd != 0", ret, pcm_format_size);
672
673 }
674 else if (fds[1].revents & POLLHUP) {
675 /* source PCM FIFO has been terminated on the writing side */
676 debug("BlueALSA source PCM disconnected: %s", w->ba_pcm.pcm_path);
677 break;
678 }
679 else if (fds[1].revents)
680 error("Unexpected BlueALSA source PCM poll event: %#x", fds[1].revents);
681
682 if (read_samples == 0)
683 continue;
684
685 /* If current worker is not active and the single playback mode was
686 * enabled, we have to check if there is any other active worker. */
687 if (force_single_playback && !w->active) {
688
689 /* Before checking active worker, we need to lock the single playback
690 * mutex. It is required to lock it, because the active state is changed
691 * in the worker thread after opening the PCM device, so we have to
692 * synchronize all threads at this point. */
693 pthread_mutex_lock(&single_playback_mutex);
694 single_playback_mutex_locked = true;
695
696 if (get_active_io_worker() != NULL) {
697 /* In order not to flood BT connection with AVRCP packets,
698 * we are going to send pause command every 0.5 second. */
699 if (pause_retries < 5 &&
700 (pause_retry_pcm_samples += read_samples) > pcm_1s_samples / 2) {
701 if (pause_device_player(&w->ba_pcm) == -1)
702 /* pause command does not work, stop further requests */
703 pause_retries = 5;
704 pause_retry_pcm_samples = 0;
705 pause_retries++;
706 timeout = 100;
707 }
708 continue;
709 }
710
711 }
712
713 if (w->snd_pcm == NULL) {
714
715 unsigned int buffer_time = pcm_buffer_time;
716 unsigned int period_time = pcm_period_time;
717 snd_pcm_uframes_t buffer_frames;
718 snd_pcm_uframes_t period_frames;
719 char *tmp;
720
721 if (pcm_open_retries > 0) {
722 /* After PCM open failure wait some time before retry. This can not be
723 * done with a sleep() call, because we have to drain PCM FIFO, so it
724 * will not have any stale data. */
725 unsigned int interval = pcm_open_retries > ARRAYSIZE(pcm_open_retry_intervals) ?
726 pcm_open_retry_intervals[ARRAYSIZE(pcm_open_retry_intervals) - 1] :
727 pcm_open_retry_intervals[pcm_open_retries - 1];
728 if ((pcm_open_retry_pcm_samples += read_samples) <= interval * pcm_1s_samples)
729 continue;
730 }
731
732 debug("Opening ALSA playback PCM: name=%s channels=%u rate=%u",
733 pcm_device, w->ba_pcm.channels, w->ba_pcm.sampling);
734 if (alsa_pcm_open(&w->snd_pcm, pcm_device, pcm_format, w->ba_pcm.channels,
735 w->ba_pcm.sampling, &buffer_time, &period_time, &tmp) != 0) {
736 warn("Couldn't open ALSA playback PCM: %s", tmp);
737 pcm_max_read_len = pcm_max_read_len_init;
738 pcm_open_retry_pcm_samples = 0;
739 pcm_open_retries++;
740 free(tmp);
741 continue;
742 }
743
744 snd_pcm_get_params(w->snd_pcm, &buffer_frames, &period_frames);
745 pcm_max_read_len = period_frames * w->ba_pcm.channels * pcm_format_size;
746
747 io_worker_mixer_open(w, mixer_device, mixer_elem_name, mixer_elem_index);
748 io_worker_mixer_volume_sync_setup(w);
749
750 /* reset retry counters */
751 pcm_open_retry_pcm_samples = 0;
752 pcm_open_retries = 0;
753
754 if (verbose >= 2) {
755 info("Used configuration for %s:\n"
756 " ALSA PCM buffer time: %u us (%zu bytes)\n"
757 " ALSA PCM period time: %u us (%zu bytes)\n"
758 " PCM format: %s\n"
759 " Sampling rate: %u Hz\n"
760 " Channels: %u",
761 w->addr,
762 buffer_time, snd_pcm_frames_to_bytes(w->snd_pcm, buffer_frames),
763 period_time, snd_pcm_frames_to_bytes(w->snd_pcm, period_frames),
764 snd_pcm_format_name(pcm_format),
765 w->ba_pcm.sampling,
766 w->ba_pcm.channels);
767 }
768
769 if (verbose >= 3)
770 alsa_pcm_dump(w->snd_pcm, stderr);
771
772 }
773
774 /* mark device as active and set timeout to 500ms */
775 w->active = true;
776 timeout = 500;
777
778 /* Current worker was marked as active, so we can safely
779 * release the single playback mutex if it was locked. */
780 if (single_playback_mutex_locked) {
781 pthread_mutex_unlock(&single_playback_mutex);
782 single_playback_mutex_locked = false;
783 }
784
785 ffb_seek(&buffer, read_samples);
786 size_t samples = ffb_len_out(&buffer);
787
788 if (!w->mixer_has_mute_switch && pcm_muted)
789 snd_pcm_format_set_silence(pcm_format, buffer.data, samples);
790
791 snd_pcm_sframes_t frames;
792
793 retry_alsa_write:
794 frames = samples / w->ba_pcm.channels;
795 if ((frames = snd_pcm_writei(w->snd_pcm, buffer.data, frames)) < 0)
796 switch (-frames) {
797 case EINTR:
798 goto retry_alsa_write;
799 case EPIPE:
800 debug("ALSA playback PCM underrun");
801 snd_pcm_prepare(w->snd_pcm);
802 goto retry_alsa_write;
803 default:
804 error("ALSA playback PCM write error: %s", snd_strerror(frames));
805 goto close_alsa;
806 }
807
808 /* move leftovers to the beginning and reposition tail */
809 ffb_shift(&buffer, frames * w->ba_pcm.channels);
810
811 continue;
812
813 close_alsa:
814 ffb_rewind(&buffer);
815 pcm_max_read_len = pcm_max_read_len_init;
816 if (w->snd_pcm != NULL) {
817 snd_pcm_close(w->snd_pcm);
818 w->snd_pcm = NULL;
819 }
820 if (w->snd_mixer != NULL) {
821 snd_mixer_close(w->snd_mixer);
822 w->snd_mixer_elem = NULL;
823 w->snd_mixer = NULL;
824 }
825 }
826
827 fail:
828 pthread_cleanup_pop(1);
829 pthread_cleanup_pop(1);
830 return NULL;
831 }
832
833 static bool pcm_hw_params_equal(
834 const struct ba_pcm *ba_pcm_1,
835 const struct ba_pcm *ba_pcm_2) {
836 if (ba_pcm_1->format != ba_pcm_2->format)
837 return false;
838 if (ba_pcm_1->channels != ba_pcm_2->channels)
839 return false;
840 if (ba_pcm_1->sampling != ba_pcm_2->sampling)
841 return false;
842 return true;
843 }
844
845 /**
846 * Stop the worker thread at workers[index]. */
847 static void io_worker_stop(size_t index) {
848
849 /* Safety check for out-of-bounds read. */
850 assert(index < workers_count);
851
852 pthread_cancel(workers[index].thread);
853 pthread_join(workers[index].thread, NULL);
854
855 pthread_rwlock_wrlock(&workers_lock);
856
857 if (index != --workers_count)
858 /* Move the last worker in the array to position
859 * index, to prevent any "gaps" in the array. */
860 memcpy(&workers[index], &workers[workers_count], sizeof(workers[index]));
861
862 pthread_rwlock_unlock(&workers_lock);
863
864 }
865
866 static struct io_worker *supervise_io_worker_start(const struct ba_pcm *ba_pcm) {
867
868 for (size_t i = 0; i < workers_count; i++)
869 if (strcmp(workers[i].ba_pcm.pcm_path, ba_pcm->pcm_path) == 0) {
870 /* If the codec has changed after the device connected, then the
871 * audio format may have changed. If it has, the worker thread
872 * needs to be restarted. */
873 if (!pcm_hw_params_equal(&workers[i].ba_pcm, ba_pcm))
874 io_worker_stop(i);
875 else
876 return &workers[i];
877 }
878
879 pthread_rwlock_wrlock(&workers_lock);
880
881 workers_count++;
882 if (workers_size < workers_count) {
883 struct io_worker *tmp = workers;
884 workers_size += 4; /* coarse-grained realloc */
885 if ((workers = realloc(workers, sizeof(*workers) * workers_size)) == NULL) {
886 error("Couldn't (re)allocate memory for IO workers: %s", strerror(ENOMEM));
887 workers = tmp;
888 pthread_rwlock_unlock(&workers_lock);
889 return NULL;
890 }
891 }
892
893 struct io_worker *worker = &workers[workers_count - 1];
894 memcpy(&worker->ba_pcm, ba_pcm, sizeof(worker->ba_pcm));
895 ba2str(&worker->ba_pcm.addr, worker->addr);
896 worker->ba_pcm_fd = -1;
897 worker->ba_pcm_ctrl_fd = -1;
898 worker->snd_pcm = NULL;
899 worker->snd_mixer = NULL;
900 worker->snd_mixer_elem = NULL;
901 worker->mixer_has_mute_switch = false;
902 worker->active = false;
903
904 debug("Creating IO worker %s", worker->addr);
905 if ((errno = pthread_create(&worker->thread, NULL,
906 PTHREAD_FUNC(io_worker_routine), worker)) != 0) {
907 error("Couldn't create IO worker %s: %s", worker->addr, strerror(errno));
908 workers_count--;
909 worker = NULL;
910 }
911
912 pthread_rwlock_unlock(&workers_lock);
913
914 return worker;
915 }
916
917 static struct io_worker *supervise_io_worker_stop(const struct ba_pcm *ba_pcm) {
918 for (size_t i = 0; i < workers_count; i++)
919 if (strcmp(workers[i].ba_pcm.pcm_path, ba_pcm->pcm_path) == 0)
920 io_worker_stop(i);
921 return NULL;
922 }
923
924 static struct io_worker *supervise_io_worker(const struct ba_pcm *ba_pcm) {
925
926 if (ba_pcm == NULL)
927 return NULL;
928
929 if (ba_pcm->mode != BA_PCM_MODE_SOURCE)
930 goto stop;
931
932 if ((ba_profile_a2dp && !(ba_pcm->transport & BA_PCM_TRANSPORT_MASK_A2DP)) ||
933 (!ba_profile_a2dp && !(ba_pcm->transport & BA_PCM_TRANSPORT_MASK_SCO)))
934 goto stop;
935
936 /* check whether SCO has selected codec */
937 if (ba_pcm->transport & BA_PCM_TRANSPORT_MASK_SCO &&
938 ba_pcm->sampling == 0) {
939 debug("Skipping SCO with codec not selected");
940 goto stop;
941 }
942
943 if (ba_addr_any)
944 goto start;
945
946 for (size_t i = 0; i < ba_addrs_count; i++)
947 if (bacmp(&ba_addrs[i], &ba_pcm->addr) == 0)
948 goto start;
949
950 stop:
951 return supervise_io_worker_stop(ba_pcm);
952 start:
953 return supervise_io_worker_start(ba_pcm);
954 }
955
956 static DBusHandlerResult dbus_signal_handler(DBusConnection *conn, DBusMessage *message, void *data) {
957 (void)conn;
958 (void)data;
959
960 if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL)
961 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
962
963 const char *path = dbus_message_get_path(message);
964 const char *interface = dbus_message_get_interface(message);
965 const char *signal = dbus_message_get_member(message);
966
967 DBusMessageIter iter;
968 struct io_worker *worker;
969
970 if (strcmp(interface, DBUS_INTERFACE_OBJECT_MANAGER) == 0) {
971
972 if (strcmp(signal, "InterfacesAdded") == 0) {
973 if (!dbus_message_iter_init(message, &iter))
974 goto fail;
975 struct ba_pcm pcm;
976 DBusError err = DBUS_ERROR_INIT;
977 if (!dbus_message_iter_get_ba_pcm(&iter, &err, &pcm)) {
978 error("Couldn't add new BlueALSA PCM: %s", err.message);
979 dbus_error_free(&err);
980 goto fail;
981 }
982 if (pcm.transport == BA_PCM_TRANSPORT_NONE)
983 goto fail;
984 if (ba_pcm_add(&pcm) == NULL) {
985 error("Couldn't add new BlueALSA PCM: %s", strerror(errno));
986 goto fail;
987 }
988 supervise_io_worker(&pcm);
989 return DBUS_HANDLER_RESULT_HANDLED;
990 }
991
992 if (strcmp(signal, "InterfacesRemoved") == 0) {
993 if (!dbus_message_iter_init(message, &iter) ||
994 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_OBJECT_PATH) {
995 error("Couldn't remove BlueALSA PCM: %s", "Invalid signal signature");
996 goto fail;
997 }
998 dbus_message_iter_get_basic(&iter, &path);
999 struct ba_pcm *pcm;
1000 if ((pcm = ba_pcm_get(path)) == NULL)
1001 goto fail;
1002 supervise_io_worker_stop(pcm);
1003 ba_pcm_remove(path);
1004 return DBUS_HANDLER_RESULT_HANDLED;
1005 }
1006
1007 }
1008
1009 if (strcmp(interface, DBUS_INTERFACE_PROPERTIES) == 0) {
1010 struct ba_pcm *pcm;
1011 if ((pcm = ba_pcm_get(path)) == NULL)
1012 goto fail;
1013 if (!dbus_message_iter_init(message, &iter) ||
1014 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1015 error("Couldn't update BlueALSA PCM: %s", "Invalid signal signature");
1016 goto fail;
1017 }
1018 dbus_message_iter_get_basic(&iter, &interface);
1019 dbus_message_iter_next(&iter);
1020 if (!dbus_message_iter_get_ba_pcm_props(&iter, NULL, pcm))
1021 goto fail;
1022 if ((worker = supervise_io_worker(pcm)) != NULL)
1023 io_worker_mixer_volume_sync_snd_mixer_elem(worker, pcm);
1024 return DBUS_HANDLER_RESULT_HANDLED;
1025 }
1026
1027 fail:
1028 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1029 }
1030
1031 int main(int argc, char *argv[]) {
1032
1033 int opt;
1034 const char *opts = "hVSvlLB:D:M:";
1035 const struct option longopts[] = {
1036 { "help", no_argument, NULL, 'h' },
1037 { "version", no_argument, NULL, 'V' },
1038 { "syslog", no_argument, NULL, 'S' },
1039 { "loglevel", required_argument, NULL, 9 },
1040 { "verbose", no_argument, NULL, 'v' },
1041 { "list-devices", no_argument, NULL, 'l' },
1042 { "list-pcms", no_argument, NULL, 'L' },
1043 { "dbus", required_argument, NULL, 'B' },
1044 { "pcm", required_argument, NULL, 'D' },
1045 { "pcm-buffer-time", required_argument, NULL, 3 },
1046 { "pcm-period-time", required_argument, NULL, 4 },
1047 { "volume", required_argument, NULL, '8' },
1048 { "mixer-device", required_argument, NULL, 'M' },
1049 { "mixer-name", required_argument, NULL, 6 },
1050 { "mixer-index", required_argument, NULL, 7 },
1051 { "profile-a2dp", no_argument, NULL, 1 },
1052 { "profile-sco", no_argument, NULL, 2 },
1053 { "single-audio", no_argument, NULL, 5 },
1054 { 0, 0, 0, 0 },
1055 };
1056
1057 bool syslog = false;
1058 const char *volume_type_str = "auto";
1059
1060 /* Check if syslog forwarding has been enabled. This check has to be
1061 * done before anything else, so we can log early stage warnings and
1062 * errors. */
1063 opterr = 0;
1064 while ((opt = getopt_long(argc, argv, opts, longopts, NULL)) != -1)
1065 switch (opt) {
1066 case 'h' /* --help */ :
1067 printf("Usage:\n"
1068 " %s [OPTION]... [BT-ADDR]...\n"
1069 "\nOptions:\n"
1070 " -h, --help\t\t\tprint this help and exit\n"
1071 " -V, --version\t\t\tprint version and exit\n"
1072 " -S, --syslog\t\t\tsend output to syslog\n"
1073 " --loglevel=LEVEL\t\tminimum message priority\n"
1074 " -v, --verbose\t\t\tmake output more verbose\n"
1075 " -l, --list-devices\t\tlist available BT audio devices\n"
1076 " -L, --list-pcms\t\tlist available BT audio PCMs\n"
1077 " -B, --dbus=NAME\t\tBlueALSA service name suffix\n"
1078 " -D, --pcm=NAME\t\tplayback PCM device to use\n"
1079 " --pcm-buffer-time=INT\t\tplayback PCM buffer time\n"
1080 " --pcm-period-time=INT\t\tplayback PCM period time\n"
1081 " --volume=TYPE\t\t\tvolume control type [auto|mixer|none|software]\n"
1082 " -M, --mixer-device=NAME\tmixer device to use\n"
1083 " --mixer-name=NAME\t\tmixer element name\n"
1084 " --mixer-index=NUM\t\tmixer element index\n"
1085 " --profile-a2dp\t\tuse A2DP profile (default)\n"
1086 " --profile-sco\t\t\tuse SCO profile\n"
1087 " --single-audio\t\tsingle audio mode\n"
1088 "\nNote:\n"
1089 "If one wants to receive audio from more than one Bluetooth device, it is\n"
1090 "possible to specify more than one MAC address. By specifying any/empty MAC\n"
1091 "address (00:00:00:00:00:00), one will allow connections from any Bluetooth\n"
1092 "device. Without given explicit MAC address any/empty MAC is assumed.\n",
1093 argv[0]);
1094 return EXIT_SUCCESS;
1095
1096 case 'V' /* --version */ :
1097 printf("%s\n", PACKAGE_VERSION);
1098 return EXIT_SUCCESS;
1099
1100 case 'S' /* --syslog */ :
1101 syslog = true;
1102 break;
1103
1104 case 'v' /* --verbose */ :
1105 verbose++;
1106 break;
1107 }
1108
1109 log_open(basename(argv[0]), syslog);
1110 dbus_threads_init_default();
1111
1112 /* parse options */
1113 optind = 0; opterr = 1;
1114 while ((opt = getopt_long(argc, argv, opts, longopts, NULL)) != -1)
1115 switch (opt) {
1116 case 'h' /* --help */ :
1117 case 'V' /* --version */ :
1118 case 'S' /* --syslog */ :
1119 case 'v' /* --verbose */ :
1120 break;
1121
1122 case 9 /* --loglevel=LEVEL */ : {
1123
1124 static const nv_entry_t values[] = {
1125 { "error", .v.ui = LOG_ERR },
1126 { "warning", .v.ui = LOG_WARNING },
1127 { "info", .v.ui = LOG_INFO },
1128 #if DEBUG
1129 { "debug", .v.ui = LOG_DEBUG },
1130 #endif
1131 { 0 },
1132 };
1133
1134 const nv_entry_t *entry;
1135 if ((entry = nv_find(values, optarg)) == NULL) {
1136 error("Invalid loglevel {%s}: %s", nv_join_names(values), optarg);
1137 return EXIT_FAILURE;
1138 }
1139
1140 log_set_min_priority(entry->v.ui);
1141 break;
1142 }
1143
1144 case 'l' /* --list-devices */ :
1145 list_bt_devices = true;
1146 break;
1147 case 'L' /* --list-pcms */ :
1148 list_bt_pcms = true;
1149 break;
1150
1151 case 'B' /* --dbus=NAME */ :
1152 snprintf(dbus_ba_service, sizeof(dbus_ba_service), BLUEALSA_SERVICE ".%s", optarg);
1153 if (!dbus_validate_bus_name(dbus_ba_service, NULL)) {
1154 error("Invalid BlueALSA D-Bus service name: %s", dbus_ba_service);
1155 return EXIT_FAILURE;
1156 }
1157 break;
1158
1159 case 'D' /* --pcm=NAME */ :
1160 pcm_device = optarg;
1161 break;
1162 case 3 /* --pcm-buffer-time=INT */ :
1163 pcm_buffer_time = atoi(optarg);
1164 break;
1165 case 4 /* --pcm-period-time=INT */ :
1166 pcm_period_time = atoi(optarg);
1167 break;
1168
1169 case '8' /* --volume */ : {
1170
1171 static const nv_entry_t values[] = {
1172 { "auto", .v.ui = VOL_TYPE_AUTO },
1173 { "mixer", .v.ui = VOL_TYPE_MIXER },
1174 { "software", .v.ui = VOL_TYPE_SOFTWARE },
1175 { "none", .v.ui = VOL_TYPE_NONE },
1176 { 0 },
1177 };
1178
1179 const nv_entry_t *entry;
1180 if ((entry = nv_find(values, optarg)) == NULL) {
1181 error("Invalid volume control type {%s}: %s",
1182 nv_join_names(values), optarg);
1183 return EXIT_FAILURE;
1184 }
1185
1186 volume_type_str = optarg;
1187 volume_type = entry->v.ui;
1188 break;
1189 }
1190
1191 case 'M' /* --mixer-device=NAME */ :
1192 mixer_device = optarg;
1193 break;
1194 case 6 /* --mixer-name=NAME */ :
1195 mixer_elem_name = optarg;
1196 break;
1197 case 7 /* --mixer-index=NUM */ :
1198 mixer_elem_index = atoi(optarg);
1199 break;
1200
1201 case 1 /* --profile-a2dp */ :
1202 ba_profile_a2dp = true;
1203 break;
1204 case 2 /* --profile-sco */ :
1205 ba_profile_a2dp = false;
1206 break;
1207
1208 case 5 /* --single-audio */ :
1209 force_single_playback = true;
1210 break;
1211
1212 default:
1213 fprintf(stderr, "Try '%s --help' for more information.\n", argv[0]);
1214 return EXIT_FAILURE;
1215 }
1216
1217 if ((main_loop_quit_event_fd = eventfd(0, EFD_CLOEXEC)) == -1) {
1218 error("Couldn't create quit event: %s", strerror(errno));
1219 return EXIT_FAILURE;
1220 }
1221
1222 DBusError err = DBUS_ERROR_INIT;
1223 if (!ba_dbus_connection_ctx_init(&dbus_ctx, dbus_ba_service, &err)) {
1224 error("Couldn't initialize D-Bus context: %s", err.message);
1225 return EXIT_FAILURE;
1226 }
1227
1228 if (list_bt_devices || list_bt_pcms) {
1229
1230 if (!ba_dbus_pcm_get_all(&dbus_ctx, &ba_pcms, &ba_pcms_count, &err)) {
1231 warn("Couldn't get BlueALSA PCM list: %s", err.message);
1232 return EXIT_FAILURE;
1233 }
1234
1235 if (list_bt_pcms)
1236 print_bt_pcm_list();
1237
1238 if (list_bt_devices)
1239 print_bt_device_list();
1240
1241 return EXIT_SUCCESS;
1242 }
1243
1244 if (optind == argc)
1245 ba_addr_any = true;
1246 else if (parse_bt_addresses(&argv[optind], argc - optind) == -1) {
1247 error("Couldn't parse BT addresses: %s", strerror(errno));
1248 return EXIT_FAILURE;
1249 }
1250
1251 if (volume_type == VOL_TYPE_NONE || volume_type == VOL_TYPE_SOFTWARE)
1252 mixer_device = NULL;
1253
1254 if (verbose >= 1) {
1255
1256 char *ba_str = malloc(19 * ba_addrs_count + 1);
1257 char *tmp = ba_str;
1258
1259 for (size_t i = 0; i < ba_addrs_count; i++, tmp += 19)
1260 ba2str(&ba_addrs[i], stpcpy(tmp, ", "));
1261
1262 const char *mixer_device_str = "(not used)";
1263 char mixer_element_str[128] = "(not used)";
1264 if (mixer_device != NULL) {
1265 mixer_device_str = mixer_device;
1266 snprintf(mixer_element_str, sizeof(mixer_element_str), "'%s',%u",
1267 mixer_elem_name, mixer_elem_index);
1268 }
1269
1270 info("Selected configuration:\n"
1271 " BlueALSA service: %s\n"
1272 " ALSA PCM device: %s\n"
1273 " ALSA PCM buffer time: %u us\n"
1274 " ALSA PCM period time: %u us\n"
1275 " Volume control type: %s\n"
1276 " ALSA mixer device: %s\n"
1277 " ALSA mixer element: %s\n"
1278 " Bluetooth device(s): %s\n"
1279 " Profile: %s",
1280 dbus_ba_service,
1281 pcm_device, pcm_buffer_time, pcm_period_time,
1282 volume_type_str,
1283 mixer_device_str,
1284 mixer_element_str,
1285 ba_addr_any ? "ANY" : &ba_str[2],
1286 ba_profile_a2dp ? "A2DP" : "SCO");
1287
1288 free(ba_str);
1289 }
1290
1291 ba_dbus_connection_signal_match_add(&dbus_ctx,
1292 dbus_ba_service, NULL, DBUS_INTERFACE_OBJECT_MANAGER, "InterfacesAdded",
1293 "path_namespace='/org/bluealsa'");
1294 ba_dbus_connection_signal_match_add(&dbus_ctx,
1295 dbus_ba_service, NULL, DBUS_INTERFACE_OBJECT_MANAGER, "InterfacesRemoved",
1296 "path_namespace='/org/bluealsa'");
1297 ba_dbus_connection_signal_match_add(&dbus_ctx,
1298 dbus_ba_service, NULL, DBUS_INTERFACE_PROPERTIES, "PropertiesChanged",
1299 "arg0='"BLUEALSA_INTERFACE_PCM"'");
1300
1301 if (!dbus_connection_add_filter(dbus_ctx.conn, dbus_signal_handler, NULL, NULL)) {
1302 error("Couldn't add D-Bus filter: %s", err.message);
1303 return EXIT_FAILURE;
1304 }
1305
1306 if (!ba_dbus_pcm_get_all(&dbus_ctx, &ba_pcms, &ba_pcms_count, &err))
1307 warn("Couldn't get BlueALSA PCM list: %s", err.message);
1308
1309 for (size_t i = 0; i < ba_pcms_count; i++)
1310 supervise_io_worker(&ba_pcms[i]);
1311
1312 struct sigaction sigact = {
1313 .sa_handler = main_loop_stop,
1314 .sa_flags = SA_RESETHAND };
1315 /* Call to these handlers restores the default action, so on the
1316 * second call the program will be forcefully terminated. */
1317 sigaction(SIGTERM, &sigact, NULL);
1318 sigaction(SIGINT, &sigact, NULL);
1319
1320 debug("Starting main loop");
1321 for (;;) {
1322
1323 struct pollfd fds[10] = {
1324 { main_loop_quit_event_fd, POLLIN, 0 } };
1325 nfds_t nfds = ARRAYSIZE(fds) - 1;
1326
1327 if (!ba_dbus_connection_poll_fds(&dbus_ctx, &fds[1], &nfds)) {
1328 error("Couldn't get D-Bus connection file descriptors");
1329 return EXIT_FAILURE;
1330 }
1331
1332 if (poll(fds, nfds + 1, -1) == -1 &&
1333 errno == EINTR)
1334 continue;
1335
1336 if (fds[0].revents & POLLIN)
1337 break;
1338
1339 if (ba_dbus_connection_poll_dispatch(&dbus_ctx, &fds[1], nfds))
1340 while (dbus_connection_dispatch(dbus_ctx.conn) == DBUS_DISPATCH_DATA_REMAINS)
1341 continue;
1342
1343 }
1344
1345 for (size_t i = workers_count; i > 0; i--)
1346 io_worker_stop(i - 1);
1347 free(workers);
1348
1349 ba_dbus_connection_ctx_free(&dbus_ctx);
1350 return EXIT_SUCCESS;
1351 }