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?>");
83 "sco_sink=<SCO over PCM sink name> "
84 "sco_source=<SCO over PCM source name>"
88 /* TODO: not close fd when entering suspend mode in a2dp */
90 static const char* const valid_modargs[] = {
112 sbc_capabilities_t sbc_capabilities;
113 sbc_t sbc; /* Codec data */
114 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
115 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
117 void* buffer; /* Codec transfer buffer */
118 size_t buffer_size; /* Size of the buffer */
120 uint16_t seq_num; /* Cumulative packet sequence */
126 pcm_capabilities_t pcm_capabilities;
129 pa_source *sco_source;
131 pa_hook_slot *sink_state_changed_slot;
132 pa_hook_slot *source_state_changed_slot;
144 pa_bluetooth_discovery *discovery;
145 pa_bool_t auto_connect;
147 pa_dbus_connection *connection;
153 pa_thread_mq thread_mq;
155 pa_rtpoll_item *rtpoll_item;
158 uint64_t read_index, write_index;
159 pa_usec_t started_at;
160 pa_smoother *read_smoother;
162 pa_memchunk write_memchunk;
164 pa_sample_spec sample_spec, requested_sample_spec;
172 struct a2dp_info a2dp;
175 enum profile profile;
179 int stream_write_type;
180 int service_write_type, service_read_type;
182 pa_bool_t filter_added;
185 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
186 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
187 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
188 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
190 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
193 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
196 static int init_bt(struct userdata *u);
197 static int init_profile(struct userdata *u);
199 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
204 pa_assert(msg->length > 0);
206 if (u->service_fd < 0) {
207 pa_log_warn("Service not connected");
211 pa_log_debug("Sending %s -> %s",
212 pa_strnull(bt_audio_strtype(msg->type)),
213 pa_strnull(bt_audio_strname(msg->name)));
215 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
219 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
221 pa_log_error("Short write()");
226 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
230 pa_assert(u->service_fd >= 0);
232 pa_assert(room >= sizeof(*msg));
234 pa_log_debug("Trying to receive message from audio service...");
236 /* First, read the header */
237 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
240 if (msg->length < sizeof(*msg)) {
241 pa_log_error("Invalid message size.");
245 if (msg->length > room) {
246 pa_log_error("Not enough room.");
250 /* Secondly, read the payload */
251 if (msg->length > sizeof(*msg)) {
253 size_t remains = msg->length - sizeof(*msg);
255 if ((r = pa_loop_read(u->service_fd,
256 (uint8_t*) msg + sizeof(*msg),
258 &u->service_read_type)) != (ssize_t) remains)
262 pa_log_debug("Received %s <- %s",
263 pa_strnull(bt_audio_strtype(msg->type)),
264 pa_strnull(bt_audio_strname(msg->name)));
271 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
273 pa_log_error("Short read()");
278 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) {
282 pa_assert(u->service_fd >= 0);
285 if ((r = service_recv(u, rsp, room)) < 0)
288 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
289 rsp->name != expected_name ||
290 (expected_size > 0 && rsp->length != expected_size)) {
292 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
293 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
295 pa_log_error("Bogus message %s received while %s was expected",
296 pa_strnull(bt_audio_strname(rsp->name)),
297 pa_strnull(bt_audio_strname(expected_name)));
304 /* Run from main thread */
305 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
307 const codec_capabilities_t *codec;
312 bytes_left = rsp->h.length - sizeof(*rsp);
314 if (bytes_left < sizeof(codec_capabilities_t)) {
315 pa_log_error("Packet too small to store codec information.");
319 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
321 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
323 if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
324 ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
325 pa_log_error("Got capabilities for wrong codec.");
329 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
331 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
334 pa_assert(codec->type == BT_HFP_CODEC_PCM);
336 if (codec->configured && seid == 0)
339 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
341 } else if (u->profile == PROFILE_A2DP) {
343 while (bytes_left > 0) {
344 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
347 bytes_left -= codec->length;
348 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
351 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
354 pa_assert(codec->type == BT_A2DP_SBC_SINK);
356 if (codec->configured && seid == 0)
359 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
361 } else if (u->profile == PROFILE_A2DP_SOURCE) {
363 while (bytes_left > 0) {
364 if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
367 bytes_left -= codec->length;
368 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
371 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
374 pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
376 if (codec->configured && seid == 0)
379 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
385 /* Run from main thread */
386 static int get_caps(struct userdata *u, uint8_t seid) {
388 struct bt_get_capabilities_req getcaps_req;
389 struct bt_get_capabilities_rsp getcaps_rsp;
390 bt_audio_error_t error;
391 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
397 memset(&msg, 0, sizeof(msg));
398 msg.getcaps_req.h.type = BT_REQUEST;
399 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
400 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
401 msg.getcaps_req.seid = seid;
403 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
404 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
405 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
407 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
408 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
410 msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
412 if (service_send(u, &msg.getcaps_req.h) < 0)
415 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
418 ret = parse_caps(u, seid, &msg.getcaps_rsp);
422 return get_caps(u, ret);
425 /* Run from main thread */
426 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
429 case BT_SBC_SAMPLING_FREQ_16000:
430 case BT_SBC_SAMPLING_FREQ_32000:
433 case BT_SBC_SAMPLING_FREQ_44100:
436 case BT_A2DP_CHANNEL_MODE_MONO:
437 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
440 case BT_A2DP_CHANNEL_MODE_STEREO:
441 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
445 pa_log_warn("Invalid channel mode %u", mode);
449 case BT_SBC_SAMPLING_FREQ_48000:
452 case BT_A2DP_CHANNEL_MODE_MONO:
453 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
456 case BT_A2DP_CHANNEL_MODE_STEREO:
457 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
461 pa_log_warn("Invalid channel mode %u", mode);
466 pa_log_warn("Invalid sampling freq %u", freq);
471 /* Run from main thread */
472 static int setup_a2dp(struct userdata *u) {
473 sbc_capabilities_t *cap;
476 static const struct {
480 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
481 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
482 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
483 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
487 pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
489 cap = &u->a2dp.sbc_capabilities;
491 /* Find the lowest freq that is at least as high as the requested
493 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
494 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
495 u->sample_spec.rate = freq_table[i].rate;
496 cap->frequency = freq_table[i].cap;
500 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
501 for (--i; i >= 0; i--) {
502 if (cap->frequency & freq_table[i].cap) {
503 u->sample_spec.rate = freq_table[i].rate;
504 cap->frequency = freq_table[i].cap;
510 pa_log("Not suitable sample rate");
515 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
517 if (cap->capability.configured)
520 if (u->sample_spec.channels <= 1) {
521 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
522 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
523 u->sample_spec.channels = 1;
525 u->sample_spec.channels = 2;
528 if (u->sample_spec.channels >= 2) {
529 u->sample_spec.channels = 2;
531 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
532 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
533 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
534 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
535 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
536 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
537 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
538 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
539 u->sample_spec.channels = 1;
541 pa_log("No supported channel modes");
546 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
547 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
548 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
549 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
550 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
551 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
552 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
553 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
555 pa_log_error("No supported block lengths");
559 if (cap->subbands & BT_A2DP_SUBBANDS_8)
560 cap->subbands = BT_A2DP_SUBBANDS_8;
561 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
562 cap->subbands = BT_A2DP_SUBBANDS_4;
564 pa_log_error("No supported subbands");
568 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
569 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
570 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
571 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
573 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
574 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
579 /* Run from main thread */
580 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
581 sbc_capabilities_t *active_capabilities;
585 active_capabilities = &a2dp->sbc_capabilities;
587 if (a2dp->sbc_initialized)
588 sbc_reinit(&a2dp->sbc, 0);
590 sbc_init(&a2dp->sbc, 0);
591 a2dp->sbc_initialized = TRUE;
593 switch (active_capabilities->frequency) {
594 case BT_SBC_SAMPLING_FREQ_16000:
595 a2dp->sbc.frequency = SBC_FREQ_16000;
597 case BT_SBC_SAMPLING_FREQ_32000:
598 a2dp->sbc.frequency = SBC_FREQ_32000;
600 case BT_SBC_SAMPLING_FREQ_44100:
601 a2dp->sbc.frequency = SBC_FREQ_44100;
603 case BT_SBC_SAMPLING_FREQ_48000:
604 a2dp->sbc.frequency = SBC_FREQ_48000;
607 pa_assert_not_reached();
610 switch (active_capabilities->channel_mode) {
611 case BT_A2DP_CHANNEL_MODE_MONO:
612 a2dp->sbc.mode = SBC_MODE_MONO;
614 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
615 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
617 case BT_A2DP_CHANNEL_MODE_STEREO:
618 a2dp->sbc.mode = SBC_MODE_STEREO;
620 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
621 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
624 pa_assert_not_reached();
627 switch (active_capabilities->allocation_method) {
628 case BT_A2DP_ALLOCATION_SNR:
629 a2dp->sbc.allocation = SBC_AM_SNR;
631 case BT_A2DP_ALLOCATION_LOUDNESS:
632 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
635 pa_assert_not_reached();
638 switch (active_capabilities->subbands) {
639 case BT_A2DP_SUBBANDS_4:
640 a2dp->sbc.subbands = SBC_SB_4;
642 case BT_A2DP_SUBBANDS_8:
643 a2dp->sbc.subbands = SBC_SB_8;
646 pa_assert_not_reached();
649 switch (active_capabilities->block_length) {
650 case BT_A2DP_BLOCK_LENGTH_4:
651 a2dp->sbc.blocks = SBC_BLK_4;
653 case BT_A2DP_BLOCK_LENGTH_8:
654 a2dp->sbc.blocks = SBC_BLK_8;
656 case BT_A2DP_BLOCK_LENGTH_12:
657 a2dp->sbc.blocks = SBC_BLK_12;
659 case BT_A2DP_BLOCK_LENGTH_16:
660 a2dp->sbc.blocks = SBC_BLK_16;
663 pa_assert_not_reached();
666 a2dp->min_bitpool = active_capabilities->min_bitpool;
667 a2dp->max_bitpool = active_capabilities->max_bitpool;
669 /* Set minimum bitpool for source to get the maximum possible block_size */
670 a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
671 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
672 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
675 /* Run from main thread */
676 static int set_conf(struct userdata *u) {
678 struct bt_open_req open_req;
679 struct bt_open_rsp open_rsp;
680 struct bt_set_configuration_req setconf_req;
681 struct bt_set_configuration_rsp setconf_rsp;
682 bt_audio_error_t error;
683 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
686 memset(&msg, 0, sizeof(msg));
687 msg.open_req.h.type = BT_REQUEST;
688 msg.open_req.h.name = BT_OPEN;
689 msg.open_req.h.length = sizeof(msg.open_req);
691 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
692 msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
693 msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
695 if (service_send(u, &msg.open_req.h) < 0)
698 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
701 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
702 u->sample_spec.format = PA_SAMPLE_S16LE;
704 if (setup_a2dp(u) < 0)
707 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
709 u->sample_spec.format = PA_SAMPLE_S16LE;
710 u->sample_spec.channels = 1;
711 u->sample_spec.rate = 8000;
714 memset(&msg, 0, sizeof(msg));
715 msg.setconf_req.h.type = BT_REQUEST;
716 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
717 msg.setconf_req.h.length = sizeof(msg.setconf_req);
719 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
720 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
722 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
723 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
724 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
726 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
728 if (service_send(u, &msg.setconf_req.h) < 0)
731 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
734 u->link_mtu = msg.setconf_rsp.link_mtu;
736 /* setup SBC encoder now we agree on parameters */
737 if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
738 setup_sbc(&u->a2dp, u->profile);
741 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
742 / u->a2dp.frame_length
745 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
746 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
748 u->block_size = u->link_mtu;
754 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
756 struct a2dp_info *a2dp;
762 if (a2dp->sbc.bitpool == bitpool)
765 if (bitpool > a2dp->max_bitpool)
766 bitpool = a2dp->max_bitpool;
767 else if (bitpool < a2dp->min_bitpool)
768 bitpool = a2dp->min_bitpool;
770 a2dp->sbc.bitpool = bitpool;
772 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
773 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
775 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
778 (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
779 / a2dp->frame_length * a2dp->codesize;
781 pa_sink_set_max_request_within_thread(u->sink, u->block_size);
782 pa_sink_set_fixed_latency_within_thread(u->sink,
783 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
786 /* from IO thread, except in SCO over PCM */
788 static int setup_stream(struct userdata *u) {
789 struct pollfd *pollfd;
792 pa_make_fd_nonblock(u->stream_fd);
793 pa_make_socket_low_delay(u->stream_fd);
796 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
797 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
799 pa_log_debug("Stream properly set up, we're ready to roll!");
801 if (u->profile == PROFILE_A2DP)
802 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
804 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
805 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
806 pollfd->fd = u->stream_fd;
807 pollfd->events = pollfd->revents = 0;
809 u->read_index = u->write_index = 0;
813 u->read_smoother = pa_smoother_new(
825 static int start_stream_fd(struct userdata *u) {
827 bt_audio_msg_header_t rsp;
828 struct bt_start_stream_req start_req;
829 struct bt_start_stream_rsp start_rsp;
830 struct bt_new_stream_ind streamfd_ind;
831 bt_audio_error_t error;
832 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
836 pa_assert(u->rtpoll);
837 pa_assert(!u->rtpoll_item);
838 pa_assert(u->stream_fd < 0);
840 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
841 msg.start_req.h.type = BT_REQUEST;
842 msg.start_req.h.name = BT_START_STREAM;
843 msg.start_req.h.length = sizeof(msg.start_req);
845 if (service_send(u, &msg.start_req.h) < 0)
848 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
851 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
854 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
855 pa_log("Failed to get stream fd from audio service.");
859 return setup_stream(u);
863 static int stop_stream_fd(struct userdata *u) {
865 bt_audio_msg_header_t rsp;
866 struct bt_stop_stream_req start_req;
867 struct bt_stop_stream_rsp start_rsp;
868 bt_audio_error_t error;
869 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
874 pa_assert(u->rtpoll);
876 if (u->rtpoll_item) {
877 pa_rtpoll_item_free(u->rtpoll_item);
878 u->rtpoll_item = NULL;
881 if (u->stream_fd >= 0) {
882 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
883 msg.start_req.h.type = BT_REQUEST;
884 msg.start_req.h.name = BT_STOP_STREAM;
885 msg.start_req.h.length = sizeof(msg.start_req);
887 if (service_send(u, &msg.start_req.h) < 0 ||
888 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
891 pa_close(u->stream_fd);
895 if (u->read_smoother) {
896 pa_smoother_free(u->read_smoother);
897 u->read_smoother = NULL;
903 static void bt_transport_release(struct userdata *u) {
904 const char *accesstype = "rw";
905 const pa_bluetooth_transport *t;
907 /* Ignore if already released */
911 pa_log_debug("Releasing transport %s", u->transport);
913 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
915 pa_bluetooth_transport_release(t, accesstype);
917 pa_xfree(u->accesstype);
918 u->accesstype = NULL;
920 if (u->rtpoll_item) {
921 pa_rtpoll_item_free(u->rtpoll_item);
922 u->rtpoll_item = NULL;
925 if (u->stream_fd >= 0) {
926 pa_close(u->stream_fd);
930 if (u->read_smoother) {
931 pa_smoother_free(u->read_smoother);
932 u->read_smoother = NULL;
936 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
937 const char *accesstype = "rw";
938 const pa_bluetooth_transport *t;
946 pa_log_debug("Acquiring transport %s", u->transport);
948 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
950 pa_log("Transport %s no longer available", u->transport);
951 pa_xfree(u->transport);
956 /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
957 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
958 if (u->stream_fd < 0)
961 u->accesstype = pa_xstrdup(accesstype);
962 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
968 pa_log_info("Transport %s resuming", u->transport);
969 return setup_stream(u);
972 /* Run from IO thread */
973 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
974 struct userdata *u = PA_SINK(o)->userdata;
975 pa_bool_t failed = FALSE;
978 pa_assert(u->sink == PA_SINK(o));
982 case PA_SINK_MESSAGE_SET_STATE:
984 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
986 case PA_SINK_SUSPENDED:
987 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
989 /* Stop the device if the source is suspended as well */
990 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
991 /* We deliberately ignore whether stopping
992 * actually worked. Since the stream_fd is
993 * closed it doesn't really matter */
995 bt_transport_release(u);
1003 case PA_SINK_RUNNING:
1004 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1007 /* Resume the device if the source was suspended as well */
1008 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1010 if (bt_transport_acquire(u, TRUE) < 0)
1012 } else if (start_stream_fd(u) < 0)
1017 case PA_SINK_UNLINKED:
1019 case PA_SINK_INVALID_STATE:
1024 case PA_SINK_MESSAGE_GET_LATENCY: {
1026 if (u->read_smoother) {
1029 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1030 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1032 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1036 ri = pa_rtclock_now() - u->started_at;
1037 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1039 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1042 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1047 r = pa_sink_process_msg(o, code, data, offset, chunk);
1049 return (r < 0 || !failed) ? r : -1;
1052 /* Run from IO thread */
1053 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1054 struct userdata *u = PA_SOURCE(o)->userdata;
1055 pa_bool_t failed = FALSE;
1058 pa_assert(u->source == PA_SOURCE(o));
1062 case PA_SOURCE_MESSAGE_SET_STATE:
1064 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1066 case PA_SOURCE_SUSPENDED:
1067 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1069 /* Stop the device if the sink is suspended as well */
1070 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1072 bt_transport_release(u);
1077 if (u->read_smoother)
1078 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1081 case PA_SOURCE_IDLE:
1082 case PA_SOURCE_RUNNING:
1083 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1086 /* Resume the device if the sink was suspended as well */
1087 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1089 if (bt_transport_acquire(u, TRUE) < 0)
1091 } else if (start_stream_fd(u) < 0)
1094 /* We don't resume the smoother here. Instead we
1095 * wait until the first packet arrives */
1098 case PA_SOURCE_UNLINKED:
1099 case PA_SOURCE_INIT:
1100 case PA_SOURCE_INVALID_STATE:
1105 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1108 if (u->read_smoother) {
1109 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1110 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1112 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1114 *((pa_usec_t*) data) = 0;
1121 r = pa_source_process_msg(o, code, data, offset, chunk);
1123 return (r < 0 || !failed) ? r : -1;
1126 /* Run from IO thread */
1127 static int hsp_process_render(struct userdata *u) {
1131 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1134 /* First, render some data */
1135 if (!u->write_memchunk.memblock)
1136 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1138 pa_assert(u->write_memchunk.length == u->block_size);
1144 /* Now write that data to the socket. The socket is of type
1145 * SEQPACKET, and we generated the data of the MTU size, so this
1146 * should just work. */
1148 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1149 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1150 pa_memblock_release(u->write_memchunk.memblock);
1157 /* Retry right away if we got interrupted */
1160 else if (errno == EAGAIN)
1161 /* Hmm, apparently the socket was not writable, give up for now */
1164 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1169 pa_assert((size_t) l <= u->write_memchunk.length);
1171 if ((size_t) l != u->write_memchunk.length) {
1172 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1173 (unsigned long long) l,
1174 (unsigned long long) u->write_memchunk.length);
1179 u->write_index += (uint64_t) u->write_memchunk.length;
1180 pa_memblock_unref(u->write_memchunk.memblock);
1181 pa_memchunk_reset(&u->write_memchunk);
1190 /* Run from IO thread */
1191 static int hsp_process_push(struct userdata *u) {
1193 pa_memchunk memchunk;
1196 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1197 pa_assert(u->source);
1198 pa_assert(u->read_smoother);
1200 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1201 memchunk.index = memchunk.length = 0;
1210 pa_bool_t found_tstamp = FALSE;
1213 memset(&m, 0, sizeof(m));
1214 memset(&aux, 0, sizeof(aux));
1215 memset(&iov, 0, sizeof(iov));
1219 m.msg_control = aux;
1220 m.msg_controllen = sizeof(aux);
1222 p = pa_memblock_acquire(memchunk.memblock);
1224 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1225 l = recvmsg(u->stream_fd, &m, 0);
1226 pa_memblock_release(memchunk.memblock);
1230 if (l < 0 && errno == EINTR)
1231 /* Retry right away if we got interrupted */
1234 else if (l < 0 && errno == EAGAIN)
1235 /* Hmm, apparently the socket was not readable, give up for now. */
1238 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1243 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1245 memchunk.length = (size_t) l;
1246 u->read_index += (uint64_t) l;
1248 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1249 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1250 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1251 pa_rtclock_from_wallclock(tv);
1252 tstamp = pa_timeval_load(tv);
1253 found_tstamp = TRUE;
1257 if (!found_tstamp) {
1258 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1259 tstamp = pa_rtclock_now();
1262 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1263 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1265 pa_source_post(u->source, &memchunk);
1271 pa_memblock_unref(memchunk.memblock);
1276 /* Run from IO thread */
1277 static void a2dp_prepare_buffer(struct userdata *u) {
1280 if (u->a2dp.buffer_size >= u->link_mtu)
1283 u->a2dp.buffer_size = 2 * u->link_mtu;
1284 pa_xfree(u->a2dp.buffer);
1285 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1288 /* Run from IO thread */
1289 static int a2dp_process_render(struct userdata *u) {
1290 struct a2dp_info *a2dp;
1291 struct rtp_header *header;
1292 struct rtp_payload *payload;
1296 size_t to_write, to_encode;
1297 unsigned frame_count;
1301 pa_assert(u->profile == PROFILE_A2DP);
1304 /* First, render some data */
1305 if (!u->write_memchunk.memblock)
1306 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1308 pa_assert(u->write_memchunk.length == u->block_size);
1310 a2dp_prepare_buffer(u);
1313 header = a2dp->buffer;
1314 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1318 /* Try to create a packet of the full MTU */
1320 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1321 to_encode = u->write_memchunk.length;
1323 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1324 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1326 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1330 encoded = sbc_encode(&a2dp->sbc,
1335 if (PA_UNLIKELY(encoded <= 0)) {
1336 pa_log_error("SBC encoding error (%li)", (long) encoded);
1337 pa_memblock_release(u->write_memchunk.memblock);
1341 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1342 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1344 pa_assert_fp((size_t) encoded <= to_encode);
1345 pa_assert_fp((size_t) encoded == a2dp->codesize);
1347 pa_assert_fp((size_t) written <= to_write);
1348 pa_assert_fp((size_t) written == a2dp->frame_length);
1350 p = (const uint8_t*) p + encoded;
1351 to_encode -= encoded;
1353 d = (uint8_t*) d + written;
1354 to_write -= written;
1359 pa_memblock_release(u->write_memchunk.memblock);
1361 pa_assert(to_encode == 0);
1364 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1367 /* write it to the fifo */
1368 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1371 header->sequence_number = htons(a2dp->seq_num++);
1372 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1373 header->ssrc = htonl(1);
1374 payload->frame_count = frame_count;
1376 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1381 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1388 /* Retry right away if we got interrupted */
1391 else if (errno == EAGAIN)
1392 /* Hmm, apparently the socket was not writable, give up for now */
1395 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1400 pa_assert((size_t) l <= nbytes);
1402 if ((size_t) l != nbytes) {
1403 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1404 (unsigned long long) l,
1405 (unsigned long long) nbytes);
1410 u->write_index += (uint64_t) u->write_memchunk.length;
1411 pa_memblock_unref(u->write_memchunk.memblock);
1412 pa_memchunk_reset(&u->write_memchunk);
1422 static int a2dp_process_push(struct userdata *u) {
1424 pa_memchunk memchunk;
1427 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1428 pa_assert(u->source);
1429 pa_assert(u->read_smoother);
1431 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1432 memchunk.index = memchunk.length = 0;
1435 pa_bool_t found_tstamp = FALSE;
1437 struct a2dp_info *a2dp;
1438 struct rtp_header *header;
1439 struct rtp_payload *payload;
1443 size_t to_write, to_decode;
1444 unsigned frame_count;
1446 a2dp_prepare_buffer(u);
1449 header = a2dp->buffer;
1450 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1452 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1456 if (l < 0 && errno == EINTR)
1457 /* Retry right away if we got interrupted */
1460 else if (l < 0 && errno == EAGAIN)
1461 /* Hmm, apparently the socket was not readable, give up for now. */
1464 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1469 pa_assert((size_t) l <= a2dp->buffer_size);
1471 u->read_index += (uint64_t) l;
1473 /* TODO: get timestamp from rtp */
1474 if (!found_tstamp) {
1475 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1476 tstamp = pa_rtclock_now();
1479 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1480 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1482 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1483 to_decode = l - sizeof(*header) - sizeof(*payload);
1485 d = pa_memblock_acquire(memchunk.memblock);
1486 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1488 while (PA_LIKELY(to_decode > 0)) {
1492 decoded = sbc_decode(&a2dp->sbc,
1497 if (PA_UNLIKELY(decoded <= 0)) {
1498 pa_log_error("SBC decoding error (%li)", (long) decoded);
1499 pa_memblock_release(memchunk.memblock);
1500 pa_memblock_unref(memchunk.memblock);
1504 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1505 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1507 /* Reset frame length, it can be changed due to bitpool change */
1508 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1510 pa_assert_fp((size_t) decoded <= to_decode);
1511 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1513 pa_assert_fp((size_t) written == a2dp->codesize);
1515 p = (const uint8_t*) p + decoded;
1516 to_decode -= decoded;
1518 d = (uint8_t*) d + written;
1519 to_write -= written;
1524 memchunk.length -= to_write;
1526 pa_memblock_release(memchunk.memblock);
1528 pa_source_post(u->source, &memchunk);
1534 pa_memblock_unref(memchunk.memblock);
1539 static void a2dp_reduce_bitpool(struct userdata *u)
1541 struct a2dp_info *a2dp;
1548 /* Check if bitpool is already at its limit */
1549 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1552 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1554 if (bitpool < BITPOOL_DEC_LIMIT)
1555 bitpool = BITPOOL_DEC_LIMIT;
1557 a2dp_set_bitpool(u, bitpool);
1560 static void thread_func(void *userdata) {
1561 struct userdata *u = userdata;
1562 unsigned do_write = 0;
1563 pa_bool_t writable = FALSE;
1567 pa_log_debug("IO Thread starting up");
1569 if (u->core->realtime_scheduling)
1570 pa_make_realtime(u->core->realtime_priority);
1572 pa_thread_mq_install(&u->thread_mq);
1575 if (bt_transport_acquire(u, TRUE) < 0)
1577 } else if (start_stream_fd(u) < 0)
1581 struct pollfd *pollfd;
1583 pa_bool_t disable_timer = TRUE;
1585 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1587 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1589 /* We should send two blocks to the device before we expect
1592 if (u->write_index == 0 && u->read_index <= 0)
1595 if (pollfd && (pollfd->revents & POLLIN)) {
1598 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1599 n_read = hsp_process_push(u);
1601 n_read = a2dp_process_push(u);
1606 /* We just read something, so we are supposed to write something, too */
1611 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1613 if (u->sink->thread_info.rewind_requested)
1614 pa_sink_process_rewind(u->sink, 0);
1617 if (pollfd->revents & POLLOUT)
1620 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1621 pa_usec_t time_passed;
1622 pa_usec_t audio_sent;
1624 /* Hmm, there is no input stream we could synchronize
1625 * to. So let's do things by time */
1627 time_passed = pa_rtclock_now() - u->started_at;
1628 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1630 if (audio_sent <= time_passed) {
1631 pa_usec_t audio_to_send = time_passed - audio_sent;
1633 /* Never try to catch up for more than 100ms */
1634 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1635 pa_usec_t skip_usec;
1636 uint64_t skip_bytes;
1638 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1639 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1641 if (skip_bytes > 0) {
1644 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1645 (unsigned long long) skip_usec,
1646 (unsigned long long) skip_bytes);
1648 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1649 pa_memblock_unref(tmp.memblock);
1650 u->write_index += skip_bytes;
1652 if (u->profile == PROFILE_A2DP)
1653 a2dp_reduce_bitpool(u);
1661 if (writable && do_write > 0) {
1664 if (u->write_index <= 0)
1665 u->started_at = pa_rtclock_now();
1667 if (u->profile == PROFILE_A2DP) {
1668 if ((n_written = a2dp_process_render(u)) < 0)
1671 if ((n_written = hsp_process_render(u)) < 0)
1676 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1678 do_write -= n_written;
1682 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1683 pa_usec_t time_passed, next_write_at, sleep_for;
1685 /* Hmm, there is no input stream we could synchronize
1686 * to. So let's estimate when we need to wake up the latest */
1688 time_passed = pa_rtclock_now() - u->started_at;
1689 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1690 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1692 /* 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); */
1694 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1695 disable_timer = FALSE;
1701 pa_rtpoll_set_timer_disabled(u->rtpoll);
1703 /* Hmm, nothing to do. Let's sleep */
1705 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1706 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1708 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1714 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1716 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1717 pa_log_info("FD error: %s%s%s%s",
1718 pollfd->revents & POLLERR ? "POLLERR " :"",
1719 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1720 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1721 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1727 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1728 pa_log_debug("IO thread failed");
1729 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1730 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1733 pa_log_debug("IO thread shutting down");
1736 /* Run from main thread */
1737 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1743 pa_assert_se(u = userdata);
1745 dbus_error_init(&err);
1747 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1748 dbus_message_get_interface(m),
1749 dbus_message_get_path(m),
1750 dbus_message_get_member(m));
1752 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1755 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1756 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1761 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1762 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1766 if (u->profile == PROFILE_HSP) {
1767 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1769 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1770 pa_sink_volume_changed(u->sink, &v);
1772 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1774 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1775 pa_source_volume_changed(u->source, &v);
1778 } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1779 DBusMessageIter arg_i;
1780 pa_bluetooth_transport *t;
1783 t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1786 if (!dbus_message_iter_init(m, &arg_i)) {
1787 pa_log("Failed to parse PropertyChanged: %s", err.message);
1793 if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1796 if (nrec != t->nrec) {
1797 pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1798 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1803 dbus_error_free(&err);
1805 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1808 /* Run from main thread */
1809 static void sink_set_volume_cb(pa_sink *s) {
1810 struct userdata *u = s->userdata;
1816 if (u->profile != PROFILE_HSP)
1819 gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1824 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1826 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1827 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1828 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1829 dbus_message_unref(m);
1832 /* Run from main thread */
1833 static void source_set_volume_cb(pa_source *s) {
1834 struct userdata *u = s->userdata;
1840 if (u->profile != PROFILE_HSP)
1843 gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1848 pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1850 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1851 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1852 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1853 dbus_message_unref(m);
1856 /* Run from main thread */
1857 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1863 pa_assert(device_id);
1864 pa_assert(namereg_fail);
1866 t = pa_sprintf_malloc("%s_name", type);
1867 n = pa_modargs_get_value(ma, t, NULL);
1871 *namereg_fail = TRUE;
1872 return pa_xstrdup(n);
1875 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1876 *namereg_fail = TRUE;
1879 *namereg_fail = FALSE;
1882 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1887 static void sco_over_pcm_state_update(struct userdata *u) {
1889 pa_assert(USE_SCO_OVER_PCM(u));
1891 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1892 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1894 if (u->service_fd >= 0)
1899 pa_log_debug("Resuming SCO over PCM");
1900 if (init_profile(u) < 0)
1901 pa_log("Can't resume SCO over PCM");
1904 bt_transport_acquire(u, TRUE);
1909 if (u->service_fd < 0)
1913 bt_transport_release(u);
1917 pa_log_debug("Closing SCO over PCM");
1918 pa_close(u->service_fd);
1923 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1925 pa_sink_assert_ref(s);
1928 if (s != u->hsp.sco_sink)
1931 sco_over_pcm_state_update(u);
1936 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1938 pa_source_assert_ref(s);
1941 if (s != u->hsp.sco_source)
1944 sco_over_pcm_state_update(u);
1951 /* Run from main thread */
1952 static int add_sink(struct userdata *u) {
1955 if (USE_SCO_OVER_PCM(u)) {
1958 u->sink = u->hsp.sco_sink;
1959 p = pa_proplist_new();
1960 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1961 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1962 pa_proplist_free(p);
1964 if (!u->hsp.sink_state_changed_slot)
1965 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);
1971 pa_sink_new_data data;
1974 pa_sink_new_data_init(&data);
1975 data.driver = __FILE__;
1976 data.module = u->module;
1977 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1978 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1979 if (u->profile == PROFILE_HSP)
1980 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1981 data.card = u->card;
1982 data.name = get_name("sink", u->modargs, u->address, &b);
1983 data.namereg_fail = b;
1985 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1986 pa_log("Invalid properties");
1987 pa_sink_new_data_done(&data);
1991 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1992 pa_sink_new_data_done(&data);
1995 pa_log_error("Failed to create sink");
1999 u->sink->userdata = u;
2000 u->sink->parent.process_msg = sink_process_msg;
2002 pa_sink_set_max_request(u->sink, u->block_size);
2003 pa_sink_set_fixed_latency(u->sink,
2004 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2005 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2008 if (u->profile == PROFILE_HSP) {
2009 u->sink->set_volume = sink_set_volume_cb;
2010 u->sink->n_volume_steps = 16;
2016 /* Run from main thread */
2017 static int add_source(struct userdata *u) {
2020 if (USE_SCO_OVER_PCM(u)) {
2021 u->source = u->hsp.sco_source;
2022 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2024 if (!u->hsp.source_state_changed_slot)
2025 u->hsp.source_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2031 pa_source_new_data data;
2034 pa_source_new_data_init(&data);
2035 data.driver = __FILE__;
2036 data.module = u->module;
2037 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2038 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2039 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2040 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2042 data.card = u->card;
2043 data.name = get_name("source", u->modargs, u->address, &b);
2044 data.namereg_fail = b;
2046 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2047 pa_log("Invalid properties");
2048 pa_source_new_data_done(&data);
2052 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2053 pa_source_new_data_done(&data);
2056 pa_log_error("Failed to create source");
2060 u->source->userdata = u;
2061 u->source->parent.process_msg = source_process_msg;
2063 pa_source_set_fixed_latency(u->source,
2064 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2065 pa_bytes_to_usec(u->block_size, &u->sample_spec));
2068 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2070 const pa_bluetooth_transport *t;
2071 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2073 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2075 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2078 if (u->profile == PROFILE_HSP) {
2079 u->source->set_volume = source_set_volume_cb;
2080 u->source->n_volume_steps = 16;
2086 /* Run from main thread */
2087 static void shutdown_bt(struct userdata *u) {
2090 if (u->stream_fd >= 0) {
2091 pa_close(u->stream_fd);
2094 u->stream_write_type = 0;
2097 if (u->service_fd >= 0) {
2098 pa_close(u->service_fd);
2100 u->service_write_type = 0;
2101 u->service_read_type = 0;
2104 if (u->write_memchunk.memblock) {
2105 pa_memblock_unref(u->write_memchunk.memblock);
2106 pa_memchunk_reset(&u->write_memchunk);
2110 static int bt_transport_config_a2dp(struct userdata *u) {
2111 const pa_bluetooth_transport *t;
2112 struct a2dp_info *a2dp = &u->a2dp;
2115 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2118 config = (a2dp_sbc_t *) t->config;
2120 if (a2dp->sbc_initialized)
2121 sbc_reinit(&a2dp->sbc, 0);
2123 sbc_init(&a2dp->sbc, 0);
2124 a2dp->sbc_initialized = TRUE;
2126 switch (config->frequency) {
2127 case BT_SBC_SAMPLING_FREQ_16000:
2128 a2dp->sbc.frequency = SBC_FREQ_16000;
2130 case BT_SBC_SAMPLING_FREQ_32000:
2131 a2dp->sbc.frequency = SBC_FREQ_32000;
2133 case BT_SBC_SAMPLING_FREQ_44100:
2134 a2dp->sbc.frequency = SBC_FREQ_44100;
2136 case BT_SBC_SAMPLING_FREQ_48000:
2137 a2dp->sbc.frequency = SBC_FREQ_48000;
2140 pa_assert_not_reached();
2143 switch (config->channel_mode) {
2144 case BT_A2DP_CHANNEL_MODE_MONO:
2145 a2dp->sbc.mode = SBC_MODE_MONO;
2147 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2148 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2150 case BT_A2DP_CHANNEL_MODE_STEREO:
2151 a2dp->sbc.mode = SBC_MODE_STEREO;
2153 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2154 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2157 pa_assert_not_reached();
2160 switch (config->allocation_method) {
2161 case BT_A2DP_ALLOCATION_SNR:
2162 a2dp->sbc.allocation = SBC_AM_SNR;
2164 case BT_A2DP_ALLOCATION_LOUDNESS:
2165 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2168 pa_assert_not_reached();
2171 switch (config->subbands) {
2172 case BT_A2DP_SUBBANDS_4:
2173 a2dp->sbc.subbands = SBC_SB_4;
2175 case BT_A2DP_SUBBANDS_8:
2176 a2dp->sbc.subbands = SBC_SB_8;
2179 pa_assert_not_reached();
2182 switch (config->block_length) {
2183 case BT_A2DP_BLOCK_LENGTH_4:
2184 a2dp->sbc.blocks = SBC_BLK_4;
2186 case BT_A2DP_BLOCK_LENGTH_8:
2187 a2dp->sbc.blocks = SBC_BLK_8;
2189 case BT_A2DP_BLOCK_LENGTH_12:
2190 a2dp->sbc.blocks = SBC_BLK_12;
2192 case BT_A2DP_BLOCK_LENGTH_16:
2193 a2dp->sbc.blocks = SBC_BLK_16;
2196 pa_assert_not_reached();
2199 a2dp->min_bitpool = config->min_bitpool;
2200 a2dp->max_bitpool = config->max_bitpool;
2202 /* Set minimum bitpool for source to get the maximum possible block_size */
2203 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2204 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2205 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2208 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2209 / a2dp->frame_length
2212 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2213 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2218 static int bt_transport_config(struct userdata *u) {
2219 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2220 u->block_size = u->link_mtu;
2224 return bt_transport_config_a2dp(u);
2227 /* Run from main thread */
2228 static int bt_transport_open(struct userdata *u) {
2229 if (bt_transport_acquire(u, FALSE) < 0)
2232 return bt_transport_config(u);
2235 /* Run from main thread */
2236 static int init_bt(struct userdata *u) {
2241 u->stream_write_type = 0;
2242 u->service_write_type = 0;
2243 u->service_read_type = 0;
2245 if ((u->service_fd = bt_audio_service_open()) < 0) {
2246 pa_log_warn("Bluetooth audio service not available");
2250 pa_log_debug("Connected to the bluetooth audio service");
2255 /* Run from main thread */
2256 static int setup_bt(struct userdata *u) {
2257 const pa_bluetooth_device *d;
2258 const pa_bluetooth_transport *t;
2262 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2263 pa_log_error("Failed to get device object.");
2267 /* release transport if exist */
2269 bt_transport_release(u);
2270 pa_xfree(u->transport);
2271 u->transport = NULL;
2274 /* check if profile has a transport */
2275 t = pa_bluetooth_device_get_transport(d, u->profile);
2277 u->transport = pa_xstrdup(t->path);
2278 return bt_transport_open(u);
2281 if (get_caps(u, 0) < 0)
2284 pa_log_debug("Got device capabilities");
2286 if (set_conf(u) < 0)
2289 pa_log_debug("Connection to the device configured");
2292 if (USE_SCO_OVER_PCM(u)) {
2293 pa_log_debug("Configured to use SCO over PCM");
2298 pa_log_debug("Got the stream socket");
2303 /* Run from main thread */
2304 static int init_profile(struct userdata *u) {
2307 pa_assert(u->profile != PROFILE_OFF);
2309 if (setup_bt(u) < 0)
2312 if (u->profile == PROFILE_A2DP ||
2313 u->profile == PROFILE_HSP ||
2314 u->profile == PROFILE_HFGW)
2315 if (add_sink(u) < 0)
2318 if (u->profile == PROFILE_HSP ||
2319 u->profile == PROFILE_A2DP_SOURCE ||
2320 u->profile == PROFILE_HFGW)
2321 if (add_source(u) < 0)
2327 /* Run from main thread */
2328 static void stop_thread(struct userdata *u) {
2332 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2333 pa_thread_free(u->thread);
2337 if (u->rtpoll_item) {
2338 pa_rtpoll_item_free(u->rtpoll_item);
2339 u->rtpoll_item = NULL;
2342 if (u->hsp.sink_state_changed_slot) {
2343 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2344 u->hsp.sink_state_changed_slot = NULL;
2347 if (u->hsp.source_state_changed_slot) {
2348 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2349 u->hsp.source_state_changed_slot = NULL;
2353 pa_sink_unref(u->sink);
2358 pa_source_unref(u->source);
2363 pa_thread_mq_done(&u->thread_mq);
2365 pa_rtpoll_free(u->rtpoll);
2369 if (u->read_smoother) {
2370 pa_smoother_free(u->read_smoother);
2371 u->read_smoother = NULL;
2375 /* Run from main thread */
2376 static int start_thread(struct userdata *u) {
2378 pa_assert(!u->thread);
2379 pa_assert(!u->rtpoll);
2380 pa_assert(!u->rtpoll_item);
2382 u->rtpoll = pa_rtpoll_new();
2383 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2386 if (USE_SCO_OVER_PCM(u)) {
2388 if (bt_transport_acquire(u, TRUE) < 0)
2390 } else if (start_stream_fd(u) < 0)
2393 pa_sink_ref(u->sink);
2394 pa_source_ref(u->source);
2395 /* FIXME: monitor stream_fd error */
2400 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2401 pa_log_error("Failed to create IO thread");
2407 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2408 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2409 pa_sink_put(u->sink);
2411 if (u->sink->set_volume)
2412 u->sink->set_volume(u->sink);
2416 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2417 pa_source_set_rtpoll(u->source, u->rtpoll);
2418 pa_source_put(u->source);
2420 if (u->source->set_volume)
2421 u->source->set_volume(u->source);
2427 /* Run from main thread */
2428 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2431 pa_queue *inputs = NULL, *outputs = NULL;
2432 const pa_bluetooth_device *device;
2435 pa_assert(new_profile);
2436 pa_assert_se(u = c->userdata);
2438 d = PA_CARD_PROFILE_DATA(new_profile);
2440 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2441 pa_log_error("Failed to get device object.");
2445 /* The state signal is sent by bluez, so it is racy to check
2446 strictly for CONNECTED, we should also accept STREAMING state
2447 as being good enough. However, if the profile is used
2448 concurrently (which is unlikely), ipc will fail later on, and
2449 module will be unloaded. */
2450 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2451 pa_log_warn("HSP is not connected, refused to switch profile");
2454 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2455 pa_log_warn("A2DP is not connected, refused to switch profile");
2458 else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2459 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2464 inputs = pa_sink_move_all_start(u->sink, NULL);
2466 if (!USE_SCO_OVER_PCM(u))
2468 pa_sink_unlink(u->sink);
2472 outputs = pa_source_move_all_start(u->source, NULL);
2474 if (!USE_SCO_OVER_PCM(u))
2476 pa_source_unlink(u->source);
2483 u->sample_spec = u->requested_sample_spec;
2487 if (u->profile != PROFILE_OFF)
2490 if (u->sink || u->source)
2495 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2497 pa_sink_move_all_fail(inputs);
2502 pa_source_move_all_finish(u->source, outputs, FALSE);
2504 pa_source_move_all_fail(outputs);
2510 /* Run from main thread */
2511 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2512 pa_card_new_data data;
2518 const char *default_profile;
2523 pa_card_new_data_init(&data);
2524 data.driver = __FILE__;
2525 data.module = u->module;
2527 n = pa_bluetooth_cleanup_name(device->name);
2528 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2530 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2531 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2532 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2533 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2534 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2535 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2536 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2537 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2538 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2539 data.name = get_name("card", u->modargs, device->address, &b);
2540 data.namereg_fail = b;
2542 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2543 pa_log("Invalid properties");
2544 pa_card_new_data_done(&data);
2548 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2550 /* we base hsp/a2dp availability on UUIDs.
2551 Ideally, it would be based on "Connected" state, but
2552 we can't afford to wait for this information when
2553 we are loaded with profile="hsp", for instance */
2554 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2555 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2559 p->max_sink_channels = 2;
2560 p->max_source_channels = 0;
2562 d = PA_CARD_PROFILE_DATA(p);
2565 pa_hashmap_put(data.profiles, p->name, p);
2568 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2569 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2573 p->max_sink_channels = 0;
2574 p->max_source_channels = 2;
2576 d = PA_CARD_PROFILE_DATA(p);
2577 *d = PROFILE_A2DP_SOURCE;
2579 pa_hashmap_put(data.profiles, p->name, p);
2582 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2583 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2584 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2588 p->max_sink_channels = 1;
2589 p->max_source_channels = 1;
2591 d = PA_CARD_PROFILE_DATA(p);
2594 pa_hashmap_put(data.profiles, p->name, p);
2597 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2598 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2602 p->max_sink_channels = 1;
2603 p->max_source_channels = 1;
2605 d = PA_CARD_PROFILE_DATA(p);
2608 pa_hashmap_put(data.profiles, p->name, p);
2611 pa_assert(!pa_hashmap_isempty(data.profiles));
2613 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2614 d = PA_CARD_PROFILE_DATA(p);
2616 pa_hashmap_put(data.profiles, p->name, p);
2618 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2619 if (pa_hashmap_get(data.profiles, default_profile))
2620 pa_card_new_data_set_profile(&data, default_profile);
2622 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2625 u->card = pa_card_new(u->core, &data);
2626 pa_card_new_data_done(&data);
2629 pa_log("Failed to allocate card.");
2633 u->card->userdata = u;
2634 u->card->set_profile = card_set_profile;
2636 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2638 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2639 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2640 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2641 pa_log_warn("Default profile not connected, selecting off profile");
2642 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2643 u->card->save_profile = FALSE;
2646 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2652 /* Run from main thread */
2653 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2654 const pa_bluetooth_device *d = NULL;
2658 if (!address && !path) {
2659 pa_log_error("Failed to get device address/path from module arguments.");
2664 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2665 pa_log_error("%s is not a valid BlueZ audio device.", path);
2669 if (address && !(pa_streq(d->address, address))) {
2670 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2675 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2676 pa_log_error("%s is not known.", address);
2682 u->address = pa_xstrdup(d->address);
2683 u->path = pa_xstrdup(d->path);
2689 /* Run from main thread */
2690 static int setup_dbus(struct userdata *u) {
2693 dbus_error_init(&err);
2695 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2697 if (dbus_error_is_set(&err) || !u->connection) {
2698 pa_log("Failed to get D-Bus connection: %s", err.message);
2699 dbus_error_free(&err);
2706 int pa__init(pa_module* m) {
2710 const char *address, *path;
2712 char *mike, *speaker, *transport;
2713 const pa_bluetooth_device *device;
2717 dbus_error_init(&err);
2719 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2720 pa_log_error("Failed to parse module arguments");
2724 m->userdata = u = pa_xnew0(struct userdata, 1);
2729 u->sample_spec = m->core->default_sample_spec;
2733 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2734 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2735 pa_log("SCO sink not found");
2739 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2740 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2741 pa_log("SCO source not found");
2746 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2747 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2748 pa_log_error("Failed to get rate from module arguments");
2752 u->auto_connect = TRUE;
2753 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2754 pa_log("Failed to parse auto_connect= argument");
2758 channels = u->sample_spec.channels;
2759 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2760 channels <= 0 || channels > PA_CHANNELS_MAX) {
2761 pa_log_error("Failed to get channels from module arguments");
2764 u->sample_spec.channels = (uint8_t) channels;
2765 u->requested_sample_spec = u->sample_spec;
2767 address = pa_modargs_get_value(ma, "address", NULL);
2768 path = pa_modargs_get_value(ma, "path", NULL);
2770 if (setup_dbus(u) < 0)
2773 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2776 if (!(device = find_device(u, address, path)))
2779 /* Add the card structure. This will also initialize the default profile */
2780 if (add_card(u, device) < 0)
2783 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2784 pa_log_error("Failed to add filter function");
2787 u->filter_added = TRUE;
2789 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2790 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2791 transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2793 if (pa_dbus_add_matches(
2794 pa_dbus_connection_get(u->connection), &err,
2802 pa_xfree(transport);
2804 pa_log("Failed to add D-Bus matches: %s", err.message);
2810 pa_xfree(transport);
2812 /* Connect to the BT service */
2815 if (u->profile != PROFILE_OFF)
2816 if (init_profile(u) < 0)
2819 if (u->sink || u->source)
2820 if (start_thread(u) < 0)
2829 dbus_error_free(&err);
2834 int pa__get_n_used(pa_module *m) {
2838 pa_assert_se(u = m->userdata);
2841 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2842 (u->source ? pa_source_linked_by(u->source) : 0);
2845 void pa__done(pa_module *m) {
2849 if (!(u = m->userdata))
2854 && !USE_SCO_OVER_PCM(u)
2857 pa_sink_unlink(u->sink);
2861 && !USE_SCO_OVER_PCM(u)
2864 pa_source_unlink(u->source);
2868 if (u->connection) {
2871 char *speaker, *mike;
2872 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2873 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2875 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2881 if (u->filter_added)
2882 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2884 pa_dbus_connection_unref(u->connection);
2888 pa_card_free(u->card);
2890 if (u->read_smoother)
2891 pa_smoother_free(u->read_smoother);
2896 pa_xfree(u->a2dp.buffer);
2898 sbc_finish(&u->a2dp.sbc);
2901 pa_modargs_free(u->modargs);
2903 pa_xfree(u->address);
2907 bt_transport_release(u);
2908 pa_xfree(u->transport);
2912 pa_bluetooth_discovery_unref(u->discovery);