2 This file is part of PulseAudio.
4 Copyright 2008 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
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulse/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.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/rtpoll.h>
46 #include <pulsecore/time-smoother.h>
47 #include <pulsecore/rtclock.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
51 #include "module-bluetooth-device-symdef.h"
55 #include "bluetooth-util.h"
57 #define MAX_BITPOOL 64
58 #define MIN_BITPOOL 2U
60 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
61 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
62 PA_MODULE_VERSION(PACKAGE_VERSION);
63 PA_MODULE_LOAD_ONCE(FALSE);
65 "name=<name for the card/sink/source, to be prefixed> "
66 "card_name=<name for the card> "
67 "sink_name=<name for the sink> "
68 "source_name=<name for the source> "
69 "address=<address of the device> "
72 "channels=<number of channels> "
73 "path=<device object path>");
77 "sco_sink=<SCO over PCM sink name> "
78 "sco_source=<SCO over PCM source name>"
82 /* TODO: not close fd when entering suspend mode in a2dp */
84 static const char* const valid_modargs[] = {
102 sbc_capabilities_t sbc_capabilities;
103 sbc_t sbc; /* Codec data */
104 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
105 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
107 void* buffer; /* Codec transfer buffer */
108 size_t buffer_size; /* Size of the buffer */
110 uint16_t seq_num; /* Cumulative packet sequence */
114 pcm_capabilities_t pcm_capabilities;
117 pa_source *sco_source;
119 pa_hook_slot *sink_state_changed_slot;
120 pa_hook_slot *source_state_changed_slot;
135 pa_bluetooth_discovery *discovery;
137 pa_dbus_connection *connection;
143 pa_thread_mq thread_mq;
145 pa_rtpoll_item *rtpoll_item;
148 uint64_t read_index, write_index;
149 pa_usec_t started_at;
150 pa_smoother *read_smoother;
152 pa_memchunk write_memchunk;
154 pa_sample_spec sample_spec, requested_sample_spec;
162 struct a2dp_info a2dp;
165 enum profile profile;
169 int stream_write_type;
170 int service_write_type, service_read_type;
173 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
174 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
175 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
177 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
180 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
183 static int init_bt(struct userdata *u);
184 static int init_profile(struct userdata *u);
186 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
190 pa_assert(u->service_fd >= 0);
192 pa_assert(msg->length > 0);
194 pa_log_debug("Sending %s -> %s",
195 pa_strnull(bt_audio_strtype(msg->type)),
196 pa_strnull(bt_audio_strname(msg->name)));
198 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
202 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
204 pa_log_error("Short write()");
209 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
213 pa_assert(u->service_fd >= 0);
217 room = BT_SUGGESTED_BUFFER_SIZE;
219 pa_log_debug("Trying to receive message from audio service...");
221 /* First, read the header */
222 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
225 if (msg->length < sizeof(*msg)) {
226 pa_log_error("Invalid message size.");
230 /* Secondly, read the payload */
231 if (msg->length > sizeof(*msg)) {
233 size_t remains = msg->length - sizeof(*msg);
235 if ((r = pa_loop_read(u->service_fd,
236 (uint8_t*) msg + sizeof(*msg),
238 &u->service_read_type)) != (ssize_t) remains)
242 pa_log_debug("Received %s <- %s",
243 pa_strnull(bt_audio_strtype(msg->type)),
244 pa_strnull(bt_audio_strname(msg->name)));
251 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
253 pa_log_error("Short read()");
258 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) {
262 pa_assert(u->service_fd >= 0);
265 if ((r = service_recv(u, rsp, room)) < 0)
268 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
269 rsp->name != expected_name ||
270 (expected_size > 0 && rsp->length != expected_size)) {
272 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
273 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
275 pa_log_error("Bogus message %s received while %s was expected",
276 pa_strnull(bt_audio_strname(rsp->name)),
277 pa_strnull(bt_audio_strname(expected_name)));
284 /* Run from main thread */
285 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
287 const codec_capabilities_t *codec;
292 bytes_left = rsp->h.length - sizeof(*rsp);
294 if (bytes_left < sizeof(codec_capabilities_t)) {
295 pa_log_error("Packet too small to store codec information.");
299 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
301 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
303 if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
304 (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
305 pa_log_error("Got capabilities for wrong codec.");
309 if (u->profile == PROFILE_HSP) {
311 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
314 pa_assert(codec->type == BT_HFP_CODEC_PCM);
316 if (codec->configured && seid == 0)
319 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
321 } else if (u->profile == PROFILE_A2DP) {
323 while (bytes_left > 0) {
324 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
327 bytes_left -= codec->length;
328 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
331 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
334 pa_assert(codec->type == BT_A2DP_SBC_SINK);
336 if (codec->configured && seid == 0)
339 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
345 /* Run from main thread */
346 static int get_caps(struct userdata *u, uint8_t seid) {
348 struct bt_get_capabilities_req getcaps_req;
349 struct bt_get_capabilities_rsp getcaps_rsp;
350 bt_audio_error_t error;
351 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
357 memset(&msg, 0, sizeof(msg));
358 msg.getcaps_req.h.type = BT_REQUEST;
359 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
360 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
361 msg.getcaps_req.seid = seid;
363 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
364 if (u->profile == PROFILE_A2DP)
365 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
367 pa_assert(u->profile == PROFILE_HSP);
368 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
370 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
372 if (service_send(u, &msg.getcaps_req.h) < 0)
375 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
378 ret = parse_caps(u, seid, &msg.getcaps_rsp);
382 return get_caps(u, ret);
385 /* Run from main thread */
386 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
389 case BT_SBC_SAMPLING_FREQ_16000:
390 case BT_SBC_SAMPLING_FREQ_32000:
393 case BT_SBC_SAMPLING_FREQ_44100:
396 case BT_A2DP_CHANNEL_MODE_MONO:
397 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
400 case BT_A2DP_CHANNEL_MODE_STEREO:
401 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
405 pa_log_warn("Invalid channel mode %u", mode);
409 case BT_SBC_SAMPLING_FREQ_48000:
412 case BT_A2DP_CHANNEL_MODE_MONO:
413 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
416 case BT_A2DP_CHANNEL_MODE_STEREO:
417 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
421 pa_log_warn("Invalid channel mode %u", mode);
426 pa_log_warn("Invalid sampling freq %u", freq);
431 /* Run from main thread */
432 static int setup_a2dp(struct userdata *u) {
433 sbc_capabilities_t *cap;
436 static const struct {
440 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
441 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
442 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
443 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
447 pa_assert(u->profile == PROFILE_A2DP);
449 cap = &u->a2dp.sbc_capabilities;
451 /* Find the lowest freq that is at least as high as the requested
453 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
454 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
455 u->sample_spec.rate = freq_table[i].rate;
456 cap->frequency = freq_table[i].cap;
460 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
461 for (--i; i >= 0; i--) {
462 if (cap->frequency & freq_table[i].cap) {
463 u->sample_spec.rate = freq_table[i].rate;
464 cap->frequency = freq_table[i].cap;
470 pa_log("Not suitable sample rate");
475 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
477 if (cap->capability.configured)
480 if (u->sample_spec.channels <= 1) {
481 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
482 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
483 u->sample_spec.channels = 1;
485 u->sample_spec.channels = 2;
488 if (u->sample_spec.channels >= 2) {
489 u->sample_spec.channels = 2;
491 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
492 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
493 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
494 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
495 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
496 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
497 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
498 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
499 u->sample_spec.channels = 1;
501 pa_log("No supported channel modes");
506 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
507 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
508 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
509 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
510 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
511 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
512 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
513 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
515 pa_log_error("No supported block lengths");
519 if (cap->subbands & BT_A2DP_SUBBANDS_8)
520 cap->subbands = BT_A2DP_SUBBANDS_8;
521 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
522 cap->subbands = BT_A2DP_SUBBANDS_4;
524 pa_log_error("No supported subbands");
528 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
529 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
530 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
531 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
533 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
534 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
539 /* Run from main thread */
540 static void setup_sbc(struct a2dp_info *a2dp) {
541 sbc_capabilities_t *active_capabilities;
545 active_capabilities = &a2dp->sbc_capabilities;
547 if (a2dp->sbc_initialized)
548 sbc_reinit(&a2dp->sbc, 0);
550 sbc_init(&a2dp->sbc, 0);
551 a2dp->sbc_initialized = TRUE;
553 switch (active_capabilities->frequency) {
554 case BT_SBC_SAMPLING_FREQ_16000:
555 a2dp->sbc.frequency = SBC_FREQ_16000;
557 case BT_SBC_SAMPLING_FREQ_32000:
558 a2dp->sbc.frequency = SBC_FREQ_32000;
560 case BT_SBC_SAMPLING_FREQ_44100:
561 a2dp->sbc.frequency = SBC_FREQ_44100;
563 case BT_SBC_SAMPLING_FREQ_48000:
564 a2dp->sbc.frequency = SBC_FREQ_48000;
567 pa_assert_not_reached();
570 switch (active_capabilities->channel_mode) {
571 case BT_A2DP_CHANNEL_MODE_MONO:
572 a2dp->sbc.mode = SBC_MODE_MONO;
574 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
575 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
577 case BT_A2DP_CHANNEL_MODE_STEREO:
578 a2dp->sbc.mode = SBC_MODE_STEREO;
580 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
581 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
584 pa_assert_not_reached();
587 switch (active_capabilities->allocation_method) {
588 case BT_A2DP_ALLOCATION_SNR:
589 a2dp->sbc.allocation = SBC_AM_SNR;
591 case BT_A2DP_ALLOCATION_LOUDNESS:
592 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
595 pa_assert_not_reached();
598 switch (active_capabilities->subbands) {
599 case BT_A2DP_SUBBANDS_4:
600 a2dp->sbc.subbands = SBC_SB_4;
602 case BT_A2DP_SUBBANDS_8:
603 a2dp->sbc.subbands = SBC_SB_8;
606 pa_assert_not_reached();
609 switch (active_capabilities->block_length) {
610 case BT_A2DP_BLOCK_LENGTH_4:
611 a2dp->sbc.blocks = SBC_BLK_4;
613 case BT_A2DP_BLOCK_LENGTH_8:
614 a2dp->sbc.blocks = SBC_BLK_8;
616 case BT_A2DP_BLOCK_LENGTH_12:
617 a2dp->sbc.blocks = SBC_BLK_12;
619 case BT_A2DP_BLOCK_LENGTH_16:
620 a2dp->sbc.blocks = SBC_BLK_16;
623 pa_assert_not_reached();
626 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
627 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
628 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
631 /* Run from main thread */
632 static int set_conf(struct userdata *u) {
634 struct bt_open_req open_req;
635 struct bt_open_rsp open_rsp;
636 struct bt_set_configuration_req setconf_req;
637 struct bt_set_configuration_rsp setconf_rsp;
638 bt_audio_error_t error;
639 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
642 memset(&msg, 0, sizeof(msg));
643 msg.open_req.h.type = BT_REQUEST;
644 msg.open_req.h.name = BT_OPEN;
645 msg.open_req.h.length = sizeof(msg.open_req);
647 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
648 msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
649 msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
651 if (service_send(u, &msg.open_req.h) < 0)
654 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
657 if (u->profile == PROFILE_A2DP ) {
658 u->sample_spec.format = PA_SAMPLE_S16LE;
660 if (setup_a2dp(u) < 0)
663 pa_assert(u->profile == PROFILE_HSP);
665 u->sample_spec.format = PA_SAMPLE_S16LE;
666 u->sample_spec.channels = 1;
667 u->sample_spec.rate = 8000;
670 memset(&msg, 0, sizeof(msg));
671 msg.setconf_req.h.type = BT_REQUEST;
672 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
673 msg.setconf_req.h.length = sizeof(msg.setconf_req);
675 if (u->profile == PROFILE_A2DP) {
676 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
678 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
679 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
680 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
682 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
684 if (service_send(u, &msg.setconf_req.h) < 0)
687 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
690 u->link_mtu = msg.setconf_rsp.link_mtu;
692 /* setup SBC encoder now we agree on parameters */
693 if (u->profile == PROFILE_A2DP) {
697 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
698 / u->a2dp.frame_length
701 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
702 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
704 u->block_size = u->link_mtu;
709 /* from IO thread, except in SCO over PCM */
710 static int start_stream_fd(struct userdata *u) {
712 bt_audio_msg_header_t rsp;
713 struct bt_start_stream_req start_req;
714 struct bt_start_stream_rsp start_rsp;
715 struct bt_new_stream_ind streamfd_ind;
716 bt_audio_error_t error;
717 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
719 struct pollfd *pollfd;
723 pa_assert(u->rtpoll);
724 pa_assert(!u->rtpoll_item);
725 pa_assert(u->stream_fd < 0);
727 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
728 msg.start_req.h.type = BT_REQUEST;
729 msg.start_req.h.name = BT_START_STREAM;
730 msg.start_req.h.length = sizeof(msg.start_req);
732 if (service_send(u, &msg.start_req.h) < 0)
735 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
738 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
741 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
742 pa_log("Failed to get stream fd from audio service.");
746 pa_make_fd_nonblock(u->stream_fd);
747 pa_make_socket_low_delay(u->stream_fd);
750 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
751 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
753 pa_log_debug("Stream properly set up, we're ready to roll!");
755 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
756 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
757 pollfd->fd = u->stream_fd;
758 pollfd->events = pollfd->revents = 0;
760 u->read_index = u->write_index = 0;
764 u->read_smoother = pa_smoother_new(
777 static int stop_stream_fd(struct userdata *u) {
779 bt_audio_msg_header_t rsp;
780 struct bt_stop_stream_req start_req;
781 struct bt_stop_stream_rsp start_rsp;
782 bt_audio_error_t error;
783 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
788 pa_assert(u->rtpoll);
789 pa_assert(u->rtpoll_item);
790 pa_assert(u->stream_fd >= 0);
792 pa_rtpoll_item_free(u->rtpoll_item);
793 u->rtpoll_item = NULL;
795 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
796 msg.start_req.h.type = BT_REQUEST;
797 msg.start_req.h.name = BT_STOP_STREAM;
798 msg.start_req.h.length = sizeof(msg.start_req);
800 if (service_send(u, &msg.start_req.h) < 0 ||
801 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
804 pa_close(u->stream_fd);
807 if (u->read_smoother) {
808 pa_smoother_free(u->read_smoother);
809 u->read_smoother = NULL;
815 /* Run from IO thread */
816 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
817 struct userdata *u = PA_SINK(o)->userdata;
818 pa_bool_t failed = FALSE;
821 pa_assert(u->sink == PA_SINK(o));
825 case PA_SINK_MESSAGE_SET_STATE:
827 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
829 case PA_SINK_SUSPENDED:
830 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
832 /* Stop the device if the source is suspended as well */
833 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
834 /* We deliberately ignore whether stopping
835 * actually worked. Since the stream_fd is
836 * closed it doesn't really matter */
842 case PA_SINK_RUNNING:
843 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
846 /* Resume the device if the source was suspended as well */
847 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
848 if (start_stream_fd(u) < 0)
852 case PA_SINK_UNLINKED:
854 case PA_SINK_INVALID_STATE:
859 case PA_SINK_MESSAGE_GET_LATENCY: {
861 if (u->read_smoother) {
864 ri = pa_smoother_get(u->read_smoother, pa_rtclock_usec());
865 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
867 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
871 ri = pa_rtclock_usec() - u->started_at;
872 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
874 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
877 *((pa_usec_t*) data) += u->sink->fixed_latency;
882 r = pa_sink_process_msg(o, code, data, offset, chunk);
884 return (r < 0 || !failed) ? r : -1;
887 /* Run from IO thread */
888 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
889 struct userdata *u = PA_SOURCE(o)->userdata;
890 pa_bool_t failed = FALSE;
893 pa_assert(u->source == PA_SOURCE(o));
897 case PA_SOURCE_MESSAGE_SET_STATE:
899 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
901 case PA_SOURCE_SUSPENDED:
902 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
904 /* Stop the device if the sink is suspended as well */
905 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
908 if (u->read_smoother)
909 pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
913 case PA_SOURCE_RUNNING:
914 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
917 /* Resume the device if the sink was suspended as well */
918 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
919 if (start_stream_fd(u) < 0)
922 /* We don't resume the smoother here. Instead we
923 * wait until the first packet arrives */
926 case PA_SOURCE_UNLINKED:
928 case PA_SOURCE_INVALID_STATE:
933 case PA_SOURCE_MESSAGE_GET_LATENCY: {
936 wi = pa_smoother_get(u->read_smoother, pa_rtclock_usec());
937 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
939 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->fixed_latency;
945 r = pa_source_process_msg(o, code, data, offset, chunk);
947 return (r < 0 || !failed) ? r : -1;
950 /* Run from IO thread */
951 static int hsp_process_render(struct userdata *u) {
955 pa_assert(u->profile == PROFILE_HSP);
958 /* First, render some data */
959 if (!u->write_memchunk.memblock)
960 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
962 pa_assert(u->write_memchunk.length == u->block_size);
968 /* Now write that data to the socket. The socket is of type
969 * SEQPACKET, and we generated the data of the MTU size, so this
970 * should just work. */
972 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
973 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
974 pa_memblock_release(u->write_memchunk.memblock);
981 /* Retry right away if we got interrupted */
984 else if (errno == EAGAIN)
985 /* Hmm, apparently the socket was not writable, give up for now */
988 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
993 pa_assert((size_t) l <= u->write_memchunk.length);
995 if ((size_t) l != u->write_memchunk.length) {
996 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
997 (unsigned long long) l,
998 (unsigned long long) u->write_memchunk.length);
1003 u->write_index += (uint64_t) u->write_memchunk.length;
1004 pa_memblock_unref(u->write_memchunk.memblock);
1005 pa_memchunk_reset(&u->write_memchunk);
1014 /* Run from IO thread */
1015 static int hsp_process_push(struct userdata *u) {
1017 pa_memchunk memchunk;
1020 pa_assert(u->profile == PROFILE_HSP);
1021 pa_assert(u->source);
1022 pa_assert(u->read_smoother);
1024 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1025 memchunk.index = memchunk.length = 0;
1034 pa_bool_t found_tstamp = FALSE;
1037 memset(&m, 0, sizeof(m));
1038 memset(&aux, 0, sizeof(aux));
1039 memset(&iov, 0, sizeof(iov));
1043 m.msg_control = aux;
1044 m.msg_controllen = sizeof(aux);
1046 p = pa_memblock_acquire(memchunk.memblock);
1048 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1049 l = recvmsg(u->stream_fd, &m, 0);
1050 pa_memblock_release(memchunk.memblock);
1054 if (l < 0 && errno == EINTR)
1055 /* Retry right away if we got interrupted */
1058 else if (l < 0 && errno == EAGAIN)
1059 /* Hmm, apparently the socket was not readable, give up for now. */
1062 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1067 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1069 memchunk.length = (size_t) l;
1070 u->read_index += (uint64_t) l;
1072 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1073 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1074 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1075 pa_rtclock_from_wallclock(tv);
1076 tstamp = pa_timeval_load(tv);
1077 found_tstamp = TRUE;
1081 if (!found_tstamp) {
1082 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1083 tstamp = pa_rtclock_usec();
1086 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1087 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1089 pa_source_post(u->source, &memchunk);
1095 pa_memblock_unref(memchunk.memblock);
1100 /* Run from IO thread */
1101 static void a2dp_prepare_buffer(struct userdata *u) {
1104 if (u->a2dp.buffer_size >= u->link_mtu)
1107 u->a2dp.buffer_size = 2 * u->link_mtu;
1108 pa_xfree(u->a2dp.buffer);
1109 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1112 /* Run from IO thread */
1113 static int a2dp_process_render(struct userdata *u) {
1114 struct a2dp_info *a2dp;
1115 struct rtp_header *header;
1116 struct rtp_payload *payload;
1120 size_t to_write, to_encode;
1121 unsigned frame_count;
1125 pa_assert(u->profile == PROFILE_A2DP);
1128 /* First, render some data */
1129 if (!u->write_memchunk.memblock)
1130 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1132 pa_assert(u->write_memchunk.length == u->block_size);
1134 a2dp_prepare_buffer(u);
1137 header = a2dp->buffer;
1138 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1142 /* Try to create a packet of the full MTU */
1144 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1145 to_encode = u->write_memchunk.length;
1147 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1148 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1150 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1154 encoded = sbc_encode(&a2dp->sbc,
1159 if (PA_UNLIKELY(encoded <= 0)) {
1160 pa_log_error("SBC encoding error (%li)", (long) encoded);
1161 pa_memblock_release(u->write_memchunk.memblock);
1165 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1166 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1168 pa_assert_fp((size_t) encoded <= to_encode);
1169 pa_assert_fp((size_t) encoded == a2dp->codesize);
1171 pa_assert_fp((size_t) written <= to_write);
1172 pa_assert_fp((size_t) written == a2dp->frame_length);
1174 p = (const uint8_t*) p + encoded;
1175 to_encode -= encoded;
1177 d = (uint8_t*) d + written;
1178 to_write -= written;
1183 pa_memblock_release(u->write_memchunk.memblock);
1185 pa_assert(to_encode == 0);
1188 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1191 /* write it to the fifo */
1192 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1195 header->sequence_number = htons(a2dp->seq_num++);
1196 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1197 header->ssrc = htonl(1);
1198 payload->frame_count = frame_count;
1200 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1205 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1212 /* Retry right away if we got interrupted */
1215 else if (errno == EAGAIN)
1216 /* Hmm, apparently the socket was not writable, give up for now */
1219 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1224 pa_assert((size_t) l <= nbytes);
1226 if ((size_t) l != nbytes) {
1227 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1228 (unsigned long long) l,
1229 (unsigned long long) nbytes);
1234 u->write_index += (uint64_t) u->write_memchunk.length;
1235 pa_memblock_unref(u->write_memchunk.memblock);
1236 pa_memchunk_reset(&u->write_memchunk);
1246 static void thread_func(void *userdata) {
1247 struct userdata *u = userdata;
1248 unsigned do_write = 0;
1249 pa_bool_t writable = FALSE;
1253 pa_log_debug("IO Thread starting up");
1255 if (u->core->realtime_scheduling)
1256 pa_make_realtime(u->core->realtime_priority);
1258 if (start_stream_fd(u) < 0)
1261 pa_thread_mq_install(&u->thread_mq);
1262 pa_rtpoll_install(u->rtpoll);
1265 struct pollfd *pollfd;
1267 pa_bool_t disable_timer = TRUE;
1269 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1271 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1273 /* We should send two blocks to the device before we expect
1276 if (u->write_index == 0 && u->read_index <= 0)
1279 if (pollfd && (pollfd->revents & POLLIN)) {
1282 if ((n_read = hsp_process_push(u)) < 0)
1285 /* We just read something, so we are supposed to write something, too */
1290 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1292 if (u->sink->thread_info.rewind_requested)
1293 pa_sink_process_rewind(u->sink, 0);
1296 if (pollfd->revents & POLLOUT)
1299 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1300 pa_usec_t time_passed;
1301 pa_usec_t audio_sent;
1303 /* Hmm, there is no input stream we could synchronize
1304 * to. So let's do things by time */
1306 time_passed = pa_rtclock_usec() - u->started_at;
1307 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1309 if (audio_sent <= time_passed) {
1310 pa_usec_t audio_to_send = time_passed - audio_sent;
1312 /* Never try to catch up for more than 100ms */
1313 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1314 pa_usec_t skip_usec;
1315 uint64_t skip_bytes;
1318 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1319 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1321 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1322 (unsigned long long) skip_usec,
1323 (unsigned long long) skip_bytes);
1325 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1326 pa_memblock_unref(tmp.memblock);
1327 u->write_index += skip_bytes;
1334 if (writable && do_write > 0) {
1337 if (u->write_index <= 0)
1338 u->started_at = pa_rtclock_usec();
1340 if (u->profile == PROFILE_A2DP) {
1341 if ((n_written = a2dp_process_render(u)) < 0)
1344 if ((n_written = hsp_process_render(u)) < 0)
1348 do_write -= n_written;
1352 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1353 pa_usec_t time_passed, next_write_at, sleep_for;
1355 /* Hmm, there is no input stream we could synchronize
1356 * to. So let's estimate when we need to wake up the latest */
1358 time_passed = pa_rtclock_usec() - u->started_at;
1359 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1360 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1362 /* 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); */
1364 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1365 disable_timer = FALSE;
1371 pa_rtpoll_set_timer_disabled(u->rtpoll);
1373 /* Hmm, nothing to do. Let's sleep */
1375 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1376 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1378 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1384 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1386 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1387 pa_log_info("FD error: %s%s%s%s",
1388 pollfd->revents & POLLERR ? "POLLERR " :"",
1389 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1390 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1391 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1397 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1398 pa_log_debug("IO thread failed");
1399 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1400 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1403 pa_log_debug("IO thread shutting down");
1406 /* Run from main thread */
1407 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1413 pa_assert_se(u = userdata);
1415 dbus_error_init(&err);
1417 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1418 dbus_message_get_interface(m),
1419 dbus_message_get_path(m),
1420 dbus_message_get_member(m));
1422 if (!dbus_message_has_path(m, u->path))
1425 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1426 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1431 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1432 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1436 if (u->profile == PROFILE_HSP) {
1437 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1439 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1440 pa_sink_volume_changed(u->sink, &v);
1442 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1444 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1445 pa_source_volume_changed(u->source, &v);
1451 dbus_error_free(&err);
1453 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1456 /* Run from main thread */
1457 static void sink_set_volume_cb(pa_sink *s) {
1458 struct userdata *u = s->userdata;
1464 if (u->profile != PROFILE_HSP)
1467 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1472 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1474 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1475 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1476 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1477 dbus_message_unref(m);
1480 /* Run from main thread */
1481 static void source_set_volume_cb(pa_source *s) {
1482 struct userdata *u = s->userdata;
1488 if (u->profile != PROFILE_HSP)
1491 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1496 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1498 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1499 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1500 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1501 dbus_message_unref(m);
1504 /* Run from main thread */
1505 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1511 pa_assert(device_id);
1512 pa_assert(namereg_fail);
1514 t = pa_sprintf_malloc("%s_name", type);
1515 n = pa_modargs_get_value(ma, t, NULL);
1519 *namereg_fail = TRUE;
1520 return pa_xstrdup(n);
1523 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1524 *namereg_fail = TRUE;
1527 *namereg_fail = FALSE;
1530 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1535 static void sco_over_pcm_state_update(struct userdata *u) {
1537 pa_assert(USE_SCO_OVER_PCM(u));
1539 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1540 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1542 if (u->service_fd >= 0)
1545 pa_log_debug("Resuming SCO over PCM");
1546 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1547 pa_log("Can't resume SCO over PCM");
1552 if (u->service_fd < 0)
1557 pa_log_debug("Closing SCO over PCM");
1558 pa_close(u->service_fd);
1563 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1565 pa_sink_assert_ref(s);
1568 if (s != u->hsp.sco_sink)
1571 sco_over_pcm_state_update(u);
1576 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1578 pa_source_assert_ref(s);
1581 if (s != u->hsp.sco_source)
1584 sco_over_pcm_state_update(u);
1591 /* Run from main thread */
1592 static int add_sink(struct userdata *u) {
1595 if (USE_SCO_OVER_PCM(u)) {
1598 u->sink = u->hsp.sco_sink;
1599 p = pa_proplist_new();
1600 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1601 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1602 pa_proplist_free(p);
1604 if (!u->hsp.sink_state_changed_slot)
1605 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);
1611 pa_sink_new_data data;
1614 pa_sink_new_data_init(&data);
1615 data.driver = __FILE__;
1616 data.module = u->module;
1617 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1618 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1619 data.card = u->card;
1620 data.name = get_name("sink", u->modargs, u->address, &b);
1621 data.namereg_fail = b;
1623 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1624 pa_sink_new_data_done(&data);
1627 pa_log_error("Failed to create sink");
1631 u->sink->userdata = u;
1632 u->sink->parent.process_msg = sink_process_msg;
1634 pa_sink_set_max_request(u->sink, u->block_size);
1635 pa_sink_set_fixed_latency(u->sink,
1636 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1637 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1640 if (u->profile == PROFILE_HSP) {
1641 u->sink->set_volume = sink_set_volume_cb;
1642 u->sink->n_volume_steps = 16;
1648 /* Run from main thread */
1649 static int add_source(struct userdata *u) {
1652 if (USE_SCO_OVER_PCM(u)) {
1653 u->source = u->hsp.sco_source;
1654 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1656 if (!u->hsp.source_state_changed_slot)
1657 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);
1663 pa_source_new_data data;
1666 pa_source_new_data_init(&data);
1667 data.driver = __FILE__;
1668 data.module = u->module;
1669 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1670 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "hsp");
1671 data.card = u->card;
1672 data.name = get_name("source", u->modargs, u->address, &b);
1673 data.namereg_fail = b;
1675 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1676 pa_source_new_data_done(&data);
1679 pa_log_error("Failed to create source");
1683 u->source->userdata = u;
1684 u->source->parent.process_msg = source_process_msg;
1686 pa_source_set_fixed_latency(u->source,
1687 (/* u->profile == PROFILE_A2DP ? FIXED_LATENCY_RECORD_A2DP : */ FIXED_LATENCY_RECORD_HSP) +
1688 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1691 if (u->profile == PROFILE_HSP) {
1692 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1693 u->source->set_volume = source_set_volume_cb;
1694 u->source->n_volume_steps = 16;
1700 /* Run from main thread */
1701 static void shutdown_bt(struct userdata *u) {
1704 if (u->stream_fd >= 0) {
1705 pa_close(u->stream_fd);
1708 u->stream_write_type = 0;
1711 if (u->service_fd >= 0) {
1712 pa_close(u->service_fd);
1714 u->service_write_type = u->service_write_type = 0;
1717 if (u->write_memchunk.memblock) {
1718 pa_memblock_unref(u->write_memchunk.memblock);
1719 pa_memchunk_reset(&u->write_memchunk);
1723 /* Run from main thread */
1724 static int init_bt(struct userdata *u) {
1729 u->stream_write_type = 0;
1730 u->service_write_type = u->service_write_type = 0;
1732 if ((u->service_fd = bt_audio_service_open()) < 0) {
1733 pa_log_error("Couldn't connect to bluetooth audio service");
1737 pa_log_debug("Connected to the bluetooth audio service");
1742 /* Run from main thread */
1743 static int setup_bt(struct userdata *u) {
1746 if (get_caps(u, 0) < 0)
1749 pa_log_debug("Got device capabilities");
1751 if (set_conf(u) < 0)
1754 pa_log_debug("Connection to the device configured");
1757 if (USE_SCO_OVER_PCM(u)) {
1758 pa_log_debug("Configured to use SCO over PCM");
1763 pa_log_debug("Got the stream socket");
1768 /* Run from main thread */
1769 static int init_profile(struct userdata *u) {
1772 pa_assert(u->profile != PROFILE_OFF);
1774 if (setup_bt(u) < 0)
1777 if (u->profile == PROFILE_A2DP ||
1778 u->profile == PROFILE_HSP)
1779 if (add_sink(u) < 0)
1782 if (u->profile == PROFILE_HSP)
1783 if (add_source(u) < 0)
1789 /* Run from main thread */
1790 static void stop_thread(struct userdata *u) {
1794 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1795 pa_thread_free(u->thread);
1799 if (u->rtpoll_item) {
1800 pa_rtpoll_item_free(u->rtpoll_item);
1801 u->rtpoll_item = NULL;
1804 if (u->hsp.sink_state_changed_slot) {
1805 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1806 u->hsp.sink_state_changed_slot = NULL;
1809 if (u->hsp.source_state_changed_slot) {
1810 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1811 u->hsp.source_state_changed_slot = NULL;
1815 pa_sink_unref(u->sink);
1820 pa_source_unref(u->source);
1825 pa_thread_mq_done(&u->thread_mq);
1827 pa_rtpoll_free(u->rtpoll);
1831 if (u->read_smoother) {
1832 pa_smoother_free(u->read_smoother);
1833 u->read_smoother = NULL;
1837 /* Run from main thread */
1838 static int start_thread(struct userdata *u) {
1840 pa_assert(!u->thread);
1841 pa_assert(!u->rtpoll);
1842 pa_assert(!u->rtpoll_item);
1844 u->rtpoll = pa_rtpoll_new();
1845 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1848 if (USE_SCO_OVER_PCM(u)) {
1849 if (start_stream_fd(u) < 0)
1852 pa_sink_ref(u->sink);
1853 pa_source_ref(u->source);
1854 /* FIXME: monitor stream_fd error */
1859 if (!(u->thread = pa_thread_new(thread_func, u))) {
1860 pa_log_error("Failed to create IO thread");
1866 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1867 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1868 pa_sink_put(u->sink);
1870 if (u->sink->set_volume)
1871 u->sink->set_volume(u->sink);
1875 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1876 pa_source_set_rtpoll(u->source, u->rtpoll);
1877 pa_source_put(u->source);
1879 if (u->source->set_volume)
1880 u->source->set_volume(u->source);
1886 /* Run from main thread */
1887 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1890 pa_queue *inputs = NULL, *outputs = NULL;
1891 const pa_bluetooth_device *device;
1894 pa_assert(new_profile);
1895 pa_assert_se(u = c->userdata);
1897 d = PA_CARD_PROFILE_DATA(new_profile);
1899 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1900 pa_log_error("Failed to get device object.");
1904 /* The state signal is sent by bluez, so it is racy to check
1905 strictly for CONNECTED, we should also accept STREAMING state
1906 as being good enough. However, if the profile is used
1907 concurrently (which is unlikely), ipc will fail later on, and
1908 module will be unloaded. */
1909 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
1910 pa_log_warn("HSP is not connected, refused to switch profile");
1913 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
1914 pa_log_warn("A2DP is not connected, refused to switch profile");
1919 inputs = pa_sink_move_all_start(u->sink);
1921 if (!USE_SCO_OVER_PCM(u))
1923 pa_sink_unlink(u->sink);
1927 outputs = pa_source_move_all_start(u->source);
1929 if (!USE_SCO_OVER_PCM(u))
1931 pa_source_unlink(u->source);
1938 u->sample_spec = u->requested_sample_spec;
1942 if (u->profile != PROFILE_OFF)
1945 if (u->sink || u->source)
1950 pa_sink_move_all_finish(u->sink, inputs, FALSE);
1952 pa_sink_move_all_fail(inputs);
1957 pa_source_move_all_finish(u->source, outputs, FALSE);
1959 pa_source_move_all_fail(outputs);
1965 /* Run from main thread */
1966 static int add_card(struct userdata *u, const char *default_profile, const pa_bluetooth_device *device) {
1967 pa_card_new_data data;
1974 pa_card_new_data_init(&data);
1975 data.driver = __FILE__;
1976 data.module = u->module;
1978 n = pa_bluetooth_cleanup_name(device->name);
1979 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1981 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
1982 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1983 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1984 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1985 if ((ff = pa_bluetooth_get_form_factor(device->class)))
1986 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1987 pa_proplist_sets(data.proplist, "bluez.path", device->path);
1988 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
1989 pa_proplist_sets(data.proplist, "bluez.name", device->name);
1990 data.name = get_name("card", u->modargs, device->address, &b);
1991 data.namereg_fail = b;
1993 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1995 /* we base hsp/a2dp availability on UUIDs.
1996 Ideally, it would be based on "Connected" state, but
1997 we can't afford to wait for this information when
1998 we are loaded with profile="hsp", for instance */
1999 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2000 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2004 p->max_sink_channels = 2;
2005 p->max_source_channels = 0;
2007 d = PA_CARD_PROFILE_DATA(p);
2010 pa_hashmap_put(data.profiles, p->name, p);
2013 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2014 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2015 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2019 p->max_sink_channels = 1;
2020 p->max_source_channels = 1;
2022 d = PA_CARD_PROFILE_DATA(p);
2025 pa_hashmap_put(data.profiles, p->name, p);
2028 pa_assert(!pa_hashmap_isempty(data.profiles));
2030 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2031 d = PA_CARD_PROFILE_DATA(p);
2033 pa_hashmap_put(data.profiles, p->name, p);
2035 if (default_profile) {
2036 if (pa_hashmap_get(data.profiles, default_profile))
2037 pa_card_new_data_set_profile(&data, default_profile);
2039 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2042 u->card = pa_card_new(u->core, &data);
2043 pa_card_new_data_done(&data);
2046 pa_log("Failed to allocate card.");
2050 u->card->userdata = u;
2051 u->card->set_profile = card_set_profile;
2053 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2059 /* Run from main thread */
2060 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2061 const pa_bluetooth_device *d = NULL;
2065 if (!address && !path) {
2066 pa_log_error("Failed to get device address/path from module arguments.");
2071 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2072 pa_log_error("%s is not a valid BlueZ audio device.", path);
2076 if (address && !(pa_streq(d->address, address))) {
2077 pa_log_error("Passed path %s and address %s don't match.", path, address);
2082 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2083 pa_log_error("%s is not known.", address);
2089 u->address = pa_xstrdup(d->address);
2090 u->path = pa_xstrdup(d->path);
2096 /* Run from main thread */
2097 static int setup_dbus(struct userdata *u) {
2100 dbus_error_init(&err);
2102 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2104 if (dbus_error_is_set(&err) || !u->connection) {
2105 pa_log("Failed to get D-Bus connection: %s", err.message);
2106 dbus_error_free(&err);
2113 int pa__init(pa_module* m) {
2117 const char *address, *path;
2119 char *mike, *speaker;
2120 const pa_bluetooth_device *device;
2124 dbus_error_init(&err);
2126 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2127 pa_log_error("Failed to parse module arguments");
2131 m->userdata = u = pa_xnew0(struct userdata, 1);
2136 u->sample_spec = m->core->default_sample_spec;
2140 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2141 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2142 pa_log("SCO sink not found");
2146 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2147 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2148 pa_log("SCO source not found");
2153 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2154 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2155 pa_log_error("Failed to get rate from module arguments");
2159 channels = u->sample_spec.channels;
2160 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2161 channels <= 0 || channels > PA_CHANNELS_MAX) {
2162 pa_log_error("Failed to get channels from module arguments");
2165 u->sample_spec.channels = (uint8_t) channels;
2166 u->requested_sample_spec = u->sample_spec;
2168 address = pa_modargs_get_value(ma, "address", NULL);
2169 path = pa_modargs_get_value(ma, "path", NULL);
2171 if (setup_dbus(u) < 0)
2174 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2177 if (!(device = find_device(u, address, path)))
2180 /* Add the card structure. This will also initialize the default profile */
2181 if (add_card(u, pa_modargs_get_value(ma, "profile", NULL), device) < 0)
2184 /* Connect to the BT service and query capabilities */
2188 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2189 pa_log_error("Failed to add filter function");
2193 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2194 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2196 if (pa_dbus_add_matches(
2197 pa_dbus_connection_get(u->connection), &err,
2205 pa_log("Failed to add D-Bus matches: %s", err.message);
2212 if (u->profile != PROFILE_OFF)
2213 if (init_profile(u) < 0)
2216 if (u->sink || u->source)
2217 if (start_thread(u) < 0)
2226 dbus_error_free(&err);
2231 int pa__get_n_used(pa_module *m) {
2235 pa_assert_se(u = m->userdata);
2238 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2239 (u->source ? pa_source_linked_by(u->source) : 0);
2242 void pa__done(pa_module *m) {
2246 if (!(u = m->userdata))
2251 && !USE_SCO_OVER_PCM(u)
2254 pa_sink_unlink(u->sink);
2258 && !USE_SCO_OVER_PCM(u)
2261 pa_source_unlink(u->source);
2265 if (u->connection) {
2268 char *speaker, *mike;
2269 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2270 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2272 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2281 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2282 pa_dbus_connection_unref(u->connection);
2286 pa_card_free(u->card);
2288 if (u->read_smoother)
2289 pa_smoother_free(u->read_smoother);
2294 pa_xfree(u->a2dp.buffer);
2296 sbc_finish(&u->a2dp.sbc);
2299 pa_modargs_free(u->modargs);
2301 pa_xfree(u->address);
2305 pa_bluetooth_discovery_unref(u->discovery);