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"
57 #include "bluetooth-util.h"
59 #define MAX_BITPOOL 64
60 #define MIN_BITPOOL 2U
62 #define BITPOOL_DEC_LIMIT 32
63 #define BITPOOL_DEC_STEP 5
64 #define HSP_MAX_GAIN 15
66 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
67 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
68 PA_MODULE_VERSION(PACKAGE_VERSION);
69 PA_MODULE_LOAD_ONCE(FALSE);
71 "name=<name for the card/sink/source, to be prefixed> "
72 "card_name=<name for the card> "
73 "card_properties=<properties for the card> "
74 "sink_name=<name for the sink> "
75 "sink_properties=<properties for the sink> "
76 "source_name=<name for the source> "
77 "source_properties=<properties for the source> "
78 "address=<address of the device> "
79 "profile=<a2dp|hsp|hfgw> "
81 "channels=<number of channels> "
82 "path=<device object path> "
83 "auto_connect=<automatically connect?> "
84 "sco_sink=<SCO over PCM sink name> "
85 "sco_source=<SCO over PCM source name>");
87 /* TODO: not close fd when entering suspend mode in a2dp */
89 static const char* const valid_modargs[] = {
109 sbc_capabilities_t sbc_capabilities;
110 sbc_t sbc; /* Codec data */
111 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
112 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
114 void* buffer; /* Codec transfer buffer */
115 size_t buffer_size; /* Size of the buffer */
117 uint16_t seq_num; /* Cumulative packet sequence */
123 pcm_capabilities_t pcm_capabilities;
125 void (*sco_sink_set_volume)(pa_sink *s);
126 pa_source *sco_source;
127 void (*sco_source_set_volume)(pa_source *s);
128 pa_hook_slot *sink_state_changed_slot;
129 pa_hook_slot *source_state_changed_slot;
141 pa_bluetooth_discovery *discovery;
142 pa_bool_t auto_connect;
144 pa_dbus_connection *connection;
150 pa_thread_mq thread_mq;
152 pa_rtpoll_item *rtpoll_item;
155 uint64_t read_index, write_index;
156 pa_usec_t started_at;
157 pa_smoother *read_smoother;
159 pa_memchunk write_memchunk;
161 pa_sample_spec sample_spec, requested_sample_spec;
169 struct a2dp_info a2dp;
172 enum profile profile;
176 int stream_write_type;
177 int service_write_type, service_read_type;
179 pa_bool_t filter_added;
182 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
183 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
184 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
185 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
187 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
189 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
191 static int init_bt(struct userdata *u);
192 static int init_profile(struct userdata *u);
194 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
199 pa_assert(msg->length > 0);
201 if (u->service_fd < 0) {
202 pa_log_warn("Service not connected");
206 pa_log_debug("Sending %s -> %s",
207 pa_strnull(bt_audio_strtype(msg->type)),
208 pa_strnull(bt_audio_strname(msg->name)));
210 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
214 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
216 pa_log_error("Short write()");
221 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
225 pa_assert(u->service_fd >= 0);
227 pa_assert(room >= sizeof(*msg));
229 pa_log_debug("Trying to receive message from audio service...");
231 /* First, read the header */
232 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
235 if (msg->length < sizeof(*msg)) {
236 pa_log_error("Invalid message size.");
240 if (msg->length > room) {
241 pa_log_error("Not enough room.");
245 /* Secondly, read the payload */
246 if (msg->length > sizeof(*msg)) {
248 size_t remains = msg->length - sizeof(*msg);
250 if ((r = pa_loop_read(u->service_fd,
251 (uint8_t*) msg + sizeof(*msg),
253 &u->service_read_type)) != (ssize_t) remains)
257 pa_log_debug("Received %s <- %s",
258 pa_strnull(bt_audio_strtype(msg->type)),
259 pa_strnull(bt_audio_strname(msg->name)));
266 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
268 pa_log_error("Short read()");
273 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) {
277 pa_assert(u->service_fd >= 0);
280 if ((r = service_recv(u, rsp, room)) < 0)
283 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
284 rsp->name != expected_name ||
285 (expected_size > 0 && rsp->length != expected_size)) {
287 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
288 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
290 pa_log_error("Bogus message %s received while %s was expected",
291 pa_strnull(bt_audio_strname(rsp->name)),
292 pa_strnull(bt_audio_strname(expected_name)));
299 /* Run from main thread */
300 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
302 const codec_capabilities_t *codec;
307 bytes_left = rsp->h.length - sizeof(*rsp);
309 if (bytes_left < sizeof(codec_capabilities_t)) {
310 pa_log_error("Packet too small to store codec information.");
314 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
316 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
318 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
319 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
320 pa_log_error("Got capabilities for wrong codec.");
324 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
326 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
329 pa_assert(codec->type == BT_HFP_CODEC_PCM);
331 if (codec->configured && seid == 0)
334 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
336 } else if (u->profile == PROFILE_A2DP) {
338 while (bytes_left > 0) {
339 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
342 bytes_left -= codec->length;
343 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
346 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
349 pa_assert(codec->type == BT_A2DP_SBC_SINK);
351 if (codec->configured && seid == 0)
354 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
356 } else if (u->profile == PROFILE_A2DP_SOURCE) {
358 while (bytes_left > 0) {
359 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
362 bytes_left -= codec->length;
363 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
366 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
369 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
371 if (codec->configured && seid == 0)
374 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
380 /* Run from main thread */
381 static int get_caps(struct userdata *u, uint8_t seid) {
383 struct bt_get_capabilities_req getcaps_req;
384 struct bt_get_capabilities_rsp getcaps_rsp;
385 bt_audio_error_t error;
386 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
392 memset(&msg, 0, sizeof(msg));
393 msg.getcaps_req.h.type = BT_REQUEST;
394 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
395 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
396 msg.getcaps_req.seid = seid;
398 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
399 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
400 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
402 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
403 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
405 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
407 if (service_send(u, &msg.getcaps_req.h) < 0)
410 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
413 ret = parse_caps(u, seid, &msg.getcaps_rsp);
417 return get_caps(u, ret);
420 /* Run from main thread */
421 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
424 case BT_SBC_SAMPLING_FREQ_16000:
425 case BT_SBC_SAMPLING_FREQ_32000:
428 case BT_SBC_SAMPLING_FREQ_44100:
431 case BT_A2DP_CHANNEL_MODE_MONO:
432 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
435 case BT_A2DP_CHANNEL_MODE_STEREO:
436 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
440 pa_log_warn("Invalid channel mode %u", mode);
444 case BT_SBC_SAMPLING_FREQ_48000:
447 case BT_A2DP_CHANNEL_MODE_MONO:
448 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
451 case BT_A2DP_CHANNEL_MODE_STEREO:
452 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
456 pa_log_warn("Invalid channel mode %u", mode);
461 pa_log_warn("Invalid sampling freq %u", freq);
466 /* Run from main thread */
467 static int setup_a2dp(struct userdata *u) {
468 sbc_capabilities_t *cap;
471 static const struct {
475 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
476 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
477 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
478 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
482 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
484 cap = &u->a2dp.sbc_capabilities;
486 /* Find the lowest freq that is at least as high as the requested
488 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
489 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
490 u->sample_spec.rate = freq_table[i].rate;
491 cap->frequency = freq_table[i].cap;
495 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
496 for (--i; i >= 0; i--) {
497 if (cap->frequency & freq_table[i].cap) {
498 u->sample_spec.rate = freq_table[i].rate;
499 cap->frequency = freq_table[i].cap;
505 pa_log("Not suitable sample rate");
510 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
512 if (cap->capability.configured)
515 if (u->sample_spec.channels <= 1) {
516 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
517 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
518 u->sample_spec.channels = 1;
520 u->sample_spec.channels = 2;
523 if (u->sample_spec.channels >= 2) {
524 u->sample_spec.channels = 2;
526 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
527 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
528 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
529 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
530 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
531 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
532 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
533 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
534 u->sample_spec.channels = 1;
536 pa_log("No supported channel modes");
541 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
542 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
543 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
544 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
545 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
546 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
547 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
548 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
550 pa_log_error("No supported block lengths");
554 if (cap->subbands & BT_A2DP_SUBBANDS_8)
555 cap->subbands = BT_A2DP_SUBBANDS_8;
556 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
557 cap->subbands = BT_A2DP_SUBBANDS_4;
559 pa_log_error("No supported subbands");
563 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
564 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
565 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
566 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
568 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
569 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
574 /* Run from main thread */
575 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
576 sbc_capabilities_t *active_capabilities;
580 active_capabilities = &a2dp->sbc_capabilities;
582 if (a2dp->sbc_initialized)
583 sbc_reinit(&a2dp->sbc, 0);
585 sbc_init(&a2dp->sbc, 0);
586 a2dp->sbc_initialized = TRUE;
588 switch (active_capabilities->frequency) {
589 case BT_SBC_SAMPLING_FREQ_16000:
590 a2dp->sbc.frequency = SBC_FREQ_16000;
592 case BT_SBC_SAMPLING_FREQ_32000:
593 a2dp->sbc.frequency = SBC_FREQ_32000;
595 case BT_SBC_SAMPLING_FREQ_44100:
596 a2dp->sbc.frequency = SBC_FREQ_44100;
598 case BT_SBC_SAMPLING_FREQ_48000:
599 a2dp->sbc.frequency = SBC_FREQ_48000;
602 pa_assert_not_reached();
605 switch (active_capabilities->channel_mode) {
606 case BT_A2DP_CHANNEL_MODE_MONO:
607 a2dp->sbc.mode = SBC_MODE_MONO;
609 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
610 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
612 case BT_A2DP_CHANNEL_MODE_STEREO:
613 a2dp->sbc.mode = SBC_MODE_STEREO;
615 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
616 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
619 pa_assert_not_reached();
622 switch (active_capabilities->allocation_method) {
623 case BT_A2DP_ALLOCATION_SNR:
624 a2dp->sbc.allocation = SBC_AM_SNR;
626 case BT_A2DP_ALLOCATION_LOUDNESS:
627 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
630 pa_assert_not_reached();
633 switch (active_capabilities->subbands) {
634 case BT_A2DP_SUBBANDS_4:
635 a2dp->sbc.subbands = SBC_SB_4;
637 case BT_A2DP_SUBBANDS_8:
638 a2dp->sbc.subbands = SBC_SB_8;
641 pa_assert_not_reached();
644 switch (active_capabilities->block_length) {
645 case BT_A2DP_BLOCK_LENGTH_4:
646 a2dp->sbc.blocks = SBC_BLK_4;
648 case BT_A2DP_BLOCK_LENGTH_8:
649 a2dp->sbc.blocks = SBC_BLK_8;
651 case BT_A2DP_BLOCK_LENGTH_12:
652 a2dp->sbc.blocks = SBC_BLK_12;
654 case BT_A2DP_BLOCK_LENGTH_16:
655 a2dp->sbc.blocks = SBC_BLK_16;
658 pa_assert_not_reached();
661 a2dp->min_bitpool = active_capabilities->min_bitpool;
662 a2dp->max_bitpool = active_capabilities->max_bitpool;
664 /* Set minimum bitpool for source to get the maximum possible block_size */
665 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
666 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
667 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
670 /* Run from main thread */
671 static int set_conf(struct userdata *u) {
673 struct bt_open_req open_req;
674 struct bt_open_rsp open_rsp;
675 struct bt_set_configuration_req setconf_req;
676 struct bt_set_configuration_rsp setconf_rsp;
677 bt_audio_error_t error;
678 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
681 memset(&msg, 0, sizeof(msg));
682 msg.open_req.h.type = BT_REQUEST;
683 msg.open_req.h.name = BT_OPEN;
684 msg.open_req.h.length = sizeof(msg.open_req);
686 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
687 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
688 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
690 if (service_send(u, &msg.open_req.h) < 0)
693 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
696 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
697 u->sample_spec.format = PA_SAMPLE_S16LE;
699 if (setup_a2dp(u) < 0)
702 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
704 u->sample_spec.format = PA_SAMPLE_S16LE;
705 u->sample_spec.channels = 1;
706 u->sample_spec.rate = 8000;
709 memset(&msg, 0, sizeof(msg));
710 msg.setconf_req.h.type = BT_REQUEST;
711 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
712 msg.setconf_req.h.length = sizeof(msg.setconf_req);
714 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
715 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
717 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
718 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
719 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
721 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
723 if (service_send(u, &msg.setconf_req.h) < 0)
726 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
729 u->link_mtu = msg.setconf_rsp.link_mtu;
731 /* setup SBC encoder now we agree on parameters */
732 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
733 setup_sbc(&u->a2dp, u->profile);
736 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
737 / u->a2dp.frame_length
740 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
741 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
743 u->block_size = u->link_mtu;
749 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
751 struct a2dp_info *a2dp;
757 if (a2dp->sbc.bitpool == bitpool)
760 if (bitpool > a2dp->max_bitpool)
761 bitpool = a2dp->max_bitpool;
762 else if (bitpool < a2dp->min_bitpool)
763 bitpool = a2dp->min_bitpool;
765 a2dp->sbc.bitpool = bitpool;
767 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
768 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
770 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
773 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
774 / a2dp->frame_length * a2dp->codesize;
776 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
777 pa_sink_set_fixed_latency_within_thread(u->sink,
778 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
781 /* from IO thread, except in SCO over PCM */
783 static int setup_stream(struct userdata *u) {
784 struct pollfd *pollfd;
787 pa_make_fd_nonblock(u->stream_fd);
788 pa_make_socket_low_delay(u->stream_fd);
791 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
792 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
794 pa_log_debug("Stream properly set up, we're ready to roll!");
796 if (u->profile == PROFILE_A2DP)
797 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
799 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
800 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
801 pollfd->fd = u->stream_fd;
802 pollfd->events = pollfd->revents = 0;
804 u->read_index = u->write_index = 0;
808 u->read_smoother = pa_smoother_new(
820 static int start_stream_fd(struct userdata *u) {
822 bt_audio_msg_header_t rsp;
823 struct bt_start_stream_req start_req;
824 struct bt_start_stream_rsp start_rsp;
825 struct bt_new_stream_ind streamfd_ind;
826 bt_audio_error_t error;
827 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
831 pa_assert(u->rtpoll);
832 pa_assert(!u->rtpoll_item);
833 pa_assert(u->stream_fd < 0);
835 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
836 msg.start_req.h.type = BT_REQUEST;
837 msg.start_req.h.name = BT_START_STREAM;
838 msg.start_req.h.length = sizeof(msg.start_req);
840 if (service_send(u, &msg.start_req.h) < 0)
843 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
846 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
849 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
850 pa_log("Failed to get stream fd from audio service.");
854 return setup_stream(u);
858 static int stop_stream_fd(struct userdata *u) {
860 bt_audio_msg_header_t rsp;
861 struct bt_stop_stream_req start_req;
862 struct bt_stop_stream_rsp start_rsp;
863 bt_audio_error_t error;
864 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
869 pa_assert(u->rtpoll);
871 if (u->rtpoll_item) {
872 pa_rtpoll_item_free(u->rtpoll_item);
873 u->rtpoll_item = NULL;
876 if (u->stream_fd >= 0) {
877 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
878 msg.start_req.h.type = BT_REQUEST;
879 msg.start_req.h.name = BT_STOP_STREAM;
880 msg.start_req.h.length = sizeof(msg.start_req);
882 if (service_send(u, &msg.start_req.h) < 0 ||
883 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
886 pa_close(u->stream_fd);
890 if (u->read_smoother) {
891 pa_smoother_free(u->read_smoother);
892 u->read_smoother = NULL;
898 static void bt_transport_release(struct userdata *u) {
899 const char *accesstype = "rw";
900 const pa_bluetooth_transport *t;
902 /* Ignore if already released */
906 pa_log_debug("Releasing transport %s", u->transport);
908 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
910 pa_bluetooth_transport_release(t, accesstype);
912 pa_xfree(u->accesstype);
913 u->accesstype = NULL;
915 if (u->rtpoll_item) {
916 pa_rtpoll_item_free(u->rtpoll_item);
917 u->rtpoll_item = NULL;
920 if (u->stream_fd >= 0) {
921 pa_close(u->stream_fd);
925 if (u->read_smoother) {
926 pa_smoother_free(u->read_smoother);
927 u->read_smoother = NULL;
931 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
932 const char *accesstype = "rw";
933 const pa_bluetooth_transport *t;
941 pa_log_debug("Acquiring transport %s", u->transport);
943 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
945 pa_log("Transport %s no longer available", u->transport);
946 pa_xfree(u->transport);
951 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
952 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
953 if (u->stream_fd < 0)
956 u->accesstype = pa_xstrdup(accesstype);
957 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
963 pa_log_info("Transport %s resuming", u->transport);
964 return setup_stream(u);
967 /* Run from IO thread */
968 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
969 struct userdata *u = PA_SINK(o)->userdata;
970 pa_bool_t failed = FALSE;
973 pa_assert(u->sink == PA_SINK(o));
977 case PA_SINK_MESSAGE_SET_STATE:
979 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
981 case PA_SINK_SUSPENDED:
982 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
984 /* Stop the device if the source is suspended as well */
985 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
986 /* We deliberately ignore whether stopping
987 * actually worked. Since the stream_fd is
988 * closed it doesn't really matter */
990 bt_transport_release(u);
998 case PA_SINK_RUNNING:
999 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1002 /* Resume the device if the source was suspended as well */
1003 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1005 if (bt_transport_acquire(u, TRUE) < 0)
1007 } else if (start_stream_fd(u) < 0)
1012 case PA_SINK_UNLINKED:
1014 case PA_SINK_INVALID_STATE:
1019 case PA_SINK_MESSAGE_GET_LATENCY: {
1021 if (u->read_smoother) {
1024 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1025 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1027 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1031 ri = pa_rtclock_now() - u->started_at;
1032 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1034 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1037 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1042 r = pa_sink_process_msg(o, code, data, offset, chunk);
1044 return (r < 0 || !failed) ? r : -1;
1047 /* Run from IO thread */
1048 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1049 struct userdata *u = PA_SOURCE(o)->userdata;
1050 pa_bool_t failed = FALSE;
1053 pa_assert(u->source == PA_SOURCE(o));
1057 case PA_SOURCE_MESSAGE_SET_STATE:
1059 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1061 case PA_SOURCE_SUSPENDED:
1062 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1064 /* Stop the device if the sink is suspended as well */
1065 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1067 bt_transport_release(u);
1072 if (u->read_smoother)
1073 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1076 case PA_SOURCE_IDLE:
1077 case PA_SOURCE_RUNNING:
1078 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1081 /* Resume the device if the sink was suspended as well */
1082 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1084 if (bt_transport_acquire(u, TRUE) < 0)
1086 } else if (start_stream_fd(u) < 0)
1089 /* We don't resume the smoother here. Instead we
1090 * wait until the first packet arrives */
1093 case PA_SOURCE_UNLINKED:
1094 case PA_SOURCE_INIT:
1095 case PA_SOURCE_INVALID_STATE:
1100 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1103 if (u->read_smoother) {
1104 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1105 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1107 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1109 *((pa_usec_t*) data) = 0;
1116 r = pa_source_process_msg(o, code, data, offset, chunk);
1118 return (r < 0 || !failed) ? r : -1;
1121 /* Run from IO thread */
1122 static int hsp_process_render(struct userdata *u) {
1126 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1129 /* First, render some data */
1130 if (!u->write_memchunk.memblock)
1131 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1133 pa_assert(u->write_memchunk.length == u->block_size);
1139 /* Now write that data to the socket. The socket is of type
1140 * SEQPACKET, and we generated the data of the MTU size, so this
1141 * should just work. */
1143 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1144 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1145 pa_memblock_release(u->write_memchunk.memblock);
1152 /* Retry right away if we got interrupted */
1155 else if (errno == EAGAIN)
1156 /* Hmm, apparently the socket was not writable, give up for now */
1159 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1164 pa_assert((size_t) l <= u->write_memchunk.length);
1166 if ((size_t) l != u->write_memchunk.length) {
1167 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1168 (unsigned long long) l,
1169 (unsigned long long) u->write_memchunk.length);
1174 u->write_index += (uint64_t) u->write_memchunk.length;
1175 pa_memblock_unref(u->write_memchunk.memblock);
1176 pa_memchunk_reset(&u->write_memchunk);
1185 /* Run from IO thread */
1186 static int hsp_process_push(struct userdata *u) {
1188 pa_memchunk memchunk;
1191 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1192 pa_assert(u->source);
1193 pa_assert(u->read_smoother);
1195 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1196 memchunk.index = memchunk.length = 0;
1205 pa_bool_t found_tstamp = FALSE;
1208 memset(&m, 0, sizeof(m));
1209 memset(&aux, 0, sizeof(aux));
1210 memset(&iov, 0, sizeof(iov));
1214 m.msg_control = aux;
1215 m.msg_controllen = sizeof(aux);
1217 p = pa_memblock_acquire(memchunk.memblock);
1219 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1220 l = recvmsg(u->stream_fd, &m, 0);
1221 pa_memblock_release(memchunk.memblock);
1225 if (l < 0 && errno == EINTR)
1226 /* Retry right away if we got interrupted */
1229 else if (l < 0 && errno == EAGAIN)
1230 /* Hmm, apparently the socket was not readable, give up for now. */
1233 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1238 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1240 memchunk.length = (size_t) l;
1241 u->read_index += (uint64_t) l;
1243 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1244 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1245 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1246 pa_rtclock_from_wallclock(tv);
1247 tstamp = pa_timeval_load(tv);
1248 found_tstamp = TRUE;
1252 if (!found_tstamp) {
1253 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1254 tstamp = pa_rtclock_now();
1257 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1258 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1260 pa_source_post(u->source, &memchunk);
1266 pa_memblock_unref(memchunk.memblock);
1271 /* Run from IO thread */
1272 static void a2dp_prepare_buffer(struct userdata *u) {
1275 if (u->a2dp.buffer_size >= u->link_mtu)
1278 u->a2dp.buffer_size = 2 * u->link_mtu;
1279 pa_xfree(u->a2dp.buffer);
1280 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1283 /* Run from IO thread */
1284 static int a2dp_process_render(struct userdata *u) {
1285 struct a2dp_info *a2dp;
1286 struct rtp_header *header;
1287 struct rtp_payload *payload;
1291 size_t to_write, to_encode;
1292 unsigned frame_count;
1296 pa_assert(u->profile == PROFILE_A2DP);
1299 /* First, render some data */
1300 if (!u->write_memchunk.memblock)
1301 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1303 pa_assert(u->write_memchunk.length == u->block_size);
1305 a2dp_prepare_buffer(u);
1308 header = a2dp->buffer;
1309 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1313 /* Try to create a packet of the full MTU */
1315 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1316 to_encode = u->write_memchunk.length;
1318 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1319 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1321 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1325 encoded = sbc_encode(&a2dp->sbc,
1330 if (PA_UNLIKELY(encoded <= 0)) {
1331 pa_log_error("SBC encoding error (%li)", (long) encoded);
1332 pa_memblock_release(u->write_memchunk.memblock);
1336 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1337 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1339 pa_assert_fp((size_t) encoded <= to_encode);
1340 pa_assert_fp((size_t) encoded == a2dp->codesize);
1342 pa_assert_fp((size_t) written <= to_write);
1343 pa_assert_fp((size_t) written == a2dp->frame_length);
1345 p = (const uint8_t*) p + encoded;
1346 to_encode -= encoded;
1348 d = (uint8_t*) d + written;
1349 to_write -= written;
1354 pa_memblock_release(u->write_memchunk.memblock);
1356 pa_assert(to_encode == 0);
1359 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1362 /* write it to the fifo */
1363 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1366 header->sequence_number = htons(a2dp->seq_num++);
1367 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1368 header->ssrc = htonl(1);
1369 payload->frame_count = frame_count;
1371 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1376 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1383 /* Retry right away if we got interrupted */
1386 else if (errno == EAGAIN)
1387 /* Hmm, apparently the socket was not writable, give up for now */
1390 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1395 pa_assert((size_t) l <= nbytes);
1397 if ((size_t) l != nbytes) {
1398 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1399 (unsigned long long) l,
1400 (unsigned long long) nbytes);
1405 u->write_index += (uint64_t) u->write_memchunk.length;
1406 pa_memblock_unref(u->write_memchunk.memblock);
1407 pa_memchunk_reset(&u->write_memchunk);
1417 static int a2dp_process_push(struct userdata *u) {
1419 pa_memchunk memchunk;
1422 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1423 pa_assert(u->source);
1424 pa_assert(u->read_smoother);
1426 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1427 memchunk.index = memchunk.length = 0;
1430 pa_bool_t found_tstamp = FALSE;
1432 struct a2dp_info *a2dp;
1433 struct rtp_header *header;
1434 struct rtp_payload *payload;
1438 size_t to_write, to_decode;
1439 unsigned frame_count;
1441 a2dp_prepare_buffer(u);
1444 header = a2dp->buffer;
1445 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1447 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1451 if (l < 0 && errno == EINTR)
1452 /* Retry right away if we got interrupted */
1455 else if (l < 0 && errno == EAGAIN)
1456 /* Hmm, apparently the socket was not readable, give up for now. */
1459 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1464 pa_assert((size_t) l <= a2dp->buffer_size);
1466 u->read_index += (uint64_t) l;
1468 /* TODO: get timestamp from rtp */
1469 if (!found_tstamp) {
1470 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1471 tstamp = pa_rtclock_now();
1474 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1475 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1477 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1478 to_decode = l - sizeof(*header) - sizeof(*payload);
1480 d = pa_memblock_acquire(memchunk.memblock);
1481 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1483 while (PA_LIKELY(to_decode > 0)) {
1487 decoded = sbc_decode(&a2dp->sbc,
1492 if (PA_UNLIKELY(decoded <= 0)) {
1493 pa_log_error("SBC decoding error (%li)", (long) decoded);
1494 pa_memblock_release(memchunk.memblock);
1495 pa_memblock_unref(memchunk.memblock);
1499 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1500 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1502 /* Reset frame length, it can be changed due to bitpool change */
1503 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1505 pa_assert_fp((size_t) decoded <= to_decode);
1506 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1508 pa_assert_fp((size_t) written == a2dp->codesize);
1510 p = (const uint8_t*) p + decoded;
1511 to_decode -= decoded;
1513 d = (uint8_t*) d + written;
1514 to_write -= written;
1519 memchunk.length -= to_write;
1521 pa_memblock_release(memchunk.memblock);
1523 pa_source_post(u->source, &memchunk);
1529 pa_memblock_unref(memchunk.memblock);
1534 static void a2dp_reduce_bitpool(struct userdata *u)
1536 struct a2dp_info *a2dp;
1543 /* Check if bitpool is already at its limit */
1544 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1547 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1549 if (bitpool < BITPOOL_DEC_LIMIT)
1550 bitpool = BITPOOL_DEC_LIMIT;
1552 a2dp_set_bitpool(u, bitpool);
1555 static void thread_func(void *userdata) {
1556 struct userdata *u = userdata;
1557 unsigned do_write = 0;
1558 pa_bool_t writable = FALSE;
1562 pa_log_debug("IO Thread starting up");
1564 if (u->core->realtime_scheduling)
1565 pa_make_realtime(u->core->realtime_priority);
1567 pa_thread_mq_install(&u->thread_mq);
1570 if (bt_transport_acquire(u, TRUE) < 0)
1572 } else if (start_stream_fd(u) < 0)
1576 struct pollfd *pollfd;
1578 pa_bool_t disable_timer = TRUE;
1580 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1582 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1584 /* We should send two blocks to the device before we expect
1587 if (u->write_index == 0 && u->read_index <= 0)
1590 if (pollfd && (pollfd->revents & POLLIN)) {
1593 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1594 n_read = hsp_process_push(u);
1596 n_read = a2dp_process_push(u);
1601 /* We just read something, so we are supposed to write something, too */
1606 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1608 if (u->sink->thread_info.rewind_requested)
1609 pa_sink_process_rewind(u->sink, 0);
1612 if (pollfd->revents & POLLOUT)
1615 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1616 pa_usec_t time_passed;
1617 pa_usec_t audio_sent;
1619 /* Hmm, there is no input stream we could synchronize
1620 * to. So let's do things by time */
1622 time_passed = pa_rtclock_now() - u->started_at;
1623 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1625 if (audio_sent <= time_passed) {
1626 pa_usec_t audio_to_send = time_passed - audio_sent;
1628 /* Never try to catch up for more than 100ms */
1629 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1630 pa_usec_t skip_usec;
1631 uint64_t skip_bytes;
1633 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1634 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1636 if (skip_bytes > 0) {
1639 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1640 (unsigned long long) skip_usec,
1641 (unsigned long long) skip_bytes);
1643 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1644 pa_memblock_unref(tmp.memblock);
1645 u->write_index += skip_bytes;
1647 if (u->profile == PROFILE_A2DP)
1648 a2dp_reduce_bitpool(u);
1656 if (writable && do_write > 0) {
1659 if (u->write_index <= 0)
1660 u->started_at = pa_rtclock_now();
1662 if (u->profile == PROFILE_A2DP) {
1663 if ((n_written = a2dp_process_render(u)) < 0)
1666 if ((n_written = hsp_process_render(u)) < 0)
1671 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1673 do_write -= n_written;
1677 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1678 pa_usec_t sleep_for;
1679 pa_usec_t time_passed, next_write_at;
1682 /* Hmm, there is no input stream we could synchronize
1683 * to. So let's estimate when we need to wake up the latest */
1684 time_passed = pa_rtclock_now() - u->started_at;
1685 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1686 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1687 /* 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); */
1689 /* drop stream every 500 ms */
1690 sleep_for = PA_USEC_PER_MSEC * 500;
1692 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1693 disable_timer = FALSE;
1699 pa_rtpoll_set_timer_disabled(u->rtpoll);
1701 /* Hmm, nothing to do. Let's sleep */
1703 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1704 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1706 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1712 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1714 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1715 pa_log_info("FD error: %s%s%s%s",
1716 pollfd->revents & POLLERR ? "POLLERR " :"",
1717 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1718 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1719 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1725 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1726 pa_log_debug("IO thread failed");
1727 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1728 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1731 pa_log_debug("IO thread shutting down");
1734 /* Run from main thread */
1735 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1741 pa_assert_se(u = userdata);
1743 dbus_error_init(&err);
1745 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1746 dbus_message_get_interface(m),
1747 dbus_message_get_path(m),
1748 dbus_message_get_member(m));
1750 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1753 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1754 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1759 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1760 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1764 if (u->profile == PROFILE_HSP) {
1765 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1766 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1768 /* increment volume by one to correct rounding errors */
1769 if (volume < PA_VOLUME_NORM)
1772 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1773 pa_sink_volume_changed(u->sink, &v);
1775 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1776 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1778 /* increment volume by one to correct rounding errors */
1779 if (volume < PA_VOLUME_NORM)
1782 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1783 pa_source_volume_changed(u->source, &v);
1786 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1787 DBusMessageIter arg_i;
1788 pa_bluetooth_transport *t;
1791 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1794 if (!dbus_message_iter_init(m, &arg_i)) {
1795 pa_log("Failed to parse PropertyChanged: %s", err.message);
1801 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1804 if (nrec != t->nrec) {
1805 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1806 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1808 }else if (dbus_message_is_signal(m, "org.bluez.Headset", "Playing")) {
1810 ret=pa_sink_suspend(u->sink,TRUE,PA_SUSPEND_IDLE);
1811 pa_log_debug("ret=%d",ret);
1812 } else if (dbus_message_is_signal(m, "org.bluez.Headset", "Stopped")) {
1814 ret=pa_sink_suspend(u->sink,FALSE,PA_SUSPEND_IDLE);
1815 pa_log_debug("ret=%d",ret);
1819 dbus_error_free(&err);
1821 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1824 /* Run from main thread */
1825 static void sink_set_volume_cb(pa_sink *s) {
1835 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1836 u = pa_shared_get(s->core, k);
1840 pa_assert(u->sink == s);
1841 pa_assert(u->profile == PROFILE_HSP);
1843 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1845 if (gain > HSP_MAX_GAIN)
1846 gain = HSP_MAX_GAIN;
1848 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1850 /* increment volume by one to correct rounding errors */
1851 if (volume < PA_VOLUME_NORM)
1854 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1856 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1857 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1858 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1859 dbus_message_unref(m);
1862 /* Run from main thread */
1863 static void source_set_volume_cb(pa_source *s) {
1873 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1874 u = pa_shared_get(s->core, k);
1878 pa_assert(u->source == s);
1879 pa_assert(u->profile == PROFILE_HSP);
1881 gain = (pa_cvolume_max(&s->volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1883 if (gain > HSP_MAX_GAIN)
1884 gain = HSP_MAX_GAIN;
1886 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1888 /* increment volume by one to correct rounding errors */
1889 if (volume < PA_VOLUME_NORM)
1892 pa_cvolume_set(&s->volume, u->sample_spec.channels, volume);
1894 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1895 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1896 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1897 dbus_message_unref(m);
1900 /* Run from main thread */
1901 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1907 pa_assert(device_id);
1908 pa_assert(namereg_fail);
1910 t = pa_sprintf_malloc("%s_name", type);
1911 n = pa_modargs_get_value(ma, t, NULL);
1915 *namereg_fail = TRUE;
1916 return pa_xstrdup(n);
1919 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1920 *namereg_fail = TRUE;
1923 *namereg_fail = FALSE;
1926 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1929 static int sco_over_pcm_state_update(struct userdata *u) {
1931 pa_assert(USE_SCO_OVER_PCM(u));
1933 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1934 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1936 if (u->service_fd >= 0 && u->stream_fd >= 0)
1941 pa_log_debug("Resuming SCO over PCM");
1942 if (init_profile(u) < 0) {
1943 pa_log("Can't resume SCO over PCM");
1948 return bt_transport_acquire(u, TRUE);
1950 return start_stream_fd(u);
1953 if (u->service_fd < 0 && u->stream_fd < 0)
1956 pa_log_debug("Closing SCO over PCM");
1959 bt_transport_release(u);
1960 else if (u->stream_fd >= 0)
1963 if (u->service_fd >= 0) {
1964 pa_close(u->service_fd);
1972 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1974 pa_sink_assert_ref(s);
1977 if (s != u->hsp.sco_sink)
1980 sco_over_pcm_state_update(u);
1985 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1987 pa_source_assert_ref(s);
1990 if (s != u->hsp.sco_source)
1993 sco_over_pcm_state_update(u);
1998 /* Run from main thread */
1999 static int add_sink(struct userdata *u) {
2002 if (USE_SCO_OVER_PCM(u)) {
2005 u->sink = u->hsp.sco_sink;
2006 p = pa_proplist_new();
2007 pa_proplist_sets(p, "bluetooth.protocol", "sco");
2008 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
2009 pa_proplist_free(p);
2011 if (!u->hsp.sink_state_changed_slot)
2012 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);
2015 pa_sink_new_data data;
2018 pa_sink_new_data_init(&data);
2019 data.driver = __FILE__;
2020 data.module = u->module;
2021 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
2022 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
2023 if (u->profile == PROFILE_HSP)
2024 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2025 data.card = u->card;
2026 data.name = get_name("sink", u->modargs, u->address, &b);
2027 data.namereg_fail = b;
2029 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2030 pa_log("Invalid properties");
2031 pa_sink_new_data_done(&data);
2035 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
2036 pa_sink_new_data_done(&data);
2039 pa_log_error("Failed to create sink");
2043 u->sink->userdata = u;
2044 u->sink->parent.process_msg = sink_process_msg;
2046 pa_sink_set_max_request(u->sink, u->block_size);
2047 pa_sink_set_fixed_latency(u->sink,
2048 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2049 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2052 if (u->profile == PROFILE_HSP) {
2053 u->sink->set_volume = sink_set_volume_cb;
2054 u->sink->n_volume_steps = 16;
2056 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2057 pa_shared_set(u->core, k, u);
2064 /* Run from main thread */
2065 static int add_source(struct userdata *u) {
2068 if (USE_SCO_OVER_PCM(u)) {
2069 u->source = u->hsp.sco_source;
2070 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2072 if (!u->hsp.source_state_changed_slot)
2073 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);
2076 pa_source_new_data data;
2079 pa_source_new_data_init(&data);
2080 data.driver = __FILE__;
2081 data.module = u->module;
2082 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2083 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2084 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2085 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2087 data.card = u->card;
2088 data.name = get_name("source", u->modargs, u->address, &b);
2089 data.namereg_fail = b;
2091 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2092 pa_log("Invalid properties");
2093 pa_source_new_data_done(&data);
2097 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2098 pa_source_new_data_done(&data);
2101 pa_log_error("Failed to create source");
2105 u->source->userdata = u;
2106 u->source->parent.process_msg = source_process_msg;
2108 pa_source_set_fixed_latency(u->source,
2109 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2110 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2113 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2115 const pa_bluetooth_transport *t;
2116 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2118 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2120 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2123 if (u->profile == PROFILE_HSP) {
2124 u->source->set_volume = source_set_volume_cb;
2125 u->source->n_volume_steps = 16;
2127 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2128 pa_shared_set(u->core, k, u);
2135 /* Run from main thread */
2136 static void shutdown_bt(struct userdata *u) {
2139 if (u->stream_fd >= 0) {
2140 pa_close(u->stream_fd);
2143 u->stream_write_type = 0;
2146 if (u->service_fd >= 0) {
2147 pa_close(u->service_fd);
2149 u->service_write_type = 0;
2150 u->service_read_type = 0;
2153 if (u->write_memchunk.memblock) {
2154 pa_memblock_unref(u->write_memchunk.memblock);
2155 pa_memchunk_reset(&u->write_memchunk);
2159 static int bt_transport_config_a2dp(struct userdata *u) {
2160 const pa_bluetooth_transport *t;
2161 struct a2dp_info *a2dp = &u->a2dp;
2162 sbc_capabilities_raw_t *config;
2164 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2167 config = (sbc_capabilities_raw_t *) t->config;
2169 if (a2dp->sbc_initialized)
2170 sbc_reinit(&a2dp->sbc, 0);
2172 sbc_init(&a2dp->sbc, 0);
2173 a2dp->sbc_initialized = TRUE;
2175 switch (config->frequency) {
2176 case BT_SBC_SAMPLING_FREQ_16000:
2177 a2dp->sbc.frequency = SBC_FREQ_16000;
2179 case BT_SBC_SAMPLING_FREQ_32000:
2180 a2dp->sbc.frequency = SBC_FREQ_32000;
2182 case BT_SBC_SAMPLING_FREQ_44100:
2183 a2dp->sbc.frequency = SBC_FREQ_44100;
2185 case BT_SBC_SAMPLING_FREQ_48000:
2186 a2dp->sbc.frequency = SBC_FREQ_48000;
2189 pa_assert_not_reached();
2192 switch (config->channel_mode) {
2193 case BT_A2DP_CHANNEL_MODE_MONO:
2194 a2dp->sbc.mode = SBC_MODE_MONO;
2196 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2197 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2199 case BT_A2DP_CHANNEL_MODE_STEREO:
2200 a2dp->sbc.mode = SBC_MODE_STEREO;
2202 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2203 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2206 pa_assert_not_reached();
2209 switch (config->allocation_method) {
2210 case BT_A2DP_ALLOCATION_SNR:
2211 a2dp->sbc.allocation = SBC_AM_SNR;
2213 case BT_A2DP_ALLOCATION_LOUDNESS:
2214 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2217 pa_assert_not_reached();
2220 switch (config->subbands) {
2221 case BT_A2DP_SUBBANDS_4:
2222 a2dp->sbc.subbands = SBC_SB_4;
2224 case BT_A2DP_SUBBANDS_8:
2225 a2dp->sbc.subbands = SBC_SB_8;
2228 pa_assert_not_reached();
2231 switch (config->block_length) {
2232 case BT_A2DP_BLOCK_LENGTH_4:
2233 a2dp->sbc.blocks = SBC_BLK_4;
2235 case BT_A2DP_BLOCK_LENGTH_8:
2236 a2dp->sbc.blocks = SBC_BLK_8;
2238 case BT_A2DP_BLOCK_LENGTH_12:
2239 a2dp->sbc.blocks = SBC_BLK_12;
2241 case BT_A2DP_BLOCK_LENGTH_16:
2242 a2dp->sbc.blocks = SBC_BLK_16;
2245 pa_assert_not_reached();
2248 a2dp->min_bitpool = config->min_bitpool;
2249 a2dp->max_bitpool = config->max_bitpool;
2251 /* Set minimum bitpool for source to get the maximum possible block_size */
2252 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2253 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2254 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2257 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2258 / a2dp->frame_length
2261 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2262 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2267 static int bt_transport_config(struct userdata *u) {
2268 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2269 u->block_size = u->link_mtu;
2273 return bt_transport_config_a2dp(u);
2276 /* Run from main thread */
2277 static int bt_transport_open(struct userdata *u) {
2278 if (bt_transport_acquire(u, FALSE) < 0)
2281 return bt_transport_config(u);
2284 /* Run from main thread */
2285 static int init_bt(struct userdata *u) {
2290 u->stream_write_type = 0;
2291 u->service_write_type = 0;
2292 u->service_read_type = 0;
2294 if ((u->service_fd = bt_audio_service_open()) < 0) {
2295 pa_log_warn("Bluetooth audio service not available");
2299 pa_log_debug("Connected to the bluetooth audio service");
2304 /* Run from main thread */
2305 static int setup_bt(struct userdata *u) {
2306 const pa_bluetooth_device *d;
2307 const pa_bluetooth_transport *t;
2311 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2312 pa_log_error("Failed to get device object.");
2316 /* release transport if exist */
2318 bt_transport_release(u);
2319 pa_xfree(u->transport);
2320 u->transport = NULL;
2323 /* check if profile has a transport */
2324 t = pa_bluetooth_device_get_transport(d, u->profile);
2326 u->transport = pa_xstrdup(t->path);
2327 return bt_transport_open(u);
2330 if (get_caps(u, 0) < 0)
2333 pa_log_debug("Got device capabilities");
2335 if (set_conf(u) < 0)
2338 pa_log_debug("Connection to the device configured");
2340 if (USE_SCO_OVER_PCM(u)) {
2341 pa_log_debug("Configured to use SCO over PCM");
2345 pa_log_debug("Got the stream socket");
2350 /* Run from main thread */
2351 static int init_profile(struct userdata *u) {
2354 pa_assert(u->profile != PROFILE_OFF);
2356 if (setup_bt(u) < 0)
2359 if (u->profile == PROFILE_A2DP ||
2360 u->profile == PROFILE_HSP ||
2361 u->profile == PROFILE_HFGW)
2362 if (add_sink(u) < 0)
2365 if (u->profile == PROFILE_HSP ||
2366 u->profile == PROFILE_A2DP_SOURCE ||
2367 u->profile == PROFILE_HFGW)
2368 if (add_source(u) < 0)
2374 /* Run from main thread */
2375 static void stop_thread(struct userdata *u) {
2381 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2382 pa_thread_free(u->thread);
2386 if (u->rtpoll_item) {
2387 pa_rtpoll_item_free(u->rtpoll_item);
2388 u->rtpoll_item = NULL;
2391 if (u->hsp.sink_state_changed_slot) {
2392 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2393 u->hsp.sink_state_changed_slot = NULL;
2396 if (u->hsp.source_state_changed_slot) {
2397 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2398 u->hsp.source_state_changed_slot = NULL;
2402 if (u->profile == PROFILE_HSP) {
2403 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2404 pa_shared_remove(u->core, k);
2408 pa_sink_unref(u->sink);
2413 if (u->profile == PROFILE_HSP) {
2414 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2415 pa_shared_remove(u->core, k);
2419 pa_source_unref(u->source);
2424 pa_thread_mq_done(&u->thread_mq);
2426 pa_rtpoll_free(u->rtpoll);
2430 if (u->read_smoother) {
2431 pa_smoother_free(u->read_smoother);
2432 u->read_smoother = NULL;
2436 /* Run from main thread */
2437 static int start_thread(struct userdata *u) {
2439 pa_assert(!u->thread);
2440 pa_assert(!u->rtpoll);
2441 pa_assert(!u->rtpoll_item);
2443 u->rtpoll = pa_rtpoll_new();
2444 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2446 if (USE_SCO_OVER_PCM(u)) {
2447 if (sco_over_pcm_state_update(u) < 0) {
2451 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2452 pa_shared_remove(u->core, k);
2457 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2458 pa_shared_remove(u->core, k);
2465 pa_sink_ref(u->sink);
2466 pa_source_ref(u->source);
2467 /* FIXME: monitor stream_fd error */
2471 //Build bug fix because our pulseaudio core is old version than bluetooth
2472 //if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2473 if (!(u->thread = pa_thread_new(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 u->hsp.sco_sink->set_volume = u->hsp.sco_sink_set_volume;
2513 u->hsp.sco_source->set_volume = 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);
2569 if (USE_SCO_OVER_PCM(u))
2570 restore_sco_volume_callbacks(u);
2573 u->sample_spec = u->requested_sample_spec;
2575 if (USE_SCO_OVER_PCM(u))
2576 save_sco_volume_callbacks(u);
2580 if (u->profile != PROFILE_OFF)
2583 if (u->sink || u->source)
2588 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2590 pa_sink_move_all_fail(inputs);
2595 pa_source_move_all_finish(u->source, outputs, FALSE);
2597 pa_source_move_all_fail(outputs);
2603 /* Run from main thread */
2604 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2605 pa_card_new_data data;
2611 const char *default_profile;
2616 pa_card_new_data_init(&data);
2617 data.driver = __FILE__;
2618 data.module = u->module;
2620 n = pa_bluetooth_cleanup_name(device->name);
2621 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2623 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2624 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2625 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2626 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2627 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2628 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2629 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2630 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2631 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2632 data.name = get_name("card", u->modargs, device->address, &b);
2633 data.namereg_fail = b;
2635 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2636 pa_log("Invalid properties");
2637 pa_card_new_data_done(&data);
2641 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2643 /* we base hsp/a2dp availability on UUIDs.
2644 Ideally, it would be based on "Connected" state, but
2645 we can't afford to wait for this information when
2646 we are loaded with profile="hsp", for instance */
2647 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2648 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2652 p->max_sink_channels = 2;
2653 p->max_source_channels = 0;
2655 d = PA_CARD_PROFILE_DATA(p);
2658 pa_hashmap_put(data.profiles, p->name, p);
2661 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2662 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2666 p->max_sink_channels = 0;
2667 p->max_source_channels = 2;
2669 d = PA_CARD_PROFILE_DATA(p);
2670 *d = PROFILE_A2DP_SOURCE;
2672 pa_hashmap_put(data.profiles, p->name, p);
2674 #ifdef BT_FULL_AUDIO_FEATURE
2675 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2676 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2677 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2681 p->max_sink_channels = 1;
2682 p->max_source_channels = 1;
2684 d = PA_CARD_PROFILE_DATA(p);
2687 pa_hashmap_put(data.profiles, p->name, p);
2690 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2691 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2695 p->max_sink_channels = 1;
2696 p->max_source_channels = 1;
2698 d = PA_CARD_PROFILE_DATA(p);
2701 pa_hashmap_put(data.profiles, p->name, p);
2705 pa_assert(!pa_hashmap_isempty(data.profiles));
2707 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2708 d = PA_CARD_PROFILE_DATA(p);
2710 pa_hashmap_put(data.profiles, p->name, p);
2712 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2713 if (pa_hashmap_get(data.profiles, default_profile))
2714 pa_card_new_data_set_profile(&data, default_profile);
2716 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2719 u->card = pa_card_new(u->core, &data);
2720 pa_card_new_data_done(&data);
2723 pa_log("Failed to allocate card.");
2727 u->card->userdata = u;
2728 u->card->set_profile = card_set_profile;
2730 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2732 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2733 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2734 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2735 pa_log_warn("Default profile not connected, selecting off profile");
2736 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2737 u->card->save_profile = FALSE;
2740 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2743 if (USE_SCO_OVER_PCM(u))
2744 save_sco_volume_callbacks(u);
2749 /* Run from main thread */
2750 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2751 const pa_bluetooth_device *d = NULL;
2755 if (!address && !path) {
2756 pa_log_error("Failed to get device address/path from module arguments.");
2761 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2762 pa_log_error("%s is not a valid BlueZ audio device.", path);
2766 if (address && !(pa_streq(d->address, address))) {
2767 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2772 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2773 pa_log_error("%s is not known.", address);
2779 u->address = pa_xstrdup(d->address);
2780 u->path = pa_xstrdup(d->path);
2786 /* Run from main thread */
2787 static int setup_dbus(struct userdata *u) {
2790 dbus_error_init(&err);
2792 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2794 if (dbus_error_is_set(&err) || !u->connection) {
2795 pa_log("Failed to get D-Bus connection: %s", err.message);
2796 dbus_error_free(&err);
2803 int pa__init(pa_module* m) {
2807 const char *address, *path;
2809 char *mike, *speaker, *transport,*headset;
2810 const pa_bluetooth_device *device;
2814 dbus_error_init(&err);
2816 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2817 pa_log_error("Failed to parse module arguments");
2821 m->userdata = u = pa_xnew0(struct userdata, 1);
2826 u->sample_spec = m->core->default_sample_spec;
2829 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2830 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2831 pa_log("SCO sink not found");
2835 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2836 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2837 pa_log("SCO source not found");
2841 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2842 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2843 pa_log_error("Failed to get rate from module arguments");
2847 u->auto_connect = TRUE;
2848 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2849 pa_log("Failed to parse auto_connect= argument");
2853 channels = u->sample_spec.channels;
2854 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2855 channels <= 0 || channels > PA_CHANNELS_MAX) {
2856 pa_log_error("Failed to get channels from module arguments");
2859 u->sample_spec.channels = (uint8_t) channels;
2860 u->requested_sample_spec = u->sample_spec;
2862 address = pa_modargs_get_value(ma, "address", NULL);
2863 path = pa_modargs_get_value(ma, "path", NULL);
2865 if (setup_dbus(u) < 0)
2868 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2871 if (!(device = find_device(u, address, path)))
2874 /* Add the card structure. This will also initialize the default profile */
2875 if (add_card(u, device) < 0)
2878 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2879 pa_log_error("Failed to add filter function");
2882 u->filter_added = TRUE;
2884 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2885 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2886 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2887 headset=pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged',path='%s'", u->path);
2889 if (pa_dbus_add_matches(
2890 pa_dbus_connection_get(u->connection), &err,
2899 pa_xfree(transport);
2901 pa_log("Failed to add D-Bus matches: %s", err.message);
2907 pa_xfree(transport);
2909 /* Connect to the BT service */
2912 if (u->profile != PROFILE_OFF)
2913 if (init_profile(u) < 0)
2916 if (u->sink || u->source)
2917 if (start_thread(u) < 0)
2926 dbus_error_free(&err);
2931 int pa__get_n_used(pa_module *m) {
2935 pa_assert_se(u = m->userdata);
2938 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2939 (u->source ? pa_source_linked_by(u->source) : 0);
2942 void pa__done(pa_module *m) {
2947 if (!(u = m->userdata))
2950 if (u->sink && !USE_SCO_OVER_PCM(u))
2951 pa_sink_unlink(u->sink);
2953 if (u->source && !USE_SCO_OVER_PCM(u))
2954 pa_source_unlink(u->source);
2958 if (USE_SCO_OVER_PCM(u))
2959 restore_sco_volume_callbacks(u);
2961 if (u->connection) {
2964 char *speaker, *mike;
2965 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2966 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2968 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2974 if (u->filter_added)
2975 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2977 pa_dbus_connection_unref(u->connection);
2981 pa_card_free(u->card);
2983 if (u->read_smoother)
2984 pa_smoother_free(u->read_smoother);
2989 pa_xfree(u->a2dp.buffer);
2991 sbc_finish(&u->a2dp.sbc);
2994 pa_modargs_free(u->modargs);
2996 pa_xfree(u->address);
3000 bt_transport_release(u);
3001 pa_xfree(u->transport);
3005 pa_bluetooth_discovery_unref(u->discovery);