2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
33 #include <pulse/i18n.h>
34 #include <pulse/rtclock.h>
35 #include <pulse/sample.h>
36 #include <pulse/timeval.h>
37 #include <pulse/xmalloc.h>
39 #include <pulsecore/module.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-rtclock.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/core-error.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/namereg.h>
50 #include <pulsecore/dbus-shared.h>
51 #include <pulsecore/llist.h>
53 #include "module-bluetooth-device-symdef.h"
57 #include "bluetooth-util.h"
59 #define MAX_BITPOOL 64
60 #define MIN_BITPOOL 2U
62 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
63 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
64 PA_MODULE_VERSION(PACKAGE_VERSION);
65 PA_MODULE_LOAD_ONCE(FALSE);
67 "name=<name for the card/sink/source, to be prefixed> "
68 "card_name=<name for the card> "
69 "card_properties=<properties for the card> "
70 "sink_name=<name for the sink> "
71 "sink_properties=<properties for the sink> "
72 "source_name=<name for the source> "
73 "source_properties=<properties for the source> "
74 "address=<address of the device> "
75 "profile=<a2dp|hsp|hfgw> "
77 "channels=<number of channels> "
78 "path=<device object path> "
79 "auto_connect=<automatically connect?>");
83 "sco_sink=<SCO over PCM sink name> "
84 "sco_source=<SCO over PCM source name>"
88 /* TODO: not close fd when entering suspend mode in a2dp */
90 static const char* const valid_modargs[] = {
112 sbc_capabilities_t sbc_capabilities;
113 sbc_t sbc; /* Codec data */
114 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
115 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
117 void* buffer; /* Codec transfer buffer */
118 size_t buffer_size; /* Size of the buffer */
120 uint16_t seq_num; /* Cumulative packet sequence */
124 pcm_capabilities_t pcm_capabilities;
127 pa_source *sco_source;
129 pa_hook_slot *sink_state_changed_slot;
130 pa_hook_slot *source_state_changed_slot;
142 pa_bluetooth_discovery *discovery;
143 pa_bool_t auto_connect;
145 pa_dbus_connection *connection;
151 pa_thread_mq thread_mq;
153 pa_rtpoll_item *rtpoll_item;
156 uint64_t read_index, write_index;
157 pa_usec_t started_at;
158 pa_smoother *read_smoother;
160 pa_memchunk write_memchunk;
162 pa_sample_spec sample_spec, requested_sample_spec;
170 struct a2dp_info a2dp;
173 enum profile profile;
177 int stream_write_type;
178 int service_write_type, service_read_type;
180 pa_bool_t filter_added;
183 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
184 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
185 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
186 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
188 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
191 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
194 static int init_bt(struct userdata *u);
195 static int init_profile(struct userdata *u);
197 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
202 pa_assert(msg->length > 0);
204 if (u->service_fd < 0) {
205 pa_log_warn("Service not connected");
209 pa_log_debug("Sending %s -> %s",
210 pa_strnull(bt_audio_strtype(msg->type)),
211 pa_strnull(bt_audio_strname(msg->name)));
213 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
217 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
219 pa_log_error("Short write()");
224 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
228 pa_assert(u->service_fd >= 0);
230 pa_assert(room >= sizeof(*msg));
232 pa_log_debug("Trying to receive message from audio service...");
234 /* First, read the header */
235 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
238 if (msg->length < sizeof(*msg)) {
239 pa_log_error("Invalid message size.");
243 if (msg->length > room) {
244 pa_log_error("Not enough room.");
248 /* Secondly, read the payload */
249 if (msg->length > sizeof(*msg)) {
251 size_t remains = msg->length - sizeof(*msg);
253 if ((r = pa_loop_read(u->service_fd,
254 (uint8_t*) msg + sizeof(*msg),
256 &u->service_read_type)) != (ssize_t) remains)
260 pa_log_debug("Received %s <- %s",
261 pa_strnull(bt_audio_strtype(msg->type)),
262 pa_strnull(bt_audio_strname(msg->name)));
269 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
271 pa_log_error("Short read()");
276 static ssize_t service_expect(struct userdata*u, bt_audio_msg_header_t *rsp, size_t room, uint8_t expected_name, size_t expected_size) {
280 pa_assert(u->service_fd >= 0);
283 if ((r = service_recv(u, rsp, room)) < 0)
286 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
287 rsp->name != expected_name ||
288 (expected_size > 0 && rsp->length != expected_size)) {
290 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
291 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
293 pa_log_error("Bogus message %s received while %s was expected",
294 pa_strnull(bt_audio_strname(rsp->name)),
295 pa_strnull(bt_audio_strname(expected_name)));
302 /* Run from main thread */
303 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
305 const codec_capabilities_t *codec;
310 bytes_left = rsp->h.length - sizeof(*rsp);
312 if (bytes_left < sizeof(codec_capabilities_t)) {
313 pa_log_error("Packet too small to store codec information.");
317 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
319 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
321 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
322 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
323 pa_log_error("Got capabilities for wrong codec.");
327 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
329 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
332 pa_assert(codec->type == BT_HFP_CODEC_PCM);
334 if (codec->configured && seid == 0)
337 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
339 } else if (u->profile == PROFILE_A2DP) {
341 while (bytes_left > 0) {
342 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
345 bytes_left -= codec->length;
346 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
349 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
352 pa_assert(codec->type == BT_A2DP_SBC_SINK);
354 if (codec->configured && seid == 0)
357 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
359 } else if (u->profile == PROFILE_A2DP_SOURCE) {
361 while (bytes_left > 0) {
362 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
365 bytes_left -= codec->length;
366 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
369 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
372 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
374 if (codec->configured && seid == 0)
377 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
383 /* Run from main thread */
384 static int get_caps(struct userdata *u, uint8_t seid) {
386 struct bt_get_capabilities_req getcaps_req;
387 struct bt_get_capabilities_rsp getcaps_rsp;
388 bt_audio_error_t error;
389 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
395 memset(&msg, 0, sizeof(msg));
396 msg.getcaps_req.h.type = BT_REQUEST;
397 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
398 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
399 msg.getcaps_req.seid = seid;
401 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
402 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
403 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
405 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
406 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
408 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
410 if (service_send(u, &msg.getcaps_req.h) < 0)
413 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
416 ret = parse_caps(u, seid, &msg.getcaps_rsp);
420 return get_caps(u, ret);
423 /* Run from main thread */
424 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
427 case BT_SBC_SAMPLING_FREQ_16000:
428 case BT_SBC_SAMPLING_FREQ_32000:
431 case BT_SBC_SAMPLING_FREQ_44100:
434 case BT_A2DP_CHANNEL_MODE_MONO:
435 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
438 case BT_A2DP_CHANNEL_MODE_STEREO:
439 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
443 pa_log_warn("Invalid channel mode %u", mode);
447 case BT_SBC_SAMPLING_FREQ_48000:
450 case BT_A2DP_CHANNEL_MODE_MONO:
451 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
454 case BT_A2DP_CHANNEL_MODE_STEREO:
455 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
459 pa_log_warn("Invalid channel mode %u", mode);
464 pa_log_warn("Invalid sampling freq %u", freq);
469 /* Run from main thread */
470 static int setup_a2dp(struct userdata *u) {
471 sbc_capabilities_t *cap;
474 static const struct {
478 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
479 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
480 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
481 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
485 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
487 cap = &u->a2dp.sbc_capabilities;
489 /* Find the lowest freq that is at least as high as the requested
491 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
492 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
493 u->sample_spec.rate = freq_table[i].rate;
494 cap->frequency = freq_table[i].cap;
498 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
499 for (--i; i >= 0; i--) {
500 if (cap->frequency & freq_table[i].cap) {
501 u->sample_spec.rate = freq_table[i].rate;
502 cap->frequency = freq_table[i].cap;
508 pa_log("Not suitable sample rate");
513 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
515 if (cap->capability.configured)
518 if (u->sample_spec.channels <= 1) {
519 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
520 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
521 u->sample_spec.channels = 1;
523 u->sample_spec.channels = 2;
526 if (u->sample_spec.channels >= 2) {
527 u->sample_spec.channels = 2;
529 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
530 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
531 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
532 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
533 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
534 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
535 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
536 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
537 u->sample_spec.channels = 1;
539 pa_log("No supported channel modes");
544 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
545 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
546 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
547 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
548 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
549 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
550 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
551 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
553 pa_log_error("No supported block lengths");
557 if (cap->subbands & BT_A2DP_SUBBANDS_8)
558 cap->subbands = BT_A2DP_SUBBANDS_8;
559 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
560 cap->subbands = BT_A2DP_SUBBANDS_4;
562 pa_log_error("No supported subbands");
566 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
567 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
568 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
569 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
571 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
572 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
577 /* Run from main thread */
578 static void setup_sbc(struct a2dp_info *a2dp) {
579 sbc_capabilities_t *active_capabilities;
583 active_capabilities = &a2dp->sbc_capabilities;
585 if (a2dp->sbc_initialized)
586 sbc_reinit(&a2dp->sbc, 0);
588 sbc_init(&a2dp->sbc, 0);
589 a2dp->sbc_initialized = TRUE;
591 switch (active_capabilities->frequency) {
592 case BT_SBC_SAMPLING_FREQ_16000:
593 a2dp->sbc.frequency = SBC_FREQ_16000;
595 case BT_SBC_SAMPLING_FREQ_32000:
596 a2dp->sbc.frequency = SBC_FREQ_32000;
598 case BT_SBC_SAMPLING_FREQ_44100:
599 a2dp->sbc.frequency = SBC_FREQ_44100;
601 case BT_SBC_SAMPLING_FREQ_48000:
602 a2dp->sbc.frequency = SBC_FREQ_48000;
605 pa_assert_not_reached();
608 switch (active_capabilities->channel_mode) {
609 case BT_A2DP_CHANNEL_MODE_MONO:
610 a2dp->sbc.mode = SBC_MODE_MONO;
612 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
613 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
615 case BT_A2DP_CHANNEL_MODE_STEREO:
616 a2dp->sbc.mode = SBC_MODE_STEREO;
618 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
619 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
622 pa_assert_not_reached();
625 switch (active_capabilities->allocation_method) {
626 case BT_A2DP_ALLOCATION_SNR:
627 a2dp->sbc.allocation = SBC_AM_SNR;
629 case BT_A2DP_ALLOCATION_LOUDNESS:
630 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
633 pa_assert_not_reached();
636 switch (active_capabilities->subbands) {
637 case BT_A2DP_SUBBANDS_4:
638 a2dp->sbc.subbands = SBC_SB_4;
640 case BT_A2DP_SUBBANDS_8:
641 a2dp->sbc.subbands = SBC_SB_8;
644 pa_assert_not_reached();
647 switch (active_capabilities->block_length) {
648 case BT_A2DP_BLOCK_LENGTH_4:
649 a2dp->sbc.blocks = SBC_BLK_4;
651 case BT_A2DP_BLOCK_LENGTH_8:
652 a2dp->sbc.blocks = SBC_BLK_8;
654 case BT_A2DP_BLOCK_LENGTH_12:
655 a2dp->sbc.blocks = SBC_BLK_12;
657 case BT_A2DP_BLOCK_LENGTH_16:
658 a2dp->sbc.blocks = SBC_BLK_16;
661 pa_assert_not_reached();
664 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
665 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
666 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
669 /* Run from main thread */
670 static int set_conf(struct userdata *u) {
672 struct bt_open_req open_req;
673 struct bt_open_rsp open_rsp;
674 struct bt_set_configuration_req setconf_req;
675 struct bt_set_configuration_rsp setconf_rsp;
676 bt_audio_error_t error;
677 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
680 memset(&msg, 0, sizeof(msg));
681 msg.open_req.h.type = BT_REQUEST;
682 msg.open_req.h.name = BT_OPEN;
683 msg.open_req.h.length = sizeof(msg.open_req);
685 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
686 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
687 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
689 if (service_send(u, &msg.open_req.h) < 0)
692 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
695 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
696 u->sample_spec.format = PA_SAMPLE_S16LE;
698 if (setup_a2dp(u) < 0)
701 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
703 u->sample_spec.format = PA_SAMPLE_S16LE;
704 u->sample_spec.channels = 1;
705 u->sample_spec.rate = 8000;
708 memset(&msg, 0, sizeof(msg));
709 msg.setconf_req.h.type = BT_REQUEST;
710 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
711 msg.setconf_req.h.length = sizeof(msg.setconf_req);
713 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
714 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
716 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
717 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
718 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
720 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
722 if (service_send(u, &msg.setconf_req.h) < 0)
725 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
728 u->link_mtu = msg.setconf_rsp.link_mtu;
730 /* setup SBC encoder now we agree on parameters */
731 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
735 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
736 / u->a2dp.frame_length
739 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
740 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
742 u->block_size = u->link_mtu;
747 /* from IO thread, except in SCO over PCM */
749 static int setup_stream(struct userdata *u) {
750 struct pollfd *pollfd;
753 pa_make_fd_nonblock(u->stream_fd);
754 pa_make_socket_low_delay(u->stream_fd);
757 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
758 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
760 pa_log_debug("Stream properly set up, we're ready to roll!");
762 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
763 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
764 pollfd->fd = u->stream_fd;
765 pollfd->events = pollfd->revents = 0;
767 u->read_index = u->write_index = 0;
771 u->read_smoother = pa_smoother_new(
783 static int start_stream_fd(struct userdata *u) {
785 bt_audio_msg_header_t rsp;
786 struct bt_start_stream_req start_req;
787 struct bt_start_stream_rsp start_rsp;
788 struct bt_new_stream_ind streamfd_ind;
789 bt_audio_error_t error;
790 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
794 pa_assert(u->rtpoll);
795 pa_assert(!u->rtpoll_item);
796 pa_assert(u->stream_fd < 0);
798 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
799 msg.start_req.h.type = BT_REQUEST;
800 msg.start_req.h.name = BT_START_STREAM;
801 msg.start_req.h.length = sizeof(msg.start_req);
803 if (service_send(u, &msg.start_req.h) < 0)
806 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
809 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
812 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
813 pa_log("Failed to get stream fd from audio service.");
817 return setup_stream(u);
821 static int stop_stream_fd(struct userdata *u) {
823 bt_audio_msg_header_t rsp;
824 struct bt_stop_stream_req start_req;
825 struct bt_stop_stream_rsp start_rsp;
826 bt_audio_error_t error;
827 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
832 pa_assert(u->rtpoll);
834 if (u->rtpoll_item) {
835 pa_rtpoll_item_free(u->rtpoll_item);
836 u->rtpoll_item = NULL;
839 if (u->stream_fd >= 0) {
840 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
841 msg.start_req.h.type = BT_REQUEST;
842 msg.start_req.h.name = BT_STOP_STREAM;
843 msg.start_req.h.length = sizeof(msg.start_req);
845 if (service_send(u, &msg.start_req.h) < 0 ||
846 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
849 pa_close(u->stream_fd);
853 if (u->read_smoother) {
854 pa_smoother_free(u->read_smoother);
855 u->read_smoother = NULL;
861 static void bt_transport_release(struct userdata *u)
863 const char *accesstype = "rw";
864 const pa_bluetooth_transport *t;
866 /* Ignore if already released */
870 pa_log_debug("Releasing transport %s", u->transport);
872 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
874 pa_bluetooth_transport_release(t, accesstype);
876 pa_xfree(u->accesstype);
877 u->accesstype = NULL;
879 if (u->rtpoll_item) {
880 pa_rtpoll_item_free(u->rtpoll_item);
881 u->rtpoll_item = NULL;
884 if (u->stream_fd >= 0) {
885 pa_close(u->stream_fd);
889 if (u->read_smoother) {
890 pa_smoother_free(u->read_smoother);
891 u->read_smoother = NULL;
895 static int bt_transport_acquire(struct userdata *u, pa_bool_t start)
897 const char *accesstype = "rw";
898 const pa_bluetooth_transport *t;
906 pa_log_debug("Acquiring transport %s", u->transport);
908 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
910 pa_log("Transport %s no longer available", u->transport);
911 pa_xfree(u->transport);
916 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype);
917 if (u->stream_fd < 0)
920 u->accesstype = pa_xstrdup(accesstype);
921 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
927 pa_log_info("Transport %s resuming", u->transport);
928 return setup_stream(u);
931 /* Run from IO thread */
932 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
933 struct userdata *u = PA_SINK(o)->userdata;
934 pa_bool_t failed = FALSE;
937 pa_assert(u->sink == PA_SINK(o));
941 case PA_SINK_MESSAGE_SET_STATE:
943 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
945 case PA_SINK_SUSPENDED:
946 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
948 /* Stop the device if the source is suspended as well */
949 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
950 /* We deliberately ignore whether stopping
951 * actually worked. Since the stream_fd is
952 * closed it doesn't really matter */
954 bt_transport_release(u);
962 case PA_SINK_RUNNING:
963 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
966 /* Resume the device if the source was suspended as well */
967 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
969 if (bt_transport_acquire(u, TRUE) < 0)
971 } else if (start_stream_fd(u) < 0)
976 case PA_SINK_UNLINKED:
978 case PA_SINK_INVALID_STATE:
983 case PA_SINK_MESSAGE_GET_LATENCY: {
985 if (u->read_smoother) {
988 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
989 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
991 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
995 ri = pa_rtclock_now() - u->started_at;
996 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
998 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1001 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1006 r = pa_sink_process_msg(o, code, data, offset, chunk);
1008 return (r < 0 || !failed) ? r : -1;
1011 /* Run from IO thread */
1012 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1013 struct userdata *u = PA_SOURCE(o)->userdata;
1014 pa_bool_t failed = FALSE;
1017 pa_assert(u->source == PA_SOURCE(o));
1021 case PA_SOURCE_MESSAGE_SET_STATE:
1023 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1025 case PA_SOURCE_SUSPENDED:
1026 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1028 /* Stop the device if the sink is suspended as well */
1029 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1031 bt_transport_release(u);
1036 if (u->read_smoother)
1037 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1040 case PA_SOURCE_IDLE:
1041 case PA_SOURCE_RUNNING:
1042 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1045 /* Resume the device if the sink was suspended as well */
1046 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1048 if (bt_transport_acquire(u, TRUE) < 0)
1050 } else if (start_stream_fd(u) < 0)
1053 /* We don't resume the smoother here. Instead we
1054 * wait until the first packet arrives */
1057 case PA_SOURCE_UNLINKED:
1058 case PA_SOURCE_INIT:
1059 case PA_SOURCE_INVALID_STATE:
1064 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1067 if (u->read_smoother) {
1068 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1069 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1071 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1073 *((pa_usec_t*) data) = 0;
1080 r = pa_source_process_msg(o, code, data, offset, chunk);
1082 return (r < 0 || !failed) ? r : -1;
1085 /* Run from IO thread */
1086 static int hsp_process_render(struct userdata *u) {
1090 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1093 /* First, render some data */
1094 if (!u->write_memchunk.memblock)
1095 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1097 pa_assert(u->write_memchunk.length == u->block_size);
1103 /* Now write that data to the socket. The socket is of type
1104 * SEQPACKET, and we generated the data of the MTU size, so this
1105 * should just work. */
1107 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1108 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1109 pa_memblock_release(u->write_memchunk.memblock);
1116 /* Retry right away if we got interrupted */
1119 else if (errno == EAGAIN)
1120 /* Hmm, apparently the socket was not writable, give up for now */
1123 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1128 pa_assert((size_t) l <= u->write_memchunk.length);
1130 if ((size_t) l != u->write_memchunk.length) {
1131 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1132 (unsigned long long) l,
1133 (unsigned long long) u->write_memchunk.length);
1138 u->write_index += (uint64_t) u->write_memchunk.length;
1139 pa_memblock_unref(u->write_memchunk.memblock);
1140 pa_memchunk_reset(&u->write_memchunk);
1149 /* Run from IO thread */
1150 static int hsp_process_push(struct userdata *u) {
1152 pa_memchunk memchunk;
1155 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1156 pa_assert(u->source);
1157 pa_assert(u->read_smoother);
1159 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1160 memchunk.index = memchunk.length = 0;
1169 pa_bool_t found_tstamp = FALSE;
1172 memset(&m, 0, sizeof(m));
1173 memset(&aux, 0, sizeof(aux));
1174 memset(&iov, 0, sizeof(iov));
1178 m.msg_control = aux;
1179 m.msg_controllen = sizeof(aux);
1181 p = pa_memblock_acquire(memchunk.memblock);
1183 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1184 l = recvmsg(u->stream_fd, &m, 0);
1185 pa_memblock_release(memchunk.memblock);
1189 if (l < 0 && errno == EINTR)
1190 /* Retry right away if we got interrupted */
1193 else if (l < 0 && errno == EAGAIN)
1194 /* Hmm, apparently the socket was not readable, give up for now. */
1197 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1202 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1204 memchunk.length = (size_t) l;
1205 u->read_index += (uint64_t) l;
1207 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1208 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1209 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1210 pa_rtclock_from_wallclock(tv);
1211 tstamp = pa_timeval_load(tv);
1212 found_tstamp = TRUE;
1216 if (!found_tstamp) {
1217 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1218 tstamp = pa_rtclock_now();
1221 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1222 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1224 pa_source_post(u->source, &memchunk);
1230 pa_memblock_unref(memchunk.memblock);
1235 /* Run from IO thread */
1236 static void a2dp_prepare_buffer(struct userdata *u) {
1239 if (u->a2dp.buffer_size >= u->link_mtu)
1242 u->a2dp.buffer_size = 2 * u->link_mtu;
1243 pa_xfree(u->a2dp.buffer);
1244 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1247 /* Run from IO thread */
1248 static int a2dp_process_render(struct userdata *u) {
1249 struct a2dp_info *a2dp;
1250 struct rtp_header *header;
1251 struct rtp_payload *payload;
1255 size_t to_write, to_encode;
1256 unsigned frame_count;
1260 pa_assert(u->profile == PROFILE_A2DP);
1263 /* First, render some data */
1264 if (!u->write_memchunk.memblock)
1265 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1267 pa_assert(u->write_memchunk.length == u->block_size);
1269 a2dp_prepare_buffer(u);
1272 header = a2dp->buffer;
1273 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1277 /* Try to create a packet of the full MTU */
1279 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1280 to_encode = u->write_memchunk.length;
1282 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1283 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1285 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1289 encoded = sbc_encode(&a2dp->sbc,
1294 if (PA_UNLIKELY(encoded <= 0)) {
1295 pa_log_error("SBC encoding error (%li)", (long) encoded);
1296 pa_memblock_release(u->write_memchunk.memblock);
1300 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1301 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1303 pa_assert_fp((size_t) encoded <= to_encode);
1304 pa_assert_fp((size_t) encoded == a2dp->codesize);
1306 pa_assert_fp((size_t) written <= to_write);
1307 pa_assert_fp((size_t) written == a2dp->frame_length);
1309 p = (const uint8_t*) p + encoded;
1310 to_encode -= encoded;
1312 d = (uint8_t*) d + written;
1313 to_write -= written;
1318 pa_memblock_release(u->write_memchunk.memblock);
1320 pa_assert(to_encode == 0);
1323 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1326 /* write it to the fifo */
1327 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1330 header->sequence_number = htons(a2dp->seq_num++);
1331 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1332 header->ssrc = htonl(1);
1333 payload->frame_count = frame_count;
1335 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1340 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1347 /* Retry right away if we got interrupted */
1350 else if (errno == EAGAIN)
1351 /* Hmm, apparently the socket was not writable, give up for now */
1354 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1359 pa_assert((size_t) l <= nbytes);
1361 if ((size_t) l != nbytes) {
1362 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1363 (unsigned long long) l,
1364 (unsigned long long) nbytes);
1369 u->write_index += (uint64_t) u->write_memchunk.length;
1370 pa_memblock_unref(u->write_memchunk.memblock);
1371 pa_memchunk_reset(&u->write_memchunk);
1381 static int a2dp_process_push(struct userdata *u) {
1383 pa_memchunk memchunk;
1386 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1387 pa_assert(u->source);
1388 pa_assert(u->read_smoother);
1390 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1391 memchunk.index = memchunk.length = 0;
1394 pa_bool_t found_tstamp = FALSE;
1396 struct a2dp_info *a2dp;
1397 struct rtp_header *header;
1398 struct rtp_payload *payload;
1402 size_t to_write, to_decode;
1403 unsigned frame_count;
1405 a2dp_prepare_buffer(u);
1408 header = a2dp->buffer;
1409 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1411 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1415 if (l < 0 && errno == EINTR)
1416 /* Retry right away if we got interrupted */
1419 else if (l < 0 && errno == EAGAIN)
1420 /* Hmm, apparently the socket was not readable, give up for now. */
1423 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1428 pa_assert((size_t) l <= a2dp->buffer_size);
1430 u->read_index += (uint64_t) l;
1432 /* TODO: get timestamp from rtp */
1433 if (!found_tstamp) {
1434 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1435 tstamp = pa_rtclock_now();
1438 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1439 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1441 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1442 to_decode = l - sizeof(*header) - sizeof(*payload);
1444 d = pa_memblock_acquire(memchunk.memblock);
1445 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1447 while (PA_LIKELY(to_decode > 0 && to_write > 0)) {
1451 decoded = sbc_decode(&a2dp->sbc,
1456 if (PA_UNLIKELY(decoded <= 0)) {
1457 pa_log_error("SBC decoding error (%li)", (long) decoded);
1458 pa_memblock_release(memchunk.memblock);
1459 pa_memblock_unref(memchunk.memblock);
1463 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1464 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1466 pa_assert_fp((size_t) decoded <= to_decode);
1467 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1469 pa_assert_fp((size_t) written <= to_write);
1470 pa_assert_fp((size_t) written == a2dp->codesize);
1472 p = (const uint8_t*) p + decoded;
1473 to_decode -= decoded;
1475 d = (uint8_t*) d + written;
1476 to_write -= written;
1481 pa_memblock_release(memchunk.memblock);
1483 pa_source_post(u->source, &memchunk);
1489 pa_memblock_unref(memchunk.memblock);
1494 static void thread_func(void *userdata) {
1495 struct userdata *u = userdata;
1496 unsigned do_write = 0;
1497 pa_bool_t writable = FALSE;
1501 pa_log_debug("IO Thread starting up");
1503 if (u->core->realtime_scheduling)
1504 pa_make_realtime(u->core->realtime_priority);
1506 pa_thread_mq_install(&u->thread_mq);
1509 if (bt_transport_acquire(u, TRUE) < 0)
1511 } else if (start_stream_fd(u) < 0)
1515 struct pollfd *pollfd;
1517 pa_bool_t disable_timer = TRUE;
1519 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1521 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1523 /* We should send two blocks to the device before we expect
1526 if (u->write_index == 0 && u->read_index <= 0)
1529 if (pollfd && (pollfd->revents & POLLIN)) {
1532 if (u->profile == PROFILE_HSP || PROFILE_HFGW)
1533 n_read = hsp_process_push(u);
1535 n_read = a2dp_process_push(u);
1540 /* We just read something, so we are supposed to write something, too */
1545 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1547 if (u->sink->thread_info.rewind_requested)
1548 pa_sink_process_rewind(u->sink, 0);
1551 if (pollfd->revents & POLLOUT)
1554 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1555 pa_usec_t time_passed;
1556 pa_usec_t audio_sent;
1558 /* Hmm, there is no input stream we could synchronize
1559 * to. So let's do things by time */
1561 time_passed = pa_rtclock_now() - u->started_at;
1562 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1564 if (audio_sent <= time_passed) {
1565 pa_usec_t audio_to_send = time_passed - audio_sent;
1567 /* Never try to catch up for more than 100ms */
1568 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1569 pa_usec_t skip_usec;
1570 uint64_t skip_bytes;
1572 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1573 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1575 if (skip_bytes > 0) {
1578 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1579 (unsigned long long) skip_usec,
1580 (unsigned long long) skip_bytes);
1582 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1583 pa_memblock_unref(tmp.memblock);
1584 u->write_index += skip_bytes;
1592 if (writable && do_write > 0) {
1595 if (u->write_index <= 0)
1596 u->started_at = pa_rtclock_now();
1598 if (u->profile == PROFILE_A2DP) {
1599 if ((n_written = a2dp_process_render(u)) < 0)
1602 if ((n_written = hsp_process_render(u)) < 0)
1607 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1609 do_write -= n_written;
1613 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1614 pa_usec_t time_passed, next_write_at, sleep_for;
1616 /* Hmm, there is no input stream we could synchronize
1617 * to. So let's estimate when we need to wake up the latest */
1619 time_passed = pa_rtclock_now() - u->started_at;
1620 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1621 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1623 /* pa_log("Sleeping for %lu; time passed %lu, next write at %lu", (unsigned long) sleep_for, (unsigned long) time_passed, (unsigned long)next_write_at); */
1625 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1626 disable_timer = FALSE;
1632 pa_rtpoll_set_timer_disabled(u->rtpoll);
1634 /* Hmm, nothing to do. Let's sleep */
1636 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1637 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1639 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1645 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1647 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1648 pa_log_info("FD error: %s%s%s%s",
1649 pollfd->revents & POLLERR ? "POLLERR " :"",
1650 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1651 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1652 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1658 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1659 pa_log_debug("IO thread failed");
1660 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1661 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1664 pa_log_debug("IO thread shutting down");
1667 /* Run from main thread */
1668 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1674 pa_assert_se(u = userdata);
1676 dbus_error_init(&err);
1678 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1679 dbus_message_get_interface(m),
1680 dbus_message_get_path(m),
1681 dbus_message_get_member(m));
1683 if (!dbus_message_has_path(m, u->path))
1686 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1687 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1692 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1693 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1697 if (u->profile == PROFILE_HSP) {
1698 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1700 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1701 pa_sink_volume_changed(u->sink, &v);
1703 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1705 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1706 pa_source_volume_changed(u->source, &v);
1712 dbus_error_free(&err);
1714 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1717 /* Run from main thread */
1718 static void sink_set_volume_cb(pa_sink *s) {
1719 struct userdata *u = s->userdata;
1725 if (u->profile != PROFILE_HSP)
1728 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1733 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1735 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1736 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1737 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1738 dbus_message_unref(m);
1741 /* Run from main thread */
1742 static void source_set_volume_cb(pa_source *s) {
1743 struct userdata *u = s->userdata;
1749 if (u->profile != PROFILE_HSP)
1752 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1757 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1759 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1760 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1761 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1762 dbus_message_unref(m);
1765 /* Run from main thread */
1766 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1772 pa_assert(device_id);
1773 pa_assert(namereg_fail);
1775 t = pa_sprintf_malloc("%s_name", type);
1776 n = pa_modargs_get_value(ma, t, NULL);
1780 *namereg_fail = TRUE;
1781 return pa_xstrdup(n);
1784 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1785 *namereg_fail = TRUE;
1788 *namereg_fail = FALSE;
1791 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1796 static void sco_over_pcm_state_update(struct userdata *u) {
1798 pa_assert(USE_SCO_OVER_PCM(u));
1800 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1801 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1803 if (u->service_fd >= 0)
1808 pa_log_debug("Resuming SCO over PCM");
1809 if (init_profile(u) < 0)
1810 pa_log("Can't resume SCO over PCM");
1813 bt_transport_acquire(u, TRUE);
1818 if (u->service_fd < 0)
1822 bt_transport_release(u);
1826 pa_log_debug("Closing SCO over PCM");
1827 pa_close(u->service_fd);
1832 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1834 pa_sink_assert_ref(s);
1837 if (s != u->hsp.sco_sink)
1840 sco_over_pcm_state_update(u);
1845 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1847 pa_source_assert_ref(s);
1850 if (s != u->hsp.sco_source)
1853 sco_over_pcm_state_update(u);
1860 /* Run from main thread */
1861 static int add_sink(struct userdata *u) {
1864 if (USE_SCO_OVER_PCM(u)) {
1867 u->sink = u->hsp.sco_sink;
1868 p = pa_proplist_new();
1869 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1870 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1871 pa_proplist_free(p);
1873 if (!u->hsp.sink_state_changed_slot)
1874 u->hsp.sink_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
1880 pa_sink_new_data data;
1883 pa_sink_new_data_init(&data);
1884 data.driver = __FILE__;
1885 data.module = u->module;
1886 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1887 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1888 if (u->profile == PROFILE_HSP)
1889 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1890 data.card = u->card;
1891 data.name = get_name("sink", u->modargs, u->address, &b);
1892 data.namereg_fail = b;
1894 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1895 pa_log("Invalid properties");
1896 pa_sink_new_data_done(&data);
1900 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1901 pa_sink_new_data_done(&data);
1904 pa_log_error("Failed to create sink");
1908 u->sink->userdata = u;
1909 u->sink->parent.process_msg = sink_process_msg;
1911 pa_sink_set_max_request(u->sink, u->block_size);
1912 pa_sink_set_fixed_latency(u->sink,
1913 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1914 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1917 if (u->profile == PROFILE_HSP) {
1918 u->sink->set_volume = sink_set_volume_cb;
1919 u->sink->n_volume_steps = 16;
1925 /* Run from main thread */
1926 static int add_source(struct userdata *u) {
1929 if (USE_SCO_OVER_PCM(u)) {
1930 u->source = u->hsp.sco_source;
1931 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1933 if (!u->hsp.source_state_changed_slot)
1934 u->hsp.source_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
1940 pa_source_new_data data;
1943 pa_source_new_data_init(&data);
1944 data.driver = __FILE__;
1945 data.module = u->module;
1946 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1947 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
1948 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
1949 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1950 data.card = u->card;
1951 data.name = get_name("source", u->modargs, u->address, &b);
1952 data.namereg_fail = b;
1954 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1955 pa_log("Invalid properties");
1956 pa_source_new_data_done(&data);
1960 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1961 pa_source_new_data_done(&data);
1964 pa_log_error("Failed to create source");
1968 u->source->userdata = u;
1969 u->source->parent.process_msg = source_process_msg;
1971 pa_source_set_fixed_latency(u->source,
1972 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
1973 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1976 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1977 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1979 if (u->profile == PROFILE_HSP) {
1980 u->source->set_volume = source_set_volume_cb;
1981 u->source->n_volume_steps = 16;
1987 /* Run from main thread */
1988 static void shutdown_bt(struct userdata *u) {
1991 if (u->stream_fd >= 0) {
1992 pa_close(u->stream_fd);
1995 u->stream_write_type = 0;
1998 if (u->service_fd >= 0) {
1999 pa_close(u->service_fd);
2001 u->service_write_type = 0;
2002 u->service_read_type = 0;
2005 if (u->write_memchunk.memblock) {
2006 pa_memblock_unref(u->write_memchunk.memblock);
2007 pa_memchunk_reset(&u->write_memchunk);
2011 static int bt_transport_config_a2dp(struct userdata *u)
2013 const pa_bluetooth_transport *t;
2014 struct a2dp_info *a2dp = &u->a2dp;
2015 sbc_capabilities_raw_t *config;
2017 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2020 config = (sbc_capabilities_raw_t *) t->config;
2022 if (a2dp->sbc_initialized)
2023 sbc_reinit(&a2dp->sbc, 0);
2025 sbc_init(&a2dp->sbc, 0);
2026 a2dp->sbc_initialized = TRUE;
2028 switch (config->frequency) {
2029 case BT_SBC_SAMPLING_FREQ_16000:
2030 a2dp->sbc.frequency = SBC_FREQ_16000;
2032 case BT_SBC_SAMPLING_FREQ_32000:
2033 a2dp->sbc.frequency = SBC_FREQ_32000;
2035 case BT_SBC_SAMPLING_FREQ_44100:
2036 a2dp->sbc.frequency = SBC_FREQ_44100;
2038 case BT_SBC_SAMPLING_FREQ_48000:
2039 a2dp->sbc.frequency = SBC_FREQ_48000;
2042 pa_assert_not_reached();
2045 switch (config->channel_mode) {
2046 case BT_A2DP_CHANNEL_MODE_MONO:
2047 a2dp->sbc.mode = SBC_MODE_MONO;
2049 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2050 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2052 case BT_A2DP_CHANNEL_MODE_STEREO:
2053 a2dp->sbc.mode = SBC_MODE_STEREO;
2055 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2056 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2059 pa_assert_not_reached();
2062 switch (config->allocation_method) {
2063 case BT_A2DP_ALLOCATION_SNR:
2064 a2dp->sbc.allocation = SBC_AM_SNR;
2066 case BT_A2DP_ALLOCATION_LOUDNESS:
2067 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2070 pa_assert_not_reached();
2073 switch (config->subbands) {
2074 case BT_A2DP_SUBBANDS_4:
2075 a2dp->sbc.subbands = SBC_SB_4;
2077 case BT_A2DP_SUBBANDS_8:
2078 a2dp->sbc.subbands = SBC_SB_8;
2081 pa_assert_not_reached();
2084 switch (config->block_length) {
2085 case BT_A2DP_BLOCK_LENGTH_4:
2086 a2dp->sbc.blocks = SBC_BLK_4;
2088 case BT_A2DP_BLOCK_LENGTH_8:
2089 a2dp->sbc.blocks = SBC_BLK_8;
2091 case BT_A2DP_BLOCK_LENGTH_12:
2092 a2dp->sbc.blocks = SBC_BLK_12;
2094 case BT_A2DP_BLOCK_LENGTH_16:
2095 a2dp->sbc.blocks = SBC_BLK_16;
2098 pa_assert_not_reached();
2101 a2dp->sbc.bitpool = config->max_bitpool;
2102 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2103 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2106 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2107 / a2dp->frame_length
2110 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2111 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2116 static int bt_transport_config(struct userdata *u)
2118 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2119 u->block_size = u->link_mtu;
2123 return bt_transport_config_a2dp(u);
2126 static int parse_transport_property(struct userdata *u, DBusMessageIter *i)
2129 DBusMessageIter variant_i;
2134 if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_STRING) {
2135 pa_log("Property name not a string.");
2139 dbus_message_iter_get_basic(i, &key);
2141 if (!dbus_message_iter_next(i)) {
2142 pa_log("Property value missing");
2146 if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_VARIANT) {
2147 pa_log("Property value not a variant.");
2151 dbus_message_iter_recurse(i, &variant_i);
2153 switch (dbus_message_iter_get_arg_type(&variant_i)) {
2155 case DBUS_TYPE_UINT16: {
2158 dbus_message_iter_get_basic(&variant_i, &value);
2160 if (pa_streq(key, "OMTU"))
2161 u->link_mtu = value;
2171 /* Run from main thread */
2172 static int bt_transport_open(struct userdata *u)
2175 DBusMessageIter arg_i, element_i;
2178 if (bt_transport_acquire(u, FALSE) < 0)
2181 dbus_error_init(&err);
2183 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->transport, "org.bluez.MediaTransport", "GetProperties"));
2184 r = dbus_connection_send_with_reply_and_block(pa_dbus_connection_get(u->connection), m, -1, &err);
2186 if (dbus_error_is_set(&err) || !r) {
2187 pa_log("Failed to get transport properties: %s", err.message);
2191 if (!dbus_message_iter_init(r, &arg_i)) {
2192 pa_log("GetProperties reply has no arguments.");
2196 if (dbus_message_iter_get_arg_type(&arg_i) != DBUS_TYPE_ARRAY) {
2197 pa_log("GetProperties argument is not an array.");
2201 dbus_message_iter_recurse(&arg_i, &element_i);
2202 while (dbus_message_iter_get_arg_type(&element_i) != DBUS_TYPE_INVALID) {
2204 if (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
2205 DBusMessageIter dict_i;
2207 dbus_message_iter_recurse(&element_i, &dict_i);
2209 parse_transport_property(u, &dict_i);
2212 if (!dbus_message_iter_next(&element_i))
2216 return bt_transport_config(u);
2219 dbus_message_unref(r);
2223 /* Run from main thread */
2224 static int init_bt(struct userdata *u) {
2229 u->stream_write_type = 0;
2230 u->service_write_type = 0;
2231 u->service_read_type = 0;
2233 if ((u->service_fd = bt_audio_service_open()) < 0) {
2234 pa_log_warn("Bluetooth audio service not available");
2238 pa_log_debug("Connected to the bluetooth audio service");
2243 /* Run from main thread */
2244 static int setup_bt(struct userdata *u) {
2245 const pa_bluetooth_device *d;
2246 const pa_bluetooth_transport *t;
2250 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2251 pa_log_error("Failed to get device object.");
2255 /* release transport if exist */
2257 bt_transport_release(u);
2258 pa_xfree(u->transport);
2259 u->transport = NULL;
2262 /* check if profile has a transport */
2263 t = pa_bluetooth_device_get_transport(d, u->profile);
2265 u->transport = pa_xstrdup(t->path);
2266 return bt_transport_open(u);
2269 if (get_caps(u, 0) < 0)
2272 pa_log_debug("Got device capabilities");
2274 if (set_conf(u) < 0)
2277 pa_log_debug("Connection to the device configured");
2280 if (USE_SCO_OVER_PCM(u)) {
2281 pa_log_debug("Configured to use SCO over PCM");
2286 pa_log_debug("Got the stream socket");
2291 /* Run from main thread */
2292 static int init_profile(struct userdata *u) {
2295 pa_assert(u->profile != PROFILE_OFF);
2297 if (setup_bt(u) < 0)
2300 if (u->profile == PROFILE_A2DP ||
2301 u->profile == PROFILE_HSP ||
2302 u->profile == PROFILE_HFGW)
2303 if (add_sink(u) < 0)
2306 if (u->profile == PROFILE_HSP ||
2307 u->profile == PROFILE_A2DP_SOURCE ||
2308 u->profile == PROFILE_HFGW)
2309 if (add_source(u) < 0)
2315 /* Run from main thread */
2316 static void stop_thread(struct userdata *u) {
2320 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2321 pa_thread_free(u->thread);
2325 if (u->rtpoll_item) {
2326 pa_rtpoll_item_free(u->rtpoll_item);
2327 u->rtpoll_item = NULL;
2330 if (u->hsp.sink_state_changed_slot) {
2331 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2332 u->hsp.sink_state_changed_slot = NULL;
2335 if (u->hsp.source_state_changed_slot) {
2336 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2337 u->hsp.source_state_changed_slot = NULL;
2341 pa_sink_unref(u->sink);
2346 pa_source_unref(u->source);
2351 pa_thread_mq_done(&u->thread_mq);
2353 pa_rtpoll_free(u->rtpoll);
2357 if (u->read_smoother) {
2358 pa_smoother_free(u->read_smoother);
2359 u->read_smoother = NULL;
2363 /* Run from main thread */
2364 static int start_thread(struct userdata *u) {
2366 pa_assert(!u->thread);
2367 pa_assert(!u->rtpoll);
2368 pa_assert(!u->rtpoll_item);
2370 u->rtpoll = pa_rtpoll_new();
2371 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2374 if (USE_SCO_OVER_PCM(u)) {
2376 if (bt_transport_acquire(u, TRUE) < 0)
2378 } else if (start_stream_fd(u) < 0)
2381 pa_sink_ref(u->sink);
2382 pa_source_ref(u->source);
2383 /* FIXME: monitor stream_fd error */
2388 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2389 pa_log_error("Failed to create IO thread");
2395 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2396 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2397 pa_sink_put(u->sink);
2399 if (u->sink->set_volume)
2400 u->sink->set_volume(u->sink);
2404 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2405 pa_source_set_rtpoll(u->source, u->rtpoll);
2406 pa_source_put(u->source);
2408 if (u->source->set_volume)
2409 u->source->set_volume(u->source);
2415 /* Run from main thread */
2416 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2419 pa_queue *inputs = NULL, *outputs = NULL;
2420 const pa_bluetooth_device *device;
2423 pa_assert(new_profile);
2424 pa_assert_se(u = c->userdata);
2426 d = PA_CARD_PROFILE_DATA(new_profile);
2428 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2429 pa_log_error("Failed to get device object.");
2433 /* The state signal is sent by bluez, so it is racy to check
2434 strictly for CONNECTED, we should also accept STREAMING state
2435 as being good enough. However, if the profile is used
2436 concurrently (which is unlikely), ipc will fail later on, and
2437 module will be unloaded. */
2438 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2439 pa_log_warn("HSP is not connected, refused to switch profile");
2442 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2443 pa_log_warn("A2DP is not connected, refused to switch profile");
2446 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2447 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2452 inputs = pa_sink_move_all_start(u->sink, NULL);
2454 if (!USE_SCO_OVER_PCM(u))
2456 pa_sink_unlink(u->sink);
2460 outputs = pa_source_move_all_start(u->source, NULL);
2462 if (!USE_SCO_OVER_PCM(u))
2464 pa_source_unlink(u->source);
2471 u->sample_spec = u->requested_sample_spec;
2475 if (u->profile != PROFILE_OFF)
2478 if (u->sink || u->source)
2483 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2485 pa_sink_move_all_fail(inputs);
2490 pa_source_move_all_finish(u->source, outputs, FALSE);
2492 pa_source_move_all_fail(outputs);
2498 /* Run from main thread */
2499 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2500 pa_card_new_data data;
2506 const char *default_profile;
2511 pa_card_new_data_init(&data);
2512 data.driver = __FILE__;
2513 data.module = u->module;
2515 n = pa_bluetooth_cleanup_name(device->name);
2516 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2518 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2519 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2520 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2521 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2522 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2523 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2524 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2525 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2526 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2527 data.name = get_name("card", u->modargs, device->address, &b);
2528 data.namereg_fail = b;
2530 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2531 pa_log("Invalid properties");
2532 pa_card_new_data_done(&data);
2536 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2538 /* we base hsp/a2dp availability on UUIDs.
2539 Ideally, it would be based on "Connected" state, but
2540 we can't afford to wait for this information when
2541 we are loaded with profile="hsp", for instance */
2542 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2543 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2547 p->max_sink_channels = 2;
2548 p->max_source_channels = 0;
2550 d = PA_CARD_PROFILE_DATA(p);
2553 pa_hashmap_put(data.profiles, p->name, p);
2556 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2557 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2561 p->max_sink_channels = 0;
2562 p->max_source_channels = 2;
2564 d = PA_CARD_PROFILE_DATA(p);
2565 *d = PROFILE_A2DP_SOURCE;
2567 pa_hashmap_put(data.profiles, p->name, p);
2570 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2571 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2572 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2576 p->max_sink_channels = 1;
2577 p->max_source_channels = 1;
2579 d = PA_CARD_PROFILE_DATA(p);
2582 pa_hashmap_put(data.profiles, p->name, p);
2585 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2586 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2590 p->max_sink_channels = 1;
2591 p->max_source_channels = 1;
2593 d = PA_CARD_PROFILE_DATA(p);
2596 pa_hashmap_put(data.profiles, p->name, p);
2599 pa_assert(!pa_hashmap_isempty(data.profiles));
2601 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2602 d = PA_CARD_PROFILE_DATA(p);
2604 pa_hashmap_put(data.profiles, p->name, p);
2606 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2607 if (pa_hashmap_get(data.profiles, default_profile))
2608 pa_card_new_data_set_profile(&data, default_profile);
2610 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2613 u->card = pa_card_new(u->core, &data);
2614 pa_card_new_data_done(&data);
2617 pa_log("Failed to allocate card.");
2621 u->card->userdata = u;
2622 u->card->set_profile = card_set_profile;
2624 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2626 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2627 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2628 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2629 pa_log_warn("Default profile not connected, selecting off profile");
2630 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2631 u->card->save_profile = FALSE;
2634 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2640 /* Run from main thread */
2641 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2642 const pa_bluetooth_device *d = NULL;
2646 if (!address && !path) {
2647 pa_log_error("Failed to get device address/path from module arguments.");
2652 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2653 pa_log_error("%s is not a valid BlueZ audio device.", path);
2657 if (address && !(pa_streq(d->address, address))) {
2658 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2663 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2664 pa_log_error("%s is not known.", address);
2670 u->address = pa_xstrdup(d->address);
2671 u->path = pa_xstrdup(d->path);
2677 /* Run from main thread */
2678 static int setup_dbus(struct userdata *u) {
2681 dbus_error_init(&err);
2683 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2685 if (dbus_error_is_set(&err) || !u->connection) {
2686 pa_log("Failed to get D-Bus connection: %s", err.message);
2687 dbus_error_free(&err);
2694 int pa__init(pa_module* m) {
2698 const char *address, *path;
2700 char *mike, *speaker;
2701 const pa_bluetooth_device *device;
2705 dbus_error_init(&err);
2707 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2708 pa_log_error("Failed to parse module arguments");
2712 m->userdata = u = pa_xnew0(struct userdata, 1);
2717 u->sample_spec = m->core->default_sample_spec;
2721 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2722 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2723 pa_log("SCO sink not found");
2727 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2728 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2729 pa_log("SCO source not found");
2734 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2735 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2736 pa_log_error("Failed to get rate from module arguments");
2740 u->auto_connect = TRUE;
2741 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2742 pa_log("Failed to parse auto_connect= argument");
2746 channels = u->sample_spec.channels;
2747 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2748 channels <= 0 || channels > PA_CHANNELS_MAX) {
2749 pa_log_error("Failed to get channels from module arguments");
2752 u->sample_spec.channels = (uint8_t) channels;
2753 u->requested_sample_spec = u->sample_spec;
2755 address = pa_modargs_get_value(ma, "address", NULL);
2756 path = pa_modargs_get_value(ma, "path", NULL);
2758 if (setup_dbus(u) < 0)
2761 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2764 if (!(device = find_device(u, address, path)))
2767 /* Add the card structure. This will also initialize the default profile */
2768 if (add_card(u, device) < 0)
2771 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2772 pa_log_error("Failed to add filter function");
2775 u->filter_added = TRUE;
2777 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2778 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2780 if (pa_dbus_add_matches(
2781 pa_dbus_connection_get(u->connection), &err,
2789 pa_log("Failed to add D-Bus matches: %s", err.message);
2796 /* Connect to the BT service */
2799 if (u->profile != PROFILE_OFF)
2800 if (init_profile(u) < 0)
2803 if (u->sink || u->source)
2804 if (start_thread(u) < 0)
2813 dbus_error_free(&err);
2818 int pa__get_n_used(pa_module *m) {
2822 pa_assert_se(u = m->userdata);
2825 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2826 (u->source ? pa_source_linked_by(u->source) : 0);
2829 void pa__done(pa_module *m) {
2833 if (!(u = m->userdata))
2838 && !USE_SCO_OVER_PCM(u)
2841 pa_sink_unlink(u->sink);
2845 && !USE_SCO_OVER_PCM(u)
2848 pa_source_unlink(u->source);
2852 if (u->connection) {
2855 char *speaker, *mike;
2856 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2857 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2859 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2868 if (u->filter_added)
2869 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2871 pa_dbus_connection_unref(u->connection);
2875 pa_card_free(u->card);
2877 if (u->read_smoother)
2878 pa_smoother_free(u->read_smoother);
2883 pa_xfree(u->a2dp.buffer);
2885 sbc_finish(&u->a2dp.sbc);
2888 pa_modargs_free(u->modargs);
2890 pa_xfree(u->address);
2894 bt_transport_release(u);
2895 pa_xfree(u->transport);
2899 pa_bluetooth_discovery_unref(u->discovery);