2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
28 #include <linux/sockios.h>
29 #include <arpa/inet.h>
31 #include <pulse/rtclock.h>
32 #include <pulse/sample.h>
33 #include <pulse/timeval.h>
34 #include <pulse/xmalloc.h>
36 #include <pulsecore/i18n.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/modargs.h>
39 #include <pulsecore/core-rtclock.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/shared.h>
43 #include <pulsecore/socket-util.h>
44 #include <pulsecore/thread.h>
45 #include <pulsecore/thread-mq.h>
46 #include <pulsecore/poll.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/namereg.h>
50 #include <pulsecore/dbus-shared.h>
52 #include "module-bluetooth-device-symdef.h"
55 #include "a2dp-codecs.h"
57 #include "bluetooth-util.h"
59 #define BITPOOL_DEC_LIMIT 32
60 #define BITPOOL_DEC_STEP 5
61 #define HSP_MAX_GAIN 15
63 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(FALSE);
68 "name=<name for the card/sink/source, to be prefixed> "
69 "card_name=<name for the card> "
70 "card_properties=<properties for the card> "
71 "sink_name=<name for the sink> "
72 "sink_properties=<properties for the sink> "
73 "source_name=<name for the source> "
74 "source_properties=<properties for the source> "
75 "address=<address of the device> "
76 "profile=<a2dp|hsp|hfgw> "
78 "channels=<number of channels> "
79 "path=<device object path> "
80 "auto_connect=<automatically connect?> "
81 "sco_sink=<SCO over PCM sink name> "
82 "sco_source=<SCO over PCM source name>");
84 /* TODO: not close fd when entering suspend mode in a2dp */
86 static const char* const valid_modargs[] = {
106 sbc_capabilities_t sbc_capabilities;
107 sbc_t sbc; /* Codec data */
108 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
109 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
111 void* buffer; /* Codec transfer buffer */
112 size_t buffer_size; /* Size of the buffer */
114 uint16_t seq_num; /* Cumulative packet sequence */
120 pcm_capabilities_t pcm_capabilities;
122 void (*sco_sink_set_volume)(pa_sink *s);
123 pa_source *sco_source;
124 void (*sco_source_set_volume)(pa_source *s);
125 pa_hook_slot *sink_state_changed_slot;
126 pa_hook_slot *source_state_changed_slot;
138 pa_bluetooth_discovery *discovery;
139 pa_bool_t auto_connect;
141 pa_dbus_connection *connection;
147 pa_thread_mq thread_mq;
149 pa_rtpoll_item *rtpoll_item;
152 uint64_t read_index, write_index;
153 pa_usec_t started_at;
154 pa_smoother *read_smoother;
156 pa_memchunk write_memchunk;
158 pa_sample_spec sample_spec, requested_sample_spec;
166 struct a2dp_info a2dp;
169 enum profile profile;
173 int stream_write_type;
174 int service_write_type, service_read_type;
176 pa_bool_t filter_added;
179 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
180 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
181 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
182 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
184 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
186 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
188 static int init_bt(struct userdata *u);
189 static int init_profile(struct userdata *u);
191 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
196 pa_assert(msg->length > 0);
198 if (u->service_fd < 0) {
199 pa_log_warn("Service not connected");
203 pa_log_debug("Sending %s -> %s",
204 pa_strnull(bt_audio_strtype(msg->type)),
205 pa_strnull(bt_audio_strname(msg->name)));
207 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
211 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
213 pa_log_error("Short write()");
218 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
222 pa_assert(u->service_fd >= 0);
224 pa_assert(room >= sizeof(*msg));
226 pa_log_debug("Trying to receive message from audio service...");
228 /* First, read the header */
229 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
232 if (msg->length < sizeof(*msg)) {
233 pa_log_error("Invalid message size.");
237 if (msg->length > room) {
238 pa_log_error("Not enough room.");
242 /* Secondly, read the payload */
243 if (msg->length > sizeof(*msg)) {
245 size_t remains = msg->length - sizeof(*msg);
247 if ((r = pa_loop_read(u->service_fd,
248 (uint8_t*) msg + sizeof(*msg),
250 &u->service_read_type)) != (ssize_t) remains)
254 pa_log_debug("Received %s <- %s",
255 pa_strnull(bt_audio_strtype(msg->type)),
256 pa_strnull(bt_audio_strname(msg->name)));
263 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
265 pa_log_error("Short read()");
270 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) {
274 pa_assert(u->service_fd >= 0);
277 if ((r = service_recv(u, rsp, room)) < 0)
280 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
281 rsp->name != expected_name ||
282 (expected_size > 0 && rsp->length != expected_size)) {
284 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
285 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
287 pa_log_error("Bogus message %s received while %s was expected",
288 pa_strnull(bt_audio_strname(rsp->name)),
289 pa_strnull(bt_audio_strname(expected_name)));
296 /* Run from main thread */
297 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
299 const codec_capabilities_t *codec;
304 bytes_left = rsp->h.length - sizeof(*rsp);
306 if (bytes_left < sizeof(codec_capabilities_t)) {
307 pa_log_error("Packet too small to store codec information.");
311 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
313 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
315 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
316 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
317 pa_log_error("Got capabilities for wrong codec.");
321 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
323 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
326 pa_assert(codec->type == BT_HFP_CODEC_PCM);
328 if (codec->configured && seid == 0)
331 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
333 } else if (u->profile == PROFILE_A2DP) {
335 while (bytes_left > 0) {
336 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
339 bytes_left -= codec->length;
340 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
343 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
346 pa_assert(codec->type == BT_A2DP_SBC_SINK);
348 if (codec->configured && seid == 0)
351 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
353 } else if (u->profile == PROFILE_A2DP_SOURCE) {
355 while (bytes_left > 0) {
356 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
359 bytes_left -= codec->length;
360 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
363 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
366 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
368 if (codec->configured && seid == 0)
371 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
377 /* Run from main thread */
378 static int get_caps(struct userdata *u, uint8_t seid) {
380 struct bt_get_capabilities_req getcaps_req;
381 struct bt_get_capabilities_rsp getcaps_rsp;
382 bt_audio_error_t error;
383 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
389 memset(&msg, 0, sizeof(msg));
390 msg.getcaps_req.h.type = BT_REQUEST;
391 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
392 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
393 msg.getcaps_req.seid = seid;
395 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
396 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
397 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
399 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
400 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
402 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
404 if (service_send(u, &msg.getcaps_req.h) < 0)
407 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
410 ret = parse_caps(u, seid, &msg.getcaps_rsp);
414 return get_caps(u, ret);
417 /* Run from main thread */
418 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
421 case BT_SBC_SAMPLING_FREQ_16000:
422 case BT_SBC_SAMPLING_FREQ_32000:
425 case BT_SBC_SAMPLING_FREQ_44100:
428 case BT_A2DP_CHANNEL_MODE_MONO:
429 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
432 case BT_A2DP_CHANNEL_MODE_STEREO:
433 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
437 pa_log_warn("Invalid channel mode %u", mode);
441 case BT_SBC_SAMPLING_FREQ_48000:
444 case BT_A2DP_CHANNEL_MODE_MONO:
445 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
448 case BT_A2DP_CHANNEL_MODE_STEREO:
449 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
453 pa_log_warn("Invalid channel mode %u", mode);
458 pa_log_warn("Invalid sampling freq %u", freq);
463 /* Run from main thread */
464 static int setup_a2dp(struct userdata *u) {
465 sbc_capabilities_t *cap;
468 static const struct {
472 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
473 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
474 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
475 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
479 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
481 cap = &u->a2dp.sbc_capabilities;
483 /* Find the lowest freq that is at least as high as the requested
485 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
486 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
487 u->sample_spec.rate = freq_table[i].rate;
488 cap->frequency = freq_table[i].cap;
492 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
493 for (--i; i >= 0; i--) {
494 if (cap->frequency & freq_table[i].cap) {
495 u->sample_spec.rate = freq_table[i].rate;
496 cap->frequency = freq_table[i].cap;
502 pa_log("Not suitable sample rate");
507 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
509 if (cap->capability.configured)
512 if (u->sample_spec.channels <= 1) {
513 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
514 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
515 u->sample_spec.channels = 1;
517 u->sample_spec.channels = 2;
520 if (u->sample_spec.channels >= 2) {
521 u->sample_spec.channels = 2;
523 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
524 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
525 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
526 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
527 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
528 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
529 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
530 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
531 u->sample_spec.channels = 1;
533 pa_log("No supported channel modes");
538 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
539 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
540 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
541 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
542 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
543 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
544 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
545 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
547 pa_log_error("No supported block lengths");
551 if (cap->subbands & BT_A2DP_SUBBANDS_8)
552 cap->subbands = BT_A2DP_SUBBANDS_8;
553 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
554 cap->subbands = BT_A2DP_SUBBANDS_4;
556 pa_log_error("No supported subbands");
560 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
561 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
562 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
563 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
565 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
566 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
571 /* Run from main thread */
572 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
573 sbc_capabilities_t *active_capabilities;
577 active_capabilities = &a2dp->sbc_capabilities;
579 if (a2dp->sbc_initialized)
580 sbc_reinit(&a2dp->sbc, 0);
582 sbc_init(&a2dp->sbc, 0);
583 a2dp->sbc_initialized = TRUE;
585 switch (active_capabilities->frequency) {
586 case BT_SBC_SAMPLING_FREQ_16000:
587 a2dp->sbc.frequency = SBC_FREQ_16000;
589 case BT_SBC_SAMPLING_FREQ_32000:
590 a2dp->sbc.frequency = SBC_FREQ_32000;
592 case BT_SBC_SAMPLING_FREQ_44100:
593 a2dp->sbc.frequency = SBC_FREQ_44100;
595 case BT_SBC_SAMPLING_FREQ_48000:
596 a2dp->sbc.frequency = SBC_FREQ_48000;
599 pa_assert_not_reached();
602 switch (active_capabilities->channel_mode) {
603 case BT_A2DP_CHANNEL_MODE_MONO:
604 a2dp->sbc.mode = SBC_MODE_MONO;
606 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
607 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
609 case BT_A2DP_CHANNEL_MODE_STEREO:
610 a2dp->sbc.mode = SBC_MODE_STEREO;
612 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
613 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
616 pa_assert_not_reached();
619 switch (active_capabilities->allocation_method) {
620 case BT_A2DP_ALLOCATION_SNR:
621 a2dp->sbc.allocation = SBC_AM_SNR;
623 case BT_A2DP_ALLOCATION_LOUDNESS:
624 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
627 pa_assert_not_reached();
630 switch (active_capabilities->subbands) {
631 case BT_A2DP_SUBBANDS_4:
632 a2dp->sbc.subbands = SBC_SB_4;
634 case BT_A2DP_SUBBANDS_8:
635 a2dp->sbc.subbands = SBC_SB_8;
638 pa_assert_not_reached();
641 switch (active_capabilities->block_length) {
642 case BT_A2DP_BLOCK_LENGTH_4:
643 a2dp->sbc.blocks = SBC_BLK_4;
645 case BT_A2DP_BLOCK_LENGTH_8:
646 a2dp->sbc.blocks = SBC_BLK_8;
648 case BT_A2DP_BLOCK_LENGTH_12:
649 a2dp->sbc.blocks = SBC_BLK_12;
651 case BT_A2DP_BLOCK_LENGTH_16:
652 a2dp->sbc.blocks = SBC_BLK_16;
655 pa_assert_not_reached();
658 a2dp->min_bitpool = active_capabilities->min_bitpool;
659 a2dp->max_bitpool = active_capabilities->max_bitpool;
661 /* Set minimum bitpool for source to get the maximum possible block_size */
662 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
663 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
664 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
667 /* Run from main thread */
668 static int set_conf(struct userdata *u) {
670 struct bt_open_req open_req;
671 struct bt_open_rsp open_rsp;
672 struct bt_set_configuration_req setconf_req;
673 struct bt_set_configuration_rsp setconf_rsp;
674 bt_audio_error_t error;
675 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
678 memset(&msg, 0, sizeof(msg));
679 msg.open_req.h.type = BT_REQUEST;
680 msg.open_req.h.name = BT_OPEN;
681 msg.open_req.h.length = sizeof(msg.open_req);
683 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
684 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
685 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
687 if (service_send(u, &msg.open_req.h) < 0)
690 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
693 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
694 u->sample_spec.format = PA_SAMPLE_S16LE;
696 if (setup_a2dp(u) < 0)
699 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
701 u->sample_spec.format = PA_SAMPLE_S16LE;
702 u->sample_spec.channels = 1;
703 u->sample_spec.rate = 8000;
706 memset(&msg, 0, sizeof(msg));
707 msg.setconf_req.h.type = BT_REQUEST;
708 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
709 msg.setconf_req.h.length = sizeof(msg.setconf_req);
711 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
712 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
714 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
715 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
716 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
718 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
720 if (service_send(u, &msg.setconf_req.h) < 0)
723 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
726 u->link_mtu = msg.setconf_rsp.link_mtu;
728 /* setup SBC encoder now we agree on parameters */
729 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
730 setup_sbc(&u->a2dp, u->profile);
733 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
734 / u->a2dp.frame_length
737 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
738 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
740 u->block_size = u->link_mtu;
746 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
748 struct a2dp_info *a2dp;
754 if (a2dp->sbc.bitpool == bitpool)
757 if (bitpool > a2dp->max_bitpool)
758 bitpool = a2dp->max_bitpool;
759 else if (bitpool < a2dp->min_bitpool)
760 bitpool = a2dp->min_bitpool;
762 a2dp->sbc.bitpool = bitpool;
764 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
765 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
767 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
770 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
771 / a2dp->frame_length * a2dp->codesize;
773 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
774 pa_sink_set_fixed_latency_within_thread(u->sink,
775 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
778 /* from IO thread, except in SCO over PCM */
780 static int setup_stream(struct userdata *u) {
781 struct pollfd *pollfd;
784 pa_make_fd_nonblock(u->stream_fd);
785 pa_make_socket_low_delay(u->stream_fd);
788 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
789 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
791 pa_log_debug("Stream properly set up, we're ready to roll!");
793 if (u->profile == PROFILE_A2DP)
794 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
796 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
797 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
798 pollfd->fd = u->stream_fd;
799 pollfd->events = pollfd->revents = 0;
801 u->read_index = u->write_index = 0;
805 u->read_smoother = pa_smoother_new(
817 static int start_stream_fd(struct userdata *u) {
819 bt_audio_msg_header_t rsp;
820 struct bt_start_stream_req start_req;
821 struct bt_start_stream_rsp start_rsp;
822 struct bt_new_stream_ind streamfd_ind;
823 bt_audio_error_t error;
824 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
828 pa_assert(u->rtpoll);
829 pa_assert(!u->rtpoll_item);
830 pa_assert(u->stream_fd < 0);
832 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
833 msg.start_req.h.type = BT_REQUEST;
834 msg.start_req.h.name = BT_START_STREAM;
835 msg.start_req.h.length = sizeof(msg.start_req);
837 if (service_send(u, &msg.start_req.h) < 0)
840 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
843 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
846 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
847 pa_log("Failed to get stream fd from audio service.");
851 return setup_stream(u);
855 static int stop_stream_fd(struct userdata *u) {
857 bt_audio_msg_header_t rsp;
858 struct bt_stop_stream_req start_req;
859 struct bt_stop_stream_rsp start_rsp;
860 bt_audio_error_t error;
861 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
866 pa_assert(u->rtpoll);
868 if (u->rtpoll_item) {
869 pa_rtpoll_item_free(u->rtpoll_item);
870 u->rtpoll_item = NULL;
873 if (u->stream_fd >= 0) {
874 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
875 msg.start_req.h.type = BT_REQUEST;
876 msg.start_req.h.name = BT_STOP_STREAM;
877 msg.start_req.h.length = sizeof(msg.start_req);
879 if (service_send(u, &msg.start_req.h) < 0 ||
880 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
883 pa_close(u->stream_fd);
887 if (u->read_smoother) {
888 pa_smoother_free(u->read_smoother);
889 u->read_smoother = NULL;
895 static void bt_transport_release(struct userdata *u) {
896 const char *accesstype = "rw";
897 const pa_bluetooth_transport *t;
899 /* Ignore if already released */
903 pa_log_debug("Releasing transport %s", u->transport);
905 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
907 pa_bluetooth_transport_release(t, accesstype);
909 pa_xfree(u->accesstype);
910 u->accesstype = NULL;
912 if (u->rtpoll_item) {
913 pa_rtpoll_item_free(u->rtpoll_item);
914 u->rtpoll_item = NULL;
917 if (u->stream_fd >= 0) {
918 pa_close(u->stream_fd);
922 if (u->read_smoother) {
923 pa_smoother_free(u->read_smoother);
924 u->read_smoother = NULL;
928 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
929 const char *accesstype = "rw";
930 const pa_bluetooth_transport *t;
938 pa_log_debug("Acquiring transport %s", u->transport);
940 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
942 pa_log("Transport %s no longer available", u->transport);
943 pa_xfree(u->transport);
948 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
949 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
950 if (u->stream_fd < 0)
953 u->accesstype = pa_xstrdup(accesstype);
954 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
960 pa_log_info("Transport %s resuming", u->transport);
961 return setup_stream(u);
964 /* Run from IO thread */
965 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
966 struct userdata *u = PA_SINK(o)->userdata;
967 pa_bool_t failed = FALSE;
970 pa_assert(u->sink == PA_SINK(o));
974 case PA_SINK_MESSAGE_SET_STATE:
976 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
978 case PA_SINK_SUSPENDED:
979 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
981 /* Stop the device if the source is suspended as well */
982 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
983 /* We deliberately ignore whether stopping
984 * actually worked. Since the stream_fd is
985 * closed it doesn't really matter */
987 bt_transport_release(u);
995 case PA_SINK_RUNNING:
996 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
999 /* Resume the device if the source was suspended as well */
1000 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1002 if (bt_transport_acquire(u, TRUE) < 0)
1004 } else if (start_stream_fd(u) < 0)
1009 case PA_SINK_UNLINKED:
1011 case PA_SINK_INVALID_STATE:
1016 case PA_SINK_MESSAGE_GET_LATENCY: {
1018 if (u->read_smoother) {
1021 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1022 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1024 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1028 ri = pa_rtclock_now() - u->started_at;
1029 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1031 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1034 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1039 r = pa_sink_process_msg(o, code, data, offset, chunk);
1041 return (r < 0 || !failed) ? r : -1;
1044 /* Run from IO thread */
1045 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1046 struct userdata *u = PA_SOURCE(o)->userdata;
1047 pa_bool_t failed = FALSE;
1050 pa_assert(u->source == PA_SOURCE(o));
1054 case PA_SOURCE_MESSAGE_SET_STATE:
1056 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1058 case PA_SOURCE_SUSPENDED:
1059 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1061 /* Stop the device if the sink is suspended as well */
1062 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1064 bt_transport_release(u);
1069 if (u->read_smoother)
1070 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1073 case PA_SOURCE_IDLE:
1074 case PA_SOURCE_RUNNING:
1075 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1078 /* Resume the device if the sink was suspended as well */
1079 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1081 if (bt_transport_acquire(u, TRUE) < 0)
1083 } else if (start_stream_fd(u) < 0)
1086 /* We don't resume the smoother here. Instead we
1087 * wait until the first packet arrives */
1090 case PA_SOURCE_UNLINKED:
1091 case PA_SOURCE_INIT:
1092 case PA_SOURCE_INVALID_STATE:
1097 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1100 if (u->read_smoother) {
1101 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1102 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1104 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1106 *((pa_usec_t*) data) = 0;
1113 r = pa_source_process_msg(o, code, data, offset, chunk);
1115 return (r < 0 || !failed) ? r : -1;
1118 /* Run from IO thread */
1119 static int hsp_process_render(struct userdata *u) {
1123 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1126 /* First, render some data */
1127 if (!u->write_memchunk.memblock)
1128 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1130 pa_assert(u->write_memchunk.length == u->block_size);
1136 /* Now write that data to the socket. The socket is of type
1137 * SEQPACKET, and we generated the data of the MTU size, so this
1138 * should just work. */
1140 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1141 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1142 pa_memblock_release(u->write_memchunk.memblock);
1149 /* Retry right away if we got interrupted */
1152 else if (errno == EAGAIN)
1153 /* Hmm, apparently the socket was not writable, give up for now */
1156 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1161 pa_assert((size_t) l <= u->write_memchunk.length);
1163 if ((size_t) l != u->write_memchunk.length) {
1164 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1165 (unsigned long long) l,
1166 (unsigned long long) u->write_memchunk.length);
1171 u->write_index += (uint64_t) u->write_memchunk.length;
1172 pa_memblock_unref(u->write_memchunk.memblock);
1173 pa_memchunk_reset(&u->write_memchunk);
1182 /* Run from IO thread */
1183 static int hsp_process_push(struct userdata *u) {
1185 pa_memchunk memchunk;
1188 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1189 pa_assert(u->source);
1190 pa_assert(u->read_smoother);
1192 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1193 memchunk.index = memchunk.length = 0;
1202 pa_bool_t found_tstamp = FALSE;
1205 memset(&m, 0, sizeof(m));
1206 memset(&aux, 0, sizeof(aux));
1207 memset(&iov, 0, sizeof(iov));
1211 m.msg_control = aux;
1212 m.msg_controllen = sizeof(aux);
1214 p = pa_memblock_acquire(memchunk.memblock);
1216 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1217 l = recvmsg(u->stream_fd, &m, 0);
1218 pa_memblock_release(memchunk.memblock);
1222 if (l < 0 && errno == EINTR)
1223 /* Retry right away if we got interrupted */
1226 else if (l < 0 && errno == EAGAIN)
1227 /* Hmm, apparently the socket was not readable, give up for now. */
1230 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1235 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1237 memchunk.length = (size_t) l;
1238 u->read_index += (uint64_t) l;
1240 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1241 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1242 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1243 pa_rtclock_from_wallclock(tv);
1244 tstamp = pa_timeval_load(tv);
1245 found_tstamp = TRUE;
1249 if (!found_tstamp) {
1250 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1251 tstamp = pa_rtclock_now();
1254 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1255 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1257 pa_source_post(u->source, &memchunk);
1263 pa_memblock_unref(memchunk.memblock);
1268 /* Run from IO thread */
1269 static void a2dp_prepare_buffer(struct userdata *u) {
1272 if (u->a2dp.buffer_size >= u->link_mtu)
1275 u->a2dp.buffer_size = 2 * u->link_mtu;
1276 pa_xfree(u->a2dp.buffer);
1277 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1280 /* Run from IO thread */
1281 static int a2dp_process_render(struct userdata *u) {
1282 struct a2dp_info *a2dp;
1283 struct rtp_header *header;
1284 struct rtp_payload *payload;
1288 size_t to_write, to_encode;
1289 unsigned frame_count;
1293 pa_assert(u->profile == PROFILE_A2DP);
1296 /* First, render some data */
1297 if (!u->write_memchunk.memblock)
1298 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1300 pa_assert(u->write_memchunk.length == u->block_size);
1302 a2dp_prepare_buffer(u);
1305 header = a2dp->buffer;
1306 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1310 /* Try to create a packet of the full MTU */
1312 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1313 to_encode = u->write_memchunk.length;
1315 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1316 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1318 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1322 encoded = sbc_encode(&a2dp->sbc,
1327 if (PA_UNLIKELY(encoded <= 0)) {
1328 pa_log_error("SBC encoding error (%li)", (long) encoded);
1329 pa_memblock_release(u->write_memchunk.memblock);
1333 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1334 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1336 pa_assert_fp((size_t) encoded <= to_encode);
1337 pa_assert_fp((size_t) encoded == a2dp->codesize);
1339 pa_assert_fp((size_t) written <= to_write);
1340 pa_assert_fp((size_t) written == a2dp->frame_length);
1342 p = (const uint8_t*) p + encoded;
1343 to_encode -= encoded;
1345 d = (uint8_t*) d + written;
1346 to_write -= written;
1351 pa_memblock_release(u->write_memchunk.memblock);
1353 pa_assert(to_encode == 0);
1356 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1359 /* write it to the fifo */
1360 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1363 header->sequence_number = htons(a2dp->seq_num++);
1364 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1365 header->ssrc = htonl(1);
1366 payload->frame_count = frame_count;
1368 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1373 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1380 /* Retry right away if we got interrupted */
1383 else if (errno == EAGAIN)
1384 /* Hmm, apparently the socket was not writable, give up for now */
1387 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1392 pa_assert((size_t) l <= nbytes);
1394 if ((size_t) l != nbytes) {
1395 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1396 (unsigned long long) l,
1397 (unsigned long long) nbytes);
1402 u->write_index += (uint64_t) u->write_memchunk.length;
1403 pa_memblock_unref(u->write_memchunk.memblock);
1404 pa_memchunk_reset(&u->write_memchunk);
1414 static int a2dp_process_push(struct userdata *u) {
1416 pa_memchunk memchunk;
1419 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1420 pa_assert(u->source);
1421 pa_assert(u->read_smoother);
1423 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1424 memchunk.index = memchunk.length = 0;
1427 pa_bool_t found_tstamp = FALSE;
1429 struct a2dp_info *a2dp;
1430 struct rtp_header *header;
1431 struct rtp_payload *payload;
1435 size_t to_write, to_decode;
1436 unsigned frame_count;
1438 a2dp_prepare_buffer(u);
1441 header = a2dp->buffer;
1442 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1444 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1448 if (l < 0 && errno == EINTR)
1449 /* Retry right away if we got interrupted */
1452 else if (l < 0 && errno == EAGAIN)
1453 /* Hmm, apparently the socket was not readable, give up for now. */
1456 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1461 pa_assert((size_t) l <= a2dp->buffer_size);
1463 u->read_index += (uint64_t) l;
1465 /* TODO: get timestamp from rtp */
1466 if (!found_tstamp) {
1467 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1468 tstamp = pa_rtclock_now();
1471 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1472 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1474 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1475 to_decode = l - sizeof(*header) - sizeof(*payload);
1477 d = pa_memblock_acquire(memchunk.memblock);
1478 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1480 while (PA_LIKELY(to_decode > 0)) {
1484 decoded = sbc_decode(&a2dp->sbc,
1489 if (PA_UNLIKELY(decoded <= 0)) {
1490 pa_log_error("SBC decoding error (%li)", (long) decoded);
1491 pa_memblock_release(memchunk.memblock);
1492 pa_memblock_unref(memchunk.memblock);
1496 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1497 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1499 /* Reset frame length, it can be changed due to bitpool change */
1500 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1502 pa_assert_fp((size_t) decoded <= to_decode);
1503 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1505 pa_assert_fp((size_t) written == a2dp->codesize);
1507 p = (const uint8_t*) p + decoded;
1508 to_decode -= decoded;
1510 d = (uint8_t*) d + written;
1511 to_write -= written;
1516 memchunk.length -= to_write;
1518 pa_memblock_release(memchunk.memblock);
1520 pa_source_post(u->source, &memchunk);
1526 pa_memblock_unref(memchunk.memblock);
1531 static void a2dp_reduce_bitpool(struct userdata *u)
1533 struct a2dp_info *a2dp;
1540 /* Check if bitpool is already at its limit */
1541 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1544 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1546 if (bitpool < BITPOOL_DEC_LIMIT)
1547 bitpool = BITPOOL_DEC_LIMIT;
1549 a2dp_set_bitpool(u, bitpool);
1552 static void thread_func(void *userdata) {
1553 struct userdata *u = userdata;
1554 unsigned do_write = 0;
1555 pa_bool_t writable = FALSE;
1559 pa_log_debug("IO Thread starting up");
1561 if (u->core->realtime_scheduling)
1562 pa_make_realtime(u->core->realtime_priority);
1564 pa_thread_mq_install(&u->thread_mq);
1567 if (bt_transport_acquire(u, TRUE) < 0)
1569 } else if (start_stream_fd(u) < 0)
1573 struct pollfd *pollfd;
1575 pa_bool_t disable_timer = TRUE;
1577 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1579 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1581 /* We should send two blocks to the device before we expect
1584 if (u->write_index == 0 && u->read_index <= 0)
1587 if (pollfd && (pollfd->revents & POLLIN)) {
1590 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1591 n_read = hsp_process_push(u);
1593 n_read = a2dp_process_push(u);
1598 /* We just read something, so we are supposed to write something, too */
1603 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1605 if (u->sink->thread_info.rewind_requested)
1606 pa_sink_process_rewind(u->sink, 0);
1609 if (pollfd->revents & POLLOUT)
1612 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1613 pa_usec_t time_passed;
1614 pa_usec_t audio_sent;
1616 /* Hmm, there is no input stream we could synchronize
1617 * to. So let's do things by time */
1619 time_passed = pa_rtclock_now() - u->started_at;
1620 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1622 if (audio_sent <= time_passed) {
1623 pa_usec_t audio_to_send = time_passed - audio_sent;
1625 /* Never try to catch up for more than 100ms */
1626 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1627 pa_usec_t skip_usec;
1628 uint64_t skip_bytes;
1630 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1631 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1633 if (skip_bytes > 0) {
1636 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1637 (unsigned long long) skip_usec,
1638 (unsigned long long) skip_bytes);
1640 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1641 pa_memblock_unref(tmp.memblock);
1642 u->write_index += skip_bytes;
1644 if (u->profile == PROFILE_A2DP)
1645 a2dp_reduce_bitpool(u);
1653 if (writable && do_write > 0) {
1656 if (u->write_index <= 0)
1657 u->started_at = pa_rtclock_now();
1659 if (u->profile == PROFILE_A2DP) {
1660 if ((n_written = a2dp_process_render(u)) < 0)
1663 if ((n_written = hsp_process_render(u)) < 0)
1668 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1670 do_write -= n_written;
1674 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1675 pa_usec_t sleep_for;
1676 pa_usec_t time_passed, next_write_at;
1679 /* Hmm, there is no input stream we could synchronize
1680 * to. So let's estimate when we need to wake up the latest */
1681 time_passed = pa_rtclock_now() - u->started_at;
1682 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1683 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1684 /* 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); */
1686 /* drop stream every 500 ms */
1687 sleep_for = PA_USEC_PER_MSEC * 500;
1689 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1690 disable_timer = FALSE;
1696 pa_rtpoll_set_timer_disabled(u->rtpoll);
1698 /* Hmm, nothing to do. Let's sleep */
1700 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1701 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1703 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1709 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1711 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1712 pa_log_info("FD error: %s%s%s%s",
1713 pollfd->revents & POLLERR ? "POLLERR " :"",
1714 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1715 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1716 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1722 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1723 pa_log_debug("IO thread failed");
1724 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1727 pa_log_debug("IO thread shutting down");
1730 /* Run from main thread */
1731 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1737 pa_assert_se(u = userdata);
1739 dbus_error_init(&err);
1741 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1742 dbus_message_get_interface(m),
1743 dbus_message_get_path(m),
1744 dbus_message_get_member(m));
1746 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1749 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1750 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1755 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1756 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1760 if (u->profile == PROFILE_HSP) {
1761 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1762 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1764 /* increment volume by one to correct rounding errors */
1765 if (volume < PA_VOLUME_NORM)
1768 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1769 pa_sink_volume_changed(u->sink, &v);
1771 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1772 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1774 /* increment volume by one to correct rounding errors */
1775 if (volume < PA_VOLUME_NORM)
1778 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1779 pa_source_volume_changed(u->source, &v);
1782 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1783 DBusMessageIter arg_i;
1784 pa_bluetooth_transport *t;
1787 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1790 if (!dbus_message_iter_init(m, &arg_i)) {
1791 pa_log("Failed to parse PropertyChanged: %s", err.message);
1797 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1800 if (nrec != t->nrec) {
1801 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1802 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1807 dbus_error_free(&err);
1809 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1812 /* Run from main thread */
1813 static void sink_set_volume_cb(pa_sink *s) {
1823 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1824 u = pa_shared_get(s->core, k);
1828 pa_assert(u->sink == s);
1829 pa_assert(u->profile == PROFILE_HSP);
1831 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1833 if (gain > HSP_MAX_GAIN)
1834 gain = HSP_MAX_GAIN;
1836 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1838 /* increment volume by one to correct rounding errors */
1839 if (volume < PA_VOLUME_NORM)
1842 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1844 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1845 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1846 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1847 dbus_message_unref(m);
1850 /* Run from main thread */
1851 static void source_set_volume_cb(pa_source *s) {
1861 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1862 u = pa_shared_get(s->core, k);
1866 pa_assert(u->source == s);
1867 pa_assert(u->profile == PROFILE_HSP);
1869 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1871 if (gain > HSP_MAX_GAIN)
1872 gain = HSP_MAX_GAIN;
1874 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1876 /* increment volume by one to correct rounding errors */
1877 if (volume < PA_VOLUME_NORM)
1880 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1882 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1883 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1884 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1885 dbus_message_unref(m);
1888 /* Run from main thread */
1889 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1895 pa_assert(device_id);
1896 pa_assert(namereg_fail);
1898 t = pa_sprintf_malloc("%s_name", type);
1899 n = pa_modargs_get_value(ma, t, NULL);
1903 *namereg_fail = TRUE;
1904 return pa_xstrdup(n);
1907 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1908 *namereg_fail = TRUE;
1911 *namereg_fail = FALSE;
1914 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1917 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1919 pa_assert(USE_SCO_OVER_PCM(u));
1921 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1922 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1924 if (u->service_fd >= 0 && u->stream_fd >= 0)
1929 pa_log_debug("Resuming SCO over PCM");
1930 if (init_profile(u) < 0) {
1931 pa_log("Can't resume SCO over PCM");
1936 return bt_transport_acquire(u, TRUE);
1938 return start_stream_fd(u);
1942 if (u->service_fd < 0 && u->stream_fd < 0)
1945 pa_log_debug("Closing SCO over PCM");
1948 bt_transport_release(u);
1949 else if (u->stream_fd >= 0)
1952 if (u->service_fd >= 0) {
1953 pa_close(u->service_fd);
1961 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1963 pa_sink_assert_ref(s);
1966 if (s != u->hsp.sco_sink)
1969 sco_over_pcm_state_update(u, TRUE);
1974 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1976 pa_source_assert_ref(s);
1979 if (s != u->hsp.sco_source)
1982 sco_over_pcm_state_update(u, TRUE);
1987 /* Run from main thread */
1988 static int add_sink(struct userdata *u) {
1991 if (USE_SCO_OVER_PCM(u)) {
1994 u->sink = u->hsp.sco_sink;
1995 p = pa_proplist_new();
1996 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1997 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1998 pa_proplist_free(p);
2000 if (!u->hsp.sink_state_changed_slot)
2001 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);
2004 pa_sink_new_data data;
2007 pa_sink_new_data_init(&data);
2008 data.driver = __FILE__;
2009 data.module = u->module;
2010 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
2011 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
2012 if (u->profile == PROFILE_HSP)
2013 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2014 data.card = u->card;
2015 data.name = get_name("sink", u->modargs, u->address, &b);
2016 data.namereg_fail = b;
2018 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2019 pa_log("Invalid properties");
2020 pa_sink_new_data_done(&data);
2024 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
2025 pa_sink_new_data_done(&data);
2028 pa_log_error("Failed to create sink");
2032 u->sink->userdata = u;
2033 u->sink->parent.process_msg = sink_process_msg;
2035 pa_sink_set_max_request(u->sink, u->block_size);
2036 pa_sink_set_fixed_latency(u->sink,
2037 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2038 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2041 if (u->profile == PROFILE_HSP) {
2042 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
2043 u->sink->n_volume_steps = 16;
2045 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2046 pa_shared_set(u->core, k, u);
2053 /* Run from main thread */
2054 static int add_source(struct userdata *u) {
2057 if (USE_SCO_OVER_PCM(u)) {
2058 u->source = u->hsp.sco_source;
2059 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2061 if (!u->hsp.source_state_changed_slot)
2062 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);
2065 pa_source_new_data data;
2068 pa_source_new_data_init(&data);
2069 data.driver = __FILE__;
2070 data.module = u->module;
2071 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2072 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2073 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2074 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2076 data.card = u->card;
2077 data.name = get_name("source", u->modargs, u->address, &b);
2078 data.namereg_fail = b;
2080 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2081 pa_log("Invalid properties");
2082 pa_source_new_data_done(&data);
2086 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
2087 pa_source_new_data_done(&data);
2090 pa_log_error("Failed to create source");
2094 u->source->userdata = u;
2095 u->source->parent.process_msg = source_process_msg;
2097 pa_source_set_fixed_latency(u->source,
2098 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2099 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2102 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2104 const pa_bluetooth_transport *t;
2105 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2107 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2109 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2112 if (u->profile == PROFILE_HSP) {
2113 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
2114 u->source->n_volume_steps = 16;
2116 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2117 pa_shared_set(u->core, k, u);
2124 /* Run from main thread */
2125 static void shutdown_bt(struct userdata *u) {
2128 if (u->stream_fd >= 0) {
2129 pa_close(u->stream_fd);
2132 u->stream_write_type = 0;
2135 if (u->service_fd >= 0) {
2136 pa_close(u->service_fd);
2138 u->service_write_type = 0;
2139 u->service_read_type = 0;
2142 if (u->write_memchunk.memblock) {
2143 pa_memblock_unref(u->write_memchunk.memblock);
2144 pa_memchunk_reset(&u->write_memchunk);
2148 static int bt_transport_config_a2dp(struct userdata *u) {
2149 const pa_bluetooth_transport *t;
2150 struct a2dp_info *a2dp = &u->a2dp;
2153 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2156 config = (a2dp_sbc_t *) t->config;
2158 u->sample_spec.format = PA_SAMPLE_S16LE;
2160 if (a2dp->sbc_initialized)
2161 sbc_reinit(&a2dp->sbc, 0);
2163 sbc_init(&a2dp->sbc, 0);
2164 a2dp->sbc_initialized = TRUE;
2166 switch (config->frequency) {
2167 case BT_SBC_SAMPLING_FREQ_16000:
2168 a2dp->sbc.frequency = SBC_FREQ_16000;
2169 u->sample_spec.rate = 16000U;
2171 case BT_SBC_SAMPLING_FREQ_32000:
2172 a2dp->sbc.frequency = SBC_FREQ_32000;
2173 u->sample_spec.rate = 32000U;
2175 case BT_SBC_SAMPLING_FREQ_44100:
2176 a2dp->sbc.frequency = SBC_FREQ_44100;
2177 u->sample_spec.rate = 44100U;
2179 case BT_SBC_SAMPLING_FREQ_48000:
2180 a2dp->sbc.frequency = SBC_FREQ_48000;
2181 u->sample_spec.rate = 48000U;
2184 pa_assert_not_reached();
2187 switch (config->channel_mode) {
2188 case BT_A2DP_CHANNEL_MODE_MONO:
2189 a2dp->sbc.mode = SBC_MODE_MONO;
2190 u->sample_spec.channels = 1;
2192 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2193 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2194 u->sample_spec.channels = 2;
2196 case BT_A2DP_CHANNEL_MODE_STEREO:
2197 a2dp->sbc.mode = SBC_MODE_STEREO;
2198 u->sample_spec.channels = 2;
2200 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2201 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2202 u->sample_spec.channels = 2;
2205 pa_assert_not_reached();
2208 switch (config->allocation_method) {
2209 case BT_A2DP_ALLOCATION_SNR:
2210 a2dp->sbc.allocation = SBC_AM_SNR;
2212 case BT_A2DP_ALLOCATION_LOUDNESS:
2213 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2216 pa_assert_not_reached();
2219 switch (config->subbands) {
2220 case BT_A2DP_SUBBANDS_4:
2221 a2dp->sbc.subbands = SBC_SB_4;
2223 case BT_A2DP_SUBBANDS_8:
2224 a2dp->sbc.subbands = SBC_SB_8;
2227 pa_assert_not_reached();
2230 switch (config->block_length) {
2231 case BT_A2DP_BLOCK_LENGTH_4:
2232 a2dp->sbc.blocks = SBC_BLK_4;
2234 case BT_A2DP_BLOCK_LENGTH_8:
2235 a2dp->sbc.blocks = SBC_BLK_8;
2237 case BT_A2DP_BLOCK_LENGTH_12:
2238 a2dp->sbc.blocks = SBC_BLK_12;
2240 case BT_A2DP_BLOCK_LENGTH_16:
2241 a2dp->sbc.blocks = SBC_BLK_16;
2244 pa_assert_not_reached();
2247 a2dp->min_bitpool = config->min_bitpool;
2248 a2dp->max_bitpool = config->max_bitpool;
2250 /* Set minimum bitpool for source to get the maximum possible block_size */
2251 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2252 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2253 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2256 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2257 / a2dp->frame_length
2260 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2261 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2266 static int bt_transport_config(struct userdata *u) {
2267 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2268 u->block_size = u->link_mtu;
2269 u->sample_spec.format = PA_SAMPLE_S16LE;
2270 u->sample_spec.channels = 1;
2271 u->sample_spec.rate = 8000;
2275 return bt_transport_config_a2dp(u);
2278 /* Run from main thread */
2279 static int bt_transport_open(struct userdata *u) {
2280 if (bt_transport_acquire(u, FALSE) < 0)
2283 return bt_transport_config(u);
2286 /* Run from main thread */
2287 static int init_bt(struct userdata *u) {
2292 u->stream_write_type = 0;
2293 u->service_write_type = 0;
2294 u->service_read_type = 0;
2296 if ((u->service_fd = bt_audio_service_open()) < 0) {
2297 pa_log_warn("Bluetooth audio service not available");
2301 pa_log_debug("Connected to the bluetooth audio service");
2306 /* Run from main thread */
2307 static int setup_bt(struct userdata *u) {
2308 const pa_bluetooth_device *d;
2309 const pa_bluetooth_transport *t;
2313 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2314 pa_log_error("Failed to get device object.");
2318 /* release transport if exist */
2320 bt_transport_release(u);
2321 pa_xfree(u->transport);
2322 u->transport = NULL;
2325 /* check if profile has a transport */
2326 t = pa_bluetooth_device_get_transport(d, u->profile);
2328 u->transport = pa_xstrdup(t->path);
2329 return bt_transport_open(u);
2332 if (get_caps(u, 0) < 0)
2335 pa_log_debug("Got device capabilities");
2337 if (set_conf(u) < 0)
2340 pa_log_debug("Connection to the device configured");
2342 if (USE_SCO_OVER_PCM(u)) {
2343 pa_log_debug("Configured to use SCO over PCM");
2347 pa_log_debug("Got the stream socket");
2352 /* Run from main thread */
2353 static int init_profile(struct userdata *u) {
2356 pa_assert(u->profile != PROFILE_OFF);
2358 if (setup_bt(u) < 0)
2361 if (u->profile == PROFILE_A2DP ||
2362 u->profile == PROFILE_HSP ||
2363 u->profile == PROFILE_HFGW)
2364 if (add_sink(u) < 0)
2367 if (u->profile == PROFILE_HSP ||
2368 u->profile == PROFILE_A2DP_SOURCE ||
2369 u->profile == PROFILE_HFGW)
2370 if (add_source(u) < 0)
2376 /* Run from main thread */
2377 static void stop_thread(struct userdata *u) {
2383 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2384 pa_thread_free(u->thread);
2388 if (u->rtpoll_item) {
2389 pa_rtpoll_item_free(u->rtpoll_item);
2390 u->rtpoll_item = NULL;
2393 if (u->hsp.sink_state_changed_slot) {
2394 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2395 u->hsp.sink_state_changed_slot = NULL;
2398 if (u->hsp.source_state_changed_slot) {
2399 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2400 u->hsp.source_state_changed_slot = NULL;
2404 if (u->profile == PROFILE_HSP) {
2405 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2406 pa_shared_remove(u->core, k);
2410 pa_sink_unref(u->sink);
2415 if (u->profile == PROFILE_HSP) {
2416 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2417 pa_shared_remove(u->core, k);
2421 pa_source_unref(u->source);
2426 pa_thread_mq_done(&u->thread_mq);
2428 pa_rtpoll_free(u->rtpoll);
2432 if (u->read_smoother) {
2433 pa_smoother_free(u->read_smoother);
2434 u->read_smoother = NULL;
2438 /* Run from main thread */
2439 static int start_thread(struct userdata *u) {
2441 pa_assert(!u->thread);
2442 pa_assert(!u->rtpoll);
2443 pa_assert(!u->rtpoll_item);
2445 u->rtpoll = pa_rtpoll_new();
2446 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2448 if (USE_SCO_OVER_PCM(u)) {
2449 if (sco_over_pcm_state_update(u, FALSE) < 0) {
2453 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2454 pa_shared_remove(u->core, k);
2459 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2460 pa_shared_remove(u->core, k);
2467 pa_sink_ref(u->sink);
2468 pa_source_ref(u->source);
2469 /* FIXME: monitor stream_fd error */
2473 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2474 pa_log_error("Failed to create IO thread");
2480 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2481 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2482 pa_sink_put(u->sink);
2484 if (u->sink->set_volume)
2485 u->sink->set_volume(u->sink);
2489 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2490 pa_source_set_rtpoll(u->source, u->rtpoll);
2491 pa_source_put(u->source);
2493 if (u->source->set_volume)
2494 u->source->set_volume(u->source);
2500 static void save_sco_volume_callbacks(struct userdata *u) {
2502 pa_assert(USE_SCO_OVER_PCM(u));
2504 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2505 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2508 static void restore_sco_volume_callbacks(struct userdata *u) {
2510 pa_assert(USE_SCO_OVER_PCM(u));
2512 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2513 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2516 /* Run from main thread */
2517 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2520 pa_queue *inputs = NULL, *outputs = NULL;
2521 const pa_bluetooth_device *device;
2524 pa_assert(new_profile);
2525 pa_assert_se(u = c->userdata);
2527 d = PA_CARD_PROFILE_DATA(new_profile);
2529 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2530 pa_log_error("Failed to get device object.");
2534 /* The state signal is sent by bluez, so it is racy to check
2535 strictly for CONNECTED, we should also accept STREAMING state
2536 as being good enough. However, if the profile is used
2537 concurrently (which is unlikely), ipc will fail later on, and
2538 module will be unloaded. */
2539 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2540 pa_log_warn("HSP is not connected, refused to switch profile");
2543 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2544 pa_log_warn("A2DP is not connected, refused to switch profile");
2547 else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2548 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2553 inputs = pa_sink_move_all_start(u->sink, NULL);
2555 if (!USE_SCO_OVER_PCM(u))
2556 pa_sink_unlink(u->sink);
2560 outputs = pa_source_move_all_start(u->source, NULL);
2562 if (!USE_SCO_OVER_PCM(u))
2563 pa_source_unlink(u->source);
2568 if (u->profile != PROFILE_OFF && u->transport) {
2569 bt_transport_release(u);
2570 pa_xfree(u->transport);
2571 u->transport = NULL;
2576 if (USE_SCO_OVER_PCM(u))
2577 restore_sco_volume_callbacks(u);
2580 u->sample_spec = u->requested_sample_spec;
2582 if (USE_SCO_OVER_PCM(u))
2583 save_sco_volume_callbacks(u);
2587 if (u->profile != PROFILE_OFF)
2590 if (u->sink || u->source)
2595 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2597 pa_sink_move_all_fail(inputs);
2602 pa_source_move_all_finish(u->source, outputs, FALSE);
2604 pa_source_move_all_fail(outputs);
2610 /* Run from main thread */
2611 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2612 pa_card_new_data data;
2618 const char *default_profile;
2623 pa_card_new_data_init(&data);
2624 data.driver = __FILE__;
2625 data.module = u->module;
2627 n = pa_bluetooth_cleanup_name(device->name);
2628 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2630 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2631 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2632 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2633 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2634 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2635 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2636 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2637 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2638 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2639 data.name = get_name("card", u->modargs, device->address, &b);
2640 data.namereg_fail = b;
2642 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2643 pa_log("Invalid properties");
2644 pa_card_new_data_done(&data);
2648 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2650 /* we base hsp/a2dp availability on UUIDs.
2651 Ideally, it would be based on "Connected" state, but
2652 we can't afford to wait for this information when
2653 we are loaded with profile="hsp", for instance */
2654 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2655 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2659 p->max_sink_channels = 2;
2660 p->max_source_channels = 0;
2662 d = PA_CARD_PROFILE_DATA(p);
2665 pa_hashmap_put(data.profiles, p->name, p);
2668 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2669 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2673 p->max_sink_channels = 0;
2674 p->max_source_channels = 2;
2676 d = PA_CARD_PROFILE_DATA(p);
2677 *d = PROFILE_A2DP_SOURCE;
2679 pa_hashmap_put(data.profiles, p->name, p);
2682 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2683 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2684 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2688 p->max_sink_channels = 1;
2689 p->max_source_channels = 1;
2691 d = PA_CARD_PROFILE_DATA(p);
2694 pa_hashmap_put(data.profiles, p->name, p);
2697 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2698 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2702 p->max_sink_channels = 1;
2703 p->max_source_channels = 1;
2705 d = PA_CARD_PROFILE_DATA(p);
2708 pa_hashmap_put(data.profiles, p->name, p);
2711 pa_assert(!pa_hashmap_isempty(data.profiles));
2713 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2714 d = PA_CARD_PROFILE_DATA(p);
2716 pa_hashmap_put(data.profiles, p->name, p);
2718 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2719 if (pa_hashmap_get(data.profiles, default_profile))
2720 pa_card_new_data_set_profile(&data, default_profile);
2722 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2725 u->card = pa_card_new(u->core, &data);
2726 pa_card_new_data_done(&data);
2729 pa_log("Failed to allocate card.");
2733 u->card->userdata = u;
2734 u->card->set_profile = card_set_profile;
2736 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2738 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2739 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2740 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2741 pa_log_warn("Default profile not connected, selecting off profile");
2742 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2743 u->card->save_profile = FALSE;
2746 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2749 if (USE_SCO_OVER_PCM(u))
2750 save_sco_volume_callbacks(u);
2755 /* Run from main thread */
2756 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2757 const pa_bluetooth_device *d = NULL;
2761 if (!address && !path) {
2762 pa_log_error("Failed to get device address/path from module arguments.");
2767 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2768 pa_log_error("%s is not a valid BlueZ audio device.", path);
2772 if (address && !(pa_streq(d->address, address))) {
2773 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2778 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2779 pa_log_error("%s is not known.", address);
2785 u->address = pa_xstrdup(d->address);
2786 u->path = pa_xstrdup(d->path);
2792 /* Run from main thread */
2793 static int setup_dbus(struct userdata *u) {
2796 dbus_error_init(&err);
2798 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2800 if (dbus_error_is_set(&err) || !u->connection) {
2801 pa_log("Failed to get D-Bus connection: %s", err.message);
2802 dbus_error_free(&err);
2809 int pa__init(pa_module* m) {
2813 const char *address, *path;
2815 char *mike, *speaker, *transport;
2816 const pa_bluetooth_device *device;
2820 dbus_error_init(&err);
2822 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2823 pa_log_error("Failed to parse module arguments");
2827 m->userdata = u = pa_xnew0(struct userdata, 1);
2832 u->sample_spec = m->core->default_sample_spec;
2835 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2836 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2837 pa_log("SCO sink not found");
2841 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2842 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2843 pa_log("SCO source not found");
2847 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2848 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2849 pa_log_error("Failed to get rate from module arguments");
2853 u->auto_connect = TRUE;
2854 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2855 pa_log("Failed to parse auto_connect= argument");
2859 channels = u->sample_spec.channels;
2860 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2861 channels <= 0 || channels > PA_CHANNELS_MAX) {
2862 pa_log_error("Failed to get channels from module arguments");
2865 u->sample_spec.channels = (uint8_t) channels;
2866 u->requested_sample_spec = u->sample_spec;
2868 address = pa_modargs_get_value(ma, "address", NULL);
2869 path = pa_modargs_get_value(ma, "path", NULL);
2871 if (setup_dbus(u) < 0)
2874 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2877 if (!(device = find_device(u, address, path)))
2880 /* Add the card structure. This will also initialize the default profile */
2881 if (add_card(u, device) < 0)
2884 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2885 pa_log_error("Failed to add filter function");
2888 u->filter_added = TRUE;
2890 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2891 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2892 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2894 if (pa_dbus_add_matches(
2895 pa_dbus_connection_get(u->connection), &err,
2903 pa_xfree(transport);
2905 pa_log("Failed to add D-Bus matches: %s", err.message);
2911 pa_xfree(transport);
2913 /* Connect to the BT service */
2916 if (u->profile != PROFILE_OFF)
2917 if (init_profile(u) < 0)
2920 if (u->sink || u->source)
2921 if (start_thread(u) < 0)
2930 dbus_error_free(&err);
2935 int pa__get_n_used(pa_module *m) {
2939 pa_assert_se(u = m->userdata);
2942 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2943 (u->source ? pa_source_linked_by(u->source) : 0);
2946 void pa__done(pa_module *m) {
2951 if (!(u = m->userdata))
2954 if (u->sink && !USE_SCO_OVER_PCM(u))
2955 pa_sink_unlink(u->sink);
2957 if (u->source && !USE_SCO_OVER_PCM(u))
2958 pa_source_unlink(u->source);
2962 if (USE_SCO_OVER_PCM(u))
2963 restore_sco_volume_callbacks(u);
2965 if (u->connection) {
2968 char *speaker, *mike;
2969 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2970 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2972 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2978 if (u->filter_added)
2979 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2981 pa_dbus_connection_unref(u->connection);
2985 pa_card_free(u->card);
2987 if (u->read_smoother)
2988 pa_smoother_free(u->read_smoother);
2993 pa_xfree(u->a2dp.buffer);
2995 sbc_finish(&u->a2dp.sbc);
2998 pa_modargs_free(u->modargs);
3000 pa_xfree(u->address);
3004 bt_transport_release(u);
3005 pa_xfree(u->transport);
3009 pa_bluetooth_discovery_unref(u->discovery);