2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
28 #include <linux/sockios.h>
29 #include <arpa/inet.h>
31 #include <pulse/i18n.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/modargs.h>
39 #include <pulsecore/core-rtclock.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/socket-util.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/poll.h>
46 #include <pulsecore/rtpoll.h>
47 #include <pulsecore/time-smoother.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
50 #include <pulsecore/llist.h>
52 #include "module-bluetooth-device-symdef.h"
55 #include "a2dp-codecs.h"
57 #include "bluetooth-util.h"
59 #define BITPOOL_DEC_LIMIT 32
60 #define BITPOOL_DEC_STEP 5
62 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
63 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
64 PA_MODULE_VERSION(PACKAGE_VERSION);
65 PA_MODULE_LOAD_ONCE(FALSE);
67 "name=<name for the card/sink/source, to be prefixed> "
68 "card_name=<name for the card> "
69 "card_properties=<properties for the card> "
70 "sink_name=<name for the sink> "
71 "sink_properties=<properties for the sink> "
72 "source_name=<name for the source> "
73 "source_properties=<properties for the source> "
74 "address=<address of the device> "
75 "profile=<a2dp|hsp|hfgw> "
77 "channels=<number of channels> "
78 "path=<device object path> "
79 "auto_connect=<automatically connect?> "
80 "sco_sink=<SCO over PCM sink name> "
81 "sco_source=<SCO over PCM source name>");
83 /* TODO: not close fd when entering suspend mode in a2dp */
85 static const char* const valid_modargs[] = {
105 sbc_capabilities_t sbc_capabilities;
106 sbc_t sbc; /* Codec data */
107 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
108 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
110 void* buffer; /* Codec transfer buffer */
111 size_t buffer_size; /* Size of the buffer */
113 uint16_t seq_num; /* Cumulative packet sequence */
119 pcm_capabilities_t pcm_capabilities;
121 pa_source *sco_source;
122 pa_hook_slot *sink_state_changed_slot;
123 pa_hook_slot *source_state_changed_slot;
135 pa_bluetooth_discovery *discovery;
136 pa_bool_t auto_connect;
138 pa_dbus_connection *connection;
144 pa_thread_mq thread_mq;
146 pa_rtpoll_item *rtpoll_item;
149 uint64_t read_index, write_index;
150 pa_usec_t started_at;
151 pa_smoother *read_smoother;
153 pa_memchunk write_memchunk;
155 pa_sample_spec sample_spec, requested_sample_spec;
163 struct a2dp_info a2dp;
166 enum profile profile;
170 int stream_write_type;
171 int service_write_type, service_read_type;
173 pa_bool_t filter_added;
176 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
177 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
178 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
179 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
181 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
183 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
185 static int init_bt(struct userdata *u);
186 static int init_profile(struct userdata *u);
188 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
193 pa_assert(msg->length > 0);
195 if (u->service_fd < 0) {
196 pa_log_warn("Service not connected");
200 pa_log_debug("Sending %s -> %s",
201 pa_strnull(bt_audio_strtype(msg->type)),
202 pa_strnull(bt_audio_strname(msg->name)));
204 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
208 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
210 pa_log_error("Short write()");
215 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
219 pa_assert(u->service_fd >= 0);
221 pa_assert(room >= sizeof(*msg));
223 pa_log_debug("Trying to receive message from audio service...");
225 /* First, read the header */
226 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
229 if (msg->length < sizeof(*msg)) {
230 pa_log_error("Invalid message size.");
234 if (msg->length > room) {
235 pa_log_error("Not enough room.");
239 /* Secondly, read the payload */
240 if (msg->length > sizeof(*msg)) {
242 size_t remains = msg->length - sizeof(*msg);
244 if ((r = pa_loop_read(u->service_fd,
245 (uint8_t*) msg + sizeof(*msg),
247 &u->service_read_type)) != (ssize_t) remains)
251 pa_log_debug("Received %s <- %s",
252 pa_strnull(bt_audio_strtype(msg->type)),
253 pa_strnull(bt_audio_strname(msg->name)));
260 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
262 pa_log_error("Short read()");
267 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) {
271 pa_assert(u->service_fd >= 0);
274 if ((r = service_recv(u, rsp, room)) < 0)
277 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
278 rsp->name != expected_name ||
279 (expected_size > 0 && rsp->length != expected_size)) {
281 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
282 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
284 pa_log_error("Bogus message %s received while %s was expected",
285 pa_strnull(bt_audio_strname(rsp->name)),
286 pa_strnull(bt_audio_strname(expected_name)));
293 /* Run from main thread */
294 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
296 const codec_capabilities_t *codec;
301 bytes_left = rsp->h.length - sizeof(*rsp);
303 if (bytes_left < sizeof(codec_capabilities_t)) {
304 pa_log_error("Packet too small to store codec information.");
308 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
310 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
312 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
313 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
314 pa_log_error("Got capabilities for wrong codec.");
318 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
320 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
323 pa_assert(codec->type == BT_HFP_CODEC_PCM);
325 if (codec->configured && seid == 0)
328 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
330 } else if (u->profile == PROFILE_A2DP) {
332 while (bytes_left > 0) {
333 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
336 bytes_left -= codec->length;
337 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
340 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
343 pa_assert(codec->type == BT_A2DP_SBC_SINK);
345 if (codec->configured && seid == 0)
348 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
350 } else if (u->profile == PROFILE_A2DP_SOURCE) {
352 while (bytes_left > 0) {
353 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
356 bytes_left -= codec->length;
357 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
360 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
363 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
365 if (codec->configured && seid == 0)
368 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
374 /* Run from main thread */
375 static int get_caps(struct userdata *u, uint8_t seid) {
377 struct bt_get_capabilities_req getcaps_req;
378 struct bt_get_capabilities_rsp getcaps_rsp;
379 bt_audio_error_t error;
380 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
386 memset(&msg, 0, sizeof(msg));
387 msg.getcaps_req.h.type = BT_REQUEST;
388 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
389 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
390 msg.getcaps_req.seid = seid;
392 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
393 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
394 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
396 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
397 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
399 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
401 if (service_send(u, &msg.getcaps_req.h) < 0)
404 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
407 ret = parse_caps(u, seid, &msg.getcaps_rsp);
411 return get_caps(u, ret);
414 /* Run from main thread */
415 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
418 case BT_SBC_SAMPLING_FREQ_16000:
419 case BT_SBC_SAMPLING_FREQ_32000:
422 case BT_SBC_SAMPLING_FREQ_44100:
425 case BT_A2DP_CHANNEL_MODE_MONO:
426 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
429 case BT_A2DP_CHANNEL_MODE_STEREO:
430 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
434 pa_log_warn("Invalid channel mode %u", mode);
438 case BT_SBC_SAMPLING_FREQ_48000:
441 case BT_A2DP_CHANNEL_MODE_MONO:
442 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
445 case BT_A2DP_CHANNEL_MODE_STEREO:
446 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
450 pa_log_warn("Invalid channel mode %u", mode);
455 pa_log_warn("Invalid sampling freq %u", freq);
460 /* Run from main thread */
461 static int setup_a2dp(struct userdata *u) {
462 sbc_capabilities_t *cap;
465 static const struct {
469 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
470 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
471 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
472 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
476 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
478 cap = &u->a2dp.sbc_capabilities;
480 /* Find the lowest freq that is at least as high as the requested
482 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
483 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
484 u->sample_spec.rate = freq_table[i].rate;
485 cap->frequency = freq_table[i].cap;
489 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
490 for (--i; i >= 0; i--) {
491 if (cap->frequency & freq_table[i].cap) {
492 u->sample_spec.rate = freq_table[i].rate;
493 cap->frequency = freq_table[i].cap;
499 pa_log("Not suitable sample rate");
504 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
506 if (cap->capability.configured)
509 if (u->sample_spec.channels <= 1) {
510 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
511 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
512 u->sample_spec.channels = 1;
514 u->sample_spec.channels = 2;
517 if (u->sample_spec.channels >= 2) {
518 u->sample_spec.channels = 2;
520 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
521 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
522 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
523 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
524 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
525 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
526 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
527 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
528 u->sample_spec.channels = 1;
530 pa_log("No supported channel modes");
535 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
536 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
537 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
538 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
539 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
540 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
541 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
542 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
544 pa_log_error("No supported block lengths");
548 if (cap->subbands & BT_A2DP_SUBBANDS_8)
549 cap->subbands = BT_A2DP_SUBBANDS_8;
550 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
551 cap->subbands = BT_A2DP_SUBBANDS_4;
553 pa_log_error("No supported subbands");
557 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
558 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
559 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
560 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
562 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
563 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
568 /* Run from main thread */
569 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
570 sbc_capabilities_t *active_capabilities;
574 active_capabilities = &a2dp->sbc_capabilities;
576 if (a2dp->sbc_initialized)
577 sbc_reinit(&a2dp->sbc, 0);
579 sbc_init(&a2dp->sbc, 0);
580 a2dp->sbc_initialized = TRUE;
582 switch (active_capabilities->frequency) {
583 case BT_SBC_SAMPLING_FREQ_16000:
584 a2dp->sbc.frequency = SBC_FREQ_16000;
586 case BT_SBC_SAMPLING_FREQ_32000:
587 a2dp->sbc.frequency = SBC_FREQ_32000;
589 case BT_SBC_SAMPLING_FREQ_44100:
590 a2dp->sbc.frequency = SBC_FREQ_44100;
592 case BT_SBC_SAMPLING_FREQ_48000:
593 a2dp->sbc.frequency = SBC_FREQ_48000;
596 pa_assert_not_reached();
599 switch (active_capabilities->channel_mode) {
600 case BT_A2DP_CHANNEL_MODE_MONO:
601 a2dp->sbc.mode = SBC_MODE_MONO;
603 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
604 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
606 case BT_A2DP_CHANNEL_MODE_STEREO:
607 a2dp->sbc.mode = SBC_MODE_STEREO;
609 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
610 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
613 pa_assert_not_reached();
616 switch (active_capabilities->allocation_method) {
617 case BT_A2DP_ALLOCATION_SNR:
618 a2dp->sbc.allocation = SBC_AM_SNR;
620 case BT_A2DP_ALLOCATION_LOUDNESS:
621 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
624 pa_assert_not_reached();
627 switch (active_capabilities->subbands) {
628 case BT_A2DP_SUBBANDS_4:
629 a2dp->sbc.subbands = SBC_SB_4;
631 case BT_A2DP_SUBBANDS_8:
632 a2dp->sbc.subbands = SBC_SB_8;
635 pa_assert_not_reached();
638 switch (active_capabilities->block_length) {
639 case BT_A2DP_BLOCK_LENGTH_4:
640 a2dp->sbc.blocks = SBC_BLK_4;
642 case BT_A2DP_BLOCK_LENGTH_8:
643 a2dp->sbc.blocks = SBC_BLK_8;
645 case BT_A2DP_BLOCK_LENGTH_12:
646 a2dp->sbc.blocks = SBC_BLK_12;
648 case BT_A2DP_BLOCK_LENGTH_16:
649 a2dp->sbc.blocks = SBC_BLK_16;
652 pa_assert_not_reached();
655 a2dp->min_bitpool = active_capabilities->min_bitpool;
656 a2dp->max_bitpool = active_capabilities->max_bitpool;
658 /* Set minimum bitpool for source to get the maximum possible block_size */
659 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
660 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
661 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
664 /* Run from main thread */
665 static int set_conf(struct userdata *u) {
667 struct bt_open_req open_req;
668 struct bt_open_rsp open_rsp;
669 struct bt_set_configuration_req setconf_req;
670 struct bt_set_configuration_rsp setconf_rsp;
671 bt_audio_error_t error;
672 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
675 memset(&msg, 0, sizeof(msg));
676 msg.open_req.h.type = BT_REQUEST;
677 msg.open_req.h.name = BT_OPEN;
678 msg.open_req.h.length = sizeof(msg.open_req);
680 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
681 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
682 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
684 if (service_send(u, &msg.open_req.h) < 0)
687 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
690 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
691 u->sample_spec.format = PA_SAMPLE_S16LE;
693 if (setup_a2dp(u) < 0)
696 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
698 u->sample_spec.format = PA_SAMPLE_S16LE;
699 u->sample_spec.channels = 1;
700 u->sample_spec.rate = 8000;
703 memset(&msg, 0, sizeof(msg));
704 msg.setconf_req.h.type = BT_REQUEST;
705 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
706 msg.setconf_req.h.length = sizeof(msg.setconf_req);
708 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
709 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
711 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
712 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
713 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
715 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
717 if (service_send(u, &msg.setconf_req.h) < 0)
720 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
723 u->link_mtu = msg.setconf_rsp.link_mtu;
725 /* setup SBC encoder now we agree on parameters */
726 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
727 setup_sbc(&u->a2dp, u->profile);
730 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
731 / u->a2dp.frame_length
734 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
735 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
737 u->block_size = u->link_mtu;
743 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
745 struct a2dp_info *a2dp;
751 if (a2dp->sbc.bitpool == bitpool)
754 if (bitpool > a2dp->max_bitpool)
755 bitpool = a2dp->max_bitpool;
756 else if (bitpool < a2dp->min_bitpool)
757 bitpool = a2dp->min_bitpool;
759 a2dp->sbc.bitpool = bitpool;
761 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
762 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
764 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
767 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
768 / a2dp->frame_length * a2dp->codesize;
770 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
771 pa_sink_set_fixed_latency_within_thread(u->sink,
772 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
775 /* from IO thread, except in SCO over PCM */
777 static int setup_stream(struct userdata *u) {
778 struct pollfd *pollfd;
781 pa_make_fd_nonblock(u->stream_fd);
782 pa_make_socket_low_delay(u->stream_fd);
785 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
786 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
788 pa_log_debug("Stream properly set up, we're ready to roll!");
790 if (u->profile == PROFILE_A2DP)
791 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
793 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
794 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
795 pollfd->fd = u->stream_fd;
796 pollfd->events = pollfd->revents = 0;
798 u->read_index = u->write_index = 0;
802 u->read_smoother = pa_smoother_new(
814 static int start_stream_fd(struct userdata *u) {
816 bt_audio_msg_header_t rsp;
817 struct bt_start_stream_req start_req;
818 struct bt_start_stream_rsp start_rsp;
819 struct bt_new_stream_ind streamfd_ind;
820 bt_audio_error_t error;
821 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
825 pa_assert(u->rtpoll);
826 pa_assert(!u->rtpoll_item);
827 pa_assert(u->stream_fd < 0);
829 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
830 msg.start_req.h.type = BT_REQUEST;
831 msg.start_req.h.name = BT_START_STREAM;
832 msg.start_req.h.length = sizeof(msg.start_req);
834 if (service_send(u, &msg.start_req.h) < 0)
837 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
840 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
843 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
844 pa_log("Failed to get stream fd from audio service.");
848 return setup_stream(u);
852 static int stop_stream_fd(struct userdata *u) {
854 bt_audio_msg_header_t rsp;
855 struct bt_stop_stream_req start_req;
856 struct bt_stop_stream_rsp start_rsp;
857 bt_audio_error_t error;
858 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
863 pa_assert(u->rtpoll);
865 if (u->rtpoll_item) {
866 pa_rtpoll_item_free(u->rtpoll_item);
867 u->rtpoll_item = NULL;
870 if (u->stream_fd >= 0) {
871 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
872 msg.start_req.h.type = BT_REQUEST;
873 msg.start_req.h.name = BT_STOP_STREAM;
874 msg.start_req.h.length = sizeof(msg.start_req);
876 if (service_send(u, &msg.start_req.h) < 0 ||
877 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
880 pa_close(u->stream_fd);
884 if (u->read_smoother) {
885 pa_smoother_free(u->read_smoother);
886 u->read_smoother = NULL;
892 static void bt_transport_release(struct userdata *u) {
893 const char *accesstype = "rw";
894 const pa_bluetooth_transport *t;
896 /* Ignore if already released */
900 pa_log_debug("Releasing transport %s", u->transport);
902 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
904 pa_bluetooth_transport_release(t, accesstype);
906 pa_xfree(u->accesstype);
907 u->accesstype = NULL;
909 if (u->rtpoll_item) {
910 pa_rtpoll_item_free(u->rtpoll_item);
911 u->rtpoll_item = NULL;
914 if (u->stream_fd >= 0) {
915 pa_close(u->stream_fd);
919 if (u->read_smoother) {
920 pa_smoother_free(u->read_smoother);
921 u->read_smoother = NULL;
925 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
926 const char *accesstype = "rw";
927 const pa_bluetooth_transport *t;
935 pa_log_debug("Acquiring transport %s", u->transport);
937 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
939 pa_log("Transport %s no longer available", u->transport);
940 pa_xfree(u->transport);
945 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
946 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
947 if (u->stream_fd < 0)
950 u->accesstype = pa_xstrdup(accesstype);
951 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
957 pa_log_info("Transport %s resuming", u->transport);
958 return setup_stream(u);
961 /* Run from IO thread */
962 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
963 struct userdata *u = PA_SINK(o)->userdata;
964 pa_bool_t failed = FALSE;
967 pa_assert(u->sink == PA_SINK(o));
971 case PA_SINK_MESSAGE_SET_STATE:
973 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
975 case PA_SINK_SUSPENDED:
976 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
978 /* Stop the device if the source is suspended as well */
979 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
980 /* We deliberately ignore whether stopping
981 * actually worked. Since the stream_fd is
982 * closed it doesn't really matter */
984 bt_transport_release(u);
992 case PA_SINK_RUNNING:
993 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
996 /* Resume the device if the source was suspended as well */
997 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
999 if (bt_transport_acquire(u, TRUE) < 0)
1001 } else if (start_stream_fd(u) < 0)
1006 case PA_SINK_UNLINKED:
1008 case PA_SINK_INVALID_STATE:
1013 case PA_SINK_MESSAGE_GET_LATENCY: {
1015 if (u->read_smoother) {
1018 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1019 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1021 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1025 ri = pa_rtclock_now() - u->started_at;
1026 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1028 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1031 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1036 r = pa_sink_process_msg(o, code, data, offset, chunk);
1038 return (r < 0 || !failed) ? r : -1;
1041 /* Run from IO thread */
1042 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1043 struct userdata *u = PA_SOURCE(o)->userdata;
1044 pa_bool_t failed = FALSE;
1047 pa_assert(u->source == PA_SOURCE(o));
1051 case PA_SOURCE_MESSAGE_SET_STATE:
1053 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1055 case PA_SOURCE_SUSPENDED:
1056 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1058 /* Stop the device if the sink is suspended as well */
1059 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1061 bt_transport_release(u);
1066 if (u->read_smoother)
1067 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1070 case PA_SOURCE_IDLE:
1071 case PA_SOURCE_RUNNING:
1072 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1075 /* Resume the device if the sink was suspended as well */
1076 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1078 if (bt_transport_acquire(u, TRUE) < 0)
1080 } else if (start_stream_fd(u) < 0)
1083 /* We don't resume the smoother here. Instead we
1084 * wait until the first packet arrives */
1087 case PA_SOURCE_UNLINKED:
1088 case PA_SOURCE_INIT:
1089 case PA_SOURCE_INVALID_STATE:
1094 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1097 if (u->read_smoother) {
1098 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1099 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1101 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1103 *((pa_usec_t*) data) = 0;
1110 r = pa_source_process_msg(o, code, data, offset, chunk);
1112 return (r < 0 || !failed) ? r : -1;
1115 /* Run from IO thread */
1116 static int hsp_process_render(struct userdata *u) {
1120 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1123 /* First, render some data */
1124 if (!u->write_memchunk.memblock)
1125 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1127 pa_assert(u->write_memchunk.length == u->block_size);
1133 /* Now write that data to the socket. The socket is of type
1134 * SEQPACKET, and we generated the data of the MTU size, so this
1135 * should just work. */
1137 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1138 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1139 pa_memblock_release(u->write_memchunk.memblock);
1146 /* Retry right away if we got interrupted */
1149 else if (errno == EAGAIN)
1150 /* Hmm, apparently the socket was not writable, give up for now */
1153 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1158 pa_assert((size_t) l <= u->write_memchunk.length);
1160 if ((size_t) l != u->write_memchunk.length) {
1161 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1162 (unsigned long long) l,
1163 (unsigned long long) u->write_memchunk.length);
1168 u->write_index += (uint64_t) u->write_memchunk.length;
1169 pa_memblock_unref(u->write_memchunk.memblock);
1170 pa_memchunk_reset(&u->write_memchunk);
1179 /* Run from IO thread */
1180 static int hsp_process_push(struct userdata *u) {
1182 pa_memchunk memchunk;
1185 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1186 pa_assert(u->source);
1187 pa_assert(u->read_smoother);
1189 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1190 memchunk.index = memchunk.length = 0;
1199 pa_bool_t found_tstamp = FALSE;
1202 memset(&m, 0, sizeof(m));
1203 memset(&aux, 0, sizeof(aux));
1204 memset(&iov, 0, sizeof(iov));
1208 m.msg_control = aux;
1209 m.msg_controllen = sizeof(aux);
1211 p = pa_memblock_acquire(memchunk.memblock);
1213 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1214 l = recvmsg(u->stream_fd, &m, 0);
1215 pa_memblock_release(memchunk.memblock);
1219 if (l < 0 && errno == EINTR)
1220 /* Retry right away if we got interrupted */
1223 else if (l < 0 && errno == EAGAIN)
1224 /* Hmm, apparently the socket was not readable, give up for now. */
1227 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1232 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1234 memchunk.length = (size_t) l;
1235 u->read_index += (uint64_t) l;
1237 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1238 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1239 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1240 pa_rtclock_from_wallclock(tv);
1241 tstamp = pa_timeval_load(tv);
1242 found_tstamp = TRUE;
1246 if (!found_tstamp) {
1247 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1248 tstamp = pa_rtclock_now();
1251 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1252 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1254 pa_source_post(u->source, &memchunk);
1260 pa_memblock_unref(memchunk.memblock);
1265 /* Run from IO thread */
1266 static void a2dp_prepare_buffer(struct userdata *u) {
1269 if (u->a2dp.buffer_size >= u->link_mtu)
1272 u->a2dp.buffer_size = 2 * u->link_mtu;
1273 pa_xfree(u->a2dp.buffer);
1274 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1277 /* Run from IO thread */
1278 static int a2dp_process_render(struct userdata *u) {
1279 struct a2dp_info *a2dp;
1280 struct rtp_header *header;
1281 struct rtp_payload *payload;
1285 size_t to_write, to_encode;
1286 unsigned frame_count;
1290 pa_assert(u->profile == PROFILE_A2DP);
1293 /* First, render some data */
1294 if (!u->write_memchunk.memblock)
1295 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1297 pa_assert(u->write_memchunk.length == u->block_size);
1299 a2dp_prepare_buffer(u);
1302 header = a2dp->buffer;
1303 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1307 /* Try to create a packet of the full MTU */
1309 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1310 to_encode = u->write_memchunk.length;
1312 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1313 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1315 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1319 encoded = sbc_encode(&a2dp->sbc,
1324 if (PA_UNLIKELY(encoded <= 0)) {
1325 pa_log_error("SBC encoding error (%li)", (long) encoded);
1326 pa_memblock_release(u->write_memchunk.memblock);
1330 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1331 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1333 pa_assert_fp((size_t) encoded <= to_encode);
1334 pa_assert_fp((size_t) encoded == a2dp->codesize);
1336 pa_assert_fp((size_t) written <= to_write);
1337 pa_assert_fp((size_t) written == a2dp->frame_length);
1339 p = (const uint8_t*) p + encoded;
1340 to_encode -= encoded;
1342 d = (uint8_t*) d + written;
1343 to_write -= written;
1348 pa_memblock_release(u->write_memchunk.memblock);
1350 pa_assert(to_encode == 0);
1353 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1356 /* write it to the fifo */
1357 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1360 header->sequence_number = htons(a2dp->seq_num++);
1361 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1362 header->ssrc = htonl(1);
1363 payload->frame_count = frame_count;
1365 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1370 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1377 /* Retry right away if we got interrupted */
1380 else if (errno == EAGAIN)
1381 /* Hmm, apparently the socket was not writable, give up for now */
1384 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1389 pa_assert((size_t) l <= nbytes);
1391 if ((size_t) l != nbytes) {
1392 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1393 (unsigned long long) l,
1394 (unsigned long long) nbytes);
1399 u->write_index += (uint64_t) u->write_memchunk.length;
1400 pa_memblock_unref(u->write_memchunk.memblock);
1401 pa_memchunk_reset(&u->write_memchunk);
1411 static int a2dp_process_push(struct userdata *u) {
1413 pa_memchunk memchunk;
1416 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1417 pa_assert(u->source);
1418 pa_assert(u->read_smoother);
1420 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1421 memchunk.index = memchunk.length = 0;
1424 pa_bool_t found_tstamp = FALSE;
1426 struct a2dp_info *a2dp;
1427 struct rtp_header *header;
1428 struct rtp_payload *payload;
1432 size_t to_write, to_decode;
1433 unsigned frame_count;
1435 a2dp_prepare_buffer(u);
1438 header = a2dp->buffer;
1439 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1441 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1445 if (l < 0 && errno == EINTR)
1446 /* Retry right away if we got interrupted */
1449 else if (l < 0 && errno == EAGAIN)
1450 /* Hmm, apparently the socket was not readable, give up for now. */
1453 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1458 pa_assert((size_t) l <= a2dp->buffer_size);
1460 u->read_index += (uint64_t) l;
1462 /* TODO: get timestamp from rtp */
1463 if (!found_tstamp) {
1464 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1465 tstamp = pa_rtclock_now();
1468 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1469 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1471 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1472 to_decode = l - sizeof(*header) - sizeof(*payload);
1474 d = pa_memblock_acquire(memchunk.memblock);
1475 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1477 while (PA_LIKELY(to_decode > 0)) {
1481 decoded = sbc_decode(&a2dp->sbc,
1486 if (PA_UNLIKELY(decoded <= 0)) {
1487 pa_log_error("SBC decoding error (%li)", (long) decoded);
1488 pa_memblock_release(memchunk.memblock);
1489 pa_memblock_unref(memchunk.memblock);
1493 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1494 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1496 /* Reset frame length, it can be changed due to bitpool change */
1497 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1499 pa_assert_fp((size_t) decoded <= to_decode);
1500 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1502 pa_assert_fp((size_t) written == a2dp->codesize);
1504 p = (const uint8_t*) p + decoded;
1505 to_decode -= decoded;
1507 d = (uint8_t*) d + written;
1508 to_write -= written;
1513 memchunk.length -= to_write;
1515 pa_memblock_release(memchunk.memblock);
1517 pa_source_post(u->source, &memchunk);
1523 pa_memblock_unref(memchunk.memblock);
1528 static void a2dp_reduce_bitpool(struct userdata *u)
1530 struct a2dp_info *a2dp;
1537 /* Check if bitpool is already at its limit */
1538 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1541 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1543 if (bitpool < BITPOOL_DEC_LIMIT)
1544 bitpool = BITPOOL_DEC_LIMIT;
1546 a2dp_set_bitpool(u, bitpool);
1549 static void thread_func(void *userdata) {
1550 struct userdata *u = userdata;
1551 unsigned do_write = 0;
1552 pa_bool_t writable = FALSE;
1556 pa_log_debug("IO Thread starting up");
1558 if (u->core->realtime_scheduling)
1559 pa_make_realtime(u->core->realtime_priority);
1561 pa_thread_mq_install(&u->thread_mq);
1564 if (bt_transport_acquire(u, TRUE) < 0)
1566 } else if (start_stream_fd(u) < 0)
1570 struct pollfd *pollfd;
1572 pa_bool_t disable_timer = TRUE;
1574 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1576 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1578 /* We should send two blocks to the device before we expect
1581 if (u->write_index == 0 && u->read_index <= 0)
1584 if (pollfd && (pollfd->revents & POLLIN)) {
1587 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1588 n_read = hsp_process_push(u);
1590 n_read = a2dp_process_push(u);
1595 /* We just read something, so we are supposed to write something, too */
1600 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1602 if (u->sink->thread_info.rewind_requested)
1603 pa_sink_process_rewind(u->sink, 0);
1606 if (pollfd->revents & POLLOUT)
1609 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1610 pa_usec_t time_passed;
1611 pa_usec_t audio_sent;
1613 /* Hmm, there is no input stream we could synchronize
1614 * to. So let's do things by time */
1616 time_passed = pa_rtclock_now() - u->started_at;
1617 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1619 if (audio_sent <= time_passed) {
1620 pa_usec_t audio_to_send = time_passed - audio_sent;
1622 /* Never try to catch up for more than 100ms */
1623 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1624 pa_usec_t skip_usec;
1625 uint64_t skip_bytes;
1627 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1628 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1630 if (skip_bytes > 0) {
1633 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1634 (unsigned long long) skip_usec,
1635 (unsigned long long) skip_bytes);
1637 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1638 pa_memblock_unref(tmp.memblock);
1639 u->write_index += skip_bytes;
1641 if (u->profile == PROFILE_A2DP)
1642 a2dp_reduce_bitpool(u);
1650 if (writable && do_write > 0) {
1653 if (u->write_index <= 0)
1654 u->started_at = pa_rtclock_now();
1656 if (u->profile == PROFILE_A2DP) {
1657 if ((n_written = a2dp_process_render(u)) < 0)
1660 if ((n_written = hsp_process_render(u)) < 0)
1665 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1667 do_write -= n_written;
1671 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1672 pa_usec_t time_passed, next_write_at, sleep_for;
1674 /* Hmm, there is no input stream we could synchronize
1675 * to. So let's estimate when we need to wake up the latest */
1677 time_passed = pa_rtclock_now() - u->started_at;
1678 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1679 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1681 /* 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); */
1683 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1684 disable_timer = FALSE;
1690 pa_rtpoll_set_timer_disabled(u->rtpoll);
1692 /* Hmm, nothing to do. Let's sleep */
1694 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1695 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1697 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1703 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1705 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1706 pa_log_info("FD error: %s%s%s%s",
1707 pollfd->revents & POLLERR ? "POLLERR " :"",
1708 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1709 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1710 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1716 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1717 pa_log_debug("IO thread failed");
1718 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1719 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1722 pa_log_debug("IO thread shutting down");
1725 /* Run from main thread */
1726 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1732 pa_assert_se(u = userdata);
1734 dbus_error_init(&err);
1736 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1737 dbus_message_get_interface(m),
1738 dbus_message_get_path(m),
1739 dbus_message_get_member(m));
1741 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1744 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1745 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1750 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1751 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1755 if (u->profile == PROFILE_HSP) {
1756 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1758 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1759 pa_sink_volume_changed(u->sink, &v);
1761 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1763 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1764 pa_source_volume_changed(u->source, &v);
1767 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1768 DBusMessageIter arg_i;
1769 pa_bluetooth_transport *t;
1772 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1775 if (!dbus_message_iter_init(m, &arg_i)) {
1776 pa_log("Failed to parse PropertyChanged: %s", err.message);
1782 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1785 if (nrec != t->nrec) {
1786 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1787 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1792 dbus_error_free(&err);
1794 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1797 /* Run from main thread */
1798 static void sink_set_volume_cb(pa_sink *s) {
1799 struct userdata *u = s->userdata;
1805 if (u->profile != PROFILE_HSP)
1808 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1813 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1815 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1816 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1817 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1818 dbus_message_unref(m);
1821 /* Run from main thread */
1822 static void source_set_volume_cb(pa_source *s) {
1823 struct userdata *u = s->userdata;
1829 if (u->profile != PROFILE_HSP)
1832 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1837 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1839 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1840 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1841 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1842 dbus_message_unref(m);
1845 /* Run from main thread */
1846 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1852 pa_assert(device_id);
1853 pa_assert(namereg_fail);
1855 t = pa_sprintf_malloc("%s_name", type);
1856 n = pa_modargs_get_value(ma, t, NULL);
1860 *namereg_fail = TRUE;
1861 return pa_xstrdup(n);
1864 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1865 *namereg_fail = TRUE;
1868 *namereg_fail = FALSE;
1871 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1874 static void sco_over_pcm_state_update(struct userdata *u) {
1876 pa_assert(USE_SCO_OVER_PCM(u));
1878 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1879 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1881 if (u->service_fd >= 0)
1886 pa_log_debug("Resuming SCO over PCM");
1887 if (init_profile(u) < 0)
1888 pa_log("Can't resume SCO over PCM");
1891 bt_transport_acquire(u, TRUE);
1896 if (u->service_fd < 0)
1900 bt_transport_release(u);
1904 pa_log_debug("Closing SCO over PCM");
1905 pa_close(u->service_fd);
1910 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1912 pa_sink_assert_ref(s);
1915 if (s != u->hsp.sco_sink)
1918 sco_over_pcm_state_update(u);
1923 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1925 pa_source_assert_ref(s);
1928 if (s != u->hsp.sco_source)
1931 sco_over_pcm_state_update(u);
1936 /* Run from main thread */
1937 static int add_sink(struct userdata *u) {
1938 if (USE_SCO_OVER_PCM(u)) {
1941 u->sink = u->hsp.sco_sink;
1942 p = pa_proplist_new();
1943 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1944 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1945 pa_proplist_free(p);
1947 if (!u->hsp.sink_state_changed_slot)
1948 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);
1951 pa_sink_new_data data;
1954 pa_sink_new_data_init(&data);
1955 data.driver = __FILE__;
1956 data.module = u->module;
1957 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1958 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1959 if (u->profile == PROFILE_HSP)
1960 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1961 data.card = u->card;
1962 data.name = get_name("sink", u->modargs, u->address, &b);
1963 data.namereg_fail = b;
1965 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1966 pa_log("Invalid properties");
1967 pa_sink_new_data_done(&data);
1971 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1972 pa_sink_new_data_done(&data);
1975 pa_log_error("Failed to create sink");
1979 u->sink->userdata = u;
1980 u->sink->parent.process_msg = sink_process_msg;
1982 pa_sink_set_max_request(u->sink, u->block_size);
1983 pa_sink_set_fixed_latency(u->sink,
1984 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1985 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1988 if (u->profile == PROFILE_HSP) {
1989 u->sink->set_volume = sink_set_volume_cb;
1990 u->sink->n_volume_steps = 16;
1996 /* Run from main thread */
1997 static int add_source(struct userdata *u) {
1998 if (USE_SCO_OVER_PCM(u)) {
1999 u->source = u->hsp.sco_source;
2000 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2002 if (!u->hsp.source_state_changed_slot)
2003 u->hsp.source_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2006 pa_source_new_data data;
2009 pa_source_new_data_init(&data);
2010 data.driver = __FILE__;
2011 data.module = u->module;
2012 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2013 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2014 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2015 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2017 data.card = u->card;
2018 data.name = get_name("source", u->modargs, u->address, &b);
2019 data.namereg_fail = b;
2021 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2022 pa_log("Invalid properties");
2023 pa_source_new_data_done(&data);
2027 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2028 pa_source_new_data_done(&data);
2031 pa_log_error("Failed to create source");
2035 u->source->userdata = u;
2036 u->source->parent.process_msg = source_process_msg;
2038 pa_source_set_fixed_latency(u->source,
2039 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2040 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2043 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2045 const pa_bluetooth_transport *t;
2046 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2048 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2050 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2053 if (u->profile == PROFILE_HSP) {
2054 u->source->set_volume = source_set_volume_cb;
2055 u->source->n_volume_steps = 16;
2061 /* Run from main thread */
2062 static void shutdown_bt(struct userdata *u) {
2065 if (u->stream_fd >= 0) {
2066 pa_close(u->stream_fd);
2069 u->stream_write_type = 0;
2072 if (u->service_fd >= 0) {
2073 pa_close(u->service_fd);
2075 u->service_write_type = 0;
2076 u->service_read_type = 0;
2079 if (u->write_memchunk.memblock) {
2080 pa_memblock_unref(u->write_memchunk.memblock);
2081 pa_memchunk_reset(&u->write_memchunk);
2085 static int bt_transport_config_a2dp(struct userdata *u) {
2086 const pa_bluetooth_transport *t;
2087 struct a2dp_info *a2dp = &u->a2dp;
2090 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2093 config = (a2dp_sbc_t *) t->config;
2095 if (a2dp->sbc_initialized)
2096 sbc_reinit(&a2dp->sbc, 0);
2098 sbc_init(&a2dp->sbc, 0);
2099 a2dp->sbc_initialized = TRUE;
2101 switch (config->frequency) {
2102 case BT_SBC_SAMPLING_FREQ_16000:
2103 a2dp->sbc.frequency = SBC_FREQ_16000;
2105 case BT_SBC_SAMPLING_FREQ_32000:
2106 a2dp->sbc.frequency = SBC_FREQ_32000;
2108 case BT_SBC_SAMPLING_FREQ_44100:
2109 a2dp->sbc.frequency = SBC_FREQ_44100;
2111 case BT_SBC_SAMPLING_FREQ_48000:
2112 a2dp->sbc.frequency = SBC_FREQ_48000;
2115 pa_assert_not_reached();
2118 switch (config->channel_mode) {
2119 case BT_A2DP_CHANNEL_MODE_MONO:
2120 a2dp->sbc.mode = SBC_MODE_MONO;
2122 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2123 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2125 case BT_A2DP_CHANNEL_MODE_STEREO:
2126 a2dp->sbc.mode = SBC_MODE_STEREO;
2128 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2129 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2132 pa_assert_not_reached();
2135 switch (config->allocation_method) {
2136 case BT_A2DP_ALLOCATION_SNR:
2137 a2dp->sbc.allocation = SBC_AM_SNR;
2139 case BT_A2DP_ALLOCATION_LOUDNESS:
2140 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2143 pa_assert_not_reached();
2146 switch (config->subbands) {
2147 case BT_A2DP_SUBBANDS_4:
2148 a2dp->sbc.subbands = SBC_SB_4;
2150 case BT_A2DP_SUBBANDS_8:
2151 a2dp->sbc.subbands = SBC_SB_8;
2154 pa_assert_not_reached();
2157 switch (config->block_length) {
2158 case BT_A2DP_BLOCK_LENGTH_4:
2159 a2dp->sbc.blocks = SBC_BLK_4;
2161 case BT_A2DP_BLOCK_LENGTH_8:
2162 a2dp->sbc.blocks = SBC_BLK_8;
2164 case BT_A2DP_BLOCK_LENGTH_12:
2165 a2dp->sbc.blocks = SBC_BLK_12;
2167 case BT_A2DP_BLOCK_LENGTH_16:
2168 a2dp->sbc.blocks = SBC_BLK_16;
2171 pa_assert_not_reached();
2174 a2dp->min_bitpool = config->min_bitpool;
2175 a2dp->max_bitpool = config->max_bitpool;
2177 /* Set minimum bitpool for source to get the maximum possible block_size */
2178 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2179 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2180 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2183 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2184 / a2dp->frame_length
2187 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2188 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2193 static int bt_transport_config(struct userdata *u) {
2194 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2195 u->block_size = u->link_mtu;
2199 return bt_transport_config_a2dp(u);
2202 /* Run from main thread */
2203 static int bt_transport_open(struct userdata *u) {
2204 if (bt_transport_acquire(u, FALSE) < 0)
2207 return bt_transport_config(u);
2210 /* Run from main thread */
2211 static int init_bt(struct userdata *u) {
2216 u->stream_write_type = 0;
2217 u->service_write_type = 0;
2218 u->service_read_type = 0;
2220 if ((u->service_fd = bt_audio_service_open()) < 0) {
2221 pa_log_warn("Bluetooth audio service not available");
2225 pa_log_debug("Connected to the bluetooth audio service");
2230 /* Run from main thread */
2231 static int setup_bt(struct userdata *u) {
2232 const pa_bluetooth_device *d;
2233 const pa_bluetooth_transport *t;
2237 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2238 pa_log_error("Failed to get device object.");
2242 /* release transport if exist */
2244 bt_transport_release(u);
2245 pa_xfree(u->transport);
2246 u->transport = NULL;
2249 /* check if profile has a transport */
2250 t = pa_bluetooth_device_get_transport(d, u->profile);
2252 u->transport = pa_xstrdup(t->path);
2253 return bt_transport_open(u);
2256 if (get_caps(u, 0) < 0)
2259 pa_log_debug("Got device capabilities");
2261 if (set_conf(u) < 0)
2264 pa_log_debug("Connection to the device configured");
2266 if (USE_SCO_OVER_PCM(u)) {
2267 pa_log_debug("Configured to use SCO over PCM");
2271 pa_log_debug("Got the stream socket");
2276 /* Run from main thread */
2277 static int init_profile(struct userdata *u) {
2280 pa_assert(u->profile != PROFILE_OFF);
2282 if (setup_bt(u) < 0)
2285 if (u->profile == PROFILE_A2DP ||
2286 u->profile == PROFILE_HSP ||
2287 u->profile == PROFILE_HFGW)
2288 if (add_sink(u) < 0)
2291 if (u->profile == PROFILE_HSP ||
2292 u->profile == PROFILE_A2DP_SOURCE ||
2293 u->profile == PROFILE_HFGW)
2294 if (add_source(u) < 0)
2300 /* Run from main thread */
2301 static void stop_thread(struct userdata *u) {
2305 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2306 pa_thread_free(u->thread);
2310 if (u->rtpoll_item) {
2311 pa_rtpoll_item_free(u->rtpoll_item);
2312 u->rtpoll_item = NULL;
2315 if (u->hsp.sink_state_changed_slot) {
2316 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2317 u->hsp.sink_state_changed_slot = NULL;
2320 if (u->hsp.source_state_changed_slot) {
2321 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2322 u->hsp.source_state_changed_slot = NULL;
2326 pa_sink_unref(u->sink);
2331 pa_source_unref(u->source);
2336 pa_thread_mq_done(&u->thread_mq);
2338 pa_rtpoll_free(u->rtpoll);
2342 if (u->read_smoother) {
2343 pa_smoother_free(u->read_smoother);
2344 u->read_smoother = NULL;
2348 /* Run from main thread */
2349 static int start_thread(struct userdata *u) {
2351 pa_assert(!u->thread);
2352 pa_assert(!u->rtpoll);
2353 pa_assert(!u->rtpoll_item);
2355 u->rtpoll = pa_rtpoll_new();
2356 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2358 if (USE_SCO_OVER_PCM(u)) {
2360 if (bt_transport_acquire(u, TRUE) < 0)
2362 } else if (start_stream_fd(u) < 0)
2365 pa_sink_ref(u->sink);
2366 pa_source_ref(u->source);
2367 /* FIXME: monitor stream_fd error */
2371 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2372 pa_log_error("Failed to create IO thread");
2378 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2379 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2380 pa_sink_put(u->sink);
2382 if (u->sink->set_volume)
2383 u->sink->set_volume(u->sink);
2387 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2388 pa_source_set_rtpoll(u->source, u->rtpoll);
2389 pa_source_put(u->source);
2391 if (u->source->set_volume)
2392 u->source->set_volume(u->source);
2398 /* Run from main thread */
2399 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2402 pa_queue *inputs = NULL, *outputs = NULL;
2403 const pa_bluetooth_device *device;
2406 pa_assert(new_profile);
2407 pa_assert_se(u = c->userdata);
2409 d = PA_CARD_PROFILE_DATA(new_profile);
2411 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2412 pa_log_error("Failed to get device object.");
2416 /* The state signal is sent by bluez, so it is racy to check
2417 strictly for CONNECTED, we should also accept STREAMING state
2418 as being good enough. However, if the profile is used
2419 concurrently (which is unlikely), ipc will fail later on, and
2420 module will be unloaded. */
2421 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2422 pa_log_warn("HSP is not connected, refused to switch profile");
2425 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2426 pa_log_warn("A2DP is not connected, refused to switch profile");
2429 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2430 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2435 inputs = pa_sink_move_all_start(u->sink, NULL);
2437 if (!USE_SCO_OVER_PCM(u))
2438 pa_sink_unlink(u->sink);
2442 outputs = pa_source_move_all_start(u->source, NULL);
2444 if (!USE_SCO_OVER_PCM(u))
2445 pa_source_unlink(u->source);
2452 u->sample_spec = u->requested_sample_spec;
2456 if (u->profile != PROFILE_OFF)
2459 if (u->sink || u->source)
2464 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2466 pa_sink_move_all_fail(inputs);
2471 pa_source_move_all_finish(u->source, outputs, FALSE);
2473 pa_source_move_all_fail(outputs);
2479 /* Run from main thread */
2480 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2481 pa_card_new_data data;
2487 const char *default_profile;
2492 pa_card_new_data_init(&data);
2493 data.driver = __FILE__;
2494 data.module = u->module;
2496 n = pa_bluetooth_cleanup_name(device->name);
2497 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2499 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2500 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2501 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2502 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2503 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2504 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2505 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2506 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2507 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2508 data.name = get_name("card", u->modargs, device->address, &b);
2509 data.namereg_fail = b;
2511 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2512 pa_log("Invalid properties");
2513 pa_card_new_data_done(&data);
2517 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2519 /* we base hsp/a2dp availability on UUIDs.
2520 Ideally, it would be based on "Connected" state, but
2521 we can't afford to wait for this information when
2522 we are loaded with profile="hsp", for instance */
2523 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2524 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2528 p->max_sink_channels = 2;
2529 p->max_source_channels = 0;
2531 d = PA_CARD_PROFILE_DATA(p);
2534 pa_hashmap_put(data.profiles, p->name, p);
2537 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2538 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2542 p->max_sink_channels = 0;
2543 p->max_source_channels = 2;
2545 d = PA_CARD_PROFILE_DATA(p);
2546 *d = PROFILE_A2DP_SOURCE;
2548 pa_hashmap_put(data.profiles, p->name, p);
2551 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2552 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2553 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2557 p->max_sink_channels = 1;
2558 p->max_source_channels = 1;
2560 d = PA_CARD_PROFILE_DATA(p);
2563 pa_hashmap_put(data.profiles, p->name, p);
2566 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2567 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2571 p->max_sink_channels = 1;
2572 p->max_source_channels = 1;
2574 d = PA_CARD_PROFILE_DATA(p);
2577 pa_hashmap_put(data.profiles, p->name, p);
2580 pa_assert(!pa_hashmap_isempty(data.profiles));
2582 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2583 d = PA_CARD_PROFILE_DATA(p);
2585 pa_hashmap_put(data.profiles, p->name, p);
2587 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2588 if (pa_hashmap_get(data.profiles, default_profile))
2589 pa_card_new_data_set_profile(&data, default_profile);
2591 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2594 u->card = pa_card_new(u->core, &data);
2595 pa_card_new_data_done(&data);
2598 pa_log("Failed to allocate card.");
2602 u->card->userdata = u;
2603 u->card->set_profile = card_set_profile;
2605 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2607 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2608 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2609 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2610 pa_log_warn("Default profile not connected, selecting off profile");
2611 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2612 u->card->save_profile = FALSE;
2615 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2621 /* Run from main thread */
2622 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2623 const pa_bluetooth_device *d = NULL;
2627 if (!address && !path) {
2628 pa_log_error("Failed to get device address/path from module arguments.");
2633 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2634 pa_log_error("%s is not a valid BlueZ audio device.", path);
2638 if (address && !(pa_streq(d->address, address))) {
2639 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2644 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2645 pa_log_error("%s is not known.", address);
2651 u->address = pa_xstrdup(d->address);
2652 u->path = pa_xstrdup(d->path);
2658 /* Run from main thread */
2659 static int setup_dbus(struct userdata *u) {
2662 dbus_error_init(&err);
2664 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2666 if (dbus_error_is_set(&err) || !u->connection) {
2667 pa_log("Failed to get D-Bus connection: %s", err.message);
2668 dbus_error_free(&err);
2675 int pa__init(pa_module* m) {
2679 const char *address, *path;
2681 char *mike, *speaker, *transport;
2682 const pa_bluetooth_device *device;
2686 dbus_error_init(&err);
2688 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2689 pa_log_error("Failed to parse module arguments");
2693 m->userdata = u = pa_xnew0(struct userdata, 1);
2698 u->sample_spec = m->core->default_sample_spec;
2701 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2702 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2703 pa_log("SCO sink not found");
2707 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2708 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2709 pa_log("SCO source not found");
2713 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2714 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2715 pa_log_error("Failed to get rate from module arguments");
2719 u->auto_connect = TRUE;
2720 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2721 pa_log("Failed to parse auto_connect= argument");
2725 channels = u->sample_spec.channels;
2726 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2727 channels <= 0 || channels > PA_CHANNELS_MAX) {
2728 pa_log_error("Failed to get channels from module arguments");
2731 u->sample_spec.channels = (uint8_t) channels;
2732 u->requested_sample_spec = u->sample_spec;
2734 address = pa_modargs_get_value(ma, "address", NULL);
2735 path = pa_modargs_get_value(ma, "path", NULL);
2737 if (setup_dbus(u) < 0)
2740 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2743 if (!(device = find_device(u, address, path)))
2746 /* Add the card structure. This will also initialize the default profile */
2747 if (add_card(u, device) < 0)
2750 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2751 pa_log_error("Failed to add filter function");
2754 u->filter_added = TRUE;
2756 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2757 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2758 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2760 if (pa_dbus_add_matches(
2761 pa_dbus_connection_get(u->connection), &err,
2769 pa_xfree(transport);
2771 pa_log("Failed to add D-Bus matches: %s", err.message);
2777 pa_xfree(transport);
2779 /* Connect to the BT service */
2782 if (u->profile != PROFILE_OFF)
2783 if (init_profile(u) < 0)
2786 if (u->sink || u->source)
2787 if (start_thread(u) < 0)
2796 dbus_error_free(&err);
2801 int pa__get_n_used(pa_module *m) {
2805 pa_assert_se(u = m->userdata);
2808 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2809 (u->source ? pa_source_linked_by(u->source) : 0);
2812 void pa__done(pa_module *m) {
2816 if (!(u = m->userdata))
2819 if (u->sink && !USE_SCO_OVER_PCM(u))
2820 pa_sink_unlink(u->sink);
2822 if (u->source && !USE_SCO_OVER_PCM(u))
2823 pa_source_unlink(u->source);
2827 if (u->connection) {
2830 char *speaker, *mike;
2831 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2832 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2834 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2840 if (u->filter_added)
2841 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2843 pa_dbus_connection_unref(u->connection);
2847 pa_card_free(u->card);
2849 if (u->read_smoother)
2850 pa_smoother_free(u->read_smoother);
2855 pa_xfree(u->a2dp.buffer);
2857 sbc_finish(&u->a2dp.sbc);
2860 pa_modargs_free(u->modargs);
2862 pa_xfree(u->address);
2866 bt_transport_release(u);
2867 pa_xfree(u->transport);
2871 pa_bluetooth_discovery_unref(u->discovery);