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>
52 #include "module-bluetooth-device-symdef.h"
56 #include "bluetooth-util.h"
58 #define MAX_BITPOOL 64
59 #define MIN_BITPOOL 2U
61 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION);
64 PA_MODULE_LOAD_ONCE(FALSE);
66 "name=<name for the card/sink/source, to be prefixed> "
67 "card_name=<name for the card> "
68 "card_properties=<properties for the card> "
69 "sink_name=<name for the sink> "
70 "sink_properties=<properties for the sink> "
71 "source_name=<name for the source> "
72 "source_properties=<properties for the source> "
73 "address=<address of the device> "
74 "profile=<a2dp|hsp|hfgw> "
76 "channels=<number of channels> "
77 "path=<device object path> "
78 "auto_connect=<automatically connect?>");
82 "sco_sink=<SCO over PCM sink name> "
83 "sco_source=<SCO over PCM source name>"
87 /* TODO: not close fd when entering suspend mode in a2dp */
89 static const char* const valid_modargs[] = {
111 sbc_capabilities_t sbc_capabilities;
112 sbc_t sbc; /* Codec data */
113 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
114 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
116 void* buffer; /* Codec transfer buffer */
117 size_t buffer_size; /* Size of the buffer */
119 uint16_t seq_num; /* Cumulative packet sequence */
123 pcm_capabilities_t pcm_capabilities;
126 pa_source *sco_source;
128 pa_hook_slot *sink_state_changed_slot;
129 pa_hook_slot *source_state_changed_slot;
146 pa_bluetooth_discovery *discovery;
147 pa_bool_t auto_connect;
149 pa_dbus_connection *connection;
155 pa_thread_mq thread_mq;
157 pa_rtpoll_item *rtpoll_item;
160 uint64_t read_index, write_index;
161 pa_usec_t started_at;
162 pa_smoother *read_smoother;
164 pa_memchunk write_memchunk;
166 pa_sample_spec sample_spec, requested_sample_spec;
174 struct a2dp_info a2dp;
177 enum profile profile;
181 int stream_write_type;
182 int service_write_type, service_read_type;
184 pa_bool_t filter_added;
187 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
188 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
189 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
190 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
192 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
195 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
198 static int init_bt(struct userdata *u);
199 static int init_profile(struct userdata *u);
201 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
205 pa_assert(u->service_fd >= 0);
207 pa_assert(msg->length > 0);
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 */
748 static int start_stream_fd(struct userdata *u) {
750 bt_audio_msg_header_t rsp;
751 struct bt_start_stream_req start_req;
752 struct bt_start_stream_rsp start_rsp;
753 struct bt_new_stream_ind streamfd_ind;
754 bt_audio_error_t error;
755 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
757 struct pollfd *pollfd;
761 pa_assert(u->rtpoll);
762 pa_assert(!u->rtpoll_item);
763 pa_assert(u->stream_fd < 0);
765 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
766 msg.start_req.h.type = BT_REQUEST;
767 msg.start_req.h.name = BT_START_STREAM;
768 msg.start_req.h.length = sizeof(msg.start_req);
770 if (service_send(u, &msg.start_req.h) < 0)
773 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
776 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
779 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
780 pa_log("Failed to get stream fd from audio service.");
784 pa_make_fd_nonblock(u->stream_fd);
785 pa_make_socket_low_delay(u->stream_fd);
788 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
789 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
791 pa_log_debug("Stream properly set up, we're ready to roll!");
793 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
794 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
795 pollfd->fd = u->stream_fd;
796 pollfd->events = pollfd->revents = 0;
798 u->read_index = u->write_index = 0;
802 u->read_smoother = pa_smoother_new(
815 static int stop_stream_fd(struct userdata *u) {
817 bt_audio_msg_header_t rsp;
818 struct bt_stop_stream_req start_req;
819 struct bt_stop_stream_rsp start_rsp;
820 bt_audio_error_t error;
821 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
826 pa_assert(u->rtpoll);
828 if (u->rtpoll_item) {
829 pa_rtpoll_item_free(u->rtpoll_item);
830 u->rtpoll_item = NULL;
833 if (u->stream_fd >= 0) {
834 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
835 msg.start_req.h.type = BT_REQUEST;
836 msg.start_req.h.name = BT_STOP_STREAM;
837 msg.start_req.h.length = sizeof(msg.start_req);
839 if (service_send(u, &msg.start_req.h) < 0 ||
840 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
843 pa_close(u->stream_fd);
847 if (u->read_smoother) {
848 pa_smoother_free(u->read_smoother);
849 u->read_smoother = NULL;
855 /* Run from IO thread */
856 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
857 struct userdata *u = PA_SINK(o)->userdata;
858 pa_bool_t failed = FALSE;
861 pa_assert(u->sink == PA_SINK(o));
865 case PA_SINK_MESSAGE_SET_STATE:
867 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
869 case PA_SINK_SUSPENDED:
870 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
872 /* Stop the device if the source is suspended as well */
873 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
874 /* We deliberately ignore whether stopping
875 * actually worked. Since the stream_fd is
876 * closed it doesn't really matter */
882 case PA_SINK_RUNNING:
883 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
886 /* Resume the device if the source was suspended as well */
887 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
888 if (start_stream_fd(u) < 0)
892 case PA_SINK_UNLINKED:
894 case PA_SINK_INVALID_STATE:
899 case PA_SINK_MESSAGE_GET_LATENCY: {
901 if (u->read_smoother) {
904 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
905 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
907 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
911 ri = pa_rtclock_now() - u->started_at;
912 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
914 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
917 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
922 r = pa_sink_process_msg(o, code, data, offset, chunk);
924 return (r < 0 || !failed) ? r : -1;
927 /* Run from IO thread */
928 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
929 struct userdata *u = PA_SOURCE(o)->userdata;
930 pa_bool_t failed = FALSE;
933 pa_assert(u->source == PA_SOURCE(o));
937 case PA_SOURCE_MESSAGE_SET_STATE:
939 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
941 case PA_SOURCE_SUSPENDED:
942 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
944 /* Stop the device if the sink is suspended as well */
945 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
948 if (u->read_smoother)
949 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
953 case PA_SOURCE_RUNNING:
954 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
957 /* Resume the device if the sink was suspended as well */
958 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
959 if (start_stream_fd(u) < 0)
962 /* We don't resume the smoother here. Instead we
963 * wait until the first packet arrives */
966 case PA_SOURCE_UNLINKED:
968 case PA_SOURCE_INVALID_STATE:
973 case PA_SOURCE_MESSAGE_GET_LATENCY: {
976 if (u->read_smoother) {
977 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
978 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
980 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
982 *((pa_usec_t*) data) = 0;
989 r = pa_source_process_msg(o, code, data, offset, chunk);
991 return (r < 0 || !failed) ? r : -1;
994 /* Run from IO thread */
995 static int hsp_process_render(struct userdata *u) {
999 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1002 /* First, render some data */
1003 if (!u->write_memchunk.memblock)
1004 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1006 pa_assert(u->write_memchunk.length == u->block_size);
1012 /* Now write that data to the socket. The socket is of type
1013 * SEQPACKET, and we generated the data of the MTU size, so this
1014 * should just work. */
1016 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1017 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1018 pa_memblock_release(u->write_memchunk.memblock);
1025 /* Retry right away if we got interrupted */
1028 else if (errno == EAGAIN)
1029 /* Hmm, apparently the socket was not writable, give up for now */
1032 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1037 pa_assert((size_t) l <= u->write_memchunk.length);
1039 if ((size_t) l != u->write_memchunk.length) {
1040 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1041 (unsigned long long) l,
1042 (unsigned long long) u->write_memchunk.length);
1047 u->write_index += (uint64_t) u->write_memchunk.length;
1048 pa_memblock_unref(u->write_memchunk.memblock);
1049 pa_memchunk_reset(&u->write_memchunk);
1058 /* Run from IO thread */
1059 static int hsp_process_push(struct userdata *u) {
1061 pa_memchunk memchunk;
1064 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1065 pa_assert(u->source);
1066 pa_assert(u->read_smoother);
1068 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1069 memchunk.index = memchunk.length = 0;
1078 pa_bool_t found_tstamp = FALSE;
1081 memset(&m, 0, sizeof(m));
1082 memset(&aux, 0, sizeof(aux));
1083 memset(&iov, 0, sizeof(iov));
1087 m.msg_control = aux;
1088 m.msg_controllen = sizeof(aux);
1090 p = pa_memblock_acquire(memchunk.memblock);
1092 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1093 l = recvmsg(u->stream_fd, &m, 0);
1094 pa_memblock_release(memchunk.memblock);
1098 if (l < 0 && errno == EINTR)
1099 /* Retry right away if we got interrupted */
1102 else if (l < 0 && errno == EAGAIN)
1103 /* Hmm, apparently the socket was not readable, give up for now. */
1106 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1111 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1113 memchunk.length = (size_t) l;
1114 u->read_index += (uint64_t) l;
1116 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1117 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1118 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1119 pa_rtclock_from_wallclock(tv);
1120 tstamp = pa_timeval_load(tv);
1121 found_tstamp = TRUE;
1125 if (!found_tstamp) {
1126 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1127 tstamp = pa_rtclock_now();
1130 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1131 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1133 pa_source_post(u->source, &memchunk);
1139 pa_memblock_unref(memchunk.memblock);
1144 /* Run from IO thread */
1145 static void a2dp_prepare_buffer(struct userdata *u) {
1148 if (u->a2dp.buffer_size >= u->link_mtu)
1151 u->a2dp.buffer_size = 2 * u->link_mtu;
1152 pa_xfree(u->a2dp.buffer);
1153 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1156 /* Run from IO thread */
1157 static int a2dp_process_render(struct userdata *u) {
1158 struct a2dp_info *a2dp;
1159 struct rtp_header *header;
1160 struct rtp_payload *payload;
1164 size_t to_write, to_encode;
1165 unsigned frame_count;
1169 pa_assert(u->profile == PROFILE_A2DP);
1172 /* First, render some data */
1173 if (!u->write_memchunk.memblock)
1174 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1176 pa_assert(u->write_memchunk.length == u->block_size);
1178 a2dp_prepare_buffer(u);
1181 header = a2dp->buffer;
1182 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1186 /* Try to create a packet of the full MTU */
1188 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1189 to_encode = u->write_memchunk.length;
1191 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1192 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1194 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1198 encoded = sbc_encode(&a2dp->sbc,
1203 if (PA_UNLIKELY(encoded <= 0)) {
1204 pa_log_error("SBC encoding error (%li)", (long) encoded);
1205 pa_memblock_release(u->write_memchunk.memblock);
1209 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1210 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1212 pa_assert_fp((size_t) encoded <= to_encode);
1213 pa_assert_fp((size_t) encoded == a2dp->codesize);
1215 pa_assert_fp((size_t) written <= to_write);
1216 pa_assert_fp((size_t) written == a2dp->frame_length);
1218 p = (const uint8_t*) p + encoded;
1219 to_encode -= encoded;
1221 d = (uint8_t*) d + written;
1222 to_write -= written;
1227 pa_memblock_release(u->write_memchunk.memblock);
1229 pa_assert(to_encode == 0);
1232 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1235 /* write it to the fifo */
1236 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1239 header->sequence_number = htons(a2dp->seq_num++);
1240 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1241 header->ssrc = htonl(1);
1242 payload->frame_count = frame_count;
1244 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1249 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1256 /* Retry right away if we got interrupted */
1259 else if (errno == EAGAIN)
1260 /* Hmm, apparently the socket was not writable, give up for now */
1263 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1268 pa_assert((size_t) l <= nbytes);
1270 if ((size_t) l != nbytes) {
1271 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1272 (unsigned long long) l,
1273 (unsigned long long) nbytes);
1278 u->write_index += (uint64_t) u->write_memchunk.length;
1279 pa_memblock_unref(u->write_memchunk.memblock);
1280 pa_memchunk_reset(&u->write_memchunk);
1290 static int a2dp_process_push(struct userdata *u) {
1292 pa_memchunk memchunk;
1295 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1296 pa_assert(u->source);
1297 pa_assert(u->read_smoother);
1299 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1300 memchunk.index = memchunk.length = 0;
1303 pa_bool_t found_tstamp = FALSE;
1305 struct a2dp_info *a2dp;
1306 struct rtp_header *header;
1307 struct rtp_payload *payload;
1311 size_t to_write, to_decode;
1312 unsigned frame_count;
1314 a2dp_prepare_buffer(u);
1317 header = a2dp->buffer;
1318 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1320 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1324 if (l < 0 && errno == EINTR)
1325 /* Retry right away if we got interrupted */
1328 else if (l < 0 && errno == EAGAIN)
1329 /* Hmm, apparently the socket was not readable, give up for now. */
1332 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1337 pa_assert((size_t) l <= a2dp->buffer_size);
1339 u->read_index += (uint64_t) l;
1341 /* TODO: get timestamp from rtp */
1342 if (!found_tstamp) {
1343 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1344 tstamp = pa_rtclock_now();
1347 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1348 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1350 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1351 to_decode = l - sizeof(*header) - sizeof(*payload);
1353 d = pa_memblock_acquire(memchunk.memblock);
1354 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1356 while (PA_LIKELY(to_decode > 0 && to_write > 0)) {
1360 decoded = sbc_decode(&a2dp->sbc,
1365 if (PA_UNLIKELY(decoded <= 0)) {
1366 pa_log_error("SBC decoding error (%li)", (long) decoded);
1367 pa_memblock_release(memchunk.memblock);
1368 pa_memblock_unref(memchunk.memblock);
1372 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1373 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1375 pa_assert_fp((size_t) decoded <= to_decode);
1376 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1378 pa_assert_fp((size_t) written <= to_write);
1379 pa_assert_fp((size_t) written == a2dp->codesize);
1381 p = (const uint8_t*) p + decoded;
1382 to_decode -= decoded;
1384 d = (uint8_t*) d + written;
1385 to_write -= written;
1390 pa_memblock_release(memchunk.memblock);
1392 pa_source_post(u->source, &memchunk);
1398 pa_memblock_unref(memchunk.memblock);
1403 static void thread_func(void *userdata) {
1404 struct userdata *u = userdata;
1405 unsigned do_write = 0;
1406 pa_bool_t writable = FALSE;
1410 pa_log_debug("IO Thread starting up");
1412 if (u->core->realtime_scheduling)
1413 pa_make_realtime(u->core->realtime_priority);
1415 pa_thread_mq_install(&u->thread_mq);
1417 if (start_stream_fd(u) < 0)
1421 struct pollfd *pollfd;
1423 pa_bool_t disable_timer = TRUE;
1425 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1427 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1429 /* We should send two blocks to the device before we expect
1432 if (u->write_index == 0 && u->read_index <= 0)
1435 if (pollfd && (pollfd->revents & POLLIN)) {
1438 if (u->profile == PROFILE_HSP || PROFILE_HFGW)
1439 n_read = hsp_process_push(u);
1441 n_read = a2dp_process_push(u);
1446 /* We just read something, so we are supposed to write something, too */
1451 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1453 if (u->sink->thread_info.rewind_requested)
1454 pa_sink_process_rewind(u->sink, 0);
1457 if (pollfd->revents & POLLOUT)
1460 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1461 pa_usec_t time_passed;
1462 pa_usec_t audio_sent;
1464 /* Hmm, there is no input stream we could synchronize
1465 * to. So let's do things by time */
1467 time_passed = pa_rtclock_now() - u->started_at;
1468 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1470 if (audio_sent <= time_passed) {
1471 pa_usec_t audio_to_send = time_passed - audio_sent;
1473 /* Never try to catch up for more than 100ms */
1474 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1475 pa_usec_t skip_usec;
1476 uint64_t skip_bytes;
1478 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1479 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1481 if (skip_bytes > 0) {
1484 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1485 (unsigned long long) skip_usec,
1486 (unsigned long long) skip_bytes);
1488 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1489 pa_memblock_unref(tmp.memblock);
1490 u->write_index += skip_bytes;
1498 if (writable && do_write > 0) {
1501 if (u->write_index <= 0)
1502 u->started_at = pa_rtclock_now();
1504 if (u->profile == PROFILE_A2DP) {
1505 if ((n_written = a2dp_process_render(u)) < 0)
1508 if ((n_written = hsp_process_render(u)) < 0)
1513 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1515 do_write -= n_written;
1519 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1520 pa_usec_t time_passed, next_write_at, sleep_for;
1522 /* Hmm, there is no input stream we could synchronize
1523 * to. So let's estimate when we need to wake up the latest */
1525 time_passed = pa_rtclock_now() - u->started_at;
1526 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1527 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1529 /* 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); */
1531 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1532 disable_timer = FALSE;
1538 pa_rtpoll_set_timer_disabled(u->rtpoll);
1540 /* Hmm, nothing to do. Let's sleep */
1542 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1543 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1545 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1551 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1553 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1554 pa_log_info("FD error: %s%s%s%s",
1555 pollfd->revents & POLLERR ? "POLLERR " :"",
1556 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1557 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1558 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1564 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1565 pa_log_debug("IO thread failed");
1566 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1567 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1570 pa_log_debug("IO thread shutting down");
1573 /* Run from main thread */
1574 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1580 pa_assert_se(u = userdata);
1582 dbus_error_init(&err);
1584 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1585 dbus_message_get_interface(m),
1586 dbus_message_get_path(m),
1587 dbus_message_get_member(m));
1589 if (!dbus_message_has_path(m, u->path))
1592 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1593 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1598 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1599 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1603 if (u->profile == PROFILE_HSP) {
1604 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1606 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1607 pa_sink_volume_changed(u->sink, &v);
1609 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1611 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1612 pa_source_volume_changed(u->source, &v);
1618 dbus_error_free(&err);
1620 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1623 /* Run from main thread */
1624 static void sink_set_volume_cb(pa_sink *s) {
1625 struct userdata *u = s->userdata;
1631 if (u->profile != PROFILE_HSP)
1634 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1639 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1641 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1642 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1643 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1644 dbus_message_unref(m);
1647 /* Run from main thread */
1648 static void source_set_volume_cb(pa_source *s) {
1649 struct userdata *u = s->userdata;
1655 if (u->profile != PROFILE_HSP)
1658 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1663 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1665 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1666 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1667 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1668 dbus_message_unref(m);
1671 /* Run from main thread */
1672 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1678 pa_assert(device_id);
1679 pa_assert(namereg_fail);
1681 t = pa_sprintf_malloc("%s_name", type);
1682 n = pa_modargs_get_value(ma, t, NULL);
1686 *namereg_fail = TRUE;
1687 return pa_xstrdup(n);
1690 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1691 *namereg_fail = TRUE;
1694 *namereg_fail = FALSE;
1697 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1702 static void sco_over_pcm_state_update(struct userdata *u) {
1704 pa_assert(USE_SCO_OVER_PCM(u));
1706 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1707 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1709 if (u->service_fd >= 0)
1712 pa_log_debug("Resuming SCO over PCM");
1713 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1714 pa_log("Can't resume SCO over PCM");
1719 if (u->service_fd < 0)
1724 pa_log_debug("Closing SCO over PCM");
1725 pa_close(u->service_fd);
1730 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1732 pa_sink_assert_ref(s);
1735 if (s != u->hsp.sco_sink)
1738 sco_over_pcm_state_update(u);
1743 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1745 pa_source_assert_ref(s);
1748 if (s != u->hsp.sco_source)
1751 sco_over_pcm_state_update(u);
1758 /* Run from main thread */
1759 static int add_sink(struct userdata *u) {
1762 if (USE_SCO_OVER_PCM(u)) {
1765 u->sink = u->hsp.sco_sink;
1766 p = pa_proplist_new();
1767 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1768 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1769 pa_proplist_free(p);
1771 if (!u->hsp.sink_state_changed_slot)
1772 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);
1778 pa_sink_new_data data;
1781 pa_sink_new_data_init(&data);
1782 data.driver = __FILE__;
1783 data.module = u->module;
1784 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1785 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1786 if (u->profile == PROFILE_HSP)
1787 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1788 data.card = u->card;
1789 data.name = get_name("sink", u->modargs, u->address, &b);
1790 data.namereg_fail = b;
1792 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1793 pa_log("Invalid properties");
1794 pa_sink_new_data_done(&data);
1798 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1799 pa_sink_new_data_done(&data);
1802 pa_log_error("Failed to create sink");
1806 u->sink->userdata = u;
1807 u->sink->parent.process_msg = sink_process_msg;
1809 pa_sink_set_max_request(u->sink, u->block_size);
1810 pa_sink_set_fixed_latency(u->sink,
1811 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1812 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1815 if (u->profile == PROFILE_HSP) {
1816 u->sink->set_volume = sink_set_volume_cb;
1817 u->sink->n_volume_steps = 16;
1823 /* Run from main thread */
1824 static int add_source(struct userdata *u) {
1827 if (USE_SCO_OVER_PCM(u)) {
1828 u->source = u->hsp.sco_source;
1829 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1831 if (!u->hsp.source_state_changed_slot)
1832 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);
1838 pa_source_new_data data;
1841 pa_source_new_data_init(&data);
1842 data.driver = __FILE__;
1843 data.module = u->module;
1844 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1845 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
1846 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
1847 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1848 data.card = u->card;
1849 data.name = get_name("source", u->modargs, u->address, &b);
1850 data.namereg_fail = b;
1852 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1853 pa_log("Invalid properties");
1854 pa_source_new_data_done(&data);
1858 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1859 pa_source_new_data_done(&data);
1862 pa_log_error("Failed to create source");
1866 u->source->userdata = u;
1867 u->source->parent.process_msg = source_process_msg;
1869 pa_source_set_fixed_latency(u->source,
1870 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
1871 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1874 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1875 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1877 if (u->profile == PROFILE_HSP) {
1878 u->source->set_volume = source_set_volume_cb;
1879 u->source->n_volume_steps = 16;
1885 /* Run from main thread */
1886 static void shutdown_bt(struct userdata *u) {
1889 if (u->stream_fd >= 0) {
1890 pa_close(u->stream_fd);
1893 u->stream_write_type = 0;
1896 if (u->service_fd >= 0) {
1897 pa_close(u->service_fd);
1899 u->service_write_type = 0;
1900 u->service_read_type = 0;
1903 if (u->write_memchunk.memblock) {
1904 pa_memblock_unref(u->write_memchunk.memblock);
1905 pa_memchunk_reset(&u->write_memchunk);
1909 /* Run from main thread */
1910 static int init_bt(struct userdata *u) {
1915 u->stream_write_type = 0;
1916 u->service_write_type = 0;
1917 u->service_read_type = 0;
1919 if ((u->service_fd = bt_audio_service_open()) < 0) {
1920 pa_log_error("Couldn't connect to bluetooth audio service");
1924 pa_log_debug("Connected to the bluetooth audio service");
1929 /* Run from main thread */
1930 static int setup_bt(struct userdata *u) {
1933 if (get_caps(u, 0) < 0)
1936 pa_log_debug("Got device capabilities");
1938 if (set_conf(u) < 0)
1941 pa_log_debug("Connection to the device configured");
1944 if (USE_SCO_OVER_PCM(u)) {
1945 pa_log_debug("Configured to use SCO over PCM");
1950 pa_log_debug("Got the stream socket");
1955 /* Run from main thread */
1956 static int init_profile(struct userdata *u) {
1959 pa_assert(u->profile != PROFILE_OFF);
1961 if (setup_bt(u) < 0)
1964 if (u->profile == PROFILE_A2DP ||
1965 u->profile == PROFILE_HSP ||
1966 u->profile == PROFILE_HFGW)
1967 if (add_sink(u) < 0)
1970 if (u->profile == PROFILE_HSP ||
1971 u->profile == PROFILE_A2DP_SOURCE ||
1972 u->profile == PROFILE_HFGW)
1973 if (add_source(u) < 0)
1979 /* Run from main thread */
1980 static void stop_thread(struct userdata *u) {
1984 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1985 pa_thread_free(u->thread);
1989 if (u->rtpoll_item) {
1990 pa_rtpoll_item_free(u->rtpoll_item);
1991 u->rtpoll_item = NULL;
1994 if (u->hsp.sink_state_changed_slot) {
1995 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1996 u->hsp.sink_state_changed_slot = NULL;
1999 if (u->hsp.source_state_changed_slot) {
2000 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2001 u->hsp.source_state_changed_slot = NULL;
2005 pa_sink_unref(u->sink);
2010 pa_source_unref(u->source);
2015 pa_thread_mq_done(&u->thread_mq);
2017 pa_rtpoll_free(u->rtpoll);
2021 if (u->read_smoother) {
2022 pa_smoother_free(u->read_smoother);
2023 u->read_smoother = NULL;
2027 /* Run from main thread */
2028 static int start_thread(struct userdata *u) {
2030 pa_assert(!u->thread);
2031 pa_assert(!u->rtpoll);
2032 pa_assert(!u->rtpoll_item);
2034 u->rtpoll = pa_rtpoll_new();
2035 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2038 if (USE_SCO_OVER_PCM(u)) {
2039 if (start_stream_fd(u) < 0)
2042 pa_sink_ref(u->sink);
2043 pa_source_ref(u->source);
2044 /* FIXME: monitor stream_fd error */
2049 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2050 pa_log_error("Failed to create IO thread");
2056 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2057 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2058 pa_sink_put(u->sink);
2060 if (u->sink->set_volume)
2061 u->sink->set_volume(u->sink);
2065 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2066 pa_source_set_rtpoll(u->source, u->rtpoll);
2067 pa_source_put(u->source);
2069 if (u->source->set_volume)
2070 u->source->set_volume(u->source);
2076 /* Run from main thread */
2077 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2080 pa_queue *inputs = NULL, *outputs = NULL;
2081 const pa_bluetooth_device *device;
2084 pa_assert(new_profile);
2085 pa_assert_se(u = c->userdata);
2087 d = PA_CARD_PROFILE_DATA(new_profile);
2089 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2090 pa_log_error("Failed to get device object.");
2094 /* The state signal is sent by bluez, so it is racy to check
2095 strictly for CONNECTED, we should also accept STREAMING state
2096 as being good enough. However, if the profile is used
2097 concurrently (which is unlikely), ipc will fail later on, and
2098 module will be unloaded. */
2099 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2100 pa_log_warn("HSP is not connected, refused to switch profile");
2103 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2104 pa_log_warn("A2DP is not connected, refused to switch profile");
2107 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2108 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2113 inputs = pa_sink_move_all_start(u->sink, NULL);
2115 if (!USE_SCO_OVER_PCM(u))
2117 pa_sink_unlink(u->sink);
2121 outputs = pa_source_move_all_start(u->source, NULL);
2123 if (!USE_SCO_OVER_PCM(u))
2125 pa_source_unlink(u->source);
2132 u->sample_spec = u->requested_sample_spec;
2136 if (u->profile != PROFILE_OFF)
2139 if (u->sink || u->source)
2144 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2146 pa_sink_move_all_fail(inputs);
2151 pa_source_move_all_finish(u->source, outputs, FALSE);
2153 pa_source_move_all_fail(outputs);
2159 /* Run from main thread */
2160 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2161 pa_card_new_data data;
2167 const char *default_profile;
2172 pa_card_new_data_init(&data);
2173 data.driver = __FILE__;
2174 data.module = u->module;
2176 n = pa_bluetooth_cleanup_name(device->name);
2177 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2179 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2180 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2181 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2182 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2183 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2184 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2185 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2186 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2187 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2188 data.name = get_name("card", u->modargs, device->address, &b);
2189 data.namereg_fail = b;
2191 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2192 pa_log("Invalid properties");
2193 pa_card_new_data_done(&data);
2197 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2199 /* we base hsp/a2dp availability on UUIDs.
2200 Ideally, it would be based on "Connected" state, but
2201 we can't afford to wait for this information when
2202 we are loaded with profile="hsp", for instance */
2203 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2204 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2208 p->max_sink_channels = 2;
2209 p->max_source_channels = 0;
2211 d = PA_CARD_PROFILE_DATA(p);
2214 pa_hashmap_put(data.profiles, p->name, p);
2217 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2218 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2222 p->max_sink_channels = 0;
2223 p->max_source_channels = 2;
2225 d = PA_CARD_PROFILE_DATA(p);
2226 *d = PROFILE_A2DP_SOURCE;
2228 pa_hashmap_put(data.profiles, p->name, p);
2231 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2232 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2233 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2237 p->max_sink_channels = 1;
2238 p->max_source_channels = 1;
2240 d = PA_CARD_PROFILE_DATA(p);
2243 pa_hashmap_put(data.profiles, p->name, p);
2246 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2247 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2251 p->max_sink_channels = 1;
2252 p->max_source_channels = 1;
2254 d = PA_CARD_PROFILE_DATA(p);
2257 pa_hashmap_put(data.profiles, p->name, p);
2260 pa_assert(!pa_hashmap_isempty(data.profiles));
2262 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2263 d = PA_CARD_PROFILE_DATA(p);
2265 pa_hashmap_put(data.profiles, p->name, p);
2267 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2268 if (pa_hashmap_get(data.profiles, default_profile))
2269 pa_card_new_data_set_profile(&data, default_profile);
2271 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2274 u->card = pa_card_new(u->core, &data);
2275 pa_card_new_data_done(&data);
2278 pa_log("Failed to allocate card.");
2282 u->card->userdata = u;
2283 u->card->set_profile = card_set_profile;
2285 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2287 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2288 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2289 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2290 pa_log_warn("Default profile not connected, selecting off profile");
2291 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2292 u->card->save_profile = FALSE;
2295 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2301 /* Run from main thread */
2302 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2303 const pa_bluetooth_device *d = NULL;
2307 if (!address && !path) {
2308 pa_log_error("Failed to get device address/path from module arguments.");
2313 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2314 pa_log_error("%s is not a valid BlueZ audio device.", path);
2318 if (address && !(pa_streq(d->address, address))) {
2319 pa_log_error("Passed path %s and address %s don't match.", path, address);
2324 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2325 pa_log_error("%s is not known.", address);
2331 u->address = pa_xstrdup(d->address);
2332 u->path = pa_xstrdup(d->path);
2338 /* Run from main thread */
2339 static int setup_dbus(struct userdata *u) {
2342 dbus_error_init(&err);
2344 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2346 if (dbus_error_is_set(&err) || !u->connection) {
2347 pa_log("Failed to get D-Bus connection: %s", err.message);
2348 dbus_error_free(&err);
2355 int pa__init(pa_module* m) {
2359 const char *address, *path;
2361 char *mike, *speaker;
2362 const pa_bluetooth_device *device;
2366 dbus_error_init(&err);
2368 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2369 pa_log_error("Failed to parse module arguments");
2373 m->userdata = u = pa_xnew0(struct userdata, 1);
2378 u->sample_spec = m->core->default_sample_spec;
2382 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2383 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2384 pa_log("SCO sink not found");
2388 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2389 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2390 pa_log("SCO source not found");
2395 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2396 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2397 pa_log_error("Failed to get rate from module arguments");
2401 u->auto_connect = TRUE;
2402 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2403 pa_log("Failed to parse auto_connect= argument");
2407 channels = u->sample_spec.channels;
2408 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2409 channels <= 0 || channels > PA_CHANNELS_MAX) {
2410 pa_log_error("Failed to get channels from module arguments");
2413 u->sample_spec.channels = (uint8_t) channels;
2414 u->requested_sample_spec = u->sample_spec;
2416 address = pa_modargs_get_value(ma, "address", NULL);
2417 path = pa_modargs_get_value(ma, "path", NULL);
2419 if (setup_dbus(u) < 0)
2422 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2425 if (!(device = find_device(u, address, path)))
2428 /* Add the card structure. This will also initialize the default profile */
2429 if (add_card(u, device) < 0)
2432 /* Connect to the BT service and query capabilities */
2436 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2437 pa_log_error("Failed to add filter function");
2440 u->filter_added = TRUE;
2442 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2443 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2445 if (pa_dbus_add_matches(
2446 pa_dbus_connection_get(u->connection), &err,
2454 pa_log("Failed to add D-Bus matches: %s", err.message);
2461 if (u->profile != PROFILE_OFF)
2462 if (init_profile(u) < 0)
2465 if (u->sink || u->source)
2466 if (start_thread(u) < 0)
2475 dbus_error_free(&err);
2480 int pa__get_n_used(pa_module *m) {
2484 pa_assert_se(u = m->userdata);
2487 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2488 (u->source ? pa_source_linked_by(u->source) : 0);
2491 void pa__done(pa_module *m) {
2495 if (!(u = m->userdata))
2500 && !USE_SCO_OVER_PCM(u)
2503 pa_sink_unlink(u->sink);
2507 && !USE_SCO_OVER_PCM(u)
2510 pa_source_unlink(u->source);
2514 if (u->connection) {
2517 char *speaker, *mike;
2518 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2519 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2521 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2530 if (u->filter_added)
2531 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2533 pa_dbus_connection_unref(u->connection);
2537 pa_card_free(u->card);
2539 if (u->read_smoother)
2540 pa_smoother_free(u->read_smoother);
2545 pa_xfree(u->a2dp.buffer);
2547 sbc_finish(&u->a2dp.sbc);
2550 pa_modargs_free(u->modargs);
2552 pa_xfree(u->address);
2556 pa_bluetooth_discovery_unref(u->discovery);