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/shared.h>
43 #include <pulsecore/socket-util.h>
44 #include <pulsecore/thread.h>
45 #include <pulsecore/thread-mq.h>
46 #include <pulsecore/poll.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/namereg.h>
50 #include <pulsecore/dbus-shared.h>
51 #include <pulsecore/llist.h>
53 #include "module-bluetooth-device-symdef.h"
56 #include "a2dp-codecs.h"
58 #include "bluetooth-util.h"
60 #define BITPOOL_DEC_LIMIT 32
61 #define BITPOOL_DEC_STEP 5
63 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(FALSE);
68 "name=<name for the card/sink/source, to be prefixed> "
69 "card_name=<name for the card> "
70 "card_properties=<properties for the card> "
71 "sink_name=<name for the sink> "
72 "sink_properties=<properties for the sink> "
73 "source_name=<name for the source> "
74 "source_properties=<properties for the source> "
75 "address=<address of the device> "
76 "profile=<a2dp|hsp|hfgw> "
78 "channels=<number of channels> "
79 "path=<device object path> "
80 "auto_connect=<automatically connect?> "
81 "sco_sink=<SCO over PCM sink name> "
82 "sco_source=<SCO over PCM source name>");
84 /* TODO: not close fd when entering suspend mode in a2dp */
86 static const char* const valid_modargs[] = {
106 sbc_capabilities_t sbc_capabilities;
107 sbc_t sbc; /* Codec data */
108 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
109 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
111 void* buffer; /* Codec transfer buffer */
112 size_t buffer_size; /* Size of the buffer */
114 uint16_t seq_num; /* Cumulative packet sequence */
120 pcm_capabilities_t pcm_capabilities;
122 pa_source *sco_source;
123 pa_hook_slot *sink_state_changed_slot;
124 pa_hook_slot *source_state_changed_slot;
136 pa_bluetooth_discovery *discovery;
137 pa_bool_t auto_connect;
139 pa_dbus_connection *connection;
145 pa_thread_mq thread_mq;
147 pa_rtpoll_item *rtpoll_item;
150 uint64_t read_index, write_index;
151 pa_usec_t started_at;
152 pa_smoother *read_smoother;
154 pa_memchunk write_memchunk;
156 pa_sample_spec sample_spec, requested_sample_spec;
164 struct a2dp_info a2dp;
167 enum profile profile;
171 int stream_write_type;
172 int service_write_type, service_read_type;
174 pa_bool_t filter_added;
177 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
178 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
179 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
180 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
182 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
184 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
186 static int init_bt(struct userdata *u);
187 static int init_profile(struct userdata *u);
189 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
194 pa_assert(msg->length > 0);
196 if (u->service_fd < 0) {
197 pa_log_warn("Service not connected");
201 pa_log_debug("Sending %s -> %s",
202 pa_strnull(bt_audio_strtype(msg->type)),
203 pa_strnull(bt_audio_strname(msg->name)));
205 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
209 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
211 pa_log_error("Short write()");
216 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
220 pa_assert(u->service_fd >= 0);
222 pa_assert(room >= sizeof(*msg));
224 pa_log_debug("Trying to receive message from audio service...");
226 /* First, read the header */
227 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
230 if (msg->length < sizeof(*msg)) {
231 pa_log_error("Invalid message size.");
235 if (msg->length > room) {
236 pa_log_error("Not enough room.");
240 /* Secondly, read the payload */
241 if (msg->length > sizeof(*msg)) {
243 size_t remains = msg->length - sizeof(*msg);
245 if ((r = pa_loop_read(u->service_fd,
246 (uint8_t*) msg + sizeof(*msg),
248 &u->service_read_type)) != (ssize_t) remains)
252 pa_log_debug("Received %s <- %s",
253 pa_strnull(bt_audio_strtype(msg->type)),
254 pa_strnull(bt_audio_strname(msg->name)));
261 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
263 pa_log_error("Short read()");
268 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) {
272 pa_assert(u->service_fd >= 0);
275 if ((r = service_recv(u, rsp, room)) < 0)
278 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
279 rsp->name != expected_name ||
280 (expected_size > 0 && rsp->length != expected_size)) {
282 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
283 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
285 pa_log_error("Bogus message %s received while %s was expected",
286 pa_strnull(bt_audio_strname(rsp->name)),
287 pa_strnull(bt_audio_strname(expected_name)));
294 /* Run from main thread */
295 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
297 const codec_capabilities_t *codec;
302 bytes_left = rsp->h.length - sizeof(*rsp);
304 if (bytes_left < sizeof(codec_capabilities_t)) {
305 pa_log_error("Packet too small to store codec information.");
309 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
311 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
313 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
314 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
315 pa_log_error("Got capabilities for wrong codec.");
319 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
321 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
324 pa_assert(codec->type == BT_HFP_CODEC_PCM);
326 if (codec->configured && seid == 0)
329 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
331 } else if (u->profile == PROFILE_A2DP) {
333 while (bytes_left > 0) {
334 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
337 bytes_left -= codec->length;
338 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
341 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
344 pa_assert(codec->type == BT_A2DP_SBC_SINK);
346 if (codec->configured && seid == 0)
349 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
351 } else if (u->profile == PROFILE_A2DP_SOURCE) {
353 while (bytes_left > 0) {
354 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
357 bytes_left -= codec->length;
358 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
361 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
364 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
366 if (codec->configured && seid == 0)
369 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
375 /* Run from main thread */
376 static int get_caps(struct userdata *u, uint8_t seid) {
378 struct bt_get_capabilities_req getcaps_req;
379 struct bt_get_capabilities_rsp getcaps_rsp;
380 bt_audio_error_t error;
381 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
387 memset(&msg, 0, sizeof(msg));
388 msg.getcaps_req.h.type = BT_REQUEST;
389 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
390 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
391 msg.getcaps_req.seid = seid;
393 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
394 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
395 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
397 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
398 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
400 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
402 if (service_send(u, &msg.getcaps_req.h) < 0)
405 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
408 ret = parse_caps(u, seid, &msg.getcaps_rsp);
412 return get_caps(u, ret);
415 /* Run from main thread */
416 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
419 case BT_SBC_SAMPLING_FREQ_16000:
420 case BT_SBC_SAMPLING_FREQ_32000:
423 case BT_SBC_SAMPLING_FREQ_44100:
426 case BT_A2DP_CHANNEL_MODE_MONO:
427 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
430 case BT_A2DP_CHANNEL_MODE_STEREO:
431 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
435 pa_log_warn("Invalid channel mode %u", mode);
439 case BT_SBC_SAMPLING_FREQ_48000:
442 case BT_A2DP_CHANNEL_MODE_MONO:
443 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
446 case BT_A2DP_CHANNEL_MODE_STEREO:
447 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
451 pa_log_warn("Invalid channel mode %u", mode);
456 pa_log_warn("Invalid sampling freq %u", freq);
461 /* Run from main thread */
462 static int setup_a2dp(struct userdata *u) {
463 sbc_capabilities_t *cap;
466 static const struct {
470 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
471 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
472 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
473 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
477 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
479 cap = &u->a2dp.sbc_capabilities;
481 /* Find the lowest freq that is at least as high as the requested
483 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
484 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
485 u->sample_spec.rate = freq_table[i].rate;
486 cap->frequency = freq_table[i].cap;
490 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
491 for (--i; i >= 0; i--) {
492 if (cap->frequency & freq_table[i].cap) {
493 u->sample_spec.rate = freq_table[i].rate;
494 cap->frequency = freq_table[i].cap;
500 pa_log("Not suitable sample rate");
505 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
507 if (cap->capability.configured)
510 if (u->sample_spec.channels <= 1) {
511 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
512 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
513 u->sample_spec.channels = 1;
515 u->sample_spec.channels = 2;
518 if (u->sample_spec.channels >= 2) {
519 u->sample_spec.channels = 2;
521 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
522 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
523 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
524 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
525 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
526 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
527 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
528 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
529 u->sample_spec.channels = 1;
531 pa_log("No supported channel modes");
536 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
537 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
538 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
539 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
540 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
541 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
542 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
543 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
545 pa_log_error("No supported block lengths");
549 if (cap->subbands & BT_A2DP_SUBBANDS_8)
550 cap->subbands = BT_A2DP_SUBBANDS_8;
551 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
552 cap->subbands = BT_A2DP_SUBBANDS_4;
554 pa_log_error("No supported subbands");
558 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
559 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
560 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
561 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
563 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
564 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
569 /* Run from main thread */
570 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
571 sbc_capabilities_t *active_capabilities;
575 active_capabilities = &a2dp->sbc_capabilities;
577 if (a2dp->sbc_initialized)
578 sbc_reinit(&a2dp->sbc, 0);
580 sbc_init(&a2dp->sbc, 0);
581 a2dp->sbc_initialized = TRUE;
583 switch (active_capabilities->frequency) {
584 case BT_SBC_SAMPLING_FREQ_16000:
585 a2dp->sbc.frequency = SBC_FREQ_16000;
587 case BT_SBC_SAMPLING_FREQ_32000:
588 a2dp->sbc.frequency = SBC_FREQ_32000;
590 case BT_SBC_SAMPLING_FREQ_44100:
591 a2dp->sbc.frequency = SBC_FREQ_44100;
593 case BT_SBC_SAMPLING_FREQ_48000:
594 a2dp->sbc.frequency = SBC_FREQ_48000;
597 pa_assert_not_reached();
600 switch (active_capabilities->channel_mode) {
601 case BT_A2DP_CHANNEL_MODE_MONO:
602 a2dp->sbc.mode = SBC_MODE_MONO;
604 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
605 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
607 case BT_A2DP_CHANNEL_MODE_STEREO:
608 a2dp->sbc.mode = SBC_MODE_STEREO;
610 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
611 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
614 pa_assert_not_reached();
617 switch (active_capabilities->allocation_method) {
618 case BT_A2DP_ALLOCATION_SNR:
619 a2dp->sbc.allocation = SBC_AM_SNR;
621 case BT_A2DP_ALLOCATION_LOUDNESS:
622 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
625 pa_assert_not_reached();
628 switch (active_capabilities->subbands) {
629 case BT_A2DP_SUBBANDS_4:
630 a2dp->sbc.subbands = SBC_SB_4;
632 case BT_A2DP_SUBBANDS_8:
633 a2dp->sbc.subbands = SBC_SB_8;
636 pa_assert_not_reached();
639 switch (active_capabilities->block_length) {
640 case BT_A2DP_BLOCK_LENGTH_4:
641 a2dp->sbc.blocks = SBC_BLK_4;
643 case BT_A2DP_BLOCK_LENGTH_8:
644 a2dp->sbc.blocks = SBC_BLK_8;
646 case BT_A2DP_BLOCK_LENGTH_12:
647 a2dp->sbc.blocks = SBC_BLK_12;
649 case BT_A2DP_BLOCK_LENGTH_16:
650 a2dp->sbc.blocks = SBC_BLK_16;
653 pa_assert_not_reached();
656 a2dp->min_bitpool = active_capabilities->min_bitpool;
657 a2dp->max_bitpool = active_capabilities->max_bitpool;
659 /* Set minimum bitpool for source to get the maximum possible block_size */
660 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
661 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
662 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
665 /* Run from main thread */
666 static int set_conf(struct userdata *u) {
668 struct bt_open_req open_req;
669 struct bt_open_rsp open_rsp;
670 struct bt_set_configuration_req setconf_req;
671 struct bt_set_configuration_rsp setconf_rsp;
672 bt_audio_error_t error;
673 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
676 memset(&msg, 0, sizeof(msg));
677 msg.open_req.h.type = BT_REQUEST;
678 msg.open_req.h.name = BT_OPEN;
679 msg.open_req.h.length = sizeof(msg.open_req);
681 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
682 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
683 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
685 if (service_send(u, &msg.open_req.h) < 0)
688 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
691 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
692 u->sample_spec.format = PA_SAMPLE_S16LE;
694 if (setup_a2dp(u) < 0)
697 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
699 u->sample_spec.format = PA_SAMPLE_S16LE;
700 u->sample_spec.channels = 1;
701 u->sample_spec.rate = 8000;
704 memset(&msg, 0, sizeof(msg));
705 msg.setconf_req.h.type = BT_REQUEST;
706 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
707 msg.setconf_req.h.length = sizeof(msg.setconf_req);
709 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
710 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
712 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
713 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
714 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
716 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
718 if (service_send(u, &msg.setconf_req.h) < 0)
721 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
724 u->link_mtu = msg.setconf_rsp.link_mtu;
726 /* setup SBC encoder now we agree on parameters */
727 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
728 setup_sbc(&u->a2dp, u->profile);
731 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
732 / u->a2dp.frame_length
735 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
736 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
738 u->block_size = u->link_mtu;
744 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
746 struct a2dp_info *a2dp;
752 if (a2dp->sbc.bitpool == bitpool)
755 if (bitpool > a2dp->max_bitpool)
756 bitpool = a2dp->max_bitpool;
757 else if (bitpool < a2dp->min_bitpool)
758 bitpool = a2dp->min_bitpool;
760 a2dp->sbc.bitpool = bitpool;
762 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
763 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
765 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
768 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
769 / a2dp->frame_length * a2dp->codesize;
771 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
772 pa_sink_set_fixed_latency_within_thread(u->sink,
773 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
776 /* from IO thread, except in SCO over PCM */
778 static int setup_stream(struct userdata *u) {
779 struct pollfd *pollfd;
782 pa_make_fd_nonblock(u->stream_fd);
783 pa_make_socket_low_delay(u->stream_fd);
786 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
787 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
789 pa_log_debug("Stream properly set up, we're ready to roll!");
791 if (u->profile == PROFILE_A2DP)
792 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
794 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
795 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
796 pollfd->fd = u->stream_fd;
797 pollfd->events = pollfd->revents = 0;
799 u->read_index = u->write_index = 0;
803 u->read_smoother = pa_smoother_new(
815 static int start_stream_fd(struct userdata *u) {
817 bt_audio_msg_header_t rsp;
818 struct bt_start_stream_req start_req;
819 struct bt_start_stream_rsp start_rsp;
820 struct bt_new_stream_ind streamfd_ind;
821 bt_audio_error_t error;
822 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
826 pa_assert(u->rtpoll);
827 pa_assert(!u->rtpoll_item);
828 pa_assert(u->stream_fd < 0);
830 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
831 msg.start_req.h.type = BT_REQUEST;
832 msg.start_req.h.name = BT_START_STREAM;
833 msg.start_req.h.length = sizeof(msg.start_req);
835 if (service_send(u, &msg.start_req.h) < 0)
838 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
841 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
844 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
845 pa_log("Failed to get stream fd from audio service.");
849 return setup_stream(u);
853 static int stop_stream_fd(struct userdata *u) {
855 bt_audio_msg_header_t rsp;
856 struct bt_stop_stream_req start_req;
857 struct bt_stop_stream_rsp start_rsp;
858 bt_audio_error_t error;
859 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
864 pa_assert(u->rtpoll);
866 if (u->rtpoll_item) {
867 pa_rtpoll_item_free(u->rtpoll_item);
868 u->rtpoll_item = NULL;
871 if (u->stream_fd >= 0) {
872 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
873 msg.start_req.h.type = BT_REQUEST;
874 msg.start_req.h.name = BT_STOP_STREAM;
875 msg.start_req.h.length = sizeof(msg.start_req);
877 if (service_send(u, &msg.start_req.h) < 0 ||
878 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
881 pa_close(u->stream_fd);
885 if (u->read_smoother) {
886 pa_smoother_free(u->read_smoother);
887 u->read_smoother = NULL;
893 static void bt_transport_release(struct userdata *u) {
894 const char *accesstype = "rw";
895 const pa_bluetooth_transport *t;
897 /* Ignore if already released */
901 pa_log_debug("Releasing transport %s", u->transport);
903 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
905 pa_bluetooth_transport_release(t, accesstype);
907 pa_xfree(u->accesstype);
908 u->accesstype = NULL;
910 if (u->rtpoll_item) {
911 pa_rtpoll_item_free(u->rtpoll_item);
912 u->rtpoll_item = NULL;
915 if (u->stream_fd >= 0) {
916 pa_close(u->stream_fd);
920 if (u->read_smoother) {
921 pa_smoother_free(u->read_smoother);
922 u->read_smoother = NULL;
926 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
927 const char *accesstype = "rw";
928 const pa_bluetooth_transport *t;
936 pa_log_debug("Acquiring transport %s", u->transport);
938 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
940 pa_log("Transport %s no longer available", u->transport);
941 pa_xfree(u->transport);
946 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
947 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
948 if (u->stream_fd < 0)
951 u->accesstype = pa_xstrdup(accesstype);
952 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
958 pa_log_info("Transport %s resuming", u->transport);
959 return setup_stream(u);
962 /* Run from IO thread */
963 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
964 struct userdata *u = PA_SINK(o)->userdata;
965 pa_bool_t failed = FALSE;
968 pa_assert(u->sink == PA_SINK(o));
972 case PA_SINK_MESSAGE_SET_STATE:
974 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
976 case PA_SINK_SUSPENDED:
977 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
979 /* Stop the device if the source is suspended as well */
980 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
981 /* We deliberately ignore whether stopping
982 * actually worked. Since the stream_fd is
983 * closed it doesn't really matter */
985 bt_transport_release(u);
993 case PA_SINK_RUNNING:
994 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
997 /* Resume the device if the source was suspended as well */
998 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1000 if (bt_transport_acquire(u, TRUE) < 0)
1002 } else if (start_stream_fd(u) < 0)
1007 case PA_SINK_UNLINKED:
1009 case PA_SINK_INVALID_STATE:
1014 case PA_SINK_MESSAGE_GET_LATENCY: {
1016 if (u->read_smoother) {
1019 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1020 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1022 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1026 ri = pa_rtclock_now() - u->started_at;
1027 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1029 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1032 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1037 r = pa_sink_process_msg(o, code, data, offset, chunk);
1039 return (r < 0 || !failed) ? r : -1;
1042 /* Run from IO thread */
1043 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1044 struct userdata *u = PA_SOURCE(o)->userdata;
1045 pa_bool_t failed = FALSE;
1048 pa_assert(u->source == PA_SOURCE(o));
1052 case PA_SOURCE_MESSAGE_SET_STATE:
1054 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1056 case PA_SOURCE_SUSPENDED:
1057 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1059 /* Stop the device if the sink is suspended as well */
1060 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1062 bt_transport_release(u);
1067 if (u->read_smoother)
1068 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1071 case PA_SOURCE_IDLE:
1072 case PA_SOURCE_RUNNING:
1073 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1076 /* Resume the device if the sink was suspended as well */
1077 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1079 if (bt_transport_acquire(u, TRUE) < 0)
1081 } else if (start_stream_fd(u) < 0)
1084 /* We don't resume the smoother here. Instead we
1085 * wait until the first packet arrives */
1088 case PA_SOURCE_UNLINKED:
1089 case PA_SOURCE_INIT:
1090 case PA_SOURCE_INVALID_STATE:
1095 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1098 if (u->read_smoother) {
1099 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1100 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1102 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1104 *((pa_usec_t*) data) = 0;
1111 r = pa_source_process_msg(o, code, data, offset, chunk);
1113 return (r < 0 || !failed) ? r : -1;
1116 /* Run from IO thread */
1117 static int hsp_process_render(struct userdata *u) {
1121 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1124 /* First, render some data */
1125 if (!u->write_memchunk.memblock)
1126 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1128 pa_assert(u->write_memchunk.length == u->block_size);
1134 /* Now write that data to the socket. The socket is of type
1135 * SEQPACKET, and we generated the data of the MTU size, so this
1136 * should just work. */
1138 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1139 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1140 pa_memblock_release(u->write_memchunk.memblock);
1147 /* Retry right away if we got interrupted */
1150 else if (errno == EAGAIN)
1151 /* Hmm, apparently the socket was not writable, give up for now */
1154 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1159 pa_assert((size_t) l <= u->write_memchunk.length);
1161 if ((size_t) l != u->write_memchunk.length) {
1162 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1163 (unsigned long long) l,
1164 (unsigned long long) u->write_memchunk.length);
1169 u->write_index += (uint64_t) u->write_memchunk.length;
1170 pa_memblock_unref(u->write_memchunk.memblock);
1171 pa_memchunk_reset(&u->write_memchunk);
1180 /* Run from IO thread */
1181 static int hsp_process_push(struct userdata *u) {
1183 pa_memchunk memchunk;
1186 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1187 pa_assert(u->source);
1188 pa_assert(u->read_smoother);
1190 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1191 memchunk.index = memchunk.length = 0;
1200 pa_bool_t found_tstamp = FALSE;
1203 memset(&m, 0, sizeof(m));
1204 memset(&aux, 0, sizeof(aux));
1205 memset(&iov, 0, sizeof(iov));
1209 m.msg_control = aux;
1210 m.msg_controllen = sizeof(aux);
1212 p = pa_memblock_acquire(memchunk.memblock);
1214 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1215 l = recvmsg(u->stream_fd, &m, 0);
1216 pa_memblock_release(memchunk.memblock);
1220 if (l < 0 && errno == EINTR)
1221 /* Retry right away if we got interrupted */
1224 else if (l < 0 && errno == EAGAIN)
1225 /* Hmm, apparently the socket was not readable, give up for now. */
1228 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1233 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1235 memchunk.length = (size_t) l;
1236 u->read_index += (uint64_t) l;
1238 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1239 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1240 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1241 pa_rtclock_from_wallclock(tv);
1242 tstamp = pa_timeval_load(tv);
1243 found_tstamp = TRUE;
1247 if (!found_tstamp) {
1248 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1249 tstamp = pa_rtclock_now();
1252 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1253 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1255 pa_source_post(u->source, &memchunk);
1261 pa_memblock_unref(memchunk.memblock);
1266 /* Run from IO thread */
1267 static void a2dp_prepare_buffer(struct userdata *u) {
1270 if (u->a2dp.buffer_size >= u->link_mtu)
1273 u->a2dp.buffer_size = 2 * u->link_mtu;
1274 pa_xfree(u->a2dp.buffer);
1275 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1278 /* Run from IO thread */
1279 static int a2dp_process_render(struct userdata *u) {
1280 struct a2dp_info *a2dp;
1281 struct rtp_header *header;
1282 struct rtp_payload *payload;
1286 size_t to_write, to_encode;
1287 unsigned frame_count;
1291 pa_assert(u->profile == PROFILE_A2DP);
1294 /* First, render some data */
1295 if (!u->write_memchunk.memblock)
1296 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1298 pa_assert(u->write_memchunk.length == u->block_size);
1300 a2dp_prepare_buffer(u);
1303 header = a2dp->buffer;
1304 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1308 /* Try to create a packet of the full MTU */
1310 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1311 to_encode = u->write_memchunk.length;
1313 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1314 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1316 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1320 encoded = sbc_encode(&a2dp->sbc,
1325 if (PA_UNLIKELY(encoded <= 0)) {
1326 pa_log_error("SBC encoding error (%li)", (long) encoded);
1327 pa_memblock_release(u->write_memchunk.memblock);
1331 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1332 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1334 pa_assert_fp((size_t) encoded <= to_encode);
1335 pa_assert_fp((size_t) encoded == a2dp->codesize);
1337 pa_assert_fp((size_t) written <= to_write);
1338 pa_assert_fp((size_t) written == a2dp->frame_length);
1340 p = (const uint8_t*) p + encoded;
1341 to_encode -= encoded;
1343 d = (uint8_t*) d + written;
1344 to_write -= written;
1349 pa_memblock_release(u->write_memchunk.memblock);
1351 pa_assert(to_encode == 0);
1354 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1357 /* write it to the fifo */
1358 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1361 header->sequence_number = htons(a2dp->seq_num++);
1362 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1363 header->ssrc = htonl(1);
1364 payload->frame_count = frame_count;
1366 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1371 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1378 /* Retry right away if we got interrupted */
1381 else if (errno == EAGAIN)
1382 /* Hmm, apparently the socket was not writable, give up for now */
1385 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1390 pa_assert((size_t) l <= nbytes);
1392 if ((size_t) l != nbytes) {
1393 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1394 (unsigned long long) l,
1395 (unsigned long long) nbytes);
1400 u->write_index += (uint64_t) u->write_memchunk.length;
1401 pa_memblock_unref(u->write_memchunk.memblock);
1402 pa_memchunk_reset(&u->write_memchunk);
1412 static int a2dp_process_push(struct userdata *u) {
1414 pa_memchunk memchunk;
1417 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1418 pa_assert(u->source);
1419 pa_assert(u->read_smoother);
1421 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1422 memchunk.index = memchunk.length = 0;
1425 pa_bool_t found_tstamp = FALSE;
1427 struct a2dp_info *a2dp;
1428 struct rtp_header *header;
1429 struct rtp_payload *payload;
1433 size_t to_write, to_decode;
1434 unsigned frame_count;
1436 a2dp_prepare_buffer(u);
1439 header = a2dp->buffer;
1440 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1442 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1446 if (l < 0 && errno == EINTR)
1447 /* Retry right away if we got interrupted */
1450 else if (l < 0 && errno == EAGAIN)
1451 /* Hmm, apparently the socket was not readable, give up for now. */
1454 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1459 pa_assert((size_t) l <= a2dp->buffer_size);
1461 u->read_index += (uint64_t) l;
1463 /* TODO: get timestamp from rtp */
1464 if (!found_tstamp) {
1465 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1466 tstamp = pa_rtclock_now();
1469 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1470 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1472 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1473 to_decode = l - sizeof(*header) - sizeof(*payload);
1475 d = pa_memblock_acquire(memchunk.memblock);
1476 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1478 while (PA_LIKELY(to_decode > 0)) {
1482 decoded = sbc_decode(&a2dp->sbc,
1487 if (PA_UNLIKELY(decoded <= 0)) {
1488 pa_log_error("SBC decoding error (%li)", (long) decoded);
1489 pa_memblock_release(memchunk.memblock);
1490 pa_memblock_unref(memchunk.memblock);
1494 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1495 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1497 /* Reset frame length, it can be changed due to bitpool change */
1498 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1500 pa_assert_fp((size_t) decoded <= to_decode);
1501 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1503 pa_assert_fp((size_t) written == a2dp->codesize);
1505 p = (const uint8_t*) p + decoded;
1506 to_decode -= decoded;
1508 d = (uint8_t*) d + written;
1509 to_write -= written;
1514 memchunk.length -= to_write;
1516 pa_memblock_release(memchunk.memblock);
1518 pa_source_post(u->source, &memchunk);
1524 pa_memblock_unref(memchunk.memblock);
1529 static void a2dp_reduce_bitpool(struct userdata *u)
1531 struct a2dp_info *a2dp;
1538 /* Check if bitpool is already at its limit */
1539 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1542 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1544 if (bitpool < BITPOOL_DEC_LIMIT)
1545 bitpool = BITPOOL_DEC_LIMIT;
1547 a2dp_set_bitpool(u, bitpool);
1550 static void thread_func(void *userdata) {
1551 struct userdata *u = userdata;
1552 unsigned do_write = 0;
1553 pa_bool_t writable = FALSE;
1557 pa_log_debug("IO Thread starting up");
1559 if (u->core->realtime_scheduling)
1560 pa_make_realtime(u->core->realtime_priority);
1562 pa_thread_mq_install(&u->thread_mq);
1565 if (bt_transport_acquire(u, TRUE) < 0)
1567 } else if (start_stream_fd(u) < 0)
1571 struct pollfd *pollfd;
1573 pa_bool_t disable_timer = TRUE;
1575 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1577 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1579 /* We should send two blocks to the device before we expect
1582 if (u->write_index == 0 && u->read_index <= 0)
1585 if (pollfd && (pollfd->revents & POLLIN)) {
1588 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1589 n_read = hsp_process_push(u);
1591 n_read = a2dp_process_push(u);
1596 /* We just read something, so we are supposed to write something, too */
1601 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1603 if (u->sink->thread_info.rewind_requested)
1604 pa_sink_process_rewind(u->sink, 0);
1607 if (pollfd->revents & POLLOUT)
1610 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1611 pa_usec_t time_passed;
1612 pa_usec_t audio_sent;
1614 /* Hmm, there is no input stream we could synchronize
1615 * to. So let's do things by time */
1617 time_passed = pa_rtclock_now() - u->started_at;
1618 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1620 if (audio_sent <= time_passed) {
1621 pa_usec_t audio_to_send = time_passed - audio_sent;
1623 /* Never try to catch up for more than 100ms */
1624 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1625 pa_usec_t skip_usec;
1626 uint64_t skip_bytes;
1628 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1629 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1631 if (skip_bytes > 0) {
1634 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1635 (unsigned long long) skip_usec,
1636 (unsigned long long) skip_bytes);
1638 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1639 pa_memblock_unref(tmp.memblock);
1640 u->write_index += skip_bytes;
1642 if (u->profile == PROFILE_A2DP)
1643 a2dp_reduce_bitpool(u);
1651 if (writable && do_write > 0) {
1654 if (u->write_index <= 0)
1655 u->started_at = pa_rtclock_now();
1657 if (u->profile == PROFILE_A2DP) {
1658 if ((n_written = a2dp_process_render(u)) < 0)
1661 if ((n_written = hsp_process_render(u)) < 0)
1666 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1668 do_write -= n_written;
1672 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1673 pa_usec_t time_passed, next_write_at, sleep_for;
1675 /* Hmm, there is no input stream we could synchronize
1676 * to. So let's estimate when we need to wake up the latest */
1678 time_passed = pa_rtclock_now() - u->started_at;
1679 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1680 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1682 /* 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); */
1684 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1685 disable_timer = FALSE;
1691 pa_rtpoll_set_timer_disabled(u->rtpoll);
1693 /* Hmm, nothing to do. Let's sleep */
1695 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1696 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1698 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1704 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1706 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1707 pa_log_info("FD error: %s%s%s%s",
1708 pollfd->revents & POLLERR ? "POLLERR " :"",
1709 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1710 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1711 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1717 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1718 pa_log_debug("IO thread failed");
1719 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1720 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1723 pa_log_debug("IO thread shutting down");
1726 /* Run from main thread */
1727 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1733 pa_assert_se(u = userdata);
1735 dbus_error_init(&err);
1737 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1738 dbus_message_get_interface(m),
1739 dbus_message_get_path(m),
1740 dbus_message_get_member(m));
1742 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1745 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1746 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1751 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1752 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1756 if (u->profile == PROFILE_HSP) {
1757 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1759 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1760 pa_sink_volume_changed(u->sink, &v);
1762 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1764 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1765 pa_source_volume_changed(u->source, &v);
1768 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1769 DBusMessageIter arg_i;
1770 pa_bluetooth_transport *t;
1773 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1776 if (!dbus_message_iter_init(m, &arg_i)) {
1777 pa_log("Failed to parse PropertyChanged: %s", err.message);
1783 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1786 if (nrec != t->nrec) {
1787 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1788 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1793 dbus_error_free(&err);
1795 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1798 /* Run from main thread */
1799 static void sink_set_volume_cb(pa_sink *s) {
1808 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1809 u = pa_shared_get(s->core, k);
1813 pa_assert(u->sink == s);
1814 pa_assert(u->profile == PROFILE_HSP);
1816 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1821 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1823 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1824 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1825 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1826 dbus_message_unref(m);
1829 /* Run from main thread */
1830 static void source_set_volume_cb(pa_source *s) {
1839 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1840 u = pa_shared_get(s->core, k);
1844 pa_assert(u->source == s);
1845 pa_assert(u->profile == PROFILE_HSP);
1847 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1852 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1854 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1855 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1856 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1857 dbus_message_unref(m);
1860 /* Run from main thread */
1861 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1867 pa_assert(device_id);
1868 pa_assert(namereg_fail);
1870 t = pa_sprintf_malloc("%s_name", type);
1871 n = pa_modargs_get_value(ma, t, NULL);
1875 *namereg_fail = TRUE;
1876 return pa_xstrdup(n);
1879 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1880 *namereg_fail = TRUE;
1883 *namereg_fail = FALSE;
1886 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1889 static int 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 && u->stream_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");
1908 return bt_transport_acquire(u, TRUE);
1910 return start_stream_fd(u);
1913 if (u->service_fd < 0 && u->stream_fd < 0)
1916 pa_log_debug("Closing SCO over PCM");
1919 bt_transport_release(u);
1920 else if (u->stream_fd >= 0)
1923 if (u->service_fd >= 0) {
1924 pa_close(u->service_fd);
1932 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1934 pa_sink_assert_ref(s);
1937 if (s != u->hsp.sco_sink)
1940 sco_over_pcm_state_update(u);
1945 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1947 pa_source_assert_ref(s);
1950 if (s != u->hsp.sco_source)
1953 sco_over_pcm_state_update(u);
1958 /* Run from main thread */
1959 static int add_sink(struct userdata *u) {
1960 if (USE_SCO_OVER_PCM(u)) {
1963 u->sink = u->hsp.sco_sink;
1964 p = pa_proplist_new();
1965 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1966 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1967 pa_proplist_free(p);
1969 if (!u->hsp.sink_state_changed_slot)
1970 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) {
2020 if (USE_SCO_OVER_PCM(u)) {
2021 u->source = u->hsp.sco_source;
2022 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2024 if (!u->hsp.source_state_changed_slot)
2025 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);
2028 pa_source_new_data data;
2031 pa_source_new_data_init(&data);
2032 data.driver = __FILE__;
2033 data.module = u->module;
2034 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2035 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2036 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2037 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2039 data.card = u->card;
2040 data.name = get_name("source", u->modargs, u->address, &b);
2041 data.namereg_fail = b;
2043 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2044 pa_log("Invalid properties");
2045 pa_source_new_data_done(&data);
2049 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2050 pa_source_new_data_done(&data);
2053 pa_log_error("Failed to create source");
2057 u->source->userdata = u;
2058 u->source->parent.process_msg = source_process_msg;
2060 pa_source_set_fixed_latency(u->source,
2061 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2062 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2065 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2067 const pa_bluetooth_transport *t;
2068 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2070 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2072 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2075 if (u->profile == PROFILE_HSP) {
2076 u->source->set_volume = source_set_volume_cb;
2077 u->source->n_volume_steps = 16;
2083 /* Run from main thread */
2084 static void shutdown_bt(struct userdata *u) {
2087 if (u->stream_fd >= 0) {
2088 pa_close(u->stream_fd);
2091 u->stream_write_type = 0;
2094 if (u->service_fd >= 0) {
2095 pa_close(u->service_fd);
2097 u->service_write_type = 0;
2098 u->service_read_type = 0;
2101 if (u->write_memchunk.memblock) {
2102 pa_memblock_unref(u->write_memchunk.memblock);
2103 pa_memchunk_reset(&u->write_memchunk);
2107 static int bt_transport_config_a2dp(struct userdata *u) {
2108 const pa_bluetooth_transport *t;
2109 struct a2dp_info *a2dp = &u->a2dp;
2112 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2115 config = (a2dp_sbc_t *) t->config;
2117 if (a2dp->sbc_initialized)
2118 sbc_reinit(&a2dp->sbc, 0);
2120 sbc_init(&a2dp->sbc, 0);
2121 a2dp->sbc_initialized = TRUE;
2123 switch (config->frequency) {
2124 case BT_SBC_SAMPLING_FREQ_16000:
2125 a2dp->sbc.frequency = SBC_FREQ_16000;
2127 case BT_SBC_SAMPLING_FREQ_32000:
2128 a2dp->sbc.frequency = SBC_FREQ_32000;
2130 case BT_SBC_SAMPLING_FREQ_44100:
2131 a2dp->sbc.frequency = SBC_FREQ_44100;
2133 case BT_SBC_SAMPLING_FREQ_48000:
2134 a2dp->sbc.frequency = SBC_FREQ_48000;
2137 pa_assert_not_reached();
2140 switch (config->channel_mode) {
2141 case BT_A2DP_CHANNEL_MODE_MONO:
2142 a2dp->sbc.mode = SBC_MODE_MONO;
2144 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2145 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2147 case BT_A2DP_CHANNEL_MODE_STEREO:
2148 a2dp->sbc.mode = SBC_MODE_STEREO;
2150 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2151 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2154 pa_assert_not_reached();
2157 switch (config->allocation_method) {
2158 case BT_A2DP_ALLOCATION_SNR:
2159 a2dp->sbc.allocation = SBC_AM_SNR;
2161 case BT_A2DP_ALLOCATION_LOUDNESS:
2162 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2165 pa_assert_not_reached();
2168 switch (config->subbands) {
2169 case BT_A2DP_SUBBANDS_4:
2170 a2dp->sbc.subbands = SBC_SB_4;
2172 case BT_A2DP_SUBBANDS_8:
2173 a2dp->sbc.subbands = SBC_SB_8;
2176 pa_assert_not_reached();
2179 switch (config->block_length) {
2180 case BT_A2DP_BLOCK_LENGTH_4:
2181 a2dp->sbc.blocks = SBC_BLK_4;
2183 case BT_A2DP_BLOCK_LENGTH_8:
2184 a2dp->sbc.blocks = SBC_BLK_8;
2186 case BT_A2DP_BLOCK_LENGTH_12:
2187 a2dp->sbc.blocks = SBC_BLK_12;
2189 case BT_A2DP_BLOCK_LENGTH_16:
2190 a2dp->sbc.blocks = SBC_BLK_16;
2193 pa_assert_not_reached();
2196 a2dp->min_bitpool = config->min_bitpool;
2197 a2dp->max_bitpool = config->max_bitpool;
2199 /* Set minimum bitpool for source to get the maximum possible block_size */
2200 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2201 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2202 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2205 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2206 / a2dp->frame_length
2209 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2210 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2215 static int bt_transport_config(struct userdata *u) {
2216 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2217 u->block_size = u->link_mtu;
2221 return bt_transport_config_a2dp(u);
2224 /* Run from main thread */
2225 static int bt_transport_open(struct userdata *u) {
2226 if (bt_transport_acquire(u, FALSE) < 0)
2229 return bt_transport_config(u);
2232 /* Run from main thread */
2233 static int init_bt(struct userdata *u) {
2238 u->stream_write_type = 0;
2239 u->service_write_type = 0;
2240 u->service_read_type = 0;
2242 if ((u->service_fd = bt_audio_service_open()) < 0) {
2243 pa_log_warn("Bluetooth audio service not available");
2247 pa_log_debug("Connected to the bluetooth audio service");
2252 /* Run from main thread */
2253 static int setup_bt(struct userdata *u) {
2254 const pa_bluetooth_device *d;
2255 const pa_bluetooth_transport *t;
2259 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2260 pa_log_error("Failed to get device object.");
2264 /* release transport if exist */
2266 bt_transport_release(u);
2267 pa_xfree(u->transport);
2268 u->transport = NULL;
2271 /* check if profile has a transport */
2272 t = pa_bluetooth_device_get_transport(d, u->profile);
2274 u->transport = pa_xstrdup(t->path);
2275 return bt_transport_open(u);
2278 if (get_caps(u, 0) < 0)
2281 pa_log_debug("Got device capabilities");
2283 if (set_conf(u) < 0)
2286 pa_log_debug("Connection to the device configured");
2288 if (USE_SCO_OVER_PCM(u)) {
2289 pa_log_debug("Configured to use SCO over PCM");
2293 pa_log_debug("Got the stream socket");
2298 /* Run from main thread */
2299 static int init_profile(struct userdata *u) {
2302 pa_assert(u->profile != PROFILE_OFF);
2304 if (setup_bt(u) < 0)
2307 if (u->profile == PROFILE_A2DP ||
2308 u->profile == PROFILE_HSP ||
2309 u->profile == PROFILE_HFGW)
2310 if (add_sink(u) < 0)
2313 if (u->profile == PROFILE_HSP ||
2314 u->profile == PROFILE_A2DP_SOURCE ||
2315 u->profile == PROFILE_HFGW)
2316 if (add_source(u) < 0)
2322 /* Run from main thread */
2323 static void stop_thread(struct userdata *u) {
2327 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2328 pa_thread_free(u->thread);
2332 if (u->rtpoll_item) {
2333 pa_rtpoll_item_free(u->rtpoll_item);
2334 u->rtpoll_item = NULL;
2337 if (u->hsp.sink_state_changed_slot) {
2338 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2339 u->hsp.sink_state_changed_slot = NULL;
2342 if (u->hsp.source_state_changed_slot) {
2343 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2344 u->hsp.source_state_changed_slot = NULL;
2348 pa_sink_unref(u->sink);
2353 pa_source_unref(u->source);
2358 pa_thread_mq_done(&u->thread_mq);
2360 pa_rtpoll_free(u->rtpoll);
2364 if (u->read_smoother) {
2365 pa_smoother_free(u->read_smoother);
2366 u->read_smoother = NULL;
2370 /* Run from main thread */
2371 static int start_thread(struct userdata *u) {
2373 pa_assert(!u->thread);
2374 pa_assert(!u->rtpoll);
2375 pa_assert(!u->rtpoll_item);
2377 u->rtpoll = pa_rtpoll_new();
2378 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2380 if (USE_SCO_OVER_PCM(u)) {
2381 if (sco_over_pcm_state_update(u) < 0) {
2387 pa_sink_ref(u->sink);
2388 pa_source_ref(u->source);
2389 /* FIXME: monitor stream_fd error */
2393 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2394 pa_log_error("Failed to create IO thread");
2400 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2401 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2402 pa_sink_put(u->sink);
2404 if (u->sink->set_volume)
2405 u->sink->set_volume(u->sink);
2409 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2410 pa_source_set_rtpoll(u->source, u->rtpoll);
2411 pa_source_put(u->source);
2413 if (u->source->set_volume)
2414 u->source->set_volume(u->source);
2420 /* Run from main thread */
2421 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2424 pa_queue *inputs = NULL, *outputs = NULL;
2425 const pa_bluetooth_device *device;
2428 pa_assert(new_profile);
2429 pa_assert_se(u = c->userdata);
2431 d = PA_CARD_PROFILE_DATA(new_profile);
2433 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2434 pa_log_error("Failed to get device object.");
2438 /* The state signal is sent by bluez, so it is racy to check
2439 strictly for CONNECTED, we should also accept STREAMING state
2440 as being good enough. However, if the profile is used
2441 concurrently (which is unlikely), ipc will fail later on, and
2442 module will be unloaded. */
2443 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2444 pa_log_warn("HSP is not connected, refused to switch profile");
2447 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2448 pa_log_warn("A2DP is not connected, refused to switch profile");
2451 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2452 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2457 inputs = pa_sink_move_all_start(u->sink, NULL);
2459 if (!USE_SCO_OVER_PCM(u))
2460 pa_sink_unlink(u->sink);
2464 outputs = pa_source_move_all_start(u->source, NULL);
2466 if (!USE_SCO_OVER_PCM(u))
2467 pa_source_unlink(u->source);
2474 u->sample_spec = u->requested_sample_spec;
2478 if (u->profile != PROFILE_OFF)
2481 if (u->sink || u->source)
2486 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2488 pa_sink_move_all_fail(inputs);
2493 pa_source_move_all_finish(u->source, outputs, FALSE);
2495 pa_source_move_all_fail(outputs);
2501 /* Run from main thread */
2502 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2503 pa_card_new_data data;
2509 const char *default_profile;
2514 pa_card_new_data_init(&data);
2515 data.driver = __FILE__;
2516 data.module = u->module;
2518 n = pa_bluetooth_cleanup_name(device->name);
2519 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2521 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2522 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2523 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2524 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2525 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2526 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2527 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2528 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2529 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2530 data.name = get_name("card", u->modargs, device->address, &b);
2531 data.namereg_fail = b;
2533 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2534 pa_log("Invalid properties");
2535 pa_card_new_data_done(&data);
2539 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2541 /* we base hsp/a2dp availability on UUIDs.
2542 Ideally, it would be based on "Connected" state, but
2543 we can't afford to wait for this information when
2544 we are loaded with profile="hsp", for instance */
2545 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2546 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2550 p->max_sink_channels = 2;
2551 p->max_source_channels = 0;
2553 d = PA_CARD_PROFILE_DATA(p);
2556 pa_hashmap_put(data.profiles, p->name, p);
2559 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2560 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2564 p->max_sink_channels = 0;
2565 p->max_source_channels = 2;
2567 d = PA_CARD_PROFILE_DATA(p);
2568 *d = PROFILE_A2DP_SOURCE;
2570 pa_hashmap_put(data.profiles, p->name, p);
2573 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2574 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2575 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2579 p->max_sink_channels = 1;
2580 p->max_source_channels = 1;
2582 d = PA_CARD_PROFILE_DATA(p);
2585 pa_hashmap_put(data.profiles, p->name, p);
2588 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2589 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2593 p->max_sink_channels = 1;
2594 p->max_source_channels = 1;
2596 d = PA_CARD_PROFILE_DATA(p);
2599 pa_hashmap_put(data.profiles, p->name, p);
2602 pa_assert(!pa_hashmap_isempty(data.profiles));
2604 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2605 d = PA_CARD_PROFILE_DATA(p);
2607 pa_hashmap_put(data.profiles, p->name, p);
2609 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2610 if (pa_hashmap_get(data.profiles, default_profile))
2611 pa_card_new_data_set_profile(&data, default_profile);
2613 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2616 u->card = pa_card_new(u->core, &data);
2617 pa_card_new_data_done(&data);
2620 pa_log("Failed to allocate card.");
2624 u->card->userdata = u;
2625 u->card->set_profile = card_set_profile;
2627 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2629 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2630 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2631 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2632 pa_log_warn("Default profile not connected, selecting off profile");
2633 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2634 u->card->save_profile = FALSE;
2637 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2643 /* Run from main thread */
2644 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2645 const pa_bluetooth_device *d = NULL;
2649 if (!address && !path) {
2650 pa_log_error("Failed to get device address/path from module arguments.");
2655 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2656 pa_log_error("%s is not a valid BlueZ audio device.", path);
2660 if (address && !(pa_streq(d->address, address))) {
2661 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2666 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2667 pa_log_error("%s is not known.", address);
2673 u->address = pa_xstrdup(d->address);
2674 u->path = pa_xstrdup(d->path);
2680 /* Run from main thread */
2681 static int setup_dbus(struct userdata *u) {
2684 dbus_error_init(&err);
2686 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2688 if (dbus_error_is_set(&err) || !u->connection) {
2689 pa_log("Failed to get D-Bus connection: %s", err.message);
2690 dbus_error_free(&err);
2697 int pa__init(pa_module* m) {
2701 const char *address, *path;
2703 char *mike, *speaker, *transport, *k;
2704 const pa_bluetooth_device *device;
2708 dbus_error_init(&err);
2710 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2711 pa_log_error("Failed to parse module arguments");
2715 m->userdata = u = pa_xnew0(struct userdata, 1);
2720 u->sample_spec = m->core->default_sample_spec;
2723 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2724 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2725 pa_log("SCO sink not found");
2729 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2730 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2731 pa_log("SCO source not found");
2735 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2736 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2737 pa_log_error("Failed to get rate from module arguments");
2741 u->auto_connect = TRUE;
2742 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2743 pa_log("Failed to parse auto_connect= argument");
2747 channels = u->sample_spec.channels;
2748 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2749 channels <= 0 || channels > PA_CHANNELS_MAX) {
2750 pa_log_error("Failed to get channels from module arguments");
2753 u->sample_spec.channels = (uint8_t) channels;
2754 u->requested_sample_spec = u->sample_spec;
2756 address = pa_modargs_get_value(ma, "address", NULL);
2757 path = pa_modargs_get_value(ma, "path", NULL);
2759 if (setup_dbus(u) < 0)
2762 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2765 if (!(device = find_device(u, address, path)))
2768 /* Add the card structure. This will also initialize the default profile */
2769 if (add_card(u, device) < 0)
2772 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2773 pa_log_error("Failed to add filter function");
2776 u->filter_added = TRUE;
2778 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2779 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2780 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2782 if (pa_dbus_add_matches(
2783 pa_dbus_connection_get(u->connection), &err,
2791 pa_xfree(transport);
2793 pa_log("Failed to add D-Bus matches: %s", err.message);
2799 pa_xfree(transport);
2801 /* Connect to the BT service */
2804 if (u->hsp.sco_sink) {
2805 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->hsp.sco_sink);
2806 pa_shared_set(u->core, k, u);
2810 if (u->hsp.sco_source) {
2811 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->hsp.sco_source);
2812 pa_shared_set(u->core, k, u);
2816 if (u->profile != PROFILE_OFF)
2817 if (init_profile(u) < 0)
2820 if (u->sink || u->source)
2821 if (start_thread(u) < 0)
2830 dbus_error_free(&err);
2835 int pa__get_n_used(pa_module *m) {
2839 pa_assert_se(u = m->userdata);
2842 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2843 (u->source ? pa_source_linked_by(u->source) : 0);
2846 void pa__done(pa_module *m) {
2852 if (!(u = m->userdata))
2855 if (u->sink && !USE_SCO_OVER_PCM(u))
2856 pa_sink_unlink(u->sink);
2858 if (u->source && !USE_SCO_OVER_PCM(u))
2859 pa_source_unlink(u->source);
2863 if (u->connection) {
2866 char *speaker, *mike;
2867 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2868 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2870 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2876 if (u->filter_added)
2877 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2879 pa_dbus_connection_unref(u->connection);
2883 pa_card_free(u->card);
2885 if (u->read_smoother)
2886 pa_smoother_free(u->read_smoother);
2890 if (u->hsp.sco_sink) {
2891 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->hsp.sco_sink);
2892 pa_shared_remove(u->core, k);
2896 if (u->hsp.sco_source) {
2897 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->hsp.sco_source);
2898 pa_shared_remove(u->core, k);
2903 pa_xfree(u->a2dp.buffer);
2905 sbc_finish(&u->a2dp.sbc);
2908 pa_modargs_free(u->modargs);
2910 pa_xfree(u->address);
2914 bt_transport_release(u);
2915 pa_xfree(u->transport);
2919 pa_bluetooth_discovery_unref(u->discovery);