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
28 #include <linux/sockios.h>
29 #include <arpa/inet.h>
31 #include <pulse/rtclock.h>
32 #include <pulse/sample.h>
33 #include <pulse/timeval.h>
34 #include <pulse/xmalloc.h>
36 #include <pulsecore/i18n.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/modargs.h>
39 #include <pulsecore/core-rtclock.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/shared.h>
43 #include <pulsecore/socket-util.h>
44 #include <pulsecore/thread.h>
45 #include <pulsecore/thread-mq.h>
46 #include <pulsecore/poll.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"
55 #include "a2dp-codecs.h"
57 #include "bluetooth-util.h"
59 #define BITPOOL_DEC_LIMIT 32
60 #define BITPOOL_DEC_STEP 5
61 #define HSP_MAX_GAIN 15
63 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(FALSE);
68 "name=<name for the card/sink/source, to be prefixed> "
69 "card_name=<name for the card> "
70 "card_properties=<properties for the card> "
71 "sink_name=<name for the sink> "
72 "sink_properties=<properties for the sink> "
73 "source_name=<name for the source> "
74 "source_properties=<properties for the source> "
75 "address=<address of the device> "
76 "profile=<a2dp|hsp|hfgw> "
78 "channels=<number of channels> "
79 "path=<device object path> "
80 "auto_connect=<automatically connect?> "
81 "sco_sink=<SCO over PCM sink name> "
82 "sco_source=<SCO over PCM source name>");
84 /* TODO: not close fd when entering suspend mode in a2dp */
86 static const char* const valid_modargs[] = {
106 sbc_capabilities_t sbc_capabilities;
107 sbc_t sbc; /* Codec data */
108 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
109 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
111 void* buffer; /* Codec transfer buffer */
112 size_t buffer_size; /* Size of the buffer */
114 uint16_t seq_num; /* Cumulative packet sequence */
120 pcm_capabilities_t pcm_capabilities;
122 void (*sco_sink_set_volume)(pa_sink *s);
123 pa_source *sco_source;
124 void (*sco_source_set_volume)(pa_source *s);
125 pa_hook_slot *sink_state_changed_slot;
126 pa_hook_slot *source_state_changed_slot;
129 struct bluetooth_msg {
134 typedef struct bluetooth_msg bluetooth_msg;
135 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
136 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
147 pa_bluetooth_discovery *discovery;
148 pa_bool_t auto_connect;
150 pa_dbus_connection *connection;
156 pa_thread_mq thread_mq;
158 pa_rtpoll_item *rtpoll_item;
162 uint64_t read_index, write_index;
163 pa_usec_t started_at;
164 pa_smoother *read_smoother;
166 pa_memchunk write_memchunk;
168 pa_sample_spec sample_spec, requested_sample_spec;
176 struct a2dp_info a2dp;
179 enum profile profile;
183 int stream_write_type;
184 int service_write_type, service_read_type;
186 pa_bool_t filter_added;
190 BLUETOOTH_MESSAGE_SET_PROFILE,
191 BLUETOOTH_MESSAGE_MAX
194 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
195 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
196 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
197 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
199 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
201 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
203 static int init_bt(struct userdata *u);
204 static int init_profile(struct userdata *u);
206 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
211 pa_assert(msg->length > 0);
213 if (u->service_fd < 0) {
214 pa_log_warn("Service not connected");
218 pa_log_debug("Sending %s -> %s",
219 pa_strnull(bt_audio_strtype(msg->type)),
220 pa_strnull(bt_audio_strname(msg->name)));
222 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
226 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
228 pa_log_error("Short write()");
233 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
237 pa_assert(u->service_fd >= 0);
239 pa_assert(room >= sizeof(*msg));
241 pa_log_debug("Trying to receive message from audio service...");
243 /* First, read the header */
244 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
247 if (msg->length < sizeof(*msg)) {
248 pa_log_error("Invalid message size.");
252 if (msg->length > room) {
253 pa_log_error("Not enough room.");
257 /* Secondly, read the payload */
258 if (msg->length > sizeof(*msg)) {
260 size_t remains = msg->length - sizeof(*msg);
262 if ((r = pa_loop_read(u->service_fd,
263 (uint8_t*) msg + sizeof(*msg),
265 &u->service_read_type)) != (ssize_t) remains)
269 pa_log_debug("Received %s <- %s",
270 pa_strnull(bt_audio_strtype(msg->type)),
271 pa_strnull(bt_audio_strname(msg->name)));
278 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
280 pa_log_error("Short read()");
285 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) {
289 pa_assert(u->service_fd >= 0);
292 if ((r = service_recv(u, rsp, room)) < 0)
295 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
296 rsp->name != expected_name ||
297 (expected_size > 0 && rsp->length != expected_size)) {
299 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
300 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
302 pa_log_error("Bogus message %s received while %s was expected",
303 pa_strnull(bt_audio_strname(rsp->name)),
304 pa_strnull(bt_audio_strname(expected_name)));
311 /* Run from main thread */
312 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
314 const codec_capabilities_t *codec;
319 bytes_left = rsp->h.length - sizeof(*rsp);
321 if (bytes_left < sizeof(codec_capabilities_t)) {
322 pa_log_error("Packet too small to store codec information.");
326 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
328 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
330 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
331 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
332 pa_log_error("Got capabilities for wrong codec.");
336 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
338 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
341 pa_assert(codec->type == BT_HFP_CODEC_PCM);
343 if (codec->configured && seid == 0)
346 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
348 } else if (u->profile == PROFILE_A2DP) {
350 while (bytes_left > 0) {
351 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
354 bytes_left -= codec->length;
355 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
358 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
361 pa_assert(codec->type == BT_A2DP_SBC_SINK);
363 if (codec->configured && seid == 0)
366 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
368 } else if (u->profile == PROFILE_A2DP_SOURCE) {
370 while (bytes_left > 0) {
371 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
374 bytes_left -= codec->length;
375 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
378 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
381 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
383 if (codec->configured && seid == 0)
386 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
392 /* Run from main thread */
393 static int get_caps(struct userdata *u, uint8_t seid) {
395 struct bt_get_capabilities_req getcaps_req;
396 struct bt_get_capabilities_rsp getcaps_rsp;
397 bt_audio_error_t error;
398 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
404 memset(&msg, 0, sizeof(msg));
405 msg.getcaps_req.h.type = BT_REQUEST;
406 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
407 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
408 msg.getcaps_req.seid = seid;
410 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
411 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
412 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
414 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
415 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
417 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
419 if (service_send(u, &msg.getcaps_req.h) < 0)
422 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
425 ret = parse_caps(u, seid, &msg.getcaps_rsp);
429 return get_caps(u, ret);
432 /* Run from main thread */
433 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
436 case BT_SBC_SAMPLING_FREQ_16000:
437 case BT_SBC_SAMPLING_FREQ_32000:
440 case BT_SBC_SAMPLING_FREQ_44100:
443 case BT_A2DP_CHANNEL_MODE_MONO:
444 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
447 case BT_A2DP_CHANNEL_MODE_STEREO:
448 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
452 pa_log_warn("Invalid channel mode %u", mode);
456 case BT_SBC_SAMPLING_FREQ_48000:
459 case BT_A2DP_CHANNEL_MODE_MONO:
460 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
463 case BT_A2DP_CHANNEL_MODE_STEREO:
464 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
468 pa_log_warn("Invalid channel mode %u", mode);
473 pa_log_warn("Invalid sampling freq %u", freq);
478 /* Run from main thread */
479 static int setup_a2dp(struct userdata *u) {
480 sbc_capabilities_t *cap;
483 static const struct {
487 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
488 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
489 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
490 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
494 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
496 cap = &u->a2dp.sbc_capabilities;
498 /* Find the lowest freq that is at least as high as the requested
500 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
501 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
502 u->sample_spec.rate = freq_table[i].rate;
503 cap->frequency = freq_table[i].cap;
507 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
508 for (--i; i >= 0; i--) {
509 if (cap->frequency & freq_table[i].cap) {
510 u->sample_spec.rate = freq_table[i].rate;
511 cap->frequency = freq_table[i].cap;
517 pa_log("Not suitable sample rate");
522 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
524 if (cap->capability.configured)
527 if (u->sample_spec.channels <= 1) {
528 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
529 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
530 u->sample_spec.channels = 1;
532 u->sample_spec.channels = 2;
535 if (u->sample_spec.channels >= 2) {
536 u->sample_spec.channels = 2;
538 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
539 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
540 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
541 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
542 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
543 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
544 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
545 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
546 u->sample_spec.channels = 1;
548 pa_log("No supported channel modes");
553 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
554 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
555 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
556 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
557 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
558 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
559 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
560 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
562 pa_log_error("No supported block lengths");
566 if (cap->subbands & BT_A2DP_SUBBANDS_8)
567 cap->subbands = BT_A2DP_SUBBANDS_8;
568 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
569 cap->subbands = BT_A2DP_SUBBANDS_4;
571 pa_log_error("No supported subbands");
575 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
576 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
577 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
578 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
580 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
581 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
586 /* Run from main thread */
587 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
588 sbc_capabilities_t *active_capabilities;
592 active_capabilities = &a2dp->sbc_capabilities;
594 if (a2dp->sbc_initialized)
595 sbc_reinit(&a2dp->sbc, 0);
597 sbc_init(&a2dp->sbc, 0);
598 a2dp->sbc_initialized = TRUE;
600 switch (active_capabilities->frequency) {
601 case BT_SBC_SAMPLING_FREQ_16000:
602 a2dp->sbc.frequency = SBC_FREQ_16000;
604 case BT_SBC_SAMPLING_FREQ_32000:
605 a2dp->sbc.frequency = SBC_FREQ_32000;
607 case BT_SBC_SAMPLING_FREQ_44100:
608 a2dp->sbc.frequency = SBC_FREQ_44100;
610 case BT_SBC_SAMPLING_FREQ_48000:
611 a2dp->sbc.frequency = SBC_FREQ_48000;
614 pa_assert_not_reached();
617 switch (active_capabilities->channel_mode) {
618 case BT_A2DP_CHANNEL_MODE_MONO:
619 a2dp->sbc.mode = SBC_MODE_MONO;
621 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
622 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
624 case BT_A2DP_CHANNEL_MODE_STEREO:
625 a2dp->sbc.mode = SBC_MODE_STEREO;
627 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
628 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
631 pa_assert_not_reached();
634 switch (active_capabilities->allocation_method) {
635 case BT_A2DP_ALLOCATION_SNR:
636 a2dp->sbc.allocation = SBC_AM_SNR;
638 case BT_A2DP_ALLOCATION_LOUDNESS:
639 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
642 pa_assert_not_reached();
645 switch (active_capabilities->subbands) {
646 case BT_A2DP_SUBBANDS_4:
647 a2dp->sbc.subbands = SBC_SB_4;
649 case BT_A2DP_SUBBANDS_8:
650 a2dp->sbc.subbands = SBC_SB_8;
653 pa_assert_not_reached();
656 switch (active_capabilities->block_length) {
657 case BT_A2DP_BLOCK_LENGTH_4:
658 a2dp->sbc.blocks = SBC_BLK_4;
660 case BT_A2DP_BLOCK_LENGTH_8:
661 a2dp->sbc.blocks = SBC_BLK_8;
663 case BT_A2DP_BLOCK_LENGTH_12:
664 a2dp->sbc.blocks = SBC_BLK_12;
666 case BT_A2DP_BLOCK_LENGTH_16:
667 a2dp->sbc.blocks = SBC_BLK_16;
670 pa_assert_not_reached();
673 a2dp->min_bitpool = active_capabilities->min_bitpool;
674 a2dp->max_bitpool = active_capabilities->max_bitpool;
676 /* Set minimum bitpool for source to get the maximum possible block_size */
677 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
678 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
679 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
682 /* Run from main thread */
683 static int set_conf(struct userdata *u) {
685 struct bt_open_req open_req;
686 struct bt_open_rsp open_rsp;
687 struct bt_set_configuration_req setconf_req;
688 struct bt_set_configuration_rsp setconf_rsp;
689 bt_audio_error_t error;
690 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
693 memset(&msg, 0, sizeof(msg));
694 msg.open_req.h.type = BT_REQUEST;
695 msg.open_req.h.name = BT_OPEN;
696 msg.open_req.h.length = sizeof(msg.open_req);
698 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
699 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
700 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
702 if (service_send(u, &msg.open_req.h) < 0)
705 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
708 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
709 u->sample_spec.format = PA_SAMPLE_S16LE;
711 if (setup_a2dp(u) < 0)
714 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
716 u->sample_spec.format = PA_SAMPLE_S16LE;
717 u->sample_spec.channels = 1;
718 u->sample_spec.rate = 8000;
721 memset(&msg, 0, sizeof(msg));
722 msg.setconf_req.h.type = BT_REQUEST;
723 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
724 msg.setconf_req.h.length = sizeof(msg.setconf_req);
726 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
727 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
729 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
730 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
731 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
733 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
735 if (service_send(u, &msg.setconf_req.h) < 0)
738 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
741 u->link_mtu = msg.setconf_rsp.link_mtu;
743 /* setup SBC encoder now we agree on parameters */
744 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
745 setup_sbc(&u->a2dp, u->profile);
748 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
749 / u->a2dp.frame_length
752 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
753 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
755 u->block_size = u->link_mtu;
761 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
763 struct a2dp_info *a2dp;
769 if (a2dp->sbc.bitpool == bitpool)
772 if (bitpool > a2dp->max_bitpool)
773 bitpool = a2dp->max_bitpool;
774 else if (bitpool < a2dp->min_bitpool)
775 bitpool = a2dp->min_bitpool;
777 a2dp->sbc.bitpool = bitpool;
779 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
780 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
782 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
785 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
786 / a2dp->frame_length * a2dp->codesize;
788 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
789 pa_sink_set_fixed_latency_within_thread(u->sink,
790 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
793 /* from IO thread, except in SCO over PCM */
795 static int setup_stream(struct userdata *u) {
796 struct pollfd *pollfd;
799 pa_make_fd_nonblock(u->stream_fd);
800 pa_make_socket_low_delay(u->stream_fd);
803 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
804 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
806 pa_log_debug("Stream properly set up, we're ready to roll!");
808 if (u->profile == PROFILE_A2DP)
809 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
811 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
812 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
813 pollfd->fd = u->stream_fd;
814 pollfd->events = pollfd->revents = 0;
816 u->read_index = u->write_index = 0;
820 u->read_smoother = pa_smoother_new(
832 static int start_stream_fd(struct userdata *u) {
834 bt_audio_msg_header_t rsp;
835 struct bt_start_stream_req start_req;
836 struct bt_start_stream_rsp start_rsp;
837 struct bt_new_stream_ind streamfd_ind;
838 bt_audio_error_t error;
839 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
843 pa_assert(u->rtpoll);
844 pa_assert(!u->rtpoll_item);
845 pa_assert(u->stream_fd < 0);
847 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
848 msg.start_req.h.type = BT_REQUEST;
849 msg.start_req.h.name = BT_START_STREAM;
850 msg.start_req.h.length = sizeof(msg.start_req);
852 if (service_send(u, &msg.start_req.h) < 0)
855 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
858 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
861 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
862 pa_log("Failed to get stream fd from audio service.");
866 return setup_stream(u);
870 static int stop_stream_fd(struct userdata *u) {
872 bt_audio_msg_header_t rsp;
873 struct bt_stop_stream_req start_req;
874 struct bt_stop_stream_rsp start_rsp;
875 bt_audio_error_t error;
876 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
881 pa_assert(u->rtpoll);
883 if (u->rtpoll_item) {
884 pa_rtpoll_item_free(u->rtpoll_item);
885 u->rtpoll_item = NULL;
888 if (u->stream_fd >= 0) {
889 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
890 msg.start_req.h.type = BT_REQUEST;
891 msg.start_req.h.name = BT_STOP_STREAM;
892 msg.start_req.h.length = sizeof(msg.start_req);
894 if (service_send(u, &msg.start_req.h) < 0 ||
895 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
898 pa_close(u->stream_fd);
902 if (u->read_smoother) {
903 pa_smoother_free(u->read_smoother);
904 u->read_smoother = NULL;
910 static void bt_transport_release(struct userdata *u) {
911 const char *accesstype = "rw";
912 const pa_bluetooth_transport *t;
914 /* Ignore if already released */
918 pa_log_debug("Releasing transport %s", u->transport);
920 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
922 pa_bluetooth_transport_release(t, accesstype);
924 pa_xfree(u->accesstype);
925 u->accesstype = NULL;
927 if (u->rtpoll_item) {
928 pa_rtpoll_item_free(u->rtpoll_item);
929 u->rtpoll_item = NULL;
932 if (u->stream_fd >= 0) {
933 pa_close(u->stream_fd);
937 if (u->read_smoother) {
938 pa_smoother_free(u->read_smoother);
939 u->read_smoother = NULL;
943 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
944 const char *accesstype = "rw";
945 const pa_bluetooth_transport *t;
953 pa_log_debug("Acquiring transport %s", u->transport);
955 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
957 pa_log("Transport %s no longer available", u->transport);
958 pa_xfree(u->transport);
963 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
964 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
965 if (u->stream_fd < 0)
968 u->accesstype = pa_xstrdup(accesstype);
969 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
975 pa_log_info("Transport %s resuming", u->transport);
976 return setup_stream(u);
979 /* Run from IO thread */
980 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
981 struct userdata *u = PA_SINK(o)->userdata;
982 pa_bool_t failed = FALSE;
985 pa_assert(u->sink == PA_SINK(o));
989 case PA_SINK_MESSAGE_SET_STATE:
991 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
993 case PA_SINK_SUSPENDED:
994 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
996 /* Stop the device if the source is suspended as well */
997 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
998 /* We deliberately ignore whether stopping
999 * actually worked. Since the stream_fd is
1000 * closed it doesn't really matter */
1002 bt_transport_release(u);
1010 case PA_SINK_RUNNING:
1011 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1014 /* Resume the device if the source was suspended as well */
1015 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1017 if (bt_transport_acquire(u, TRUE) < 0)
1019 } else if (start_stream_fd(u) < 0)
1024 case PA_SINK_UNLINKED:
1026 case PA_SINK_INVALID_STATE:
1031 case PA_SINK_MESSAGE_GET_LATENCY: {
1033 if (u->read_smoother) {
1036 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1037 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1039 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1043 ri = pa_rtclock_now() - u->started_at;
1044 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1046 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1049 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1054 r = pa_sink_process_msg(o, code, data, offset, chunk);
1056 return (r < 0 || !failed) ? r : -1;
1059 /* Run from IO thread */
1060 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1061 struct userdata *u = PA_SOURCE(o)->userdata;
1062 pa_bool_t failed = FALSE;
1065 pa_assert(u->source == PA_SOURCE(o));
1069 case PA_SOURCE_MESSAGE_SET_STATE:
1071 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1073 case PA_SOURCE_SUSPENDED:
1074 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1076 /* Stop the device if the sink is suspended as well */
1077 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1079 bt_transport_release(u);
1084 if (u->read_smoother)
1085 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1088 case PA_SOURCE_IDLE:
1089 case PA_SOURCE_RUNNING:
1090 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1093 /* Resume the device if the sink was suspended as well */
1094 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1096 if (bt_transport_acquire(u, TRUE) < 0)
1098 } else if (start_stream_fd(u) < 0)
1101 /* We don't resume the smoother here. Instead we
1102 * wait until the first packet arrives */
1105 case PA_SOURCE_UNLINKED:
1106 case PA_SOURCE_INIT:
1107 case PA_SOURCE_INVALID_STATE:
1112 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1115 if (u->read_smoother) {
1116 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1117 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1119 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1121 *((pa_usec_t*) data) = 0;
1128 r = pa_source_process_msg(o, code, data, offset, chunk);
1130 return (r < 0 || !failed) ? r : -1;
1133 /* Called from main thread context */
1134 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1135 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
1138 case BLUETOOTH_MESSAGE_SET_PROFILE: {
1139 const char *profile = data;
1140 pa_log_debug("Switch profile to %s requested", profile);
1142 if (pa_card_set_profile(u->card, profile, FALSE) < 0)
1143 pa_log_debug("Failed to switch profile to %s", profile);
1150 /* Run from IO thread */
1151 static int hsp_process_render(struct userdata *u) {
1155 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1158 /* First, render some data */
1159 if (!u->write_memchunk.memblock)
1160 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1162 pa_assert(u->write_memchunk.length == u->block_size);
1168 /* Now write that data to the socket. The socket is of type
1169 * SEQPACKET, and we generated the data of the MTU size, so this
1170 * should just work. */
1172 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1173 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1174 pa_memblock_release(u->write_memchunk.memblock);
1181 /* Retry right away if we got interrupted */
1184 else if (errno == EAGAIN)
1185 /* Hmm, apparently the socket was not writable, give up for now */
1188 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1193 pa_assert((size_t) l <= u->write_memchunk.length);
1195 if ((size_t) l != u->write_memchunk.length) {
1196 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1197 (unsigned long long) l,
1198 (unsigned long long) u->write_memchunk.length);
1203 u->write_index += (uint64_t) u->write_memchunk.length;
1204 pa_memblock_unref(u->write_memchunk.memblock);
1205 pa_memchunk_reset(&u->write_memchunk);
1214 /* Run from IO thread */
1215 static int hsp_process_push(struct userdata *u) {
1217 pa_memchunk memchunk;
1220 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1221 pa_assert(u->source);
1222 pa_assert(u->read_smoother);
1224 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1225 memchunk.index = memchunk.length = 0;
1234 pa_bool_t found_tstamp = FALSE;
1237 memset(&m, 0, sizeof(m));
1238 memset(&aux, 0, sizeof(aux));
1239 memset(&iov, 0, sizeof(iov));
1243 m.msg_control = aux;
1244 m.msg_controllen = sizeof(aux);
1246 p = pa_memblock_acquire(memchunk.memblock);
1248 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1249 l = recvmsg(u->stream_fd, &m, 0);
1250 pa_memblock_release(memchunk.memblock);
1254 if (l < 0 && errno == EINTR)
1255 /* Retry right away if we got interrupted */
1258 else if (l < 0 && errno == EAGAIN)
1259 /* Hmm, apparently the socket was not readable, give up for now. */
1262 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1267 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1269 memchunk.length = (size_t) l;
1270 u->read_index += (uint64_t) l;
1272 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1273 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1274 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1275 pa_rtclock_from_wallclock(tv);
1276 tstamp = pa_timeval_load(tv);
1277 found_tstamp = TRUE;
1281 if (!found_tstamp) {
1282 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1283 tstamp = pa_rtclock_now();
1286 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1287 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1289 pa_source_post(u->source, &memchunk);
1295 pa_memblock_unref(memchunk.memblock);
1300 /* Run from IO thread */
1301 static void a2dp_prepare_buffer(struct userdata *u) {
1304 if (u->a2dp.buffer_size >= u->link_mtu)
1307 u->a2dp.buffer_size = 2 * u->link_mtu;
1308 pa_xfree(u->a2dp.buffer);
1309 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1312 /* Run from IO thread */
1313 static int a2dp_process_render(struct userdata *u) {
1314 struct a2dp_info *a2dp;
1315 struct rtp_header *header;
1316 struct rtp_payload *payload;
1320 size_t to_write, to_encode;
1321 unsigned frame_count;
1325 pa_assert(u->profile == PROFILE_A2DP);
1328 /* First, render some data */
1329 if (!u->write_memchunk.memblock)
1330 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1332 pa_assert(u->write_memchunk.length == u->block_size);
1334 a2dp_prepare_buffer(u);
1337 header = a2dp->buffer;
1338 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1342 /* Try to create a packet of the full MTU */
1344 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1345 to_encode = u->write_memchunk.length;
1347 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1348 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1350 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1354 encoded = sbc_encode(&a2dp->sbc,
1359 if (PA_UNLIKELY(encoded <= 0)) {
1360 pa_log_error("SBC encoding error (%li)", (long) encoded);
1361 pa_memblock_release(u->write_memchunk.memblock);
1365 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1366 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1368 pa_assert_fp((size_t) encoded <= to_encode);
1369 pa_assert_fp((size_t) encoded == a2dp->codesize);
1371 pa_assert_fp((size_t) written <= to_write);
1372 pa_assert_fp((size_t) written == a2dp->frame_length);
1374 p = (const uint8_t*) p + encoded;
1375 to_encode -= encoded;
1377 d = (uint8_t*) d + written;
1378 to_write -= written;
1383 pa_memblock_release(u->write_memchunk.memblock);
1385 pa_assert(to_encode == 0);
1388 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1391 /* write it to the fifo */
1392 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1395 header->sequence_number = htons(a2dp->seq_num++);
1396 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1397 header->ssrc = htonl(1);
1398 payload->frame_count = frame_count;
1400 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1405 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1412 /* Retry right away if we got interrupted */
1415 else if (errno == EAGAIN)
1416 /* Hmm, apparently the socket was not writable, give up for now */
1419 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1424 pa_assert((size_t) l <= nbytes);
1426 if ((size_t) l != nbytes) {
1427 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1428 (unsigned long long) l,
1429 (unsigned long long) nbytes);
1434 u->write_index += (uint64_t) u->write_memchunk.length;
1435 pa_memblock_unref(u->write_memchunk.memblock);
1436 pa_memchunk_reset(&u->write_memchunk);
1446 static int a2dp_process_push(struct userdata *u) {
1448 pa_memchunk memchunk;
1451 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1452 pa_assert(u->source);
1453 pa_assert(u->read_smoother);
1455 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1456 memchunk.index = memchunk.length = 0;
1459 pa_bool_t found_tstamp = FALSE;
1461 struct a2dp_info *a2dp;
1462 struct rtp_header *header;
1463 struct rtp_payload *payload;
1467 size_t to_write, to_decode;
1469 a2dp_prepare_buffer(u);
1472 header = a2dp->buffer;
1473 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1475 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1479 if (l < 0 && errno == EINTR)
1480 /* Retry right away if we got interrupted */
1483 else if (l < 0 && errno == EAGAIN)
1484 /* Hmm, apparently the socket was not readable, give up for now. */
1487 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1492 pa_assert((size_t) l <= a2dp->buffer_size);
1494 u->read_index += (uint64_t) l;
1496 /* TODO: get timestamp from rtp */
1497 if (!found_tstamp) {
1498 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1499 tstamp = pa_rtclock_now();
1502 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1503 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1505 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1506 to_decode = l - sizeof(*header) - sizeof(*payload);
1508 d = pa_memblock_acquire(memchunk.memblock);
1509 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1511 while (PA_LIKELY(to_decode > 0)) {
1515 decoded = sbc_decode(&a2dp->sbc,
1520 if (PA_UNLIKELY(decoded <= 0)) {
1521 pa_log_error("SBC decoding error (%li)", (long) decoded);
1522 pa_memblock_release(memchunk.memblock);
1523 pa_memblock_unref(memchunk.memblock);
1527 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1528 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1530 /* Reset frame length, it can be changed due to bitpool change */
1531 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1533 pa_assert_fp((size_t) decoded <= to_decode);
1534 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1536 pa_assert_fp((size_t) written == a2dp->codesize);
1538 p = (const uint8_t*) p + decoded;
1539 to_decode -= decoded;
1541 d = (uint8_t*) d + written;
1542 to_write -= written;
1545 memchunk.length -= to_write;
1547 pa_memblock_release(memchunk.memblock);
1549 pa_source_post(u->source, &memchunk);
1555 pa_memblock_unref(memchunk.memblock);
1560 static void a2dp_reduce_bitpool(struct userdata *u)
1562 struct a2dp_info *a2dp;
1569 /* Check if bitpool is already at its limit */
1570 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1573 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1575 if (bitpool < BITPOOL_DEC_LIMIT)
1576 bitpool = BITPOOL_DEC_LIMIT;
1578 a2dp_set_bitpool(u, bitpool);
1581 static void thread_func(void *userdata) {
1582 struct userdata *u = userdata;
1583 unsigned do_write = 0;
1584 pa_bool_t writable = FALSE;
1588 pa_log_debug("IO Thread starting up");
1590 if (u->core->realtime_scheduling)
1591 pa_make_realtime(u->core->realtime_priority);
1593 pa_thread_mq_install(&u->thread_mq);
1596 if (bt_transport_acquire(u, TRUE) < 0)
1598 } else if (start_stream_fd(u) < 0)
1602 struct pollfd *pollfd;
1604 pa_bool_t disable_timer = TRUE;
1606 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1608 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1610 /* We should send two blocks to the device before we expect
1613 if (u->write_index == 0 && u->read_index <= 0)
1616 if (pollfd && (pollfd->revents & POLLIN)) {
1619 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1620 n_read = hsp_process_push(u);
1622 n_read = a2dp_process_push(u);
1627 /* We just read something, so we are supposed to write something, too */
1632 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1634 if (u->sink->thread_info.rewind_requested)
1635 pa_sink_process_rewind(u->sink, 0);
1638 if (pollfd->revents & POLLOUT)
1641 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1642 pa_usec_t time_passed;
1643 pa_usec_t audio_sent;
1645 /* Hmm, there is no input stream we could synchronize
1646 * to. So let's do things by time */
1648 time_passed = pa_rtclock_now() - u->started_at;
1649 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1651 if (audio_sent <= time_passed) {
1652 pa_usec_t audio_to_send = time_passed - audio_sent;
1654 /* Never try to catch up for more than 100ms */
1655 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1656 pa_usec_t skip_usec;
1657 uint64_t skip_bytes;
1659 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1660 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1662 if (skip_bytes > 0) {
1665 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1666 (unsigned long long) skip_usec,
1667 (unsigned long long) skip_bytes);
1669 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1670 pa_memblock_unref(tmp.memblock);
1671 u->write_index += skip_bytes;
1673 if (u->profile == PROFILE_A2DP)
1674 a2dp_reduce_bitpool(u);
1682 if (writable && do_write > 0) {
1685 if (u->write_index <= 0)
1686 u->started_at = pa_rtclock_now();
1688 if (u->profile == PROFILE_A2DP) {
1689 if ((n_written = a2dp_process_render(u)) < 0)
1692 if ((n_written = hsp_process_render(u)) < 0)
1697 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1699 do_write -= n_written;
1703 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1704 pa_usec_t sleep_for;
1705 pa_usec_t time_passed, next_write_at;
1708 /* Hmm, there is no input stream we could synchronize
1709 * to. So let's estimate when we need to wake up the latest */
1710 time_passed = pa_rtclock_now() - u->started_at;
1711 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1712 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1713 /* 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); */
1715 /* drop stream every 500 ms */
1716 sleep_for = PA_USEC_PER_MSEC * 500;
1718 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1719 disable_timer = FALSE;
1725 pa_rtpoll_set_timer_disabled(u->rtpoll);
1727 /* Hmm, nothing to do. Let's sleep */
1729 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1730 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1732 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1738 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1740 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1741 pa_log_info("FD error: %s%s%s%s",
1742 pollfd->revents & POLLERR ? "POLLERR " :"",
1743 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1744 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1745 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1751 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1752 pa_log_debug("IO thread failed");
1753 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_SET_PROFILE, "off", 0, NULL, NULL);
1754 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1757 pa_log_debug("IO thread shutting down");
1760 /* Run from main thread */
1761 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1767 pa_assert_se(u = userdata);
1769 dbus_error_init(&err);
1771 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1772 dbus_message_get_interface(m),
1773 dbus_message_get_path(m),
1774 dbus_message_get_member(m));
1776 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1779 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1780 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1785 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1786 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1790 if (u->profile == PROFILE_HSP) {
1791 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1792 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1794 /* increment volume by one to correct rounding errors */
1795 if (volume < PA_VOLUME_NORM)
1798 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1799 pa_sink_volume_changed(u->sink, &v);
1801 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1802 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1804 /* increment volume by one to correct rounding errors */
1805 if (volume < PA_VOLUME_NORM)
1808 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1809 pa_source_volume_changed(u->source, &v);
1812 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1813 DBusMessageIter arg_i;
1814 pa_bluetooth_transport *t;
1817 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1820 if (!dbus_message_iter_init(m, &arg_i)) {
1821 pa_log("Failed to parse PropertyChanged: %s", err.message);
1827 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1830 if (nrec != t->nrec) {
1831 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1832 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1834 } else if (dbus_message_is_signal(m, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1836 DBusMessageIter iter;
1837 DBusMessageIter variant;
1838 pa_bt_audio_state_t state = PA_BT_AUDIO_STATE_INVALID;
1840 if (!dbus_message_iter_init(m, &iter)) {
1841 pa_log("Failed to parse PropertyChanged: %s", err.message);
1845 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1846 pa_log("Property name not a string.");
1850 dbus_message_iter_get_basic(&iter, &key);
1852 if (!dbus_message_iter_next(&iter)) {
1853 pa_log("Property value missing");
1857 dbus_message_iter_recurse(&iter, &variant);
1859 if (dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_STRING) {
1861 dbus_message_iter_get_basic(&variant, &value);
1863 if (pa_streq(key, "State")) {
1864 pa_log_debug("dbus: HSHFAG property 'State' changed to value '%s'", value);
1865 state = pa_bt_audio_state_from_string(value);
1870 case PA_BT_AUDIO_STATE_INVALID:
1871 case PA_BT_AUDIO_STATE_DISCONNECTED:
1872 case PA_BT_AUDIO_STATE_CONNECTED:
1873 case PA_BT_AUDIO_STATE_CONNECTING:
1876 case PA_BT_AUDIO_STATE_PLAYING:
1878 pa_log_debug("Changing profile to hfgw");
1879 if (pa_card_set_profile(u->card, "hfgw", FALSE) < 0)
1880 pa_log("Failed to change profile to hfgw");
1887 dbus_error_free(&err);
1889 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1892 /* Run from main thread */
1893 static void sink_set_volume_cb(pa_sink *s) {
1903 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1904 u = pa_shared_get(s->core, k);
1908 pa_assert(u->sink == s);
1909 pa_assert(u->profile == PROFILE_HSP);
1911 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1913 if (gain > HSP_MAX_GAIN)
1914 gain = HSP_MAX_GAIN;
1916 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1918 /* increment volume by one to correct rounding errors */
1919 if (volume < PA_VOLUME_NORM)
1922 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1924 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1925 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1926 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1927 dbus_message_unref(m);
1930 /* Run from main thread */
1931 static void source_set_volume_cb(pa_source *s) {
1941 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1942 u = pa_shared_get(s->core, k);
1946 pa_assert(u->source == s);
1947 pa_assert(u->profile == PROFILE_HSP);
1949 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1951 if (gain > HSP_MAX_GAIN)
1952 gain = HSP_MAX_GAIN;
1954 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1956 /* increment volume by one to correct rounding errors */
1957 if (volume < PA_VOLUME_NORM)
1960 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1962 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1963 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1964 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1965 dbus_message_unref(m);
1968 /* Run from main thread */
1969 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1975 pa_assert(device_id);
1976 pa_assert(namereg_fail);
1978 t = pa_sprintf_malloc("%s_name", type);
1979 n = pa_modargs_get_value(ma, t, NULL);
1983 *namereg_fail = TRUE;
1984 return pa_xstrdup(n);
1987 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1988 *namereg_fail = TRUE;
1991 *namereg_fail = FALSE;
1994 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1997 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1999 pa_assert(USE_SCO_OVER_PCM(u));
2001 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
2002 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
2004 if (u->service_fd >= 0 && u->stream_fd >= 0)
2009 pa_log_debug("Resuming SCO over PCM");
2010 if (init_profile(u) < 0) {
2011 pa_log("Can't resume SCO over PCM");
2016 return bt_transport_acquire(u, TRUE);
2018 return start_stream_fd(u);
2022 if (u->service_fd < 0 && u->stream_fd < 0)
2025 pa_log_debug("Closing SCO over PCM");
2028 bt_transport_release(u);
2029 else if (u->stream_fd >= 0)
2032 if (u->service_fd >= 0) {
2033 pa_close(u->service_fd);
2041 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
2043 pa_sink_assert_ref(s);
2046 if (s != u->hsp.sco_sink)
2049 sco_over_pcm_state_update(u, TRUE);
2054 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
2056 pa_source_assert_ref(s);
2059 if (s != u->hsp.sco_source)
2062 sco_over_pcm_state_update(u, TRUE);
2067 /* Run from main thread */
2068 static int add_sink(struct userdata *u) {
2071 if (USE_SCO_OVER_PCM(u)) {
2074 u->sink = u->hsp.sco_sink;
2075 p = pa_proplist_new();
2076 pa_proplist_sets(p, "bluetooth.protocol", "sco");
2077 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
2078 pa_proplist_free(p);
2080 if (!u->hsp.sink_state_changed_slot)
2081 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);
2084 pa_sink_new_data data;
2087 pa_sink_new_data_init(&data);
2088 data.driver = __FILE__;
2089 data.module = u->module;
2090 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
2091 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
2092 if (u->profile == PROFILE_HSP)
2093 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2094 data.card = u->card;
2095 data.name = get_name("sink", u->modargs, u->address, &b);
2096 data.namereg_fail = b;
2098 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2099 pa_log("Invalid properties");
2100 pa_sink_new_data_done(&data);
2104 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
2105 pa_sink_new_data_done(&data);
2108 pa_log_error("Failed to create sink");
2112 u->sink->userdata = u;
2113 u->sink->parent.process_msg = sink_process_msg;
2115 pa_sink_set_max_request(u->sink, u->block_size);
2116 pa_sink_set_fixed_latency(u->sink,
2117 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2118 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2121 if (u->profile == PROFILE_HSP) {
2122 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
2123 u->sink->n_volume_steps = 16;
2125 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2126 pa_shared_set(u->core, k, u);
2133 /* Run from main thread */
2134 static int add_source(struct userdata *u) {
2137 if (USE_SCO_OVER_PCM(u)) {
2138 u->source = u->hsp.sco_source;
2139 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2141 if (!u->hsp.source_state_changed_slot)
2142 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);
2145 pa_source_new_data data;
2148 pa_source_new_data_init(&data);
2149 data.driver = __FILE__;
2150 data.module = u->module;
2151 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2152 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2153 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2154 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2156 data.card = u->card;
2157 data.name = get_name("source", u->modargs, u->address, &b);
2158 data.namereg_fail = b;
2160 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2161 pa_log("Invalid properties");
2162 pa_source_new_data_done(&data);
2166 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
2167 pa_source_new_data_done(&data);
2170 pa_log_error("Failed to create source");
2174 u->source->userdata = u;
2175 u->source->parent.process_msg = source_process_msg;
2177 pa_source_set_fixed_latency(u->source,
2178 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2179 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2182 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2184 const pa_bluetooth_transport *t;
2185 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2187 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2189 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2192 if (u->profile == PROFILE_HSP) {
2193 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
2194 u->source->n_volume_steps = 16;
2196 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2197 pa_shared_set(u->core, k, u);
2204 /* Run from main thread */
2205 static void shutdown_bt(struct userdata *u) {
2208 if (u->stream_fd >= 0) {
2209 pa_close(u->stream_fd);
2212 u->stream_write_type = 0;
2215 if (u->service_fd >= 0) {
2216 pa_close(u->service_fd);
2218 u->service_write_type = 0;
2219 u->service_read_type = 0;
2222 if (u->write_memchunk.memblock) {
2223 pa_memblock_unref(u->write_memchunk.memblock);
2224 pa_memchunk_reset(&u->write_memchunk);
2228 static int bt_transport_config_a2dp(struct userdata *u) {
2229 const pa_bluetooth_transport *t;
2230 struct a2dp_info *a2dp = &u->a2dp;
2233 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2236 config = (a2dp_sbc_t *) t->config;
2238 u->sample_spec.format = PA_SAMPLE_S16LE;
2240 if (a2dp->sbc_initialized)
2241 sbc_reinit(&a2dp->sbc, 0);
2243 sbc_init(&a2dp->sbc, 0);
2244 a2dp->sbc_initialized = TRUE;
2246 switch (config->frequency) {
2247 case BT_SBC_SAMPLING_FREQ_16000:
2248 a2dp->sbc.frequency = SBC_FREQ_16000;
2249 u->sample_spec.rate = 16000U;
2251 case BT_SBC_SAMPLING_FREQ_32000:
2252 a2dp->sbc.frequency = SBC_FREQ_32000;
2253 u->sample_spec.rate = 32000U;
2255 case BT_SBC_SAMPLING_FREQ_44100:
2256 a2dp->sbc.frequency = SBC_FREQ_44100;
2257 u->sample_spec.rate = 44100U;
2259 case BT_SBC_SAMPLING_FREQ_48000:
2260 a2dp->sbc.frequency = SBC_FREQ_48000;
2261 u->sample_spec.rate = 48000U;
2264 pa_assert_not_reached();
2267 switch (config->channel_mode) {
2268 case BT_A2DP_CHANNEL_MODE_MONO:
2269 a2dp->sbc.mode = SBC_MODE_MONO;
2270 u->sample_spec.channels = 1;
2272 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2273 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2274 u->sample_spec.channels = 2;
2276 case BT_A2DP_CHANNEL_MODE_STEREO:
2277 a2dp->sbc.mode = SBC_MODE_STEREO;
2278 u->sample_spec.channels = 2;
2280 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2281 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2282 u->sample_spec.channels = 2;
2285 pa_assert_not_reached();
2288 switch (config->allocation_method) {
2289 case BT_A2DP_ALLOCATION_SNR:
2290 a2dp->sbc.allocation = SBC_AM_SNR;
2292 case BT_A2DP_ALLOCATION_LOUDNESS:
2293 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2296 pa_assert_not_reached();
2299 switch (config->subbands) {
2300 case BT_A2DP_SUBBANDS_4:
2301 a2dp->sbc.subbands = SBC_SB_4;
2303 case BT_A2DP_SUBBANDS_8:
2304 a2dp->sbc.subbands = SBC_SB_8;
2307 pa_assert_not_reached();
2310 switch (config->block_length) {
2311 case BT_A2DP_BLOCK_LENGTH_4:
2312 a2dp->sbc.blocks = SBC_BLK_4;
2314 case BT_A2DP_BLOCK_LENGTH_8:
2315 a2dp->sbc.blocks = SBC_BLK_8;
2317 case BT_A2DP_BLOCK_LENGTH_12:
2318 a2dp->sbc.blocks = SBC_BLK_12;
2320 case BT_A2DP_BLOCK_LENGTH_16:
2321 a2dp->sbc.blocks = SBC_BLK_16;
2324 pa_assert_not_reached();
2327 a2dp->min_bitpool = config->min_bitpool;
2328 a2dp->max_bitpool = config->max_bitpool;
2330 /* Set minimum bitpool for source to get the maximum possible block_size */
2331 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2332 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2333 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2336 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2337 / a2dp->frame_length
2340 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2341 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2346 static int bt_transport_config(struct userdata *u) {
2347 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2348 u->block_size = u->link_mtu;
2349 u->sample_spec.format = PA_SAMPLE_S16LE;
2350 u->sample_spec.channels = 1;
2351 u->sample_spec.rate = 8000;
2355 return bt_transport_config_a2dp(u);
2358 /* Run from main thread */
2359 static int bt_transport_open(struct userdata *u) {
2360 if (bt_transport_acquire(u, FALSE) < 0)
2363 return bt_transport_config(u);
2366 /* Run from main thread */
2367 static int init_bt(struct userdata *u) {
2372 u->stream_write_type = 0;
2373 u->service_write_type = 0;
2374 u->service_read_type = 0;
2376 if ((u->service_fd = bt_audio_service_open()) < 0) {
2377 pa_log_warn("Bluetooth audio service not available");
2381 pa_log_debug("Connected to the bluetooth audio service");
2386 /* Run from main thread */
2387 static int setup_bt(struct userdata *u) {
2388 const pa_bluetooth_device *d;
2389 const pa_bluetooth_transport *t;
2393 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2394 pa_log_error("Failed to get device object.");
2398 /* release transport if exist */
2400 bt_transport_release(u);
2401 pa_xfree(u->transport);
2402 u->transport = NULL;
2405 /* check if profile has a transport */
2406 t = pa_bluetooth_device_get_transport(d, u->profile);
2408 u->transport = pa_xstrdup(t->path);
2409 return bt_transport_open(u);
2412 if (get_caps(u, 0) < 0)
2415 pa_log_debug("Got device capabilities");
2417 if (set_conf(u) < 0)
2420 pa_log_debug("Connection to the device configured");
2422 if (USE_SCO_OVER_PCM(u)) {
2423 pa_log_debug("Configured to use SCO over PCM");
2427 pa_log_debug("Got the stream socket");
2432 /* Run from main thread */
2433 static int init_profile(struct userdata *u) {
2436 pa_assert(u->profile != PROFILE_OFF);
2438 if (setup_bt(u) < 0)
2441 if (u->profile == PROFILE_A2DP ||
2442 u->profile == PROFILE_HSP ||
2443 u->profile == PROFILE_HFGW)
2444 if (add_sink(u) < 0)
2447 if (u->profile == PROFILE_HSP ||
2448 u->profile == PROFILE_A2DP_SOURCE ||
2449 u->profile == PROFILE_HFGW)
2450 if (add_source(u) < 0)
2456 /* Run from main thread */
2457 static void stop_thread(struct userdata *u) {
2463 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2464 pa_thread_free(u->thread);
2468 if (u->rtpoll_item) {
2469 pa_rtpoll_item_free(u->rtpoll_item);
2470 u->rtpoll_item = NULL;
2473 if (u->hsp.sink_state_changed_slot) {
2474 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2475 u->hsp.sink_state_changed_slot = NULL;
2478 if (u->hsp.source_state_changed_slot) {
2479 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2480 u->hsp.source_state_changed_slot = NULL;
2484 if (u->profile == PROFILE_HSP) {
2485 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2486 pa_shared_remove(u->core, k);
2490 pa_sink_unref(u->sink);
2495 if (u->profile == PROFILE_HSP) {
2496 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2497 pa_shared_remove(u->core, k);
2501 pa_source_unref(u->source);
2506 pa_thread_mq_done(&u->thread_mq);
2508 pa_rtpoll_free(u->rtpoll);
2512 if (u->read_smoother) {
2513 pa_smoother_free(u->read_smoother);
2514 u->read_smoother = NULL;
2518 /* Run from main thread */
2519 static int start_thread(struct userdata *u) {
2521 pa_assert(!u->thread);
2522 pa_assert(!u->rtpoll);
2523 pa_assert(!u->rtpoll_item);
2525 u->rtpoll = pa_rtpoll_new();
2526 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2528 if (USE_SCO_OVER_PCM(u)) {
2529 if (sco_over_pcm_state_update(u, FALSE) < 0) {
2533 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2534 pa_shared_remove(u->core, k);
2539 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2540 pa_shared_remove(u->core, k);
2547 pa_sink_ref(u->sink);
2548 pa_source_ref(u->source);
2549 /* FIXME: monitor stream_fd error */
2553 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2554 pa_log_error("Failed to create IO thread");
2560 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2561 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2562 pa_sink_put(u->sink);
2564 if (u->sink->set_volume)
2565 u->sink->set_volume(u->sink);
2569 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2570 pa_source_set_rtpoll(u->source, u->rtpoll);
2571 pa_source_put(u->source);
2573 if (u->source->set_volume)
2574 u->source->set_volume(u->source);
2580 static void save_sco_volume_callbacks(struct userdata *u) {
2582 pa_assert(USE_SCO_OVER_PCM(u));
2584 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2585 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2588 static void restore_sco_volume_callbacks(struct userdata *u) {
2590 pa_assert(USE_SCO_OVER_PCM(u));
2592 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2593 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2596 /* Run from main thread */
2597 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2600 pa_queue *inputs = NULL, *outputs = NULL;
2601 const pa_bluetooth_device *device;
2604 pa_assert(new_profile);
2605 pa_assert_se(u = c->userdata);
2607 d = PA_CARD_PROFILE_DATA(new_profile);
2609 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2610 pa_log_error("Failed to get device object.");
2614 /* The state signal is sent by bluez, so it is racy to check
2615 strictly for CONNECTED, we should also accept STREAMING state
2616 as being good enough. However, if the profile is used
2617 concurrently (which is unlikely), ipc will fail later on, and
2618 module will be unloaded. */
2619 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2620 pa_log_warn("HSP is not connected, refused to switch profile");
2623 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2624 pa_log_warn("A2DP is not connected, refused to switch profile");
2627 else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2628 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2633 inputs = pa_sink_move_all_start(u->sink, NULL);
2635 if (!USE_SCO_OVER_PCM(u))
2636 pa_sink_unlink(u->sink);
2640 outputs = pa_source_move_all_start(u->source, NULL);
2642 if (!USE_SCO_OVER_PCM(u))
2643 pa_source_unlink(u->source);
2648 if (u->profile != PROFILE_OFF && u->transport) {
2649 bt_transport_release(u);
2650 pa_xfree(u->transport);
2651 u->transport = NULL;
2656 if (USE_SCO_OVER_PCM(u))
2657 restore_sco_volume_callbacks(u);
2660 u->sample_spec = u->requested_sample_spec;
2662 if (USE_SCO_OVER_PCM(u))
2663 save_sco_volume_callbacks(u);
2667 if (u->profile != PROFILE_OFF)
2670 if (u->sink || u->source)
2675 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2677 pa_sink_move_all_fail(inputs);
2682 pa_source_move_all_finish(u->source, outputs, FALSE);
2684 pa_source_move_all_fail(outputs);
2690 /* Run from main thread */
2691 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2692 pa_card_new_data data;
2698 const char *default_profile;
2703 pa_card_new_data_init(&data);
2704 data.driver = __FILE__;
2705 data.module = u->module;
2707 n = pa_bluetooth_cleanup_name(device->name);
2708 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2710 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2711 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2712 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2713 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2714 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2715 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2716 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2717 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2718 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2719 data.name = get_name("card", u->modargs, device->address, &b);
2720 data.namereg_fail = b;
2722 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2723 pa_log("Invalid properties");
2724 pa_card_new_data_done(&data);
2728 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2730 /* we base hsp/a2dp availability on UUIDs.
2731 Ideally, it would be based on "Connected" state, but
2732 we can't afford to wait for this information when
2733 we are loaded with profile="hsp", for instance */
2734 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2735 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2739 p->max_sink_channels = 2;
2740 p->max_source_channels = 0;
2742 d = PA_CARD_PROFILE_DATA(p);
2745 pa_hashmap_put(data.profiles, p->name, p);
2748 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2749 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2753 p->max_sink_channels = 0;
2754 p->max_source_channels = 2;
2756 d = PA_CARD_PROFILE_DATA(p);
2757 *d = PROFILE_A2DP_SOURCE;
2759 pa_hashmap_put(data.profiles, p->name, p);
2762 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2763 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2764 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2768 p->max_sink_channels = 1;
2769 p->max_source_channels = 1;
2771 d = PA_CARD_PROFILE_DATA(p);
2774 pa_hashmap_put(data.profiles, p->name, p);
2777 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2778 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2782 p->max_sink_channels = 1;
2783 p->max_source_channels = 1;
2785 d = PA_CARD_PROFILE_DATA(p);
2788 pa_hashmap_put(data.profiles, p->name, p);
2791 pa_assert(!pa_hashmap_isempty(data.profiles));
2793 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2794 d = PA_CARD_PROFILE_DATA(p);
2796 pa_hashmap_put(data.profiles, p->name, p);
2798 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2799 if (pa_hashmap_get(data.profiles, default_profile))
2800 pa_card_new_data_set_profile(&data, default_profile);
2802 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2805 u->card = pa_card_new(u->core, &data);
2806 pa_card_new_data_done(&data);
2809 pa_log("Failed to allocate card.");
2813 u->card->userdata = u;
2814 u->card->set_profile = card_set_profile;
2816 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2818 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2819 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2820 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2821 pa_log_warn("Default profile not connected, selecting off profile");
2822 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2823 u->card->save_profile = FALSE;
2826 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2829 if (USE_SCO_OVER_PCM(u))
2830 save_sco_volume_callbacks(u);
2835 /* Run from main thread */
2836 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2837 const pa_bluetooth_device *d = NULL;
2841 if (!address && !path) {
2842 pa_log_error("Failed to get device address/path from module arguments.");
2847 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2848 pa_log_error("%s is not a valid BlueZ audio device.", path);
2852 if (address && !(pa_streq(d->address, address))) {
2853 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2858 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2859 pa_log_error("%s is not known.", address);
2865 u->address = pa_xstrdup(d->address);
2866 u->path = pa_xstrdup(d->path);
2872 /* Run from main thread */
2873 static int setup_dbus(struct userdata *u) {
2876 dbus_error_init(&err);
2878 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2880 if (dbus_error_is_set(&err) || !u->connection) {
2881 pa_log("Failed to get D-Bus connection: %s", err.message);
2882 dbus_error_free(&err);
2889 int pa__init(pa_module* m) {
2893 const char *address, *path;
2895 char *mike, *speaker;
2896 const pa_bluetooth_device *device;
2900 dbus_error_init(&err);
2902 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2903 pa_log_error("Failed to parse module arguments");
2907 m->userdata = u = pa_xnew0(struct userdata, 1);
2912 u->sample_spec = m->core->default_sample_spec;
2915 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2916 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2917 pa_log("SCO sink not found");
2921 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2922 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2923 pa_log("SCO source not found");
2927 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2928 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2929 pa_log_error("Failed to get rate from module arguments");
2933 u->auto_connect = TRUE;
2934 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2935 pa_log("Failed to parse auto_connect= argument");
2939 channels = u->sample_spec.channels;
2940 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2941 channels <= 0 || channels > PA_CHANNELS_MAX) {
2942 pa_log_error("Failed to get channels from module arguments");
2945 u->sample_spec.channels = (uint8_t) channels;
2946 u->requested_sample_spec = u->sample_spec;
2948 address = pa_modargs_get_value(ma, "address", NULL);
2949 path = pa_modargs_get_value(ma, "path", NULL);
2951 if (setup_dbus(u) < 0)
2954 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2957 if (!(device = find_device(u, address, path)))
2960 /* Add the card structure. This will also initialize the default profile */
2961 if (add_card(u, device) < 0)
2964 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2967 u->msg->parent.process_msg = device_process_msg;
2968 u->msg->card = u->card;
2970 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2971 pa_log_error("Failed to add filter function");
2974 u->filter_added = TRUE;
2976 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2977 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2979 if (pa_dbus_add_matches(
2980 pa_dbus_connection_get(u->connection), &err,
2983 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2984 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2990 pa_log("Failed to add D-Bus matches: %s", err.message);
2997 /* Connect to the BT service */
3000 if (u->profile != PROFILE_OFF)
3001 if (init_profile(u) < 0)
3004 if (u->sink || u->source)
3005 if (start_thread(u) < 0)
3014 dbus_error_free(&err);
3019 int pa__get_n_used(pa_module *m) {
3023 pa_assert_se(u = m->userdata);
3026 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
3027 (u->source ? pa_source_linked_by(u->source) : 0);
3030 void pa__done(pa_module *m) {
3035 if (!(u = m->userdata))
3038 if (u->sink && !USE_SCO_OVER_PCM(u))
3039 pa_sink_unlink(u->sink);
3041 if (u->source && !USE_SCO_OVER_PCM(u))
3042 pa_source_unlink(u->source);
3046 if (USE_SCO_OVER_PCM(u))
3047 restore_sco_volume_callbacks(u);
3049 if (u->connection) {
3052 char *speaker, *mike;
3053 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
3054 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
3056 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
3057 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
3058 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
3065 if (u->filter_added)
3066 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
3068 pa_dbus_connection_unref(u->connection);
3075 pa_card_free(u->card);
3077 if (u->read_smoother)
3078 pa_smoother_free(u->read_smoother);
3083 pa_xfree(u->a2dp.buffer);
3085 sbc_finish(&u->a2dp.sbc);
3088 pa_modargs_free(u->modargs);
3090 pa_xfree(u->address);
3094 bt_transport_release(u);
3095 pa_xfree(u->transport);
3099 pa_bluetooth_discovery_unref(u->discovery);