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/i18n.h>
34 #include <pulse/rtclock.h>
35 #include <pulse/sample.h>
36 #include <pulse/timeval.h>
37 #include <pulse/xmalloc.h>
39 #include <pulsecore/module.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-rtclock.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/core-error.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/namereg.h>
50 #include <pulsecore/dbus-shared.h>
52 #include "module-bluetooth-device-symdef.h"
56 #include "bluetooth-util.h"
58 #define MAX_BITPOOL 64
59 #define MIN_BITPOOL 2U
61 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION);
64 PA_MODULE_LOAD_ONCE(FALSE);
66 "name=<name for the card/sink/source, to be prefixed> "
67 "card_name=<name for the card> "
68 "card_properties=<properties for the card> "
69 "sink_name=<name for the sink> "
70 "sink_properties=<properties for the sink> "
71 "source_name=<name for the source> "
72 "source_properties=<properties for the source> "
73 "address=<address of the device> "
76 "channels=<number of channels> "
77 "path=<device object path>");
81 "sco_sink=<SCO over PCM sink name> "
82 "sco_source=<SCO over PCM source name>"
86 /* TODO: not close fd when entering suspend mode in a2dp */
88 static const char* const valid_modargs[] = {
109 sbc_capabilities_t sbc_capabilities;
110 sbc_t sbc; /* Codec data */
111 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
112 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
114 void* buffer; /* Codec transfer buffer */
115 size_t buffer_size; /* Size of the buffer */
117 uint16_t seq_num; /* Cumulative packet sequence */
121 pcm_capabilities_t pcm_capabilities;
124 pa_source *sco_source;
126 pa_hook_slot *sink_state_changed_slot;
127 pa_hook_slot *source_state_changed_slot;
142 pa_bluetooth_discovery *discovery;
144 pa_dbus_connection *connection;
150 pa_thread_mq thread_mq;
152 pa_rtpoll_item *rtpoll_item;
155 uint64_t read_index, write_index;
156 pa_usec_t started_at;
157 pa_smoother *read_smoother;
159 pa_memchunk write_memchunk;
161 pa_sample_spec sample_spec, requested_sample_spec;
169 struct a2dp_info a2dp;
172 enum profile profile;
176 int stream_write_type;
177 int service_write_type, service_read_type;
180 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
181 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
182 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
184 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
187 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
190 static int init_bt(struct userdata *u);
191 static int init_profile(struct userdata *u);
193 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
197 pa_assert(u->service_fd >= 0);
199 pa_assert(msg->length > 0);
201 pa_log_debug("Sending %s -> %s",
202 pa_strnull(bt_audio_strtype(msg->type)),
203 pa_strnull(bt_audio_strname(msg->name)));
205 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
209 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
211 pa_log_error("Short write()");
216 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
220 pa_assert(u->service_fd >= 0);
224 room = BT_SUGGESTED_BUFFER_SIZE;
226 pa_log_debug("Trying to receive message from audio service...");
228 /* First, read the header */
229 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
232 if (msg->length < sizeof(*msg)) {
233 pa_log_error("Invalid message size.");
237 /* Secondly, read the payload */
238 if (msg->length > sizeof(*msg)) {
240 size_t remains = msg->length - sizeof(*msg);
242 if ((r = pa_loop_read(u->service_fd,
243 (uint8_t*) msg + sizeof(*msg),
245 &u->service_read_type)) != (ssize_t) remains)
249 pa_log_debug("Received %s <- %s",
250 pa_strnull(bt_audio_strtype(msg->type)),
251 pa_strnull(bt_audio_strname(msg->name)));
258 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
260 pa_log_error("Short read()");
265 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) {
269 pa_assert(u->service_fd >= 0);
272 if ((r = service_recv(u, rsp, room)) < 0)
275 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
276 rsp->name != expected_name ||
277 (expected_size > 0 && rsp->length != expected_size)) {
279 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
280 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
282 pa_log_error("Bogus message %s received while %s was expected",
283 pa_strnull(bt_audio_strname(rsp->name)),
284 pa_strnull(bt_audio_strname(expected_name)));
291 /* Run from main thread */
292 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
294 const codec_capabilities_t *codec;
299 bytes_left = rsp->h.length - sizeof(*rsp);
301 if (bytes_left < sizeof(codec_capabilities_t)) {
302 pa_log_error("Packet too small to store codec information.");
306 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
308 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
310 if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
311 (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
312 pa_log_error("Got capabilities for wrong codec.");
316 if (u->profile == PROFILE_HSP) {
318 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
321 pa_assert(codec->type == BT_HFP_CODEC_PCM);
323 if (codec->configured && seid == 0)
326 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
328 } else if (u->profile == PROFILE_A2DP) {
330 while (bytes_left > 0) {
331 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
334 bytes_left -= codec->length;
335 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
338 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
341 pa_assert(codec->type == BT_A2DP_SBC_SINK);
343 if (codec->configured && seid == 0)
346 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
352 /* Run from main thread */
353 static int get_caps(struct userdata *u, uint8_t seid) {
355 struct bt_get_capabilities_req getcaps_req;
356 struct bt_get_capabilities_rsp getcaps_rsp;
357 bt_audio_error_t error;
358 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
364 memset(&msg, 0, sizeof(msg));
365 msg.getcaps_req.h.type = BT_REQUEST;
366 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
367 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
368 msg.getcaps_req.seid = seid;
370 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
371 if (u->profile == PROFILE_A2DP)
372 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
374 pa_assert(u->profile == PROFILE_HSP);
375 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
377 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
379 if (service_send(u, &msg.getcaps_req.h) < 0)
382 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
385 ret = parse_caps(u, seid, &msg.getcaps_rsp);
389 return get_caps(u, ret);
392 /* Run from main thread */
393 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
396 case BT_SBC_SAMPLING_FREQ_16000:
397 case BT_SBC_SAMPLING_FREQ_32000:
400 case BT_SBC_SAMPLING_FREQ_44100:
403 case BT_A2DP_CHANNEL_MODE_MONO:
404 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
407 case BT_A2DP_CHANNEL_MODE_STEREO:
408 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
412 pa_log_warn("Invalid channel mode %u", mode);
416 case BT_SBC_SAMPLING_FREQ_48000:
419 case BT_A2DP_CHANNEL_MODE_MONO:
420 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
423 case BT_A2DP_CHANNEL_MODE_STEREO:
424 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
428 pa_log_warn("Invalid channel mode %u", mode);
433 pa_log_warn("Invalid sampling freq %u", freq);
438 /* Run from main thread */
439 static int setup_a2dp(struct userdata *u) {
440 sbc_capabilities_t *cap;
443 static const struct {
447 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
448 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
449 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
450 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
454 pa_assert(u->profile == PROFILE_A2DP);
456 cap = &u->a2dp.sbc_capabilities;
458 /* Find the lowest freq that is at least as high as the requested
460 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
461 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
462 u->sample_spec.rate = freq_table[i].rate;
463 cap->frequency = freq_table[i].cap;
467 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
468 for (--i; i >= 0; i--) {
469 if (cap->frequency & freq_table[i].cap) {
470 u->sample_spec.rate = freq_table[i].rate;
471 cap->frequency = freq_table[i].cap;
477 pa_log("Not suitable sample rate");
482 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
484 if (cap->capability.configured)
487 if (u->sample_spec.channels <= 1) {
488 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
489 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
490 u->sample_spec.channels = 1;
492 u->sample_spec.channels = 2;
495 if (u->sample_spec.channels >= 2) {
496 u->sample_spec.channels = 2;
498 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
499 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
500 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
501 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
502 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
503 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
504 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
505 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
506 u->sample_spec.channels = 1;
508 pa_log("No supported channel modes");
513 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
514 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
515 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
516 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
517 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
518 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
519 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
520 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
522 pa_log_error("No supported block lengths");
526 if (cap->subbands & BT_A2DP_SUBBANDS_8)
527 cap->subbands = BT_A2DP_SUBBANDS_8;
528 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
529 cap->subbands = BT_A2DP_SUBBANDS_4;
531 pa_log_error("No supported subbands");
535 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
536 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
537 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
538 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
540 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
541 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
546 /* Run from main thread */
547 static void setup_sbc(struct a2dp_info *a2dp) {
548 sbc_capabilities_t *active_capabilities;
552 active_capabilities = &a2dp->sbc_capabilities;
554 if (a2dp->sbc_initialized)
555 sbc_reinit(&a2dp->sbc, 0);
557 sbc_init(&a2dp->sbc, 0);
558 a2dp->sbc_initialized = TRUE;
560 switch (active_capabilities->frequency) {
561 case BT_SBC_SAMPLING_FREQ_16000:
562 a2dp->sbc.frequency = SBC_FREQ_16000;
564 case BT_SBC_SAMPLING_FREQ_32000:
565 a2dp->sbc.frequency = SBC_FREQ_32000;
567 case BT_SBC_SAMPLING_FREQ_44100:
568 a2dp->sbc.frequency = SBC_FREQ_44100;
570 case BT_SBC_SAMPLING_FREQ_48000:
571 a2dp->sbc.frequency = SBC_FREQ_48000;
574 pa_assert_not_reached();
577 switch (active_capabilities->channel_mode) {
578 case BT_A2DP_CHANNEL_MODE_MONO:
579 a2dp->sbc.mode = SBC_MODE_MONO;
581 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
582 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
584 case BT_A2DP_CHANNEL_MODE_STEREO:
585 a2dp->sbc.mode = SBC_MODE_STEREO;
587 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
588 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
591 pa_assert_not_reached();
594 switch (active_capabilities->allocation_method) {
595 case BT_A2DP_ALLOCATION_SNR:
596 a2dp->sbc.allocation = SBC_AM_SNR;
598 case BT_A2DP_ALLOCATION_LOUDNESS:
599 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
602 pa_assert_not_reached();
605 switch (active_capabilities->subbands) {
606 case BT_A2DP_SUBBANDS_4:
607 a2dp->sbc.subbands = SBC_SB_4;
609 case BT_A2DP_SUBBANDS_8:
610 a2dp->sbc.subbands = SBC_SB_8;
613 pa_assert_not_reached();
616 switch (active_capabilities->block_length) {
617 case BT_A2DP_BLOCK_LENGTH_4:
618 a2dp->sbc.blocks = SBC_BLK_4;
620 case BT_A2DP_BLOCK_LENGTH_8:
621 a2dp->sbc.blocks = SBC_BLK_8;
623 case BT_A2DP_BLOCK_LENGTH_12:
624 a2dp->sbc.blocks = SBC_BLK_12;
626 case BT_A2DP_BLOCK_LENGTH_16:
627 a2dp->sbc.blocks = SBC_BLK_16;
630 pa_assert_not_reached();
633 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
634 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
635 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
638 /* Run from main thread */
639 static int set_conf(struct userdata *u) {
641 struct bt_open_req open_req;
642 struct bt_open_rsp open_rsp;
643 struct bt_set_configuration_req setconf_req;
644 struct bt_set_configuration_rsp setconf_rsp;
645 bt_audio_error_t error;
646 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
649 memset(&msg, 0, sizeof(msg));
650 msg.open_req.h.type = BT_REQUEST;
651 msg.open_req.h.name = BT_OPEN;
652 msg.open_req.h.length = sizeof(msg.open_req);
654 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
655 msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
656 msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
658 if (service_send(u, &msg.open_req.h) < 0)
661 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
664 if (u->profile == PROFILE_A2DP ) {
665 u->sample_spec.format = PA_SAMPLE_S16LE;
667 if (setup_a2dp(u) < 0)
670 pa_assert(u->profile == PROFILE_HSP);
672 u->sample_spec.format = PA_SAMPLE_S16LE;
673 u->sample_spec.channels = 1;
674 u->sample_spec.rate = 8000;
677 memset(&msg, 0, sizeof(msg));
678 msg.setconf_req.h.type = BT_REQUEST;
679 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
680 msg.setconf_req.h.length = sizeof(msg.setconf_req);
682 if (u->profile == PROFILE_A2DP) {
683 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
685 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
686 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
687 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
689 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
691 if (service_send(u, &msg.setconf_req.h) < 0)
694 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
697 u->link_mtu = msg.setconf_rsp.link_mtu;
699 /* setup SBC encoder now we agree on parameters */
700 if (u->profile == PROFILE_A2DP) {
704 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
705 / u->a2dp.frame_length
708 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
709 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
711 u->block_size = u->link_mtu;
716 /* from IO thread, except in SCO over PCM */
717 static int start_stream_fd(struct userdata *u) {
719 bt_audio_msg_header_t rsp;
720 struct bt_start_stream_req start_req;
721 struct bt_start_stream_rsp start_rsp;
722 struct bt_new_stream_ind streamfd_ind;
723 bt_audio_error_t error;
724 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
726 struct pollfd *pollfd;
730 pa_assert(u->rtpoll);
731 pa_assert(!u->rtpoll_item);
732 pa_assert(u->stream_fd < 0);
734 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
735 msg.start_req.h.type = BT_REQUEST;
736 msg.start_req.h.name = BT_START_STREAM;
737 msg.start_req.h.length = sizeof(msg.start_req);
739 if (service_send(u, &msg.start_req.h) < 0)
742 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
745 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
748 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
749 pa_log("Failed to get stream fd from audio service.");
753 pa_make_fd_nonblock(u->stream_fd);
754 pa_make_socket_low_delay(u->stream_fd);
757 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
758 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
760 pa_log_debug("Stream properly set up, we're ready to roll!");
762 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
763 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
764 pollfd->fd = u->stream_fd;
765 pollfd->events = pollfd->revents = 0;
767 u->read_index = u->write_index = 0;
771 u->read_smoother = pa_smoother_new(
784 static int stop_stream_fd(struct userdata *u) {
786 bt_audio_msg_header_t rsp;
787 struct bt_stop_stream_req start_req;
788 struct bt_stop_stream_rsp start_rsp;
789 bt_audio_error_t error;
790 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
795 pa_assert(u->rtpoll);
796 pa_assert(u->rtpoll_item);
797 pa_assert(u->stream_fd >= 0);
799 pa_rtpoll_item_free(u->rtpoll_item);
800 u->rtpoll_item = NULL;
802 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
803 msg.start_req.h.type = BT_REQUEST;
804 msg.start_req.h.name = BT_STOP_STREAM;
805 msg.start_req.h.length = sizeof(msg.start_req);
807 if (service_send(u, &msg.start_req.h) < 0 ||
808 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
811 pa_close(u->stream_fd);
814 if (u->read_smoother) {
815 pa_smoother_free(u->read_smoother);
816 u->read_smoother = NULL;
822 /* Run from IO thread */
823 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
824 struct userdata *u = PA_SINK(o)->userdata;
825 pa_bool_t failed = FALSE;
828 pa_assert(u->sink == PA_SINK(o));
832 case PA_SINK_MESSAGE_SET_STATE:
834 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
836 case PA_SINK_SUSPENDED:
837 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
839 /* Stop the device if the source is suspended as well */
840 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
841 /* We deliberately ignore whether stopping
842 * actually worked. Since the stream_fd is
843 * closed it doesn't really matter */
849 case PA_SINK_RUNNING:
850 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
853 /* Resume the device if the source was suspended as well */
854 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
855 if (start_stream_fd(u) < 0)
859 case PA_SINK_UNLINKED:
861 case PA_SINK_INVALID_STATE:
866 case PA_SINK_MESSAGE_GET_LATENCY: {
868 if (u->read_smoother) {
871 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
872 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
874 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
878 ri = pa_rtclock_now() - u->started_at;
879 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
881 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
884 *((pa_usec_t*) data) += u->sink->fixed_latency;
889 r = pa_sink_process_msg(o, code, data, offset, chunk);
891 return (r < 0 || !failed) ? r : -1;
894 /* Run from IO thread */
895 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
896 struct userdata *u = PA_SOURCE(o)->userdata;
897 pa_bool_t failed = FALSE;
900 pa_assert(u->source == PA_SOURCE(o));
904 case PA_SOURCE_MESSAGE_SET_STATE:
906 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
908 case PA_SOURCE_SUSPENDED:
909 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
911 /* Stop the device if the sink is suspended as well */
912 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
915 if (u->read_smoother)
916 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
920 case PA_SOURCE_RUNNING:
921 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
924 /* Resume the device if the sink was suspended as well */
925 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
926 if (start_stream_fd(u) < 0)
929 /* We don't resume the smoother here. Instead we
930 * wait until the first packet arrives */
933 case PA_SOURCE_UNLINKED:
935 case PA_SOURCE_INVALID_STATE:
940 case PA_SOURCE_MESSAGE_GET_LATENCY: {
943 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
944 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
946 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->fixed_latency;
952 r = pa_source_process_msg(o, code, data, offset, chunk);
954 return (r < 0 || !failed) ? r : -1;
957 /* Run from IO thread */
958 static int hsp_process_render(struct userdata *u) {
962 pa_assert(u->profile == PROFILE_HSP);
965 /* First, render some data */
966 if (!u->write_memchunk.memblock)
967 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
969 pa_assert(u->write_memchunk.length == u->block_size);
975 /* Now write that data to the socket. The socket is of type
976 * SEQPACKET, and we generated the data of the MTU size, so this
977 * should just work. */
979 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
980 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
981 pa_memblock_release(u->write_memchunk.memblock);
988 /* Retry right away if we got interrupted */
991 else if (errno == EAGAIN)
992 /* Hmm, apparently the socket was not writable, give up for now */
995 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1000 pa_assert((size_t) l <= u->write_memchunk.length);
1002 if ((size_t) l != u->write_memchunk.length) {
1003 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1004 (unsigned long long) l,
1005 (unsigned long long) u->write_memchunk.length);
1010 u->write_index += (uint64_t) u->write_memchunk.length;
1011 pa_memblock_unref(u->write_memchunk.memblock);
1012 pa_memchunk_reset(&u->write_memchunk);
1021 /* Run from IO thread */
1022 static int hsp_process_push(struct userdata *u) {
1024 pa_memchunk memchunk;
1027 pa_assert(u->profile == PROFILE_HSP);
1028 pa_assert(u->source);
1029 pa_assert(u->read_smoother);
1031 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1032 memchunk.index = memchunk.length = 0;
1041 pa_bool_t found_tstamp = FALSE;
1044 memset(&m, 0, sizeof(m));
1045 memset(&aux, 0, sizeof(aux));
1046 memset(&iov, 0, sizeof(iov));
1050 m.msg_control = aux;
1051 m.msg_controllen = sizeof(aux);
1053 p = pa_memblock_acquire(memchunk.memblock);
1055 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1056 l = recvmsg(u->stream_fd, &m, 0);
1057 pa_memblock_release(memchunk.memblock);
1061 if (l < 0 && errno == EINTR)
1062 /* Retry right away if we got interrupted */
1065 else if (l < 0 && errno == EAGAIN)
1066 /* Hmm, apparently the socket was not readable, give up for now. */
1069 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1074 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1076 memchunk.length = (size_t) l;
1077 u->read_index += (uint64_t) l;
1079 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1080 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1081 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1082 pa_rtclock_from_wallclock(tv);
1083 tstamp = pa_timeval_load(tv);
1084 found_tstamp = TRUE;
1088 if (!found_tstamp) {
1089 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1090 tstamp = pa_rtclock_now();
1093 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1094 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1096 pa_source_post(u->source, &memchunk);
1102 pa_memblock_unref(memchunk.memblock);
1107 /* Run from IO thread */
1108 static void a2dp_prepare_buffer(struct userdata *u) {
1111 if (u->a2dp.buffer_size >= u->link_mtu)
1114 u->a2dp.buffer_size = 2 * u->link_mtu;
1115 pa_xfree(u->a2dp.buffer);
1116 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1119 /* Run from IO thread */
1120 static int a2dp_process_render(struct userdata *u) {
1121 struct a2dp_info *a2dp;
1122 struct rtp_header *header;
1123 struct rtp_payload *payload;
1127 size_t to_write, to_encode;
1128 unsigned frame_count;
1132 pa_assert(u->profile == PROFILE_A2DP);
1135 /* First, render some data */
1136 if (!u->write_memchunk.memblock)
1137 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1139 pa_assert(u->write_memchunk.length == u->block_size);
1141 a2dp_prepare_buffer(u);
1144 header = a2dp->buffer;
1145 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1149 /* Try to create a packet of the full MTU */
1151 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1152 to_encode = u->write_memchunk.length;
1154 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1155 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1157 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1161 encoded = sbc_encode(&a2dp->sbc,
1166 if (PA_UNLIKELY(encoded <= 0)) {
1167 pa_log_error("SBC encoding error (%li)", (long) encoded);
1168 pa_memblock_release(u->write_memchunk.memblock);
1172 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1173 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1175 pa_assert_fp((size_t) encoded <= to_encode);
1176 pa_assert_fp((size_t) encoded == a2dp->codesize);
1178 pa_assert_fp((size_t) written <= to_write);
1179 pa_assert_fp((size_t) written == a2dp->frame_length);
1181 p = (const uint8_t*) p + encoded;
1182 to_encode -= encoded;
1184 d = (uint8_t*) d + written;
1185 to_write -= written;
1190 pa_memblock_release(u->write_memchunk.memblock);
1192 pa_assert(to_encode == 0);
1195 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1198 /* write it to the fifo */
1199 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1202 header->sequence_number = htons(a2dp->seq_num++);
1203 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1204 header->ssrc = htonl(1);
1205 payload->frame_count = frame_count;
1207 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1212 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1219 /* Retry right away if we got interrupted */
1222 else if (errno == EAGAIN)
1223 /* Hmm, apparently the socket was not writable, give up for now */
1226 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1231 pa_assert((size_t) l <= nbytes);
1233 if ((size_t) l != nbytes) {
1234 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1235 (unsigned long long) l,
1236 (unsigned long long) nbytes);
1241 u->write_index += (uint64_t) u->write_memchunk.length;
1242 pa_memblock_unref(u->write_memchunk.memblock);
1243 pa_memchunk_reset(&u->write_memchunk);
1253 static void thread_func(void *userdata) {
1254 struct userdata *u = userdata;
1255 unsigned do_write = 0;
1256 pa_bool_t writable = FALSE;
1260 pa_log_debug("IO Thread starting up");
1262 if (u->core->realtime_scheduling)
1263 pa_make_realtime(u->core->realtime_priority);
1265 if (start_stream_fd(u) < 0)
1268 pa_thread_mq_install(&u->thread_mq);
1271 struct pollfd *pollfd;
1273 pa_bool_t disable_timer = TRUE;
1275 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1277 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1279 /* We should send two blocks to the device before we expect
1282 if (u->write_index == 0 && u->read_index <= 0)
1285 if (pollfd && (pollfd->revents & POLLIN)) {
1288 if ((n_read = hsp_process_push(u)) < 0)
1291 /* We just read something, so we are supposed to write something, too */
1296 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1298 if (u->sink->thread_info.rewind_requested)
1299 pa_sink_process_rewind(u->sink, 0);
1302 if (pollfd->revents & POLLOUT)
1305 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1306 pa_usec_t time_passed;
1307 pa_usec_t audio_sent;
1309 /* Hmm, there is no input stream we could synchronize
1310 * to. So let's do things by time */
1312 time_passed = pa_rtclock_now() - u->started_at;
1313 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1315 if (audio_sent <= time_passed) {
1316 pa_usec_t audio_to_send = time_passed - audio_sent;
1318 /* Never try to catch up for more than 100ms */
1319 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1320 pa_usec_t skip_usec;
1321 uint64_t skip_bytes;
1324 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1325 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1327 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1328 (unsigned long long) skip_usec,
1329 (unsigned long long) skip_bytes);
1331 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1332 pa_memblock_unref(tmp.memblock);
1333 u->write_index += skip_bytes;
1340 if (writable && do_write > 0) {
1343 if (u->write_index <= 0)
1344 u->started_at = pa_rtclock_now();
1346 if (u->profile == PROFILE_A2DP) {
1347 if ((n_written = a2dp_process_render(u)) < 0)
1350 if ((n_written = hsp_process_render(u)) < 0)
1355 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1357 do_write -= n_written;
1361 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1362 pa_usec_t time_passed, next_write_at, sleep_for;
1364 /* Hmm, there is no input stream we could synchronize
1365 * to. So let's estimate when we need to wake up the latest */
1367 time_passed = pa_rtclock_now() - u->started_at;
1368 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1369 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1371 /* 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); */
1373 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1374 disable_timer = FALSE;
1380 pa_rtpoll_set_timer_disabled(u->rtpoll);
1382 /* Hmm, nothing to do. Let's sleep */
1384 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1385 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1387 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1393 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1395 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1396 pa_log_info("FD error: %s%s%s%s",
1397 pollfd->revents & POLLERR ? "POLLERR " :"",
1398 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1399 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1400 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1406 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1407 pa_log_debug("IO thread failed");
1408 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1409 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1412 pa_log_debug("IO thread shutting down");
1415 /* Run from main thread */
1416 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1422 pa_assert_se(u = userdata);
1424 dbus_error_init(&err);
1426 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1427 dbus_message_get_interface(m),
1428 dbus_message_get_path(m),
1429 dbus_message_get_member(m));
1431 if (!dbus_message_has_path(m, u->path))
1434 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1435 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1440 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1441 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1445 if (u->profile == PROFILE_HSP) {
1446 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1448 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1449 pa_sink_volume_changed(u->sink, &v);
1451 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1453 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1454 pa_source_volume_changed(u->source, &v);
1460 dbus_error_free(&err);
1462 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1465 /* Run from main thread */
1466 static void sink_set_volume_cb(pa_sink *s) {
1467 struct userdata *u = s->userdata;
1473 if (u->profile != PROFILE_HSP)
1476 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1481 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1483 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1484 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1485 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1486 dbus_message_unref(m);
1489 /* Run from main thread */
1490 static void source_set_volume_cb(pa_source *s) {
1491 struct userdata *u = s->userdata;
1497 if (u->profile != PROFILE_HSP)
1500 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1505 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1507 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1508 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1509 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1510 dbus_message_unref(m);
1513 /* Run from main thread */
1514 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1520 pa_assert(device_id);
1521 pa_assert(namereg_fail);
1523 t = pa_sprintf_malloc("%s_name", type);
1524 n = pa_modargs_get_value(ma, t, NULL);
1528 *namereg_fail = TRUE;
1529 return pa_xstrdup(n);
1532 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1533 *namereg_fail = TRUE;
1536 *namereg_fail = FALSE;
1539 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1544 static void sco_over_pcm_state_update(struct userdata *u) {
1546 pa_assert(USE_SCO_OVER_PCM(u));
1548 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1549 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1551 if (u->service_fd >= 0)
1554 pa_log_debug("Resuming SCO over PCM");
1555 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1556 pa_log("Can't resume SCO over PCM");
1561 if (u->service_fd < 0)
1566 pa_log_debug("Closing SCO over PCM");
1567 pa_close(u->service_fd);
1572 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1574 pa_sink_assert_ref(s);
1577 if (s != u->hsp.sco_sink)
1580 sco_over_pcm_state_update(u);
1585 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1587 pa_source_assert_ref(s);
1590 if (s != u->hsp.sco_source)
1593 sco_over_pcm_state_update(u);
1600 /* Run from main thread */
1601 static int add_sink(struct userdata *u) {
1604 if (USE_SCO_OVER_PCM(u)) {
1607 u->sink = u->hsp.sco_sink;
1608 p = pa_proplist_new();
1609 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1610 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1611 pa_proplist_free(p);
1613 if (!u->hsp.sink_state_changed_slot)
1614 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);
1620 pa_sink_new_data data;
1623 pa_sink_new_data_init(&data);
1624 data.driver = __FILE__;
1625 data.module = u->module;
1626 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1627 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1628 if (u->profile == PROFILE_HSP)
1629 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1630 data.card = u->card;
1631 data.name = get_name("sink", u->modargs, u->address, &b);
1632 data.namereg_fail = b;
1634 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1635 pa_log("Invalid properties");
1636 pa_sink_new_data_done(&data);
1640 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1641 pa_sink_new_data_done(&data);
1644 pa_log_error("Failed to create sink");
1648 u->sink->userdata = u;
1649 u->sink->parent.process_msg = sink_process_msg;
1651 pa_sink_set_max_request(u->sink, u->block_size);
1652 pa_sink_set_fixed_latency(u->sink,
1653 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1654 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1657 if (u->profile == PROFILE_HSP) {
1658 u->sink->set_volume = sink_set_volume_cb;
1659 u->sink->n_volume_steps = 16;
1665 /* Run from main thread */
1666 static int add_source(struct userdata *u) {
1669 if (USE_SCO_OVER_PCM(u)) {
1670 u->source = u->hsp.sco_source;
1671 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1673 if (!u->hsp.source_state_changed_slot)
1674 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);
1680 pa_source_new_data data;
1683 pa_source_new_data_init(&data);
1684 data.driver = __FILE__;
1685 data.module = u->module;
1686 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1687 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "hsp");
1688 if (u->profile == PROFILE_HSP)
1689 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1690 data.card = u->card;
1691 data.name = get_name("source", u->modargs, u->address, &b);
1692 data.namereg_fail = b;
1694 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1695 pa_log("Invalid properties");
1696 pa_source_new_data_done(&data);
1700 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1701 pa_source_new_data_done(&data);
1704 pa_log_error("Failed to create source");
1708 u->source->userdata = u;
1709 u->source->parent.process_msg = source_process_msg;
1711 pa_source_set_fixed_latency(u->source,
1712 (/* u->profile == PROFILE_A2DP ? FIXED_LATENCY_RECORD_A2DP : */ FIXED_LATENCY_RECORD_HSP) +
1713 pa_bytes_to_usec(u->block_size, &u->sample_spec));
1716 if (u->profile == PROFILE_HSP) {
1717 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1718 u->source->set_volume = source_set_volume_cb;
1719 u->source->n_volume_steps = 16;
1725 /* Run from main thread */
1726 static void shutdown_bt(struct userdata *u) {
1729 if (u->stream_fd >= 0) {
1730 pa_close(u->stream_fd);
1733 u->stream_write_type = 0;
1736 if (u->service_fd >= 0) {
1737 pa_close(u->service_fd);
1739 u->service_write_type = u->service_write_type = 0;
1742 if (u->write_memchunk.memblock) {
1743 pa_memblock_unref(u->write_memchunk.memblock);
1744 pa_memchunk_reset(&u->write_memchunk);
1748 /* Run from main thread */
1749 static int init_bt(struct userdata *u) {
1754 u->stream_write_type = 0;
1755 u->service_write_type = u->service_write_type = 0;
1757 if ((u->service_fd = bt_audio_service_open()) < 0) {
1758 pa_log_error("Couldn't connect to bluetooth audio service");
1762 pa_log_debug("Connected to the bluetooth audio service");
1767 /* Run from main thread */
1768 static int setup_bt(struct userdata *u) {
1771 if (get_caps(u, 0) < 0)
1774 pa_log_debug("Got device capabilities");
1776 if (set_conf(u) < 0)
1779 pa_log_debug("Connection to the device configured");
1782 if (USE_SCO_OVER_PCM(u)) {
1783 pa_log_debug("Configured to use SCO over PCM");
1788 pa_log_debug("Got the stream socket");
1793 /* Run from main thread */
1794 static int init_profile(struct userdata *u) {
1797 pa_assert(u->profile != PROFILE_OFF);
1799 if (setup_bt(u) < 0)
1802 if (u->profile == PROFILE_A2DP ||
1803 u->profile == PROFILE_HSP)
1804 if (add_sink(u) < 0)
1807 if (u->profile == PROFILE_HSP)
1808 if (add_source(u) < 0)
1814 /* Run from main thread */
1815 static void stop_thread(struct userdata *u) {
1819 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1820 pa_thread_free(u->thread);
1824 if (u->rtpoll_item) {
1825 pa_rtpoll_item_free(u->rtpoll_item);
1826 u->rtpoll_item = NULL;
1829 if (u->hsp.sink_state_changed_slot) {
1830 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1831 u->hsp.sink_state_changed_slot = NULL;
1834 if (u->hsp.source_state_changed_slot) {
1835 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1836 u->hsp.source_state_changed_slot = NULL;
1840 pa_sink_unref(u->sink);
1845 pa_source_unref(u->source);
1850 pa_thread_mq_done(&u->thread_mq);
1852 pa_rtpoll_free(u->rtpoll);
1856 if (u->read_smoother) {
1857 pa_smoother_free(u->read_smoother);
1858 u->read_smoother = NULL;
1862 /* Run from main thread */
1863 static int start_thread(struct userdata *u) {
1865 pa_assert(!u->thread);
1866 pa_assert(!u->rtpoll);
1867 pa_assert(!u->rtpoll_item);
1869 u->rtpoll = pa_rtpoll_new();
1870 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1873 if (USE_SCO_OVER_PCM(u)) {
1874 if (start_stream_fd(u) < 0)
1877 pa_sink_ref(u->sink);
1878 pa_source_ref(u->source);
1879 /* FIXME: monitor stream_fd error */
1884 if (!(u->thread = pa_thread_new(thread_func, u))) {
1885 pa_log_error("Failed to create IO thread");
1891 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1892 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1893 pa_sink_put(u->sink);
1895 if (u->sink->set_volume)
1896 u->sink->set_volume(u->sink);
1900 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1901 pa_source_set_rtpoll(u->source, u->rtpoll);
1902 pa_source_put(u->source);
1904 if (u->source->set_volume)
1905 u->source->set_volume(u->source);
1911 /* Run from main thread */
1912 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1915 pa_queue *inputs = NULL, *outputs = NULL;
1916 const pa_bluetooth_device *device;
1919 pa_assert(new_profile);
1920 pa_assert_se(u = c->userdata);
1922 d = PA_CARD_PROFILE_DATA(new_profile);
1924 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1925 pa_log_error("Failed to get device object.");
1929 /* The state signal is sent by bluez, so it is racy to check
1930 strictly for CONNECTED, we should also accept STREAMING state
1931 as being good enough. However, if the profile is used
1932 concurrently (which is unlikely), ipc will fail later on, and
1933 module will be unloaded. */
1934 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
1935 pa_log_warn("HSP is not connected, refused to switch profile");
1938 else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
1939 pa_log_warn("A2DP is not connected, refused to switch profile");
1944 inputs = pa_sink_move_all_start(u->sink, NULL);
1946 if (!USE_SCO_OVER_PCM(u))
1948 pa_sink_unlink(u->sink);
1952 outputs = pa_source_move_all_start(u->source, NULL);
1954 if (!USE_SCO_OVER_PCM(u))
1956 pa_source_unlink(u->source);
1963 u->sample_spec = u->requested_sample_spec;
1967 if (u->profile != PROFILE_OFF)
1970 if (u->sink || u->source)
1975 pa_sink_move_all_finish(u->sink, inputs, FALSE);
1977 pa_sink_move_all_fail(inputs);
1982 pa_source_move_all_finish(u->source, outputs, FALSE);
1984 pa_source_move_all_fail(outputs);
1990 /* Run from main thread */
1991 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
1992 pa_card_new_data data;
1998 const char *default_profile;
2003 pa_card_new_data_init(&data);
2004 data.driver = __FILE__;
2005 data.module = u->module;
2007 n = pa_bluetooth_cleanup_name(device->name);
2008 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2010 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2011 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2012 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2013 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2014 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2015 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2016 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2017 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2018 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2019 data.name = get_name("card", u->modargs, device->address, &b);
2020 data.namereg_fail = b;
2022 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2023 pa_log("Invalid properties");
2024 pa_card_new_data_done(&data);
2028 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2030 /* we base hsp/a2dp availability on UUIDs.
2031 Ideally, it would be based on "Connected" state, but
2032 we can't afford to wait for this information when
2033 we are loaded with profile="hsp", for instance */
2034 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2035 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2039 p->max_sink_channels = 2;
2040 p->max_source_channels = 0;
2042 d = PA_CARD_PROFILE_DATA(p);
2045 pa_hashmap_put(data.profiles, p->name, p);
2048 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2049 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2050 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2054 p->max_sink_channels = 1;
2055 p->max_source_channels = 1;
2057 d = PA_CARD_PROFILE_DATA(p);
2060 pa_hashmap_put(data.profiles, p->name, p);
2063 pa_assert(!pa_hashmap_isempty(data.profiles));
2065 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2066 d = PA_CARD_PROFILE_DATA(p);
2068 pa_hashmap_put(data.profiles, p->name, p);
2070 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2071 if (pa_hashmap_get(data.profiles, default_profile))
2072 pa_card_new_data_set_profile(&data, default_profile);
2074 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2077 u->card = pa_card_new(u->core, &data);
2078 pa_card_new_data_done(&data);
2081 pa_log("Failed to allocate card.");
2085 u->card->userdata = u;
2086 u->card->set_profile = card_set_profile;
2088 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2090 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2091 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP)) {
2092 pa_log_warn("Default profile not connected, selecting off profile");
2093 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2094 u->card->save_profile = FALSE;
2097 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2103 /* Run from main thread */
2104 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2105 const pa_bluetooth_device *d = NULL;
2109 if (!address && !path) {
2110 pa_log_error("Failed to get device address/path from module arguments.");
2115 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2116 pa_log_error("%s is not a valid BlueZ audio device.", path);
2120 if (address && !(pa_streq(d->address, address))) {
2121 pa_log_error("Passed path %s and address %s don't match.", path, address);
2126 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2127 pa_log_error("%s is not known.", address);
2133 u->address = pa_xstrdup(d->address);
2134 u->path = pa_xstrdup(d->path);
2140 /* Run from main thread */
2141 static int setup_dbus(struct userdata *u) {
2144 dbus_error_init(&err);
2146 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2148 if (dbus_error_is_set(&err) || !u->connection) {
2149 pa_log("Failed to get D-Bus connection: %s", err.message);
2150 dbus_error_free(&err);
2157 int pa__init(pa_module* m) {
2161 const char *address, *path;
2163 char *mike, *speaker;
2164 const pa_bluetooth_device *device;
2168 dbus_error_init(&err);
2170 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2171 pa_log_error("Failed to parse module arguments");
2175 m->userdata = u = pa_xnew0(struct userdata, 1);
2180 u->sample_spec = m->core->default_sample_spec;
2184 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2185 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2186 pa_log("SCO sink not found");
2190 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2191 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2192 pa_log("SCO source not found");
2197 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2198 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2199 pa_log_error("Failed to get rate from module arguments");
2203 channels = u->sample_spec.channels;
2204 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2205 channels <= 0 || channels > PA_CHANNELS_MAX) {
2206 pa_log_error("Failed to get channels from module arguments");
2209 u->sample_spec.channels = (uint8_t) channels;
2210 u->requested_sample_spec = u->sample_spec;
2212 address = pa_modargs_get_value(ma, "address", NULL);
2213 path = pa_modargs_get_value(ma, "path", NULL);
2215 if (setup_dbus(u) < 0)
2218 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2221 if (!(device = find_device(u, address, path)))
2224 /* Add the card structure. This will also initialize the default profile */
2225 if (add_card(u, device) < 0)
2228 /* Connect to the BT service and query capabilities */
2232 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2233 pa_log_error("Failed to add filter function");
2237 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2238 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2240 if (pa_dbus_add_matches(
2241 pa_dbus_connection_get(u->connection), &err,
2249 pa_log("Failed to add D-Bus matches: %s", err.message);
2256 if (u->profile != PROFILE_OFF)
2257 if (init_profile(u) < 0)
2260 if (u->sink || u->source)
2261 if (start_thread(u) < 0)
2270 dbus_error_free(&err);
2275 int pa__get_n_used(pa_module *m) {
2279 pa_assert_se(u = m->userdata);
2282 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2283 (u->source ? pa_source_linked_by(u->source) : 0);
2286 void pa__done(pa_module *m) {
2290 if (!(u = m->userdata))
2295 && !USE_SCO_OVER_PCM(u)
2298 pa_sink_unlink(u->sink);
2302 && !USE_SCO_OVER_PCM(u)
2305 pa_source_unlink(u->source);
2309 if (u->connection) {
2312 char *speaker, *mike;
2313 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2314 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2316 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2325 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2326 pa_dbus_connection_unref(u->connection);
2330 pa_card_free(u->card);
2332 if (u->read_smoother)
2333 pa_smoother_free(u->read_smoother);
2338 pa_xfree(u->a2dp.buffer);
2340 sbc_finish(&u->a2dp.sbc);
2343 pa_modargs_free(u->modargs);
2345 pa_xfree(u->address);
2349 pa_bluetooth_discovery_unref(u->discovery);