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/i18n.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.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/socket-util.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/poll.h>
46 #include <pulsecore/rtpoll.h>
47 #include <pulsecore/time-smoother.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
50 #include <pulsecore/llist.h>
52 #include "module-bluetooth-device-symdef.h"
56 #include "bluetooth-util.h"
58 #define MAX_BITPOOL 64
59 #define MIN_BITPOOL 2U
61 #define BITPOOL_DEC_LIMIT 32
62 #define BITPOOL_DEC_STEP 5
64 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
65 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
66 PA_MODULE_VERSION(PACKAGE_VERSION);
67 PA_MODULE_LOAD_ONCE(FALSE);
69 "name=<name for the card/sink/source, to be prefixed> "
70 "card_name=<name for the card> "
71 "card_properties=<properties for the card> "
72 "sink_name=<name for the sink> "
73 "sink_properties=<properties for the sink> "
74 "source_name=<name for the source> "
75 "source_properties=<properties for the source> "
76 "address=<address of the device> "
77 "profile=<a2dp|hsp|hfgw> "
79 "channels=<number of channels> "
80 "path=<device object path> "
81 "auto_connect=<automatically connect?>");
85 "sco_sink=<SCO over PCM sink name> "
86 "sco_source=<SCO over PCM source name>"
90 /* TODO: not close fd when entering suspend mode in a2dp */
92 static const char* const valid_modargs[] = {
114 sbc_capabilities_t sbc_capabilities;
115 sbc_t sbc; /* Codec data */
116 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
117 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
119 void* buffer; /* Codec transfer buffer */
120 size_t buffer_size; /* Size of the buffer */
122 uint16_t seq_num; /* Cumulative packet sequence */
128 pcm_capabilities_t pcm_capabilities;
131 pa_source *sco_source;
133 pa_hook_slot *sink_state_changed_slot;
134 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) {
206 pa_assert(msg->length > 0);
208 if (u->service_fd < 0) {
209 pa_log_warn("Service not connected");
213 pa_log_debug("Sending %s -> %s",
214 pa_strnull(bt_audio_strtype(msg->type)),
215 pa_strnull(bt_audio_strname(msg->name)));
217 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
221 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
223 pa_log_error("Short write()");
228 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
232 pa_assert(u->service_fd >= 0);
234 pa_assert(room >= sizeof(*msg));
236 pa_log_debug("Trying to receive message from audio service...");
238 /* First, read the header */
239 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
242 if (msg->length < sizeof(*msg)) {
243 pa_log_error("Invalid message size.");
247 if (msg->length > room) {
248 pa_log_error("Not enough room.");
252 /* Secondly, read the payload */
253 if (msg->length > sizeof(*msg)) {
255 size_t remains = msg->length - sizeof(*msg);
257 if ((r = pa_loop_read(u->service_fd,
258 (uint8_t*) msg + sizeof(*msg),
260 &u->service_read_type)) != (ssize_t) remains)
264 pa_log_debug("Received %s <- %s",
265 pa_strnull(bt_audio_strtype(msg->type)),
266 pa_strnull(bt_audio_strname(msg->name)));
273 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
275 pa_log_error("Short read()");
280 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) {
284 pa_assert(u->service_fd >= 0);
287 if ((r = service_recv(u, rsp, room)) < 0)
290 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
291 rsp->name != expected_name ||
292 (expected_size > 0 && rsp->length != expected_size)) {
294 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
295 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
297 pa_log_error("Bogus message %s received while %s was expected",
298 pa_strnull(bt_audio_strname(rsp->name)),
299 pa_strnull(bt_audio_strname(expected_name)));
306 /* Run from main thread */
307 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
309 const codec_capabilities_t *codec;
314 bytes_left = rsp->h.length - sizeof(*rsp);
316 if (bytes_left < sizeof(codec_capabilities_t)) {
317 pa_log_error("Packet too small to store codec information.");
321 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
323 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
325 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
326 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
327 pa_log_error("Got capabilities for wrong codec.");
331 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
333 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
336 pa_assert(codec->type == BT_HFP_CODEC_PCM);
338 if (codec->configured && seid == 0)
341 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
343 } else if (u->profile == PROFILE_A2DP) {
345 while (bytes_left > 0) {
346 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
349 bytes_left -= codec->length;
350 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
353 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
356 pa_assert(codec->type == BT_A2DP_SBC_SINK);
358 if (codec->configured && seid == 0)
361 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
363 } else if (u->profile == PROFILE_A2DP_SOURCE) {
365 while (bytes_left > 0) {
366 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
369 bytes_left -= codec->length;
370 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
373 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
376 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
378 if (codec->configured && seid == 0)
381 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
387 /* Run from main thread */
388 static int get_caps(struct userdata *u, uint8_t seid) {
390 struct bt_get_capabilities_req getcaps_req;
391 struct bt_get_capabilities_rsp getcaps_rsp;
392 bt_audio_error_t error;
393 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
399 memset(&msg, 0, sizeof(msg));
400 msg.getcaps_req.h.type = BT_REQUEST;
401 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
402 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
403 msg.getcaps_req.seid = seid;
405 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
406 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
407 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
409 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
410 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
412 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
414 if (service_send(u, &msg.getcaps_req.h) < 0)
417 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
420 ret = parse_caps(u, seid, &msg.getcaps_rsp);
424 return get_caps(u, ret);
427 /* Run from main thread */
428 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
431 case BT_SBC_SAMPLING_FREQ_16000:
432 case BT_SBC_SAMPLING_FREQ_32000:
435 case BT_SBC_SAMPLING_FREQ_44100:
438 case BT_A2DP_CHANNEL_MODE_MONO:
439 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
442 case BT_A2DP_CHANNEL_MODE_STEREO:
443 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
447 pa_log_warn("Invalid channel mode %u", mode);
451 case BT_SBC_SAMPLING_FREQ_48000:
454 case BT_A2DP_CHANNEL_MODE_MONO:
455 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
458 case BT_A2DP_CHANNEL_MODE_STEREO:
459 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
463 pa_log_warn("Invalid channel mode %u", mode);
468 pa_log_warn("Invalid sampling freq %u", freq);
473 /* Run from main thread */
474 static int setup_a2dp(struct userdata *u) {
475 sbc_capabilities_t *cap;
478 static const struct {
482 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
483 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
484 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
485 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
489 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
491 cap = &u->a2dp.sbc_capabilities;
493 /* Find the lowest freq that is at least as high as the requested
495 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
496 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
497 u->sample_spec.rate = freq_table[i].rate;
498 cap->frequency = freq_table[i].cap;
502 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
503 for (--i; i >= 0; i--) {
504 if (cap->frequency & freq_table[i].cap) {
505 u->sample_spec.rate = freq_table[i].rate;
506 cap->frequency = freq_table[i].cap;
512 pa_log("Not suitable sample rate");
517 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
519 if (cap->capability.configured)
522 if (u->sample_spec.channels <= 1) {
523 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
524 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
525 u->sample_spec.channels = 1;
527 u->sample_spec.channels = 2;
530 if (u->sample_spec.channels >= 2) {
531 u->sample_spec.channels = 2;
533 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
534 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
535 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
536 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
537 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
538 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
539 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
540 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
541 u->sample_spec.channels = 1;
543 pa_log("No supported channel modes");
548 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
549 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
550 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
551 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
552 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
553 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
554 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
555 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
557 pa_log_error("No supported block lengths");
561 if (cap->subbands & BT_A2DP_SUBBANDS_8)
562 cap->subbands = BT_A2DP_SUBBANDS_8;
563 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
564 cap->subbands = BT_A2DP_SUBBANDS_4;
566 pa_log_error("No supported subbands");
570 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
571 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
572 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
573 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
575 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
576 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
581 /* Run from main thread */
582 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
583 sbc_capabilities_t *active_capabilities;
587 active_capabilities = &a2dp->sbc_capabilities;
589 if (a2dp->sbc_initialized)
590 sbc_reinit(&a2dp->sbc, 0);
592 sbc_init(&a2dp->sbc, 0);
593 a2dp->sbc_initialized = TRUE;
595 switch (active_capabilities->frequency) {
596 case BT_SBC_SAMPLING_FREQ_16000:
597 a2dp->sbc.frequency = SBC_FREQ_16000;
599 case BT_SBC_SAMPLING_FREQ_32000:
600 a2dp->sbc.frequency = SBC_FREQ_32000;
602 case BT_SBC_SAMPLING_FREQ_44100:
603 a2dp->sbc.frequency = SBC_FREQ_44100;
605 case BT_SBC_SAMPLING_FREQ_48000:
606 a2dp->sbc.frequency = SBC_FREQ_48000;
609 pa_assert_not_reached();
612 switch (active_capabilities->channel_mode) {
613 case BT_A2DP_CHANNEL_MODE_MONO:
614 a2dp->sbc.mode = SBC_MODE_MONO;
616 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
617 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
619 case BT_A2DP_CHANNEL_MODE_STEREO:
620 a2dp->sbc.mode = SBC_MODE_STEREO;
622 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
623 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
626 pa_assert_not_reached();
629 switch (active_capabilities->allocation_method) {
630 case BT_A2DP_ALLOCATION_SNR:
631 a2dp->sbc.allocation = SBC_AM_SNR;
633 case BT_A2DP_ALLOCATION_LOUDNESS:
634 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
637 pa_assert_not_reached();
640 switch (active_capabilities->subbands) {
641 case BT_A2DP_SUBBANDS_4:
642 a2dp->sbc.subbands = SBC_SB_4;
644 case BT_A2DP_SUBBANDS_8:
645 a2dp->sbc.subbands = SBC_SB_8;
648 pa_assert_not_reached();
651 switch (active_capabilities->block_length) {
652 case BT_A2DP_BLOCK_LENGTH_4:
653 a2dp->sbc.blocks = SBC_BLK_4;
655 case BT_A2DP_BLOCK_LENGTH_8:
656 a2dp->sbc.blocks = SBC_BLK_8;
658 case BT_A2DP_BLOCK_LENGTH_12:
659 a2dp->sbc.blocks = SBC_BLK_12;
661 case BT_A2DP_BLOCK_LENGTH_16:
662 a2dp->sbc.blocks = SBC_BLK_16;
665 pa_assert_not_reached();
668 a2dp->min_bitpool = active_capabilities->min_bitpool;
669 a2dp->max_bitpool = active_capabilities->max_bitpool;
671 /* Set minimum bitpool for source to get the maximum possible block_size */
672 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
673 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
674 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
677 /* Run from main thread */
678 static int set_conf(struct userdata *u) {
680 struct bt_open_req open_req;
681 struct bt_open_rsp open_rsp;
682 struct bt_set_configuration_req setconf_req;
683 struct bt_set_configuration_rsp setconf_rsp;
684 bt_audio_error_t error;
685 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
688 memset(&msg, 0, sizeof(msg));
689 msg.open_req.h.type = BT_REQUEST;
690 msg.open_req.h.name = BT_OPEN;
691 msg.open_req.h.length = sizeof(msg.open_req);
693 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
694 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
695 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
697 if (service_send(u, &msg.open_req.h) < 0)
700 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
703 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
704 u->sample_spec.format = PA_SAMPLE_S16LE;
706 if (setup_a2dp(u) < 0)
709 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
711 u->sample_spec.format = PA_SAMPLE_S16LE;
712 u->sample_spec.channels = 1;
713 u->sample_spec.rate = 8000;
716 memset(&msg, 0, sizeof(msg));
717 msg.setconf_req.h.type = BT_REQUEST;
718 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
719 msg.setconf_req.h.length = sizeof(msg.setconf_req);
721 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
722 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
724 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
725 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
726 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
728 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
730 if (service_send(u, &msg.setconf_req.h) < 0)
733 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
736 u->link_mtu = msg.setconf_rsp.link_mtu;
738 /* setup SBC encoder now we agree on parameters */
739 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
740 setup_sbc(&u->a2dp, u->profile);
743 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
744 / u->a2dp.frame_length
747 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
748 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
750 u->block_size = u->link_mtu;
756 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
758 struct a2dp_info *a2dp;
764 if (a2dp->sbc.bitpool == bitpool)
767 if (bitpool > a2dp->max_bitpool)
768 bitpool = a2dp->max_bitpool;
769 else if (bitpool < a2dp->min_bitpool)
770 bitpool = a2dp->min_bitpool;
772 a2dp->sbc.bitpool = bitpool;
774 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
775 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
777 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
780 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
781 / a2dp->frame_length * a2dp->codesize;
783 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
784 pa_sink_set_fixed_latency_within_thread(u->sink,
785 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
788 /* from IO thread, except in SCO over PCM */
790 static int setup_stream(struct userdata *u) {
791 struct pollfd *pollfd;
794 pa_make_fd_nonblock(u->stream_fd);
795 pa_make_socket_low_delay(u->stream_fd);
798 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
799 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
801 pa_log_debug("Stream properly set up, we're ready to roll!");
803 if (u->profile == PROFILE_A2DP)
804 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
806 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
807 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
808 pollfd->fd = u->stream_fd;
809 pollfd->events = pollfd->revents = 0;
811 u->read_index = u->write_index = 0;
815 u->read_smoother = pa_smoother_new(
827 static int start_stream_fd(struct userdata *u) {
829 bt_audio_msg_header_t rsp;
830 struct bt_start_stream_req start_req;
831 struct bt_start_stream_rsp start_rsp;
832 struct bt_new_stream_ind streamfd_ind;
833 bt_audio_error_t error;
834 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
838 pa_assert(u->rtpoll);
839 pa_assert(!u->rtpoll_item);
840 pa_assert(u->stream_fd < 0);
842 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
843 msg.start_req.h.type = BT_REQUEST;
844 msg.start_req.h.name = BT_START_STREAM;
845 msg.start_req.h.length = sizeof(msg.start_req);
847 if (service_send(u, &msg.start_req.h) < 0)
850 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
853 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
856 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
857 pa_log("Failed to get stream fd from audio service.");
861 return setup_stream(u);
865 static int stop_stream_fd(struct userdata *u) {
867 bt_audio_msg_header_t rsp;
868 struct bt_stop_stream_req start_req;
869 struct bt_stop_stream_rsp start_rsp;
870 bt_audio_error_t error;
871 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
876 pa_assert(u->rtpoll);
878 if (u->rtpoll_item) {
879 pa_rtpoll_item_free(u->rtpoll_item);
880 u->rtpoll_item = NULL;
883 if (u->stream_fd >= 0) {
884 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
885 msg.start_req.h.type = BT_REQUEST;
886 msg.start_req.h.name = BT_STOP_STREAM;
887 msg.start_req.h.length = sizeof(msg.start_req);
889 if (service_send(u, &msg.start_req.h) < 0 ||
890 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
893 pa_close(u->stream_fd);
897 if (u->read_smoother) {
898 pa_smoother_free(u->read_smoother);
899 u->read_smoother = NULL;
905 static void bt_transport_release(struct userdata *u) {
906 const char *accesstype = "rw";
907 const pa_bluetooth_transport *t;
909 /* Ignore if already released */
913 pa_log_debug("Releasing transport %s", u->transport);
915 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
917 pa_bluetooth_transport_release(t, accesstype);
919 pa_xfree(u->accesstype);
920 u->accesstype = NULL;
922 if (u->rtpoll_item) {
923 pa_rtpoll_item_free(u->rtpoll_item);
924 u->rtpoll_item = NULL;
927 if (u->stream_fd >= 0) {
928 pa_close(u->stream_fd);
932 if (u->read_smoother) {
933 pa_smoother_free(u->read_smoother);
934 u->read_smoother = NULL;
938 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
939 const char *accesstype = "rw";
940 const pa_bluetooth_transport *t;
948 pa_log_debug("Acquiring transport %s", u->transport);
950 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
952 pa_log("Transport %s no longer available", u->transport);
953 pa_xfree(u->transport);
958 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
959 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
960 if (u->stream_fd < 0)
963 u->accesstype = pa_xstrdup(accesstype);
964 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
970 pa_log_info("Transport %s resuming", u->transport);
971 return setup_stream(u);
974 /* Run from IO thread */
975 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
976 struct userdata *u = PA_SINK(o)->userdata;
977 pa_bool_t failed = FALSE;
980 pa_assert(u->sink == PA_SINK(o));
984 case PA_SINK_MESSAGE_SET_STATE:
986 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
988 case PA_SINK_SUSPENDED:
989 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
991 /* Stop the device if the source is suspended as well */
992 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
993 /* We deliberately ignore whether stopping
994 * actually worked. Since the stream_fd is
995 * closed it doesn't really matter */
997 bt_transport_release(u);
1005 case PA_SINK_RUNNING:
1006 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1009 /* Resume the device if the source was suspended as well */
1010 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1012 if (bt_transport_acquire(u, TRUE) < 0)
1014 } else if (start_stream_fd(u) < 0)
1019 case PA_SINK_UNLINKED:
1021 case PA_SINK_INVALID_STATE:
1026 case PA_SINK_MESSAGE_GET_LATENCY: {
1028 if (u->read_smoother) {
1031 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1032 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1034 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1038 ri = pa_rtclock_now() - u->started_at;
1039 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1041 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1044 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1049 r = pa_sink_process_msg(o, code, data, offset, chunk);
1051 return (r < 0 || !failed) ? r : -1;
1054 /* Run from IO thread */
1055 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1056 struct userdata *u = PA_SOURCE(o)->userdata;
1057 pa_bool_t failed = FALSE;
1060 pa_assert(u->source == PA_SOURCE(o));
1064 case PA_SOURCE_MESSAGE_SET_STATE:
1066 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1068 case PA_SOURCE_SUSPENDED:
1069 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1071 /* Stop the device if the sink is suspended as well */
1072 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1074 bt_transport_release(u);
1079 if (u->read_smoother)
1080 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1083 case PA_SOURCE_IDLE:
1084 case PA_SOURCE_RUNNING:
1085 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1088 /* Resume the device if the sink was suspended as well */
1089 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1091 if (bt_transport_acquire(u, TRUE) < 0)
1093 } else if (start_stream_fd(u) < 0)
1096 /* We don't resume the smoother here. Instead we
1097 * wait until the first packet arrives */
1100 case PA_SOURCE_UNLINKED:
1101 case PA_SOURCE_INIT:
1102 case PA_SOURCE_INVALID_STATE:
1107 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1110 if (u->read_smoother) {
1111 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1112 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1114 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1116 *((pa_usec_t*) data) = 0;
1123 r = pa_source_process_msg(o, code, data, offset, chunk);
1125 return (r < 0 || !failed) ? r : -1;
1128 /* Run from IO thread */
1129 static int hsp_process_render(struct userdata *u) {
1133 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1136 /* First, render some data */
1137 if (!u->write_memchunk.memblock)
1138 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1140 pa_assert(u->write_memchunk.length == u->block_size);
1146 /* Now write that data to the socket. The socket is of type
1147 * SEQPACKET, and we generated the data of the MTU size, so this
1148 * should just work. */
1150 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1151 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1152 pa_memblock_release(u->write_memchunk.memblock);
1159 /* Retry right away if we got interrupted */
1162 else if (errno == EAGAIN)
1163 /* Hmm, apparently the socket was not writable, give up for now */
1166 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1171 pa_assert((size_t) l <= u->write_memchunk.length);
1173 if ((size_t) l != u->write_memchunk.length) {
1174 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1175 (unsigned long long) l,
1176 (unsigned long long) u->write_memchunk.length);
1181 u->write_index += (uint64_t) u->write_memchunk.length;
1182 pa_memblock_unref(u->write_memchunk.memblock);
1183 pa_memchunk_reset(&u->write_memchunk);
1192 /* Run from IO thread */
1193 static int hsp_process_push(struct userdata *u) {
1195 pa_memchunk memchunk;
1198 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1199 pa_assert(u->source);
1200 pa_assert(u->read_smoother);
1202 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1203 memchunk.index = memchunk.length = 0;
1212 pa_bool_t found_tstamp = FALSE;
1215 memset(&m, 0, sizeof(m));
1216 memset(&aux, 0, sizeof(aux));
1217 memset(&iov, 0, sizeof(iov));
1221 m.msg_control = aux;
1222 m.msg_controllen = sizeof(aux);
1224 p = pa_memblock_acquire(memchunk.memblock);
1226 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1227 l = recvmsg(u->stream_fd, &m, 0);
1228 pa_memblock_release(memchunk.memblock);
1232 if (l < 0 && errno == EINTR)
1233 /* Retry right away if we got interrupted */
1236 else if (l < 0 && errno == EAGAIN)
1237 /* Hmm, apparently the socket was not readable, give up for now. */
1240 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1245 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1247 memchunk.length = (size_t) l;
1248 u->read_index += (uint64_t) l;
1250 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1251 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1252 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1253 pa_rtclock_from_wallclock(tv);
1254 tstamp = pa_timeval_load(tv);
1255 found_tstamp = TRUE;
1259 if (!found_tstamp) {
1260 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1261 tstamp = pa_rtclock_now();
1264 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1265 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1267 pa_source_post(u->source, &memchunk);
1273 pa_memblock_unref(memchunk.memblock);
1278 /* Run from IO thread */
1279 static void a2dp_prepare_buffer(struct userdata *u) {
1282 if (u->a2dp.buffer_size >= u->link_mtu)
1285 u->a2dp.buffer_size = 2 * u->link_mtu;
1286 pa_xfree(u->a2dp.buffer);
1287 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1290 /* Run from IO thread */
1291 static int a2dp_process_render(struct userdata *u) {
1292 struct a2dp_info *a2dp;
1293 struct rtp_header *header;
1294 struct rtp_payload *payload;
1298 size_t to_write, to_encode;
1299 unsigned frame_count;
1303 pa_assert(u->profile == PROFILE_A2DP);
1306 /* First, render some data */
1307 if (!u->write_memchunk.memblock)
1308 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1310 pa_assert(u->write_memchunk.length == u->block_size);
1312 a2dp_prepare_buffer(u);
1315 header = a2dp->buffer;
1316 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1320 /* Try to create a packet of the full MTU */
1322 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1323 to_encode = u->write_memchunk.length;
1325 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1326 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1328 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1332 encoded = sbc_encode(&a2dp->sbc,
1337 if (PA_UNLIKELY(encoded <= 0)) {
1338 pa_log_error("SBC encoding error (%li)", (long) encoded);
1339 pa_memblock_release(u->write_memchunk.memblock);
1343 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1344 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1346 pa_assert_fp((size_t) encoded <= to_encode);
1347 pa_assert_fp((size_t) encoded == a2dp->codesize);
1349 pa_assert_fp((size_t) written <= to_write);
1350 pa_assert_fp((size_t) written == a2dp->frame_length);
1352 p = (const uint8_t*) p + encoded;
1353 to_encode -= encoded;
1355 d = (uint8_t*) d + written;
1356 to_write -= written;
1361 pa_memblock_release(u->write_memchunk.memblock);
1363 pa_assert(to_encode == 0);
1366 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1369 /* write it to the fifo */
1370 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1373 header->sequence_number = htons(a2dp->seq_num++);
1374 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1375 header->ssrc = htonl(1);
1376 payload->frame_count = frame_count;
1378 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1383 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1390 /* Retry right away if we got interrupted */
1393 else if (errno == EAGAIN)
1394 /* Hmm, apparently the socket was not writable, give up for now */
1397 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1402 pa_assert((size_t) l <= nbytes);
1404 if ((size_t) l != nbytes) {
1405 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1406 (unsigned long long) l,
1407 (unsigned long long) nbytes);
1412 u->write_index += (uint64_t) u->write_memchunk.length;
1413 pa_memblock_unref(u->write_memchunk.memblock);
1414 pa_memchunk_reset(&u->write_memchunk);
1424 static int a2dp_process_push(struct userdata *u) {
1426 pa_memchunk memchunk;
1429 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1430 pa_assert(u->source);
1431 pa_assert(u->read_smoother);
1433 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1434 memchunk.index = memchunk.length = 0;
1437 pa_bool_t found_tstamp = FALSE;
1439 struct a2dp_info *a2dp;
1440 struct rtp_header *header;
1441 struct rtp_payload *payload;
1445 size_t to_write, to_decode;
1446 unsigned frame_count;
1448 a2dp_prepare_buffer(u);
1451 header = a2dp->buffer;
1452 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1454 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1458 if (l < 0 && errno == EINTR)
1459 /* Retry right away if we got interrupted */
1462 else if (l < 0 && errno == EAGAIN)
1463 /* Hmm, apparently the socket was not readable, give up for now. */
1466 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1471 pa_assert((size_t) l <= a2dp->buffer_size);
1473 u->read_index += (uint64_t) l;
1475 /* TODO: get timestamp from rtp */
1476 if (!found_tstamp) {
1477 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1478 tstamp = pa_rtclock_now();
1481 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1482 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1484 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1485 to_decode = l - sizeof(*header) - sizeof(*payload);
1487 d = pa_memblock_acquire(memchunk.memblock);
1488 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1490 while (PA_LIKELY(to_decode > 0)) {
1494 decoded = sbc_decode(&a2dp->sbc,
1499 if (PA_UNLIKELY(decoded <= 0)) {
1500 pa_log_error("SBC decoding error (%li)", (long) decoded);
1501 pa_memblock_release(memchunk.memblock);
1502 pa_memblock_unref(memchunk.memblock);
1506 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1507 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1509 /* Reset frame length, it can be changed due to bitpool change */
1510 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1512 pa_assert_fp((size_t) decoded <= to_decode);
1513 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1515 pa_assert_fp((size_t) written == a2dp->codesize);
1517 p = (const uint8_t*) p + decoded;
1518 to_decode -= decoded;
1520 d = (uint8_t*) d + written;
1521 to_write -= written;
1526 memchunk.length -= to_write;
1528 pa_memblock_release(memchunk.memblock);
1530 pa_source_post(u->source, &memchunk);
1536 pa_memblock_unref(memchunk.memblock);
1541 static void a2dp_reduce_bitpool(struct userdata *u)
1543 struct a2dp_info *a2dp;
1550 /* Check if bitpool is already at its limit */
1551 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1554 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1556 if (bitpool < BITPOOL_DEC_LIMIT)
1557 bitpool = BITPOOL_DEC_LIMIT;
1559 a2dp_set_bitpool(u, bitpool);
1562 static void thread_func(void *userdata) {
1563 struct userdata *u = userdata;
1564 unsigned do_write = 0;
1565 pa_bool_t writable = FALSE;
1569 pa_log_debug("IO Thread starting up");
1571 if (u->core->realtime_scheduling)
1572 pa_make_realtime(u->core->realtime_priority);
1574 pa_thread_mq_install(&u->thread_mq);
1577 if (bt_transport_acquire(u, TRUE) < 0)
1579 } else if (start_stream_fd(u) < 0)
1583 struct pollfd *pollfd;
1585 pa_bool_t disable_timer = TRUE;
1587 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1589 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1591 /* We should send two blocks to the device before we expect
1594 if (u->write_index == 0 && u->read_index <= 0)
1597 if (pollfd && (pollfd->revents & POLLIN)) {
1600 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1601 n_read = hsp_process_push(u);
1603 n_read = a2dp_process_push(u);
1608 /* We just read something, so we are supposed to write something, too */
1613 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1615 if (u->sink->thread_info.rewind_requested)
1616 pa_sink_process_rewind(u->sink, 0);
1619 if (pollfd->revents & POLLOUT)
1622 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1623 pa_usec_t time_passed;
1624 pa_usec_t audio_sent;
1626 /* Hmm, there is no input stream we could synchronize
1627 * to. So let's do things by time */
1629 time_passed = pa_rtclock_now() - u->started_at;
1630 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1632 if (audio_sent <= time_passed) {
1633 pa_usec_t audio_to_send = time_passed - audio_sent;
1635 /* Never try to catch up for more than 100ms */
1636 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1637 pa_usec_t skip_usec;
1638 uint64_t skip_bytes;
1640 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1641 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1643 if (skip_bytes > 0) {
1646 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1647 (unsigned long long) skip_usec,
1648 (unsigned long long) skip_bytes);
1650 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1651 pa_memblock_unref(tmp.memblock);
1652 u->write_index += skip_bytes;
1654 if (u->profile == PROFILE_A2DP)
1655 a2dp_reduce_bitpool(u);
1663 if (writable && do_write > 0) {
1666 if (u->write_index <= 0)
1667 u->started_at = pa_rtclock_now();
1669 if (u->profile == PROFILE_A2DP) {
1670 if ((n_written = a2dp_process_render(u)) < 0)
1673 if ((n_written = hsp_process_render(u)) < 0)
1678 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1680 do_write -= n_written;
1684 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1685 pa_usec_t time_passed, next_write_at, sleep_for;
1687 /* Hmm, there is no input stream we could synchronize
1688 * to. So let's estimate when we need to wake up the latest */
1690 time_passed = pa_rtclock_now() - u->started_at;
1691 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1692 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1694 /* 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); */
1696 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1697 disable_timer = FALSE;
1703 pa_rtpoll_set_timer_disabled(u->rtpoll);
1705 /* Hmm, nothing to do. Let's sleep */
1707 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1708 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1710 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1716 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1718 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1719 pa_log_info("FD error: %s%s%s%s",
1720 pollfd->revents & POLLERR ? "POLLERR " :"",
1721 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1722 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1723 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1729 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1730 pa_log_debug("IO thread failed");
1731 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1732 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1735 pa_log_debug("IO thread shutting down");
1738 /* Run from main thread */
1739 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1745 pa_assert_se(u = userdata);
1747 dbus_error_init(&err);
1749 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1750 dbus_message_get_interface(m),
1751 dbus_message_get_path(m),
1752 dbus_message_get_member(m));
1754 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1757 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1758 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1763 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1764 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1768 if (u->profile == PROFILE_HSP) {
1769 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1771 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1772 pa_sink_volume_changed(u->sink, &v);
1774 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1776 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1777 pa_source_volume_changed(u->source, &v);
1780 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1781 DBusMessageIter arg_i;
1782 pa_bluetooth_transport *t;
1785 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1788 if (!dbus_message_iter_init(m, &arg_i)) {
1789 pa_log("Failed to parse PropertyChanged: %s", err.message);
1795 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1798 if (nrec != t->nrec) {
1799 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1800 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1805 dbus_error_free(&err);
1807 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1810 /* Run from main thread */
1811 static void sink_set_volume_cb(pa_sink *s) {
1812 struct userdata *u = s->userdata;
1818 if (u->profile != PROFILE_HSP)
1821 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1826 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1828 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1829 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1830 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1831 dbus_message_unref(m);
1834 /* Run from main thread */
1835 static void source_set_volume_cb(pa_source *s) {
1836 struct userdata *u = s->userdata;
1842 if (u->profile != PROFILE_HSP)
1845 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1850 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1852 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1853 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1854 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1855 dbus_message_unref(m);
1858 /* Run from main thread */
1859 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1865 pa_assert(device_id);
1866 pa_assert(namereg_fail);
1868 t = pa_sprintf_malloc("%s_name", type);
1869 n = pa_modargs_get_value(ma, t, NULL);
1873 *namereg_fail = TRUE;
1874 return pa_xstrdup(n);
1877 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1878 *namereg_fail = TRUE;
1881 *namereg_fail = FALSE;
1884 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1889 static void sco_over_pcm_state_update(struct userdata *u) {
1891 pa_assert(USE_SCO_OVER_PCM(u));
1893 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1894 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1896 if (u->service_fd >= 0)
1901 pa_log_debug("Resuming SCO over PCM");
1902 if (init_profile(u) < 0)
1903 pa_log("Can't resume SCO over PCM");
1906 bt_transport_acquire(u, TRUE);
1911 if (u->service_fd < 0)
1915 bt_transport_release(u);
1919 pa_log_debug("Closing SCO over PCM");
1920 pa_close(u->service_fd);
1925 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1927 pa_sink_assert_ref(s);
1930 if (s != u->hsp.sco_sink)
1933 sco_over_pcm_state_update(u);
1938 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1940 pa_source_assert_ref(s);
1943 if (s != u->hsp.sco_source)
1946 sco_over_pcm_state_update(u);
1953 /* Run from main thread */
1954 static int add_sink(struct userdata *u) {
1957 if (USE_SCO_OVER_PCM(u)) {
1960 u->sink = u->hsp.sco_sink;
1961 p = pa_proplist_new();
1962 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1963 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1964 pa_proplist_free(p);
1966 if (!u->hsp.sink_state_changed_slot)
1967 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);
1973 pa_sink_new_data data;
1976 pa_sink_new_data_init(&data);
1977 data.driver = __FILE__;
1978 data.module = u->module;
1979 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1980 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1981 if (u->profile == PROFILE_HSP)
1982 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1983 data.card = u->card;
1984 data.name = get_name("sink", u->modargs, u->address, &b);
1985 data.namereg_fail = b;
1987 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1988 pa_log("Invalid properties");
1989 pa_sink_new_data_done(&data);
1993 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1994 pa_sink_new_data_done(&data);
1997 pa_log_error("Failed to create sink");
2001 u->sink->userdata = u;
2002 u->sink->parent.process_msg = sink_process_msg;
2004 pa_sink_set_max_request(u->sink, u->block_size);
2005 pa_sink_set_fixed_latency(u->sink,
2006 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2007 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2010 if (u->profile == PROFILE_HSP) {
2011 u->sink->set_volume = sink_set_volume_cb;
2012 u->sink->n_volume_steps = 16;
2018 /* Run from main thread */
2019 static int add_source(struct userdata *u) {
2022 if (USE_SCO_OVER_PCM(u)) {
2023 u->source = u->hsp.sco_source;
2024 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2026 if (!u->hsp.source_state_changed_slot)
2027 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);
2033 pa_source_new_data data;
2036 pa_source_new_data_init(&data);
2037 data.driver = __FILE__;
2038 data.module = u->module;
2039 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2040 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2041 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2042 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2044 data.card = u->card;
2045 data.name = get_name("source", u->modargs, u->address, &b);
2046 data.namereg_fail = b;
2048 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2049 pa_log("Invalid properties");
2050 pa_source_new_data_done(&data);
2054 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2055 pa_source_new_data_done(&data);
2058 pa_log_error("Failed to create source");
2062 u->source->userdata = u;
2063 u->source->parent.process_msg = source_process_msg;
2065 pa_source_set_fixed_latency(u->source,
2066 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2067 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2070 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2072 const pa_bluetooth_transport *t;
2073 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2075 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2077 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2080 if (u->profile == PROFILE_HSP) {
2081 u->source->set_volume = source_set_volume_cb;
2082 u->source->n_volume_steps = 16;
2088 /* Run from main thread */
2089 static void shutdown_bt(struct userdata *u) {
2092 if (u->stream_fd >= 0) {
2093 pa_close(u->stream_fd);
2096 u->stream_write_type = 0;
2099 if (u->service_fd >= 0) {
2100 pa_close(u->service_fd);
2102 u->service_write_type = 0;
2103 u->service_read_type = 0;
2106 if (u->write_memchunk.memblock) {
2107 pa_memblock_unref(u->write_memchunk.memblock);
2108 pa_memchunk_reset(&u->write_memchunk);
2112 static int bt_transport_config_a2dp(struct userdata *u) {
2113 const pa_bluetooth_transport *t;
2114 struct a2dp_info *a2dp = &u->a2dp;
2115 sbc_capabilities_raw_t *config;
2117 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2120 config = (sbc_capabilities_raw_t *) t->config;
2122 if (a2dp->sbc_initialized)
2123 sbc_reinit(&a2dp->sbc, 0);
2125 sbc_init(&a2dp->sbc, 0);
2126 a2dp->sbc_initialized = TRUE;
2128 switch (config->frequency) {
2129 case BT_SBC_SAMPLING_FREQ_16000:
2130 a2dp->sbc.frequency = SBC_FREQ_16000;
2132 case BT_SBC_SAMPLING_FREQ_32000:
2133 a2dp->sbc.frequency = SBC_FREQ_32000;
2135 case BT_SBC_SAMPLING_FREQ_44100:
2136 a2dp->sbc.frequency = SBC_FREQ_44100;
2138 case BT_SBC_SAMPLING_FREQ_48000:
2139 a2dp->sbc.frequency = SBC_FREQ_48000;
2142 pa_assert_not_reached();
2145 switch (config->channel_mode) {
2146 case BT_A2DP_CHANNEL_MODE_MONO:
2147 a2dp->sbc.mode = SBC_MODE_MONO;
2149 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2150 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2152 case BT_A2DP_CHANNEL_MODE_STEREO:
2153 a2dp->sbc.mode = SBC_MODE_STEREO;
2155 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2156 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2159 pa_assert_not_reached();
2162 switch (config->allocation_method) {
2163 case BT_A2DP_ALLOCATION_SNR:
2164 a2dp->sbc.allocation = SBC_AM_SNR;
2166 case BT_A2DP_ALLOCATION_LOUDNESS:
2167 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2170 pa_assert_not_reached();
2173 switch (config->subbands) {
2174 case BT_A2DP_SUBBANDS_4:
2175 a2dp->sbc.subbands = SBC_SB_4;
2177 case BT_A2DP_SUBBANDS_8:
2178 a2dp->sbc.subbands = SBC_SB_8;
2181 pa_assert_not_reached();
2184 switch (config->block_length) {
2185 case BT_A2DP_BLOCK_LENGTH_4:
2186 a2dp->sbc.blocks = SBC_BLK_4;
2188 case BT_A2DP_BLOCK_LENGTH_8:
2189 a2dp->sbc.blocks = SBC_BLK_8;
2191 case BT_A2DP_BLOCK_LENGTH_12:
2192 a2dp->sbc.blocks = SBC_BLK_12;
2194 case BT_A2DP_BLOCK_LENGTH_16:
2195 a2dp->sbc.blocks = SBC_BLK_16;
2198 pa_assert_not_reached();
2201 a2dp->min_bitpool = config->min_bitpool;
2202 a2dp->max_bitpool = config->max_bitpool;
2204 /* Set minimum bitpool for source to get the maximum possible block_size */
2205 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2206 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2207 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2210 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2211 / a2dp->frame_length
2214 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2215 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2220 static int bt_transport_config(struct userdata *u) {
2221 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2222 u->block_size = u->link_mtu;
2226 return bt_transport_config_a2dp(u);
2229 /* Run from main thread */
2230 static int bt_transport_open(struct userdata *u) {
2231 if (bt_transport_acquire(u, FALSE) < 0)
2234 return bt_transport_config(u);
2237 /* Run from main thread */
2238 static int init_bt(struct userdata *u) {
2243 u->stream_write_type = 0;
2244 u->service_write_type = 0;
2245 u->service_read_type = 0;
2247 if ((u->service_fd = bt_audio_service_open()) < 0) {
2248 pa_log_warn("Bluetooth audio service not available");
2252 pa_log_debug("Connected to the bluetooth audio service");
2257 /* Run from main thread */
2258 static int setup_bt(struct userdata *u) {
2259 const pa_bluetooth_device *d;
2260 const pa_bluetooth_transport *t;
2264 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2265 pa_log_error("Failed to get device object.");
2269 /* release transport if exist */
2271 bt_transport_release(u);
2272 pa_xfree(u->transport);
2273 u->transport = NULL;
2276 /* check if profile has a transport */
2277 t = pa_bluetooth_device_get_transport(d, u->profile);
2279 u->transport = pa_xstrdup(t->path);
2280 return bt_transport_open(u);
2283 if (get_caps(u, 0) < 0)
2286 pa_log_debug("Got device capabilities");
2288 if (set_conf(u) < 0)
2291 pa_log_debug("Connection to the device configured");
2294 if (USE_SCO_OVER_PCM(u)) {
2295 pa_log_debug("Configured to use SCO over PCM");
2300 pa_log_debug("Got the stream socket");
2305 /* Run from main thread */
2306 static int init_profile(struct userdata *u) {
2309 pa_assert(u->profile != PROFILE_OFF);
2311 if (setup_bt(u) < 0)
2314 if (u->profile == PROFILE_A2DP ||
2315 u->profile == PROFILE_HSP ||
2316 u->profile == PROFILE_HFGW)
2317 if (add_sink(u) < 0)
2320 if (u->profile == PROFILE_HSP ||
2321 u->profile == PROFILE_A2DP_SOURCE ||
2322 u->profile == PROFILE_HFGW)
2323 if (add_source(u) < 0)
2329 /* Run from main thread */
2330 static void stop_thread(struct userdata *u) {
2334 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2335 pa_thread_free(u->thread);
2339 if (u->rtpoll_item) {
2340 pa_rtpoll_item_free(u->rtpoll_item);
2341 u->rtpoll_item = NULL;
2344 if (u->hsp.sink_state_changed_slot) {
2345 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2346 u->hsp.sink_state_changed_slot = NULL;
2349 if (u->hsp.source_state_changed_slot) {
2350 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2351 u->hsp.source_state_changed_slot = NULL;
2355 pa_sink_unref(u->sink);
2360 pa_source_unref(u->source);
2365 pa_thread_mq_done(&u->thread_mq);
2367 pa_rtpoll_free(u->rtpoll);
2371 if (u->read_smoother) {
2372 pa_smoother_free(u->read_smoother);
2373 u->read_smoother = NULL;
2377 /* Run from main thread */
2378 static int start_thread(struct userdata *u) {
2380 pa_assert(!u->thread);
2381 pa_assert(!u->rtpoll);
2382 pa_assert(!u->rtpoll_item);
2384 u->rtpoll = pa_rtpoll_new();
2385 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2388 if (USE_SCO_OVER_PCM(u)) {
2390 if (bt_transport_acquire(u, TRUE) < 0)
2392 } else if (start_stream_fd(u) < 0)
2395 pa_sink_ref(u->sink);
2396 pa_source_ref(u->source);
2397 /* FIXME: monitor stream_fd error */
2402 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2403 pa_log_error("Failed to create IO thread");
2409 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2410 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2411 pa_sink_put(u->sink);
2413 if (u->sink->set_volume)
2414 u->sink->set_volume(u->sink);
2418 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2419 pa_source_set_rtpoll(u->source, u->rtpoll);
2420 pa_source_put(u->source);
2422 if (u->source->set_volume)
2423 u->source->set_volume(u->source);
2429 /* Run from main thread */
2430 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2433 pa_queue *inputs = NULL, *outputs = NULL;
2434 const pa_bluetooth_device *device;
2437 pa_assert(new_profile);
2438 pa_assert_se(u = c->userdata);
2440 d = PA_CARD_PROFILE_DATA(new_profile);
2442 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2443 pa_log_error("Failed to get device object.");
2447 /* The state signal is sent by bluez, so it is racy to check
2448 strictly for CONNECTED, we should also accept STREAMING state
2449 as being good enough. However, if the profile is used
2450 concurrently (which is unlikely), ipc will fail later on, and
2451 module will be unloaded. */
2452 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2453 pa_log_warn("HSP is not connected, refused to switch profile");
2456 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2457 pa_log_warn("A2DP is not connected, refused to switch profile");
2460 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2461 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2466 inputs = pa_sink_move_all_start(u->sink, NULL);
2468 if (!USE_SCO_OVER_PCM(u))
2470 pa_sink_unlink(u->sink);
2474 outputs = pa_source_move_all_start(u->source, NULL);
2476 if (!USE_SCO_OVER_PCM(u))
2478 pa_source_unlink(u->source);
2485 u->sample_spec = u->requested_sample_spec;
2489 if (u->profile != PROFILE_OFF)
2492 if (u->sink || u->source)
2497 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2499 pa_sink_move_all_fail(inputs);
2504 pa_source_move_all_finish(u->source, outputs, FALSE);
2506 pa_source_move_all_fail(outputs);
2512 /* Run from main thread */
2513 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2514 pa_card_new_data data;
2520 const char *default_profile;
2525 pa_card_new_data_init(&data);
2526 data.driver = __FILE__;
2527 data.module = u->module;
2529 n = pa_bluetooth_cleanup_name(device->name);
2530 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2532 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2533 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2534 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2535 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2536 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2537 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2538 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2539 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2540 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2541 data.name = get_name("card", u->modargs, device->address, &b);
2542 data.namereg_fail = b;
2544 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2545 pa_log("Invalid properties");
2546 pa_card_new_data_done(&data);
2550 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2552 /* we base hsp/a2dp availability on UUIDs.
2553 Ideally, it would be based on "Connected" state, but
2554 we can't afford to wait for this information when
2555 we are loaded with profile="hsp", for instance */
2556 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2557 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2561 p->max_sink_channels = 2;
2562 p->max_source_channels = 0;
2564 d = PA_CARD_PROFILE_DATA(p);
2567 pa_hashmap_put(data.profiles, p->name, p);
2570 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2571 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2575 p->max_sink_channels = 0;
2576 p->max_source_channels = 2;
2578 d = PA_CARD_PROFILE_DATA(p);
2579 *d = PROFILE_A2DP_SOURCE;
2581 pa_hashmap_put(data.profiles, p->name, p);
2584 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2585 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2586 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2590 p->max_sink_channels = 1;
2591 p->max_source_channels = 1;
2593 d = PA_CARD_PROFILE_DATA(p);
2596 pa_hashmap_put(data.profiles, p->name, p);
2599 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2600 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2604 p->max_sink_channels = 1;
2605 p->max_source_channels = 1;
2607 d = PA_CARD_PROFILE_DATA(p);
2610 pa_hashmap_put(data.profiles, p->name, p);
2613 pa_assert(!pa_hashmap_isempty(data.profiles));
2615 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2616 d = PA_CARD_PROFILE_DATA(p);
2618 pa_hashmap_put(data.profiles, p->name, p);
2620 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2621 if (pa_hashmap_get(data.profiles, default_profile))
2622 pa_card_new_data_set_profile(&data, default_profile);
2624 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2627 u->card = pa_card_new(u->core, &data);
2628 pa_card_new_data_done(&data);
2631 pa_log("Failed to allocate card.");
2635 u->card->userdata = u;
2636 u->card->set_profile = card_set_profile;
2638 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2640 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2641 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2642 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2643 pa_log_warn("Default profile not connected, selecting off profile");
2644 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2645 u->card->save_profile = FALSE;
2648 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2654 /* Run from main thread */
2655 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2656 const pa_bluetooth_device *d = NULL;
2660 if (!address && !path) {
2661 pa_log_error("Failed to get device address/path from module arguments.");
2666 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2667 pa_log_error("%s is not a valid BlueZ audio device.", path);
2671 if (address && !(pa_streq(d->address, address))) {
2672 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2677 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2678 pa_log_error("%s is not known.", address);
2684 u->address = pa_xstrdup(d->address);
2685 u->path = pa_xstrdup(d->path);
2691 /* Run from main thread */
2692 static int setup_dbus(struct userdata *u) {
2695 dbus_error_init(&err);
2697 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2699 if (dbus_error_is_set(&err) || !u->connection) {
2700 pa_log("Failed to get D-Bus connection: %s", err.message);
2701 dbus_error_free(&err);
2708 int pa__init(pa_module* m) {
2712 const char *address, *path;
2714 char *mike, *speaker, *transport;
2715 const pa_bluetooth_device *device;
2719 dbus_error_init(&err);
2721 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2722 pa_log_error("Failed to parse module arguments");
2726 m->userdata = u = pa_xnew0(struct userdata, 1);
2731 u->sample_spec = m->core->default_sample_spec;
2735 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2736 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2737 pa_log("SCO sink not found");
2741 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2742 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2743 pa_log("SCO source not found");
2748 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2749 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2750 pa_log_error("Failed to get rate from module arguments");
2754 u->auto_connect = TRUE;
2755 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2756 pa_log("Failed to parse auto_connect= argument");
2760 channels = u->sample_spec.channels;
2761 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2762 channels <= 0 || channels > PA_CHANNELS_MAX) {
2763 pa_log_error("Failed to get channels from module arguments");
2766 u->sample_spec.channels = (uint8_t) channels;
2767 u->requested_sample_spec = u->sample_spec;
2769 address = pa_modargs_get_value(ma, "address", NULL);
2770 path = pa_modargs_get_value(ma, "path", NULL);
2772 if (setup_dbus(u) < 0)
2775 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2778 if (!(device = find_device(u, address, path)))
2781 /* Add the card structure. This will also initialize the default profile */
2782 if (add_card(u, device) < 0)
2785 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2786 pa_log_error("Failed to add filter function");
2789 u->filter_added = TRUE;
2791 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2792 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2793 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2795 if (pa_dbus_add_matches(
2796 pa_dbus_connection_get(u->connection), &err,
2804 pa_xfree(transport);
2806 pa_log("Failed to add D-Bus matches: %s", err.message);
2812 pa_xfree(transport);
2814 /* Connect to the BT service */
2817 if (u->profile != PROFILE_OFF)
2818 if (init_profile(u) < 0)
2821 if (u->sink || u->source)
2822 if (start_thread(u) < 0)
2831 dbus_error_free(&err);
2836 int pa__get_n_used(pa_module *m) {
2840 pa_assert_se(u = m->userdata);
2843 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2844 (u->source ? pa_source_linked_by(u->source) : 0);
2847 void pa__done(pa_module *m) {
2851 if (!(u = m->userdata))
2856 && !USE_SCO_OVER_PCM(u)
2859 pa_sink_unlink(u->sink);
2863 && !USE_SCO_OVER_PCM(u)
2866 pa_source_unlink(u->source);
2870 if (u->connection) {
2873 char *speaker, *mike;
2874 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2875 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2877 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2883 if (u->filter_added)
2884 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2886 pa_dbus_connection_unref(u->connection);
2890 pa_card_free(u->card);
2892 if (u->read_smoother)
2893 pa_smoother_free(u->read_smoother);
2898 pa_xfree(u->a2dp.buffer);
2900 sbc_finish(&u->a2dp.sbc);
2903 pa_modargs_free(u->modargs);
2905 pa_xfree(u->address);
2909 bt_transport_release(u);
2910 pa_xfree(u->transport);
2914 pa_bluetooth_discovery_unref(u->discovery);