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) {
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 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
672 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
673 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
676 /* Run from main thread */
677 static int set_conf(struct userdata *u) {
679 struct bt_open_req open_req;
680 struct bt_open_rsp open_rsp;
681 struct bt_set_configuration_req setconf_req;
682 struct bt_set_configuration_rsp setconf_rsp;
683 bt_audio_error_t error;
684 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
687 memset(&msg, 0, sizeof(msg));
688 msg.open_req.h.type = BT_REQUEST;
689 msg.open_req.h.name = BT_OPEN;
690 msg.open_req.h.length = sizeof(msg.open_req);
692 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
693 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
694 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
696 if (service_send(u, &msg.open_req.h) < 0)
699 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
702 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
703 u->sample_spec.format = PA_SAMPLE_S16LE;
705 if (setup_a2dp(u) < 0)
708 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
710 u->sample_spec.format = PA_SAMPLE_S16LE;
711 u->sample_spec.channels = 1;
712 u->sample_spec.rate = 8000;
715 memset(&msg, 0, sizeof(msg));
716 msg.setconf_req.h.type = BT_REQUEST;
717 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
718 msg.setconf_req.h.length = sizeof(msg.setconf_req);
720 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
721 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
723 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
724 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
725 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
727 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
729 if (service_send(u, &msg.setconf_req.h) < 0)
732 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
735 u->link_mtu = msg.setconf_rsp.link_mtu;
737 /* setup SBC encoder now we agree on parameters */
738 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
742 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
743 / u->a2dp.frame_length
746 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
747 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
749 u->block_size = u->link_mtu;
755 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
757 struct a2dp_info *a2dp;
763 if (a2dp->sbc.bitpool == bitpool)
766 if (bitpool > a2dp->max_bitpool)
767 bitpool = a2dp->max_bitpool;
768 else if (bitpool < a2dp->min_bitpool)
769 bitpool = a2dp->min_bitpool;
771 a2dp->sbc.bitpool = bitpool;
773 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
774 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
776 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
779 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
780 / a2dp->frame_length * a2dp->codesize;
782 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
783 pa_sink_set_fixed_latency_within_thread(u->sink,
784 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
787 /* from IO thread, except in SCO over PCM */
789 static int setup_stream(struct userdata *u) {
790 struct pollfd *pollfd;
793 pa_make_fd_nonblock(u->stream_fd);
794 pa_make_socket_low_delay(u->stream_fd);
797 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
798 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
800 pa_log_debug("Stream properly set up, we're ready to roll!");
802 if (u->profile == PROFILE_A2DP)
803 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
805 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
806 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
807 pollfd->fd = u->stream_fd;
808 pollfd->events = pollfd->revents = 0;
810 u->read_index = u->write_index = 0;
814 u->read_smoother = pa_smoother_new(
826 static int start_stream_fd(struct userdata *u) {
828 bt_audio_msg_header_t rsp;
829 struct bt_start_stream_req start_req;
830 struct bt_start_stream_rsp start_rsp;
831 struct bt_new_stream_ind streamfd_ind;
832 bt_audio_error_t error;
833 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
837 pa_assert(u->rtpoll);
838 pa_assert(!u->rtpoll_item);
839 pa_assert(u->stream_fd < 0);
841 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
842 msg.start_req.h.type = BT_REQUEST;
843 msg.start_req.h.name = BT_START_STREAM;
844 msg.start_req.h.length = sizeof(msg.start_req);
846 if (service_send(u, &msg.start_req.h) < 0)
849 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
852 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
855 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
856 pa_log("Failed to get stream fd from audio service.");
860 return setup_stream(u);
864 static int stop_stream_fd(struct userdata *u) {
866 bt_audio_msg_header_t rsp;
867 struct bt_stop_stream_req start_req;
868 struct bt_stop_stream_rsp start_rsp;
869 bt_audio_error_t error;
870 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
875 pa_assert(u->rtpoll);
877 if (u->rtpoll_item) {
878 pa_rtpoll_item_free(u->rtpoll_item);
879 u->rtpoll_item = NULL;
882 if (u->stream_fd >= 0) {
883 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
884 msg.start_req.h.type = BT_REQUEST;
885 msg.start_req.h.name = BT_STOP_STREAM;
886 msg.start_req.h.length = sizeof(msg.start_req);
888 if (service_send(u, &msg.start_req.h) < 0 ||
889 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
892 pa_close(u->stream_fd);
896 if (u->read_smoother) {
897 pa_smoother_free(u->read_smoother);
898 u->read_smoother = NULL;
904 static void bt_transport_release(struct userdata *u) {
905 const char *accesstype = "rw";
906 const pa_bluetooth_transport *t;
908 /* Ignore if already released */
912 pa_log_debug("Releasing transport %s", u->transport);
914 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
916 pa_bluetooth_transport_release(t, accesstype);
918 pa_xfree(u->accesstype);
919 u->accesstype = NULL;
921 if (u->rtpoll_item) {
922 pa_rtpoll_item_free(u->rtpoll_item);
923 u->rtpoll_item = NULL;
926 if (u->stream_fd >= 0) {
927 pa_close(u->stream_fd);
931 if (u->read_smoother) {
932 pa_smoother_free(u->read_smoother);
933 u->read_smoother = NULL;
937 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
938 const char *accesstype = "rw";
939 const pa_bluetooth_transport *t;
947 pa_log_debug("Acquiring transport %s", u->transport);
949 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
951 pa_log("Transport %s no longer available", u->transport);
952 pa_xfree(u->transport);
957 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
958 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
959 if (u->stream_fd < 0)
962 u->accesstype = pa_xstrdup(accesstype);
963 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
969 pa_log_info("Transport %s resuming", u->transport);
970 return setup_stream(u);
973 /* Run from IO thread */
974 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
975 struct userdata *u = PA_SINK(o)->userdata;
976 pa_bool_t failed = FALSE;
979 pa_assert(u->sink == PA_SINK(o));
983 case PA_SINK_MESSAGE_SET_STATE:
985 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
987 case PA_SINK_SUSPENDED:
988 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
990 /* Stop the device if the source is suspended as well */
991 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
992 /* We deliberately ignore whether stopping
993 * actually worked. Since the stream_fd is
994 * closed it doesn't really matter */
996 bt_transport_release(u);
1004 case PA_SINK_RUNNING:
1005 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1008 /* Resume the device if the source was suspended as well */
1009 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1011 if (bt_transport_acquire(u, TRUE) < 0)
1013 } else if (start_stream_fd(u) < 0)
1018 case PA_SINK_UNLINKED:
1020 case PA_SINK_INVALID_STATE:
1025 case PA_SINK_MESSAGE_GET_LATENCY: {
1027 if (u->read_smoother) {
1030 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1031 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1033 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1037 ri = pa_rtclock_now() - u->started_at;
1038 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1040 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1043 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1048 r = pa_sink_process_msg(o, code, data, offset, chunk);
1050 return (r < 0 || !failed) ? r : -1;
1053 /* Run from IO thread */
1054 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1055 struct userdata *u = PA_SOURCE(o)->userdata;
1056 pa_bool_t failed = FALSE;
1059 pa_assert(u->source == PA_SOURCE(o));
1063 case PA_SOURCE_MESSAGE_SET_STATE:
1065 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1067 case PA_SOURCE_SUSPENDED:
1068 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1070 /* Stop the device if the sink is suspended as well */
1071 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1073 bt_transport_release(u);
1078 if (u->read_smoother)
1079 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1082 case PA_SOURCE_IDLE:
1083 case PA_SOURCE_RUNNING:
1084 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1087 /* Resume the device if the sink was suspended as well */
1088 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1090 if (bt_transport_acquire(u, TRUE) < 0)
1092 } else if (start_stream_fd(u) < 0)
1095 /* We don't resume the smoother here. Instead we
1096 * wait until the first packet arrives */
1099 case PA_SOURCE_UNLINKED:
1100 case PA_SOURCE_INIT:
1101 case PA_SOURCE_INVALID_STATE:
1106 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1109 if (u->read_smoother) {
1110 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1111 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1113 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1115 *((pa_usec_t*) data) = 0;
1122 r = pa_source_process_msg(o, code, data, offset, chunk);
1124 return (r < 0 || !failed) ? r : -1;
1127 /* Run from IO thread */
1128 static int hsp_process_render(struct userdata *u) {
1132 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1135 /* First, render some data */
1136 if (!u->write_memchunk.memblock)
1137 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1139 pa_assert(u->write_memchunk.length == u->block_size);
1145 /* Now write that data to the socket. The socket is of type
1146 * SEQPACKET, and we generated the data of the MTU size, so this
1147 * should just work. */
1149 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1150 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1151 pa_memblock_release(u->write_memchunk.memblock);
1158 /* Retry right away if we got interrupted */
1161 else if (errno == EAGAIN)
1162 /* Hmm, apparently the socket was not writable, give up for now */
1165 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1170 pa_assert((size_t) l <= u->write_memchunk.length);
1172 if ((size_t) l != u->write_memchunk.length) {
1173 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1174 (unsigned long long) l,
1175 (unsigned long long) u->write_memchunk.length);
1180 u->write_index += (uint64_t) u->write_memchunk.length;
1181 pa_memblock_unref(u->write_memchunk.memblock);
1182 pa_memchunk_reset(&u->write_memchunk);
1191 /* Run from IO thread */
1192 static int hsp_process_push(struct userdata *u) {
1194 pa_memchunk memchunk;
1197 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1198 pa_assert(u->source);
1199 pa_assert(u->read_smoother);
1201 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1202 memchunk.index = memchunk.length = 0;
1211 pa_bool_t found_tstamp = FALSE;
1214 memset(&m, 0, sizeof(m));
1215 memset(&aux, 0, sizeof(aux));
1216 memset(&iov, 0, sizeof(iov));
1220 m.msg_control = aux;
1221 m.msg_controllen = sizeof(aux);
1223 p = pa_memblock_acquire(memchunk.memblock);
1225 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1226 l = recvmsg(u->stream_fd, &m, 0);
1227 pa_memblock_release(memchunk.memblock);
1231 if (l < 0 && errno == EINTR)
1232 /* Retry right away if we got interrupted */
1235 else if (l < 0 && errno == EAGAIN)
1236 /* Hmm, apparently the socket was not readable, give up for now. */
1239 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1244 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1246 memchunk.length = (size_t) l;
1247 u->read_index += (uint64_t) l;
1249 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1250 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1251 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1252 pa_rtclock_from_wallclock(tv);
1253 tstamp = pa_timeval_load(tv);
1254 found_tstamp = TRUE;
1258 if (!found_tstamp) {
1259 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1260 tstamp = pa_rtclock_now();
1263 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1264 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1266 pa_source_post(u->source, &memchunk);
1272 pa_memblock_unref(memchunk.memblock);
1277 /* Run from IO thread */
1278 static void a2dp_prepare_buffer(struct userdata *u) {
1281 if (u->a2dp.buffer_size >= u->link_mtu)
1284 u->a2dp.buffer_size = 2 * u->link_mtu;
1285 pa_xfree(u->a2dp.buffer);
1286 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1289 /* Run from IO thread */
1290 static int a2dp_process_render(struct userdata *u) {
1291 struct a2dp_info *a2dp;
1292 struct rtp_header *header;
1293 struct rtp_payload *payload;
1297 size_t to_write, to_encode;
1298 unsigned frame_count;
1302 pa_assert(u->profile == PROFILE_A2DP);
1305 /* First, render some data */
1306 if (!u->write_memchunk.memblock)
1307 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1309 pa_assert(u->write_memchunk.length == u->block_size);
1311 a2dp_prepare_buffer(u);
1314 header = a2dp->buffer;
1315 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1319 /* Try to create a packet of the full MTU */
1321 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1322 to_encode = u->write_memchunk.length;
1324 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1325 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1327 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1331 encoded = sbc_encode(&a2dp->sbc,
1336 if (PA_UNLIKELY(encoded <= 0)) {
1337 pa_log_error("SBC encoding error (%li)", (long) encoded);
1338 pa_memblock_release(u->write_memchunk.memblock);
1342 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1343 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1345 pa_assert_fp((size_t) encoded <= to_encode);
1346 pa_assert_fp((size_t) encoded == a2dp->codesize);
1348 pa_assert_fp((size_t) written <= to_write);
1349 pa_assert_fp((size_t) written == a2dp->frame_length);
1351 p = (const uint8_t*) p + encoded;
1352 to_encode -= encoded;
1354 d = (uint8_t*) d + written;
1355 to_write -= written;
1360 pa_memblock_release(u->write_memchunk.memblock);
1362 pa_assert(to_encode == 0);
1365 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1368 /* write it to the fifo */
1369 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1372 header->sequence_number = htons(a2dp->seq_num++);
1373 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1374 header->ssrc = htonl(1);
1375 payload->frame_count = frame_count;
1377 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1382 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1389 /* Retry right away if we got interrupted */
1392 else if (errno == EAGAIN)
1393 /* Hmm, apparently the socket was not writable, give up for now */
1396 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1401 pa_assert((size_t) l <= nbytes);
1403 if ((size_t) l != nbytes) {
1404 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1405 (unsigned long long) l,
1406 (unsigned long long) nbytes);
1411 u->write_index += (uint64_t) u->write_memchunk.length;
1412 pa_memblock_unref(u->write_memchunk.memblock);
1413 pa_memchunk_reset(&u->write_memchunk);
1423 static int a2dp_process_push(struct userdata *u) {
1425 pa_memchunk memchunk;
1428 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1429 pa_assert(u->source);
1430 pa_assert(u->read_smoother);
1432 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1433 memchunk.index = memchunk.length = 0;
1436 pa_bool_t found_tstamp = FALSE;
1438 struct a2dp_info *a2dp;
1439 struct rtp_header *header;
1440 struct rtp_payload *payload;
1444 size_t to_write, to_decode;
1445 unsigned frame_count;
1447 a2dp_prepare_buffer(u);
1450 header = a2dp->buffer;
1451 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1453 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1457 if (l < 0 && errno == EINTR)
1458 /* Retry right away if we got interrupted */
1461 else if (l < 0 && errno == EAGAIN)
1462 /* Hmm, apparently the socket was not readable, give up for now. */
1465 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1470 pa_assert((size_t) l <= a2dp->buffer_size);
1472 u->read_index += (uint64_t) l;
1474 /* TODO: get timestamp from rtp */
1475 if (!found_tstamp) {
1476 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1477 tstamp = pa_rtclock_now();
1480 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1481 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1483 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1484 to_decode = l - sizeof(*header) - sizeof(*payload);
1486 d = pa_memblock_acquire(memchunk.memblock);
1487 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1489 while (PA_LIKELY(to_decode > 0 && to_write > 0)) {
1493 decoded = sbc_decode(&a2dp->sbc,
1498 if (PA_UNLIKELY(decoded <= 0)) {
1499 pa_log_error("SBC decoding error (%li)", (long) decoded);
1500 pa_memblock_release(memchunk.memblock);
1501 pa_memblock_unref(memchunk.memblock);
1505 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1506 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1508 pa_assert_fp((size_t) decoded <= to_decode);
1509 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1511 pa_assert_fp((size_t) written <= to_write);
1512 pa_assert_fp((size_t) written == a2dp->codesize);
1514 p = (const uint8_t*) p + decoded;
1515 to_decode -= decoded;
1517 d = (uint8_t*) d + written;
1518 to_write -= written;
1523 pa_memblock_release(memchunk.memblock);
1525 pa_source_post(u->source, &memchunk);
1531 pa_memblock_unref(memchunk.memblock);
1536 static void a2dp_reduce_bitpool(struct userdata *u)
1538 struct a2dp_info *a2dp;
1545 /* Check if bitpool is already at its limit */
1546 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1549 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1551 if (bitpool < BITPOOL_DEC_LIMIT)
1552 bitpool = BITPOOL_DEC_LIMIT;
1554 a2dp_set_bitpool(u, bitpool);
1557 static void thread_func(void *userdata) {
1558 struct userdata *u = userdata;
1559 unsigned do_write = 0;
1560 pa_bool_t writable = FALSE;
1564 pa_log_debug("IO Thread starting up");
1566 if (u->core->realtime_scheduling)
1567 pa_make_realtime(u->core->realtime_priority);
1569 pa_thread_mq_install(&u->thread_mq);
1572 if (bt_transport_acquire(u, TRUE) < 0)
1574 } else if (start_stream_fd(u) < 0)
1578 struct pollfd *pollfd;
1580 pa_bool_t disable_timer = TRUE;
1582 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1584 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1586 /* We should send two blocks to the device before we expect
1589 if (u->write_index == 0 && u->read_index <= 0)
1592 if (pollfd && (pollfd->revents & POLLIN)) {
1595 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1596 n_read = hsp_process_push(u);
1598 n_read = a2dp_process_push(u);
1603 /* We just read something, so we are supposed to write something, too */
1608 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1610 if (u->sink->thread_info.rewind_requested)
1611 pa_sink_process_rewind(u->sink, 0);
1614 if (pollfd->revents & POLLOUT)
1617 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1618 pa_usec_t time_passed;
1619 pa_usec_t audio_sent;
1621 /* Hmm, there is no input stream we could synchronize
1622 * to. So let's do things by time */
1624 time_passed = pa_rtclock_now() - u->started_at;
1625 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1627 if (audio_sent <= time_passed) {
1628 pa_usec_t audio_to_send = time_passed - audio_sent;
1630 /* Never try to catch up for more than 100ms */
1631 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1632 pa_usec_t skip_usec;
1633 uint64_t skip_bytes;
1635 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1636 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1638 if (skip_bytes > 0) {
1641 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1642 (unsigned long long) skip_usec,
1643 (unsigned long long) skip_bytes);
1645 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1646 pa_memblock_unref(tmp.memblock);
1647 u->write_index += skip_bytes;
1649 if (u->profile == PROFILE_A2DP)
1650 a2dp_reduce_bitpool(u);
1658 if (writable && do_write > 0) {
1661 if (u->write_index <= 0)
1662 u->started_at = pa_rtclock_now();
1664 if (u->profile == PROFILE_A2DP) {
1665 if ((n_written = a2dp_process_render(u)) < 0)
1668 if ((n_written = hsp_process_render(u)) < 0)
1673 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1675 do_write -= n_written;
1679 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1680 pa_usec_t time_passed, next_write_at, sleep_for;
1682 /* Hmm, there is no input stream we could synchronize
1683 * to. So let's estimate when we need to wake up the latest */
1685 time_passed = pa_rtclock_now() - u->started_at;
1686 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1687 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1689 /* 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); */
1691 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1692 disable_timer = FALSE;
1698 pa_rtpoll_set_timer_disabled(u->rtpoll);
1700 /* Hmm, nothing to do. Let's sleep */
1702 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1703 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1705 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1711 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1713 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1714 pa_log_info("FD error: %s%s%s%s",
1715 pollfd->revents & POLLERR ? "POLLERR " :"",
1716 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1717 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1718 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1724 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1725 pa_log_debug("IO thread failed");
1726 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1727 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1730 pa_log_debug("IO thread shutting down");
1733 /* Run from main thread */
1734 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1740 pa_assert_se(u = userdata);
1742 dbus_error_init(&err);
1744 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1745 dbus_message_get_interface(m),
1746 dbus_message_get_path(m),
1747 dbus_message_get_member(m));
1749 if (!dbus_message_has_path(m, u->path))
1752 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1753 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1758 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1759 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1763 if (u->profile == PROFILE_HSP) {
1764 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1766 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1767 pa_sink_volume_changed(u->sink, &v);
1769 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1771 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1772 pa_source_volume_changed(u->source, &v);
1778 dbus_error_free(&err);
1780 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1783 /* Run from main thread */
1784 static void sink_set_volume_cb(pa_sink *s) {
1785 struct userdata *u = s->userdata;
1791 if (u->profile != PROFILE_HSP)
1794 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1799 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1801 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1802 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1803 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1804 dbus_message_unref(m);
1807 /* Run from main thread */
1808 static void source_set_volume_cb(pa_source *s) {
1809 struct userdata *u = s->userdata;
1815 if (u->profile != PROFILE_HSP)
1818 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1823 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1825 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1826 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1827 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1828 dbus_message_unref(m);
1831 /* Run from main thread */
1832 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1838 pa_assert(device_id);
1839 pa_assert(namereg_fail);
1841 t = pa_sprintf_malloc("%s_name", type);
1842 n = pa_modargs_get_value(ma, t, NULL);
1846 *namereg_fail = TRUE;
1847 return pa_xstrdup(n);
1850 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1851 *namereg_fail = TRUE;
1854 *namereg_fail = FALSE;
1857 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1862 static void sco_over_pcm_state_update(struct userdata *u) {
1864 pa_assert(USE_SCO_OVER_PCM(u));
1866 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1867 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1869 if (u->service_fd >= 0)
1874 pa_log_debug("Resuming SCO over PCM");
1875 if (init_profile(u) < 0)
1876 pa_log("Can't resume SCO over PCM");
1879 bt_transport_acquire(u, TRUE);
1884 if (u->service_fd < 0)
1888 bt_transport_release(u);
1892 pa_log_debug("Closing SCO over PCM");
1893 pa_close(u->service_fd);
1898 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1900 pa_sink_assert_ref(s);
1903 if (s != u->hsp.sco_sink)
1906 sco_over_pcm_state_update(u);
1911 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1913 pa_source_assert_ref(s);
1916 if (s != u->hsp.sco_source)
1919 sco_over_pcm_state_update(u);
1926 /* Run from main thread */
1927 static int add_sink(struct userdata *u) {
1930 if (USE_SCO_OVER_PCM(u)) {
1933 u->sink = u->hsp.sco_sink;
1934 p = pa_proplist_new();
1935 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1936 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1937 pa_proplist_free(p);
1939 if (!u->hsp.sink_state_changed_slot)
1940 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);
1946 pa_sink_new_data data;
1949 pa_sink_new_data_init(&data);
1950 data.driver = __FILE__;
1951 data.module = u->module;
1952 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1953 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1954 if (u->profile == PROFILE_HSP)
1955 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1956 data.card = u->card;
1957 data.name = get_name("sink", u->modargs, u->address, &b);
1958 data.namereg_fail = b;
1960 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1961 pa_log("Invalid properties");
1962 pa_sink_new_data_done(&data);
1966 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1967 pa_sink_new_data_done(&data);
1970 pa_log_error("Failed to create sink");
1974 u->sink->userdata = u;
1975 u->sink->parent.process_msg = sink_process_msg;
1977 pa_sink_set_max_request(u->sink, u->block_size);
1978 pa_sink_set_fixed_latency(u->sink,
1979 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1980 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1983 if (u->profile == PROFILE_HSP) {
1984 u->sink->set_volume = sink_set_volume_cb;
1985 u->sink->n_volume_steps = 16;
1991 /* Run from main thread */
1992 static int add_source(struct userdata *u) {
1995 if (USE_SCO_OVER_PCM(u)) {
1996 u->source = u->hsp.sco_source;
1997 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1999 if (!u->hsp.source_state_changed_slot)
2000 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);
2006 pa_source_new_data data;
2009 pa_source_new_data_init(&data);
2010 data.driver = __FILE__;
2011 data.module = u->module;
2012 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2013 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2014 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2015 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2016 data.card = u->card;
2017 data.name = get_name("source", u->modargs, u->address, &b);
2018 data.namereg_fail = b;
2020 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2021 pa_log("Invalid properties");
2022 pa_source_new_data_done(&data);
2026 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2027 pa_source_new_data_done(&data);
2030 pa_log_error("Failed to create source");
2034 u->source->userdata = u;
2035 u->source->parent.process_msg = source_process_msg;
2037 pa_source_set_fixed_latency(u->source,
2038 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2039 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2042 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
2043 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2045 if (u->profile == PROFILE_HSP) {
2046 u->source->set_volume = source_set_volume_cb;
2047 u->source->n_volume_steps = 16;
2053 /* Run from main thread */
2054 static void shutdown_bt(struct userdata *u) {
2057 if (u->stream_fd >= 0) {
2058 pa_close(u->stream_fd);
2061 u->stream_write_type = 0;
2064 if (u->service_fd >= 0) {
2065 pa_close(u->service_fd);
2067 u->service_write_type = 0;
2068 u->service_read_type = 0;
2071 if (u->write_memchunk.memblock) {
2072 pa_memblock_unref(u->write_memchunk.memblock);
2073 pa_memchunk_reset(&u->write_memchunk);
2077 static int bt_transport_config_a2dp(struct userdata *u) {
2078 const pa_bluetooth_transport *t;
2079 struct a2dp_info *a2dp = &u->a2dp;
2080 sbc_capabilities_raw_t *config;
2082 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2085 config = (sbc_capabilities_raw_t *) t->config;
2087 if (a2dp->sbc_initialized)
2088 sbc_reinit(&a2dp->sbc, 0);
2090 sbc_init(&a2dp->sbc, 0);
2091 a2dp->sbc_initialized = TRUE;
2093 switch (config->frequency) {
2094 case BT_SBC_SAMPLING_FREQ_16000:
2095 a2dp->sbc.frequency = SBC_FREQ_16000;
2097 case BT_SBC_SAMPLING_FREQ_32000:
2098 a2dp->sbc.frequency = SBC_FREQ_32000;
2100 case BT_SBC_SAMPLING_FREQ_44100:
2101 a2dp->sbc.frequency = SBC_FREQ_44100;
2103 case BT_SBC_SAMPLING_FREQ_48000:
2104 a2dp->sbc.frequency = SBC_FREQ_48000;
2107 pa_assert_not_reached();
2110 switch (config->channel_mode) {
2111 case BT_A2DP_CHANNEL_MODE_MONO:
2112 a2dp->sbc.mode = SBC_MODE_MONO;
2114 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2115 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2117 case BT_A2DP_CHANNEL_MODE_STEREO:
2118 a2dp->sbc.mode = SBC_MODE_STEREO;
2120 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2121 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2124 pa_assert_not_reached();
2127 switch (config->allocation_method) {
2128 case BT_A2DP_ALLOCATION_SNR:
2129 a2dp->sbc.allocation = SBC_AM_SNR;
2131 case BT_A2DP_ALLOCATION_LOUDNESS:
2132 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2135 pa_assert_not_reached();
2138 switch (config->subbands) {
2139 case BT_A2DP_SUBBANDS_4:
2140 a2dp->sbc.subbands = SBC_SB_4;
2142 case BT_A2DP_SUBBANDS_8:
2143 a2dp->sbc.subbands = SBC_SB_8;
2146 pa_assert_not_reached();
2149 switch (config->block_length) {
2150 case BT_A2DP_BLOCK_LENGTH_4:
2151 a2dp->sbc.blocks = SBC_BLK_4;
2153 case BT_A2DP_BLOCK_LENGTH_8:
2154 a2dp->sbc.blocks = SBC_BLK_8;
2156 case BT_A2DP_BLOCK_LENGTH_12:
2157 a2dp->sbc.blocks = SBC_BLK_12;
2159 case BT_A2DP_BLOCK_LENGTH_16:
2160 a2dp->sbc.blocks = SBC_BLK_16;
2163 pa_assert_not_reached();
2166 a2dp->min_bitpool = config->min_bitpool;
2167 a2dp->max_bitpool = config->max_bitpool;
2169 a2dp->sbc.bitpool = config->max_bitpool;
2170 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2171 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2174 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2175 / a2dp->frame_length
2178 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2179 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2184 static int bt_transport_config(struct userdata *u) {
2185 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2186 u->block_size = u->link_mtu;
2190 return bt_transport_config_a2dp(u);
2193 static int parse_transport_property(struct userdata *u, DBusMessageIter *i) {
2195 DBusMessageIter variant_i;
2200 if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_STRING) {
2201 pa_log("Property name not a string.");
2205 dbus_message_iter_get_basic(i, &key);
2207 if (!dbus_message_iter_next(i)) {
2208 pa_log("Property value missing");
2212 if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_VARIANT) {
2213 pa_log("Property value not a variant.");
2217 dbus_message_iter_recurse(i, &variant_i);
2219 switch (dbus_message_iter_get_arg_type(&variant_i)) {
2221 case DBUS_TYPE_UINT16: {
2224 dbus_message_iter_get_basic(&variant_i, &value);
2226 if (pa_streq(key, "OMTU"))
2227 u->link_mtu = value;
2237 /* Run from main thread */
2238 static int bt_transport_open(struct userdata *u) {
2239 if (bt_transport_acquire(u, FALSE) < 0)
2242 return bt_transport_config(u);
2245 /* Run from main thread */
2246 static int init_bt(struct userdata *u) {
2251 u->stream_write_type = 0;
2252 u->service_write_type = 0;
2253 u->service_read_type = 0;
2255 if ((u->service_fd = bt_audio_service_open()) < 0) {
2256 pa_log_warn("Bluetooth audio service not available");
2260 pa_log_debug("Connected to the bluetooth audio service");
2265 /* Run from main thread */
2266 static int setup_bt(struct userdata *u) {
2267 const pa_bluetooth_device *d;
2268 const pa_bluetooth_transport *t;
2272 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2273 pa_log_error("Failed to get device object.");
2277 /* release transport if exist */
2279 bt_transport_release(u);
2280 pa_xfree(u->transport);
2281 u->transport = NULL;
2284 /* check if profile has a transport */
2285 t = pa_bluetooth_device_get_transport(d, u->profile);
2287 u->transport = pa_xstrdup(t->path);
2288 return bt_transport_open(u);
2291 if (get_caps(u, 0) < 0)
2294 pa_log_debug("Got device capabilities");
2296 if (set_conf(u) < 0)
2299 pa_log_debug("Connection to the device configured");
2302 if (USE_SCO_OVER_PCM(u)) {
2303 pa_log_debug("Configured to use SCO over PCM");
2308 pa_log_debug("Got the stream socket");
2313 /* Run from main thread */
2314 static int init_profile(struct userdata *u) {
2317 pa_assert(u->profile != PROFILE_OFF);
2319 if (setup_bt(u) < 0)
2322 if (u->profile == PROFILE_A2DP ||
2323 u->profile == PROFILE_HSP ||
2324 u->profile == PROFILE_HFGW)
2325 if (add_sink(u) < 0)
2328 if (u->profile == PROFILE_HSP ||
2329 u->profile == PROFILE_A2DP_SOURCE ||
2330 u->profile == PROFILE_HFGW)
2331 if (add_source(u) < 0)
2337 /* Run from main thread */
2338 static void stop_thread(struct userdata *u) {
2342 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2343 pa_thread_free(u->thread);
2347 if (u->rtpoll_item) {
2348 pa_rtpoll_item_free(u->rtpoll_item);
2349 u->rtpoll_item = NULL;
2352 if (u->hsp.sink_state_changed_slot) {
2353 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2354 u->hsp.sink_state_changed_slot = NULL;
2357 if (u->hsp.source_state_changed_slot) {
2358 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2359 u->hsp.source_state_changed_slot = NULL;
2363 pa_sink_unref(u->sink);
2368 pa_source_unref(u->source);
2373 pa_thread_mq_done(&u->thread_mq);
2375 pa_rtpoll_free(u->rtpoll);
2379 if (u->read_smoother) {
2380 pa_smoother_free(u->read_smoother);
2381 u->read_smoother = NULL;
2385 /* Run from main thread */
2386 static int start_thread(struct userdata *u) {
2388 pa_assert(!u->thread);
2389 pa_assert(!u->rtpoll);
2390 pa_assert(!u->rtpoll_item);
2392 u->rtpoll = pa_rtpoll_new();
2393 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2396 if (USE_SCO_OVER_PCM(u)) {
2398 if (bt_transport_acquire(u, TRUE) < 0)
2400 } else if (start_stream_fd(u) < 0)
2403 pa_sink_ref(u->sink);
2404 pa_source_ref(u->source);
2405 /* FIXME: monitor stream_fd error */
2410 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2411 pa_log_error("Failed to create IO thread");
2417 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2418 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2419 pa_sink_put(u->sink);
2421 if (u->sink->set_volume)
2422 u->sink->set_volume(u->sink);
2426 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2427 pa_source_set_rtpoll(u->source, u->rtpoll);
2428 pa_source_put(u->source);
2430 if (u->source->set_volume)
2431 u->source->set_volume(u->source);
2437 /* Run from main thread */
2438 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2441 pa_queue *inputs = NULL, *outputs = NULL;
2442 const pa_bluetooth_device *device;
2445 pa_assert(new_profile);
2446 pa_assert_se(u = c->userdata);
2448 d = PA_CARD_PROFILE_DATA(new_profile);
2450 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2451 pa_log_error("Failed to get device object.");
2455 /* The state signal is sent by bluez, so it is racy to check
2456 strictly for CONNECTED, we should also accept STREAMING state
2457 as being good enough. However, if the profile is used
2458 concurrently (which is unlikely), ipc will fail later on, and
2459 module will be unloaded. */
2460 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2461 pa_log_warn("HSP is not connected, refused to switch profile");
2464 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2465 pa_log_warn("A2DP is not connected, refused to switch profile");
2468 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2469 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2474 inputs = pa_sink_move_all_start(u->sink, NULL);
2476 if (!USE_SCO_OVER_PCM(u))
2478 pa_sink_unlink(u->sink);
2482 outputs = pa_source_move_all_start(u->source, NULL);
2484 if (!USE_SCO_OVER_PCM(u))
2486 pa_source_unlink(u->source);
2493 u->sample_spec = u->requested_sample_spec;
2497 if (u->profile != PROFILE_OFF)
2500 if (u->sink || u->source)
2505 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2507 pa_sink_move_all_fail(inputs);
2512 pa_source_move_all_finish(u->source, outputs, FALSE);
2514 pa_source_move_all_fail(outputs);
2520 /* Run from main thread */
2521 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2522 pa_card_new_data data;
2528 const char *default_profile;
2533 pa_card_new_data_init(&data);
2534 data.driver = __FILE__;
2535 data.module = u->module;
2537 n = pa_bluetooth_cleanup_name(device->name);
2538 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2540 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2541 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2542 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2543 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2544 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2545 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2546 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2547 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2548 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2549 data.name = get_name("card", u->modargs, device->address, &b);
2550 data.namereg_fail = b;
2552 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2553 pa_log("Invalid properties");
2554 pa_card_new_data_done(&data);
2558 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2560 /* we base hsp/a2dp availability on UUIDs.
2561 Ideally, it would be based on "Connected" state, but
2562 we can't afford to wait for this information when
2563 we are loaded with profile="hsp", for instance */
2564 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2565 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2569 p->max_sink_channels = 2;
2570 p->max_source_channels = 0;
2572 d = PA_CARD_PROFILE_DATA(p);
2575 pa_hashmap_put(data.profiles, p->name, p);
2578 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2579 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2583 p->max_sink_channels = 0;
2584 p->max_source_channels = 2;
2586 d = PA_CARD_PROFILE_DATA(p);
2587 *d = PROFILE_A2DP_SOURCE;
2589 pa_hashmap_put(data.profiles, p->name, p);
2592 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2593 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2594 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2598 p->max_sink_channels = 1;
2599 p->max_source_channels = 1;
2601 d = PA_CARD_PROFILE_DATA(p);
2604 pa_hashmap_put(data.profiles, p->name, p);
2607 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2608 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2612 p->max_sink_channels = 1;
2613 p->max_source_channels = 1;
2615 d = PA_CARD_PROFILE_DATA(p);
2618 pa_hashmap_put(data.profiles, p->name, p);
2621 pa_assert(!pa_hashmap_isempty(data.profiles));
2623 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2624 d = PA_CARD_PROFILE_DATA(p);
2626 pa_hashmap_put(data.profiles, p->name, p);
2628 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2629 if (pa_hashmap_get(data.profiles, default_profile))
2630 pa_card_new_data_set_profile(&data, default_profile);
2632 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2635 u->card = pa_card_new(u->core, &data);
2636 pa_card_new_data_done(&data);
2639 pa_log("Failed to allocate card.");
2643 u->card->userdata = u;
2644 u->card->set_profile = card_set_profile;
2646 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2648 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2649 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2650 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2651 pa_log_warn("Default profile not connected, selecting off profile");
2652 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2653 u->card->save_profile = FALSE;
2656 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2662 /* Run from main thread */
2663 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2664 const pa_bluetooth_device *d = NULL;
2668 if (!address && !path) {
2669 pa_log_error("Failed to get device address/path from module arguments.");
2674 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2675 pa_log_error("%s is not a valid BlueZ audio device.", path);
2679 if (address && !(pa_streq(d->address, address))) {
2680 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2685 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2686 pa_log_error("%s is not known.", address);
2692 u->address = pa_xstrdup(d->address);
2693 u->path = pa_xstrdup(d->path);
2699 /* Run from main thread */
2700 static int setup_dbus(struct userdata *u) {
2703 dbus_error_init(&err);
2705 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2707 if (dbus_error_is_set(&err) || !u->connection) {
2708 pa_log("Failed to get D-Bus connection: %s", err.message);
2709 dbus_error_free(&err);
2716 int pa__init(pa_module* m) {
2720 const char *address, *path;
2722 char *mike, *speaker;
2723 const pa_bluetooth_device *device;
2727 dbus_error_init(&err);
2729 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2730 pa_log_error("Failed to parse module arguments");
2734 m->userdata = u = pa_xnew0(struct userdata, 1);
2739 u->sample_spec = m->core->default_sample_spec;
2743 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2744 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2745 pa_log("SCO sink not found");
2749 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2750 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2751 pa_log("SCO source not found");
2756 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2757 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2758 pa_log_error("Failed to get rate from module arguments");
2762 u->auto_connect = TRUE;
2763 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2764 pa_log("Failed to parse auto_connect= argument");
2768 channels = u->sample_spec.channels;
2769 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2770 channels <= 0 || channels > PA_CHANNELS_MAX) {
2771 pa_log_error("Failed to get channels from module arguments");
2774 u->sample_spec.channels = (uint8_t) channels;
2775 u->requested_sample_spec = u->sample_spec;
2777 address = pa_modargs_get_value(ma, "address", NULL);
2778 path = pa_modargs_get_value(ma, "path", NULL);
2780 if (setup_dbus(u) < 0)
2783 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2786 if (!(device = find_device(u, address, path)))
2789 /* Add the card structure. This will also initialize the default profile */
2790 if (add_card(u, device) < 0)
2793 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2794 pa_log_error("Failed to add filter function");
2797 u->filter_added = TRUE;
2799 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2800 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2802 if (pa_dbus_add_matches(
2803 pa_dbus_connection_get(u->connection), &err,
2811 pa_log("Failed to add D-Bus matches: %s", err.message);
2818 /* Connect to the BT service */
2821 if (u->profile != PROFILE_OFF)
2822 if (init_profile(u) < 0)
2825 if (u->sink || u->source)
2826 if (start_thread(u) < 0)
2835 dbus_error_free(&err);
2840 int pa__get_n_used(pa_module *m) {
2844 pa_assert_se(u = m->userdata);
2847 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2848 (u->source ? pa_source_linked_by(u->source) : 0);
2851 void pa__done(pa_module *m) {
2855 if (!(u = m->userdata))
2860 && !USE_SCO_OVER_PCM(u)
2863 pa_sink_unlink(u->sink);
2867 && !USE_SCO_OVER_PCM(u)
2870 pa_source_unlink(u->source);
2874 if (u->connection) {
2877 char *speaker, *mike;
2878 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2879 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2881 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2887 if (u->filter_added)
2888 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2890 pa_dbus_connection_unref(u->connection);
2894 pa_card_free(u->card);
2896 if (u->read_smoother)
2897 pa_smoother_free(u->read_smoother);
2902 pa_xfree(u->a2dp.buffer);
2904 sbc_finish(&u->a2dp.sbc);
2907 pa_modargs_free(u->modargs);
2909 pa_xfree(u->address);
2913 bt_transport_release(u);
2914 pa_xfree(u->transport);
2918 pa_bluetooth_discovery_unref(u->discovery);