2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
5 Copyright 2011-2012 BMW Car IT GmbH.
7 PulseAudio is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 PulseAudio is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with PulseAudio; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 #include <linux/sockios.h>
30 #include <arpa/inet.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.h>
37 #include <pulsecore/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.h>
40 #include <pulsecore/core-rtclock.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/core-error.h>
43 #include <pulsecore/shared.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/poll.h>
48 #include <pulsecore/rtpoll.h>
49 #include <pulsecore/time-smoother.h>
50 #include <pulsecore/namereg.h>
51 #include <pulsecore/dbus-shared.h>
53 #include "module-bluetooth-device-symdef.h"
56 #include "a2dp-codecs.h"
58 #include "bluetooth-util.h"
60 #define BITPOOL_DEC_LIMIT 32
61 #define BITPOOL_DEC_STEP 5
62 #define HSP_MAX_GAIN 15
64 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
65 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
66 PA_MODULE_VERSION(PACKAGE_VERSION);
67 PA_MODULE_LOAD_ONCE(FALSE);
69 "name=<name for the card/sink/source, to be prefixed> "
70 "card_name=<name for the card> "
71 "card_properties=<properties for the card> "
72 "sink_name=<name for the sink> "
73 "sink_properties=<properties for the sink> "
74 "source_name=<name for the source> "
75 "source_properties=<properties for the source> "
76 "address=<address of the device> "
77 "profile=<a2dp|hsp|hfgw> "
79 "channels=<number of channels> "
80 "path=<device object path> "
81 "auto_connect=<automatically connect?> "
82 "sco_sink=<SCO over PCM sink name> "
83 "sco_source=<SCO over PCM source name>");
85 /* TODO: not close fd when entering suspend mode in a2dp */
87 static const char* const valid_modargs[] = {
107 sbc_capabilities_t sbc_capabilities;
108 sbc_t sbc; /* Codec data */
109 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
110 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
112 void* buffer; /* Codec transfer buffer */
113 size_t buffer_size; /* Size of the buffer */
115 uint16_t seq_num; /* Cumulative packet sequence */
121 pcm_capabilities_t pcm_capabilities;
123 void (*sco_sink_set_volume)(pa_sink *s);
124 pa_source *sco_source;
125 void (*sco_source_set_volume)(pa_source *s);
126 pa_hook_slot *sink_state_changed_slot;
127 pa_hook_slot *source_state_changed_slot;
128 pa_hook_slot *nrec_changed_slot;
131 struct bluetooth_msg {
136 typedef struct bluetooth_msg bluetooth_msg;
137 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
138 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
149 pa_bluetooth_discovery *discovery;
150 pa_bool_t auto_connect;
152 pa_dbus_connection *connection;
158 pa_thread_mq thread_mq;
160 pa_rtpoll_item *rtpoll_item;
164 uint64_t read_index, write_index;
165 pa_usec_t started_at;
166 pa_smoother *read_smoother;
168 pa_memchunk write_memchunk;
170 pa_sample_spec sample_spec, requested_sample_spec;
174 size_t read_link_mtu;
175 size_t read_block_size;
177 size_t write_link_mtu;
178 size_t write_block_size;
180 struct a2dp_info a2dp;
183 enum profile profile;
187 int stream_write_type;
189 pa_bool_t filter_added;
193 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
194 BLUETOOTH_MESSAGE_MAX
197 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
198 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
199 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
200 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
202 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
204 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
206 static int init_profile(struct userdata *u);
209 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
211 struct a2dp_info *a2dp;
217 if (a2dp->sbc.bitpool == bitpool)
220 if (bitpool > a2dp->max_bitpool)
221 bitpool = a2dp->max_bitpool;
222 else if (bitpool < a2dp->min_bitpool)
223 bitpool = a2dp->min_bitpool;
225 a2dp->sbc.bitpool = bitpool;
227 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
228 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
230 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
233 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
234 / a2dp->frame_length * a2dp->codesize;
236 u->write_block_size =
237 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
238 / a2dp->frame_length * a2dp->codesize;
240 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
241 pa_sink_set_fixed_latency_within_thread(u->sink,
242 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
245 /* from IO thread, except in SCO over PCM */
247 static void setup_stream(struct userdata *u) {
248 struct pollfd *pollfd;
251 pa_make_fd_nonblock(u->stream_fd);
252 pa_make_socket_low_delay(u->stream_fd);
255 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
256 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
258 pa_log_debug("Stream properly set up, we're ready to roll!");
260 if (u->profile == PROFILE_A2DP)
261 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
263 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
264 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
265 pollfd->fd = u->stream_fd;
266 pollfd->events = pollfd->revents = 0;
268 u->read_index = u->write_index = 0;
272 u->read_smoother = pa_smoother_new(
282 static bool bt_transport_is_acquired(struct userdata *u) {
283 if (u->accesstype == NULL) {
284 pa_assert(u->stream_fd < 0);
287 pa_assert(u->stream_fd >= 0);
292 static void bt_transport_release(struct userdata *u) {
293 const char *accesstype = "rw";
294 const pa_bluetooth_transport *t;
296 /* Ignore if already released */
297 if (!bt_transport_is_acquired(u))
300 pa_log_debug("Releasing transport %s", u->transport);
302 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
304 pa_bluetooth_transport_release(t, accesstype);
306 pa_xfree(u->accesstype);
307 u->accesstype = NULL;
309 if (u->rtpoll_item) {
310 pa_rtpoll_item_free(u->rtpoll_item);
311 u->rtpoll_item = NULL;
314 if (u->stream_fd >= 0) {
315 pa_close(u->stream_fd);
319 if (u->read_smoother) {
320 pa_smoother_free(u->read_smoother);
321 u->read_smoother = NULL;
325 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
326 const char *accesstype = "rw";
327 const pa_bluetooth_transport *t;
329 if (u->transport == NULL) {
330 pa_log("Transport no longer available.");
334 if (bt_transport_is_acquired(u)) {
340 pa_log_debug("Acquiring transport %s", u->transport);
342 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
344 pa_log("Transport %s no longer available", u->transport);
345 pa_xfree(u->transport);
350 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, &u->read_link_mtu, &u->write_link_mtu);
351 if (u->stream_fd < 0)
354 u->accesstype = pa_xstrdup(accesstype);
355 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
361 pa_log_info("Transport %s resuming", u->transport);
367 /* Run from IO thread */
368 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
369 struct userdata *u = PA_SINK(o)->userdata;
370 pa_bool_t failed = FALSE;
373 pa_assert(u->sink == PA_SINK(o));
374 pa_assert(u->transport);
378 case PA_SINK_MESSAGE_SET_STATE:
380 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
382 case PA_SINK_SUSPENDED:
383 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
384 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
387 /* Stop the device if the source is suspended as well */
388 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
389 /* We deliberately ignore whether stopping
390 * actually worked. Since the stream_fd is
391 * closed it doesn't really matter */
392 bt_transport_release(u);
397 case PA_SINK_RUNNING:
398 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
401 /* Resume the device if the source was suspended as well */
402 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
403 if (bt_transport_acquire(u, TRUE) < 0)
408 case PA_SINK_UNLINKED:
410 case PA_SINK_INVALID_STATE:
415 case PA_SINK_MESSAGE_GET_LATENCY: {
417 if (u->read_smoother) {
420 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
421 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
423 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
427 ri = pa_rtclock_now() - u->started_at;
428 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
430 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
433 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
438 r = pa_sink_process_msg(o, code, data, offset, chunk);
440 return (r < 0 || !failed) ? r : -1;
443 /* Run from IO thread */
444 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
445 struct userdata *u = PA_SOURCE(o)->userdata;
446 pa_bool_t failed = FALSE;
449 pa_assert(u->source == PA_SOURCE(o));
450 pa_assert(u->transport);
454 case PA_SOURCE_MESSAGE_SET_STATE:
456 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
458 case PA_SOURCE_SUSPENDED:
459 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
460 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
463 /* Stop the device if the sink is suspended as well */
464 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
465 bt_transport_release(u);
467 if (u->read_smoother)
468 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
472 case PA_SOURCE_RUNNING:
473 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
476 /* Resume the device if the sink was suspended as well */
477 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
478 if (bt_transport_acquire(u, TRUE) < 0)
481 /* We don't resume the smoother here. Instead we
482 * wait until the first packet arrives */
485 case PA_SOURCE_UNLINKED:
487 case PA_SOURCE_INVALID_STATE:
492 case PA_SOURCE_MESSAGE_GET_LATENCY: {
495 if (u->read_smoother) {
496 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
497 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
499 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
501 *((pa_usec_t*) data) = 0;
508 r = pa_source_process_msg(o, code, data, offset, chunk);
510 return (r < 0 || !failed) ? r : -1;
513 /* Called from main thread context */
514 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
515 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
518 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
519 if (u->card->module->unload_requested)
522 pa_log_debug("Switching the profile to off due to IO thread failure.");
524 if (pa_card_set_profile(u->card, "off", FALSE) < 0)
525 pa_log_debug("Failed to switch profile to off");
532 /* Run from IO thread */
533 static int hsp_process_render(struct userdata *u) {
537 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
540 /* First, render some data */
541 if (!u->write_memchunk.memblock)
542 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
544 pa_assert(u->write_memchunk.length == u->write_block_size);
550 /* Now write that data to the socket. The socket is of type
551 * SEQPACKET, and we generated the data of the MTU size, so this
552 * should just work. */
554 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
555 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
556 pa_memblock_release(u->write_memchunk.memblock);
563 /* Retry right away if we got interrupted */
566 else if (errno == EAGAIN)
567 /* Hmm, apparently the socket was not writable, give up for now */
570 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
575 pa_assert((size_t) l <= u->write_memchunk.length);
577 if ((size_t) l != u->write_memchunk.length) {
578 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
579 (unsigned long long) l,
580 (unsigned long long) u->write_memchunk.length);
585 u->write_index += (uint64_t) u->write_memchunk.length;
586 pa_memblock_unref(u->write_memchunk.memblock);
587 pa_memchunk_reset(&u->write_memchunk);
596 /* Run from IO thread */
597 static int hsp_process_push(struct userdata *u) {
599 pa_memchunk memchunk;
602 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
603 pa_assert(u->source);
604 pa_assert(u->read_smoother);
606 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
607 memchunk.index = memchunk.length = 0;
616 pa_bool_t found_tstamp = FALSE;
619 memset(&m, 0, sizeof(m));
620 memset(&aux, 0, sizeof(aux));
621 memset(&iov, 0, sizeof(iov));
626 m.msg_controllen = sizeof(aux);
628 p = pa_memblock_acquire(memchunk.memblock);
630 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
631 l = recvmsg(u->stream_fd, &m, 0);
632 pa_memblock_release(memchunk.memblock);
636 if (l < 0 && errno == EINTR)
637 /* Retry right away if we got interrupted */
640 else if (l < 0 && errno == EAGAIN)
641 /* Hmm, apparently the socket was not readable, give up for now. */
644 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
649 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
651 memchunk.length = (size_t) l;
652 u->read_index += (uint64_t) l;
654 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
655 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
656 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
657 pa_rtclock_from_wallclock(tv);
658 tstamp = pa_timeval_load(tv);
664 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
665 tstamp = pa_rtclock_now();
668 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
669 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
671 pa_source_post(u->source, &memchunk);
677 pa_memblock_unref(memchunk.memblock);
682 /* Run from IO thread */
683 static void a2dp_prepare_buffer(struct userdata *u) {
684 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
688 if (u->a2dp.buffer_size >= min_buffer_size)
691 u->a2dp.buffer_size = 2 * min_buffer_size;
692 pa_xfree(u->a2dp.buffer);
693 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
696 /* Run from IO thread */
697 static int a2dp_process_render(struct userdata *u) {
698 struct a2dp_info *a2dp;
699 struct rtp_header *header;
700 struct rtp_payload *payload;
704 size_t to_write, to_encode;
705 unsigned frame_count;
709 pa_assert(u->profile == PROFILE_A2DP);
712 /* First, render some data */
713 if (!u->write_memchunk.memblock)
714 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
716 pa_assert(u->write_memchunk.length == u->write_block_size);
718 a2dp_prepare_buffer(u);
721 header = a2dp->buffer;
722 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
726 /* Try to create a packet of the full MTU */
728 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
729 to_encode = u->write_memchunk.length;
731 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
732 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
734 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
738 encoded = sbc_encode(&a2dp->sbc,
743 if (PA_UNLIKELY(encoded <= 0)) {
744 pa_log_error("SBC encoding error (%li)", (long) encoded);
745 pa_memblock_release(u->write_memchunk.memblock);
749 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
750 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
752 pa_assert_fp((size_t) encoded <= to_encode);
753 pa_assert_fp((size_t) encoded == a2dp->codesize);
755 pa_assert_fp((size_t) written <= to_write);
756 pa_assert_fp((size_t) written == a2dp->frame_length);
758 p = (const uint8_t*) p + encoded;
759 to_encode -= encoded;
761 d = (uint8_t*) d + written;
767 pa_memblock_release(u->write_memchunk.memblock);
769 pa_assert(to_encode == 0);
772 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
775 /* write it to the fifo */
776 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
779 header->sequence_number = htons(a2dp->seq_num++);
780 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
781 header->ssrc = htonl(1);
782 payload->frame_count = frame_count;
784 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
789 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
796 /* Retry right away if we got interrupted */
799 else if (errno == EAGAIN)
800 /* Hmm, apparently the socket was not writable, give up for now */
803 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
808 pa_assert((size_t) l <= nbytes);
810 if ((size_t) l != nbytes) {
811 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
812 (unsigned long long) l,
813 (unsigned long long) nbytes);
818 u->write_index += (uint64_t) u->write_memchunk.length;
819 pa_memblock_unref(u->write_memchunk.memblock);
820 pa_memchunk_reset(&u->write_memchunk);
830 static int a2dp_process_push(struct userdata *u) {
832 pa_memchunk memchunk;
835 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
836 pa_assert(u->source);
837 pa_assert(u->read_smoother);
839 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
840 memchunk.index = memchunk.length = 0;
843 pa_bool_t found_tstamp = FALSE;
845 struct a2dp_info *a2dp;
846 struct rtp_header *header;
847 struct rtp_payload *payload;
851 size_t to_write, to_decode;
853 a2dp_prepare_buffer(u);
856 header = a2dp->buffer;
857 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
859 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
863 if (l < 0 && errno == EINTR)
864 /* Retry right away if we got interrupted */
867 else if (l < 0 && errno == EAGAIN)
868 /* Hmm, apparently the socket was not readable, give up for now. */
871 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
876 pa_assert((size_t) l <= a2dp->buffer_size);
878 u->read_index += (uint64_t) l;
880 /* TODO: get timestamp from rtp */
882 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
883 tstamp = pa_rtclock_now();
886 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
887 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
889 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
890 to_decode = l - sizeof(*header) - sizeof(*payload);
892 d = pa_memblock_acquire(memchunk.memblock);
893 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
895 while (PA_LIKELY(to_decode > 0)) {
899 decoded = sbc_decode(&a2dp->sbc,
904 if (PA_UNLIKELY(decoded <= 0)) {
905 pa_log_error("SBC decoding error (%li)", (long) decoded);
906 pa_memblock_release(memchunk.memblock);
907 pa_memblock_unref(memchunk.memblock);
911 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
912 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
914 /* Reset frame length, it can be changed due to bitpool change */
915 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
917 pa_assert_fp((size_t) decoded <= to_decode);
918 pa_assert_fp((size_t) decoded == a2dp->frame_length);
920 pa_assert_fp((size_t) written == a2dp->codesize);
922 p = (const uint8_t*) p + decoded;
923 to_decode -= decoded;
925 d = (uint8_t*) d + written;
929 memchunk.length -= to_write;
931 pa_memblock_release(memchunk.memblock);
933 pa_source_post(u->source, &memchunk);
939 pa_memblock_unref(memchunk.memblock);
944 static void a2dp_reduce_bitpool(struct userdata *u)
946 struct a2dp_info *a2dp;
953 /* Check if bitpool is already at its limit */
954 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
957 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
959 if (bitpool < BITPOOL_DEC_LIMIT)
960 bitpool = BITPOOL_DEC_LIMIT;
962 a2dp_set_bitpool(u, bitpool);
965 static void thread_func(void *userdata) {
966 struct userdata *u = userdata;
967 unsigned do_write = 0;
968 unsigned pending_read_bytes = 0;
969 pa_bool_t writable = FALSE;
972 pa_assert(u->transport);
974 pa_log_debug("IO Thread starting up");
976 if (u->core->realtime_scheduling)
977 pa_make_realtime(u->core->realtime_priority);
979 pa_thread_mq_install(&u->thread_mq);
981 if (bt_transport_acquire(u, TRUE) < 0)
985 struct pollfd *pollfd;
987 pa_bool_t disable_timer = TRUE;
989 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
991 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
993 /* We should send two blocks to the device before we expect
996 if (u->write_index == 0 && u->read_index <= 0)
999 if (pollfd && (pollfd->revents & POLLIN)) {
1002 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1003 n_read = hsp_process_push(u);
1005 n_read = a2dp_process_push(u);
1010 /* We just read something, so we are supposed to write something, too */
1011 pending_read_bytes += n_read;
1012 do_write += pending_read_bytes / u->write_block_size;
1013 pending_read_bytes = pending_read_bytes % u->write_block_size;
1017 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1019 if (u->sink->thread_info.rewind_requested)
1020 pa_sink_process_rewind(u->sink, 0);
1023 if (pollfd->revents & POLLOUT)
1026 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1027 pa_usec_t time_passed;
1028 pa_usec_t audio_sent;
1030 /* Hmm, there is no input stream we could synchronize
1031 * to. So let's do things by time */
1033 time_passed = pa_rtclock_now() - u->started_at;
1034 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1036 if (audio_sent <= time_passed) {
1037 pa_usec_t audio_to_send = time_passed - audio_sent;
1039 /* Never try to catch up for more than 100ms */
1040 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1041 pa_usec_t skip_usec;
1042 uint64_t skip_bytes;
1044 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1045 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1047 if (skip_bytes > 0) {
1050 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1051 (unsigned long long) skip_usec,
1052 (unsigned long long) skip_bytes);
1054 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1055 pa_memblock_unref(tmp.memblock);
1056 u->write_index += skip_bytes;
1058 if (u->profile == PROFILE_A2DP)
1059 a2dp_reduce_bitpool(u);
1064 pending_read_bytes = 0;
1068 if (writable && do_write > 0) {
1071 if (u->write_index <= 0)
1072 u->started_at = pa_rtclock_now();
1074 if (u->profile == PROFILE_A2DP) {
1075 if ((n_written = a2dp_process_render(u)) < 0)
1078 if ((n_written = hsp_process_render(u)) < 0)
1083 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1085 do_write -= n_written;
1089 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1090 pa_usec_t sleep_for;
1091 pa_usec_t time_passed, next_write_at;
1094 /* Hmm, there is no input stream we could synchronize
1095 * to. So let's estimate when we need to wake up the latest */
1096 time_passed = pa_rtclock_now() - u->started_at;
1097 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1098 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1099 /* 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); */
1101 /* drop stream every 500 ms */
1102 sleep_for = PA_USEC_PER_MSEC * 500;
1104 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1105 disable_timer = FALSE;
1111 pa_rtpoll_set_timer_disabled(u->rtpoll);
1113 /* Hmm, nothing to do. Let's sleep */
1115 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1116 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1118 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
1119 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1123 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1124 bt_transport_release(u);
1128 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1130 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1131 pa_log_info("FD error: %s%s%s%s",
1132 pollfd->revents & POLLERR ? "POLLERR " :"",
1133 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1134 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1135 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1141 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1142 pa_log_debug("IO thread failed");
1143 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1144 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1147 pa_log_debug("IO thread shutting down");
1150 static pa_bt_audio_state_t parse_state_property_change(DBusMessage *m) {
1151 DBusMessageIter iter;
1152 DBusMessageIter variant;
1155 pa_bt_audio_state_t state;
1157 if (!dbus_message_iter_init(m, &iter)) {
1158 pa_log("Failed to parse PropertyChanged");
1159 return PA_BT_AUDIO_STATE_INVALID;
1162 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1163 pa_log("Property name not a string");
1164 return PA_BT_AUDIO_STATE_INVALID;
1167 dbus_message_iter_get_basic(&iter, &key);
1169 if (!pa_streq(key, "State"))
1170 return PA_BT_AUDIO_STATE_INVALID;
1172 if (!dbus_message_iter_next(&iter)) {
1173 pa_log("Property value missing");
1174 return PA_BT_AUDIO_STATE_INVALID;
1177 dbus_message_iter_recurse(&iter, &variant);
1179 if (dbus_message_iter_get_arg_type(&variant) != DBUS_TYPE_STRING) {
1180 pa_log("Property value not a string");
1181 return PA_BT_AUDIO_STATE_INVALID;
1184 dbus_message_iter_get_basic(&variant, &value);
1186 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m), value);
1188 state = pa_bt_audio_state_from_string(value);
1190 if (state == PA_BT_AUDIO_STATE_INVALID)
1191 pa_log("Unexpected value for property 'State': '%s'", value);
1196 /* Run from main thread */
1197 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1203 pa_assert_se(u = userdata);
1205 dbus_error_init(&err);
1207 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1208 dbus_message_get_interface(m),
1209 dbus_message_get_path(m),
1210 dbus_message_get_member(m));
1212 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1215 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1216 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1221 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1222 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1226 if (u->profile == PROFILE_HSP) {
1227 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1228 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1230 /* increment volume by one to correct rounding errors */
1231 if (volume < PA_VOLUME_NORM)
1234 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1235 pa_sink_volume_changed(u->sink, &v);
1237 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1238 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1240 /* increment volume by one to correct rounding errors */
1241 if (volume < PA_VOLUME_NORM)
1244 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1245 pa_source_volume_changed(u->source, &v);
1248 } else if (dbus_message_is_signal(m, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1249 pa_bt_audio_state_t state = parse_state_property_change(m);
1252 case PA_BT_AUDIO_STATE_INVALID:
1253 case PA_BT_AUDIO_STATE_DISCONNECTED:
1254 case PA_BT_AUDIO_STATE_CONNECTED:
1255 case PA_BT_AUDIO_STATE_CONNECTING:
1258 case PA_BT_AUDIO_STATE_PLAYING:
1260 pa_log_debug("Changing profile to hfgw");
1261 if (pa_card_set_profile(u->card, "hfgw", FALSE) < 0)
1262 pa_log("Failed to change profile to hfgw");
1269 dbus_error_free(&err);
1271 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1274 /* Run from main thread */
1275 static void sink_set_volume_cb(pa_sink *s) {
1285 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1286 u = pa_shared_get(s->core, k);
1290 pa_assert(u->sink == s);
1291 pa_assert(u->profile == PROFILE_HSP);
1293 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1295 if (gain > HSP_MAX_GAIN)
1296 gain = HSP_MAX_GAIN;
1298 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1300 /* increment volume by one to correct rounding errors */
1301 if (volume < PA_VOLUME_NORM)
1304 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1306 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1307 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1308 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1309 dbus_message_unref(m);
1312 /* Run from main thread */
1313 static void source_set_volume_cb(pa_source *s) {
1323 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1324 u = pa_shared_get(s->core, k);
1328 pa_assert(u->source == s);
1329 pa_assert(u->profile == PROFILE_HSP);
1331 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1333 if (gain > HSP_MAX_GAIN)
1334 gain = HSP_MAX_GAIN;
1336 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1338 /* increment volume by one to correct rounding errors */
1339 if (volume < PA_VOLUME_NORM)
1342 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1344 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1345 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1346 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1347 dbus_message_unref(m);
1350 /* Run from main thread */
1351 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1357 pa_assert(device_id);
1358 pa_assert(namereg_fail);
1360 t = pa_sprintf_malloc("%s_name", type);
1361 n = pa_modargs_get_value(ma, t, NULL);
1365 *namereg_fail = TRUE;
1366 return pa_xstrdup(n);
1369 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1370 *namereg_fail = TRUE;
1373 *namereg_fail = FALSE;
1376 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1379 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1381 pa_assert(USE_SCO_OVER_PCM(u));
1383 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1384 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1386 if (u->stream_fd >= 0)
1389 pa_log_debug("Resuming SCO over PCM");
1390 if (init_profile(u) < 0) {
1391 pa_log("Can't resume SCO over PCM");
1395 return bt_transport_acquire(u, TRUE);
1399 if (u->stream_fd < 0)
1402 pa_log_debug("Closing SCO over PCM");
1404 bt_transport_release(u);
1410 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1412 pa_sink_assert_ref(s);
1415 if (s != u->hsp.sco_sink)
1418 sco_over_pcm_state_update(u, TRUE);
1423 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1425 pa_source_assert_ref(s);
1428 if (s != u->hsp.sco_source)
1431 sco_over_pcm_state_update(u, TRUE);
1436 static pa_hook_result_t nrec_changed_cb(pa_bluetooth_transport *t, void *call_data, struct userdata *u) {
1442 p = pa_proplist_new();
1443 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1444 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1445 pa_proplist_free(p);
1450 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1452 pa_sink_new_data *sink_new_data;
1453 pa_source_new_data *source_new_data;
1455 pa_device_port *port;
1457 if (direction == PA_DIRECTION_OUTPUT) {
1458 data.sink_new_data = sink_or_source_new_data;
1459 data.sink_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1461 data.source_new_data = sink_or_source_new_data;
1462 data.source_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1465 switch (u->profile) {
1467 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1468 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1469 pa_device_port_ref(port);
1472 case PROFILE_A2DP_SOURCE:
1473 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1474 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1475 pa_device_port_ref(port);
1479 if (direction == PA_DIRECTION_OUTPUT) {
1480 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1481 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1483 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1484 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1486 pa_device_port_ref(port);
1490 if (direction == PA_DIRECTION_OUTPUT) {
1491 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1492 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1494 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1495 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1497 pa_device_port_ref(port);
1501 pa_assert_not_reached();
1505 static const char *profile_to_string(enum profile profile) {
1509 case PROFILE_A2DP_SOURCE:
1510 return "a2dp_source";
1516 pa_assert_not_reached();
1520 /* Run from main thread */
1521 static int add_sink(struct userdata *u) {
1524 if (USE_SCO_OVER_PCM(u)) {
1527 u->sink = u->hsp.sco_sink;
1528 p = pa_proplist_new();
1529 pa_proplist_sets(p, "bluetooth.protocol", profile_to_string(u->profile));
1530 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1531 pa_proplist_free(p);
1533 if (!u->hsp.sink_state_changed_slot)
1534 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);
1537 pa_sink_new_data data;
1540 pa_sink_new_data_init(&data);
1541 data.driver = __FILE__;
1542 data.module = u->module;
1543 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1544 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1545 if (u->profile == PROFILE_HSP)
1546 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1547 data.card = u->card;
1548 data.name = get_name("sink", u->modargs, u->address, &b);
1549 data.namereg_fail = b;
1551 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1552 pa_log("Invalid properties");
1553 pa_sink_new_data_done(&data);
1556 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1558 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1559 pa_sink_new_data_done(&data);
1562 pa_log_error("Failed to create sink");
1566 u->sink->userdata = u;
1567 u->sink->parent.process_msg = sink_process_msg;
1569 pa_sink_set_max_request(u->sink, u->write_block_size);
1570 pa_sink_set_fixed_latency(u->sink,
1571 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1572 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
1575 if (u->profile == PROFILE_HSP) {
1576 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1577 u->sink->n_volume_steps = 16;
1579 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1580 pa_shared_set(u->core, k, u);
1587 /* Run from main thread */
1588 static int add_source(struct userdata *u) {
1591 if (USE_SCO_OVER_PCM(u)) {
1592 u->source = u->hsp.sco_source;
1593 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", profile_to_string(u->profile));
1595 if (!u->hsp.source_state_changed_slot)
1596 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);
1599 pa_source_new_data data;
1602 pa_source_new_data_init(&data);
1603 data.driver = __FILE__;
1604 data.module = u->module;
1605 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1606 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1607 if (u->profile == PROFILE_HSP)
1608 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1610 data.card = u->card;
1611 data.name = get_name("source", u->modargs, u->address, &b);
1612 data.namereg_fail = b;
1614 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1615 pa_log("Invalid properties");
1616 pa_source_new_data_done(&data);
1620 connect_ports(u, &data, PA_DIRECTION_INPUT);
1621 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1622 pa_source_new_data_done(&data);
1625 pa_log_error("Failed to create source");
1629 u->source->userdata = u;
1630 u->source->parent.process_msg = source_process_msg;
1632 pa_source_set_fixed_latency(u->source,
1633 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
1634 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
1637 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1638 pa_bluetooth_transport *t;
1639 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1641 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1643 if (!u->hsp.nrec_changed_slot)
1644 u->hsp.nrec_changed_slot = pa_hook_connect(&t->hooks[PA_BLUETOOTH_TRANSPORT_HOOK_NREC_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) nrec_changed_cb, u);
1647 if (u->profile == PROFILE_HSP) {
1648 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1649 u->source->n_volume_steps = 16;
1651 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1652 pa_shared_set(u->core, k, u);
1659 static void bt_transport_config_a2dp(struct userdata *u) {
1660 const pa_bluetooth_transport *t;
1661 struct a2dp_info *a2dp = &u->a2dp;
1664 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1667 config = (a2dp_sbc_t *) t->config;
1669 u->sample_spec.format = PA_SAMPLE_S16LE;
1671 if (a2dp->sbc_initialized)
1672 sbc_reinit(&a2dp->sbc, 0);
1674 sbc_init(&a2dp->sbc, 0);
1675 a2dp->sbc_initialized = TRUE;
1677 switch (config->frequency) {
1678 case BT_SBC_SAMPLING_FREQ_16000:
1679 a2dp->sbc.frequency = SBC_FREQ_16000;
1680 u->sample_spec.rate = 16000U;
1682 case BT_SBC_SAMPLING_FREQ_32000:
1683 a2dp->sbc.frequency = SBC_FREQ_32000;
1684 u->sample_spec.rate = 32000U;
1686 case BT_SBC_SAMPLING_FREQ_44100:
1687 a2dp->sbc.frequency = SBC_FREQ_44100;
1688 u->sample_spec.rate = 44100U;
1690 case BT_SBC_SAMPLING_FREQ_48000:
1691 a2dp->sbc.frequency = SBC_FREQ_48000;
1692 u->sample_spec.rate = 48000U;
1695 pa_assert_not_reached();
1698 switch (config->channel_mode) {
1699 case BT_A2DP_CHANNEL_MODE_MONO:
1700 a2dp->sbc.mode = SBC_MODE_MONO;
1701 u->sample_spec.channels = 1;
1703 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
1704 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1705 u->sample_spec.channels = 2;
1707 case BT_A2DP_CHANNEL_MODE_STEREO:
1708 a2dp->sbc.mode = SBC_MODE_STEREO;
1709 u->sample_spec.channels = 2;
1711 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
1712 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1713 u->sample_spec.channels = 2;
1716 pa_assert_not_reached();
1719 switch (config->allocation_method) {
1720 case BT_A2DP_ALLOCATION_SNR:
1721 a2dp->sbc.allocation = SBC_AM_SNR;
1723 case BT_A2DP_ALLOCATION_LOUDNESS:
1724 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1727 pa_assert_not_reached();
1730 switch (config->subbands) {
1731 case BT_A2DP_SUBBANDS_4:
1732 a2dp->sbc.subbands = SBC_SB_4;
1734 case BT_A2DP_SUBBANDS_8:
1735 a2dp->sbc.subbands = SBC_SB_8;
1738 pa_assert_not_reached();
1741 switch (config->block_length) {
1742 case BT_A2DP_BLOCK_LENGTH_4:
1743 a2dp->sbc.blocks = SBC_BLK_4;
1745 case BT_A2DP_BLOCK_LENGTH_8:
1746 a2dp->sbc.blocks = SBC_BLK_8;
1748 case BT_A2DP_BLOCK_LENGTH_12:
1749 a2dp->sbc.blocks = SBC_BLK_12;
1751 case BT_A2DP_BLOCK_LENGTH_16:
1752 a2dp->sbc.blocks = SBC_BLK_16;
1755 pa_assert_not_reached();
1758 a2dp->min_bitpool = config->min_bitpool;
1759 a2dp->max_bitpool = config->max_bitpool;
1761 /* Set minimum bitpool for source to get the maximum possible block_size */
1762 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1763 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1764 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1766 u->read_block_size =
1767 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1768 / a2dp->frame_length * a2dp->codesize;
1770 u->write_block_size =
1771 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1772 / a2dp->frame_length * a2dp->codesize;
1774 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1775 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1778 static void bt_transport_config(struct userdata *u) {
1779 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1780 u->read_block_size = u->read_link_mtu;
1781 u->write_block_size = u->write_link_mtu;
1782 u->sample_spec.format = PA_SAMPLE_S16LE;
1783 u->sample_spec.channels = 1;
1784 u->sample_spec.rate = 8000;
1786 bt_transport_config_a2dp(u);
1789 /* Run from main thread */
1790 static int setup_bt(struct userdata *u) {
1791 const pa_bluetooth_device *d;
1792 const pa_bluetooth_transport *t;
1796 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1797 pa_log_error("Failed to get device object.");
1801 /* release transport if exist */
1803 bt_transport_release(u);
1804 pa_xfree(u->transport);
1805 u->transport = NULL;
1808 /* check if profile has a transport */
1809 t = pa_bluetooth_device_get_transport(d, u->profile);
1811 pa_log_warn("Profile has no transport");
1815 u->transport = pa_xstrdup(t->path);
1817 if (bt_transport_acquire(u, FALSE) < 0)
1820 bt_transport_config(u);
1825 /* Run from main thread */
1826 static int init_profile(struct userdata *u) {
1829 pa_assert(u->profile != PROFILE_OFF);
1831 if (setup_bt(u) < 0)
1834 if (u->profile == PROFILE_A2DP ||
1835 u->profile == PROFILE_HSP ||
1836 u->profile == PROFILE_HFGW)
1837 if (add_sink(u) < 0)
1840 if (u->profile == PROFILE_HSP ||
1841 u->profile == PROFILE_A2DP_SOURCE ||
1842 u->profile == PROFILE_HFGW)
1843 if (add_source(u) < 0)
1849 /* Run from main thread */
1850 static void stop_thread(struct userdata *u) {
1856 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1857 pa_thread_free(u->thread);
1861 if (u->rtpoll_item) {
1862 pa_rtpoll_item_free(u->rtpoll_item);
1863 u->rtpoll_item = NULL;
1866 if (u->hsp.sink_state_changed_slot) {
1867 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1868 u->hsp.sink_state_changed_slot = NULL;
1871 if (u->hsp.source_state_changed_slot) {
1872 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1873 u->hsp.source_state_changed_slot = NULL;
1876 if (u->hsp.nrec_changed_slot) {
1877 pa_hook_slot_free(u->hsp.nrec_changed_slot);
1878 u->hsp.nrec_changed_slot = NULL;
1882 if (u->profile == PROFILE_HSP) {
1883 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1884 pa_shared_remove(u->core, k);
1888 pa_sink_unref(u->sink);
1893 if (u->profile == PROFILE_HSP) {
1894 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1895 pa_shared_remove(u->core, k);
1899 pa_source_unref(u->source);
1904 pa_thread_mq_done(&u->thread_mq);
1906 pa_rtpoll_free(u->rtpoll);
1910 if (u->read_smoother) {
1911 pa_smoother_free(u->read_smoother);
1912 u->read_smoother = NULL;
1916 /* Run from main thread */
1917 static int start_thread(struct userdata *u) {
1919 pa_assert(!u->thread);
1920 pa_assert(!u->rtpoll);
1921 pa_assert(!u->rtpoll_item);
1923 u->rtpoll = pa_rtpoll_new();
1924 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1926 if (USE_SCO_OVER_PCM(u)) {
1927 if (sco_over_pcm_state_update(u, FALSE) < 0) {
1931 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1932 pa_shared_remove(u->core, k);
1937 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1938 pa_shared_remove(u->core, k);
1945 pa_sink_ref(u->sink);
1946 pa_source_ref(u->source);
1947 /* FIXME: monitor stream_fd error */
1951 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1952 pa_log_error("Failed to create IO thread");
1958 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1959 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1960 pa_sink_put(u->sink);
1962 if (u->sink->set_volume)
1963 u->sink->set_volume(u->sink);
1967 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1968 pa_source_set_rtpoll(u->source, u->rtpoll);
1969 pa_source_put(u->source);
1971 if (u->source->set_volume)
1972 u->source->set_volume(u->source);
1978 static void save_sco_volume_callbacks(struct userdata *u) {
1980 pa_assert(USE_SCO_OVER_PCM(u));
1982 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
1983 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
1986 static void restore_sco_volume_callbacks(struct userdata *u) {
1988 pa_assert(USE_SCO_OVER_PCM(u));
1990 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
1991 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
1994 /* Run from main thread */
1995 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1998 pa_queue *inputs = NULL, *outputs = NULL;
1999 const pa_bluetooth_device *device;
2002 pa_assert(new_profile);
2003 pa_assert_se(u = c->userdata);
2005 d = PA_CARD_PROFILE_DATA(new_profile);
2007 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2008 pa_log_error("Failed to get device object.");
2012 /* The state signal is sent by bluez, so it is racy to check
2013 strictly for CONNECTED, we should also accept STREAMING state
2014 as being good enough. However, if the profile is used
2015 concurrently (which is unlikely), ipc will fail later on, and
2016 module will be unloaded. */
2017 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2018 pa_log_warn("HSP is not connected, refused to switch profile");
2020 } else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2021 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2023 } else if (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) {
2024 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2026 } else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2027 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2032 inputs = pa_sink_move_all_start(u->sink, NULL);
2034 if (!USE_SCO_OVER_PCM(u))
2035 pa_sink_unlink(u->sink);
2039 outputs = pa_source_move_all_start(u->source, NULL);
2041 if (!USE_SCO_OVER_PCM(u))
2042 pa_source_unlink(u->source);
2047 if (u->profile != PROFILE_OFF && u->transport) {
2048 bt_transport_release(u);
2049 pa_xfree(u->transport);
2050 u->transport = NULL;
2053 if (USE_SCO_OVER_PCM(u))
2054 restore_sco_volume_callbacks(u);
2057 u->sample_spec = u->requested_sample_spec;
2059 if (USE_SCO_OVER_PCM(u))
2060 save_sco_volume_callbacks(u);
2062 if (u->profile != PROFILE_OFF)
2065 if (u->sink || u->source)
2070 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2072 pa_sink_move_all_fail(inputs);
2077 pa_source_move_all_finish(u->source, outputs, FALSE);
2079 pa_source_move_all_fail(outputs);
2085 static void create_ports_for_profile(struct userdata *u, pa_card_new_data *card_new_data, pa_card_profile *profile) {
2086 pa_device_port *port;
2089 d = PA_CARD_PROFILE_DATA(profile);
2093 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2094 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2095 port->is_output = 1;
2097 port->priority = profile->priority * 100;
2098 pa_hashmap_put(port->profiles, profile->name, profile);
2101 case PROFILE_A2DP_SOURCE:
2102 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2103 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2104 port->is_output = 0;
2106 port->priority = profile->priority * 100;
2107 pa_hashmap_put(port->profiles, profile->name, profile);
2111 pa_assert_se(port = pa_device_port_new(u->core, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2112 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2113 port->is_output = 1;
2115 port->priority = profile->priority * 100;
2116 pa_hashmap_put(port->profiles, profile->name, profile);
2118 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2119 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2120 port->is_output = 0;
2122 port->priority = profile->priority * 100;
2123 pa_hashmap_put(port->profiles, profile->name, profile);
2127 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2128 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2129 port->is_output = 1;
2131 port->priority = profile->priority * 100;
2132 pa_hashmap_put(port->profiles, profile->name, profile);
2134 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2135 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2136 port->is_output = 0;
2138 port->priority = profile->priority * 100;
2139 pa_hashmap_put(port->profiles, profile->name, profile);
2143 pa_assert_not_reached();
2148 /* Run from main thread */
2149 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2150 pa_card_new_data data;
2156 const char *default_profile;
2161 pa_card_new_data_init(&data);
2162 data.driver = __FILE__;
2163 data.module = u->module;
2165 n = pa_bluetooth_cleanup_name(device->name);
2166 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2168 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2169 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2170 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2171 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2172 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2173 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2174 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2175 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2176 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2177 data.name = get_name("card", u->modargs, device->address, &b);
2178 data.namereg_fail = b;
2180 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2181 pa_log("Invalid properties");
2182 pa_card_new_data_done(&data);
2186 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2188 /* we base hsp/a2dp availability on UUIDs.
2189 Ideally, it would be based on "Connected" state, but
2190 we can't afford to wait for this information when
2191 we are loaded with profile="hsp", for instance */
2192 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2193 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2197 p->max_sink_channels = 2;
2198 p->max_source_channels = 0;
2200 d = PA_CARD_PROFILE_DATA(p);
2202 create_ports_for_profile(u, &data, p);
2204 pa_hashmap_put(data.profiles, p->name, p);
2207 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2208 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2212 p->max_sink_channels = 0;
2213 p->max_source_channels = 2;
2215 d = PA_CARD_PROFILE_DATA(p);
2216 *d = PROFILE_A2DP_SOURCE;
2217 create_ports_for_profile(u, &data, p);
2219 pa_hashmap_put(data.profiles, p->name, p);
2222 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2223 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2224 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2228 p->max_sink_channels = 1;
2229 p->max_source_channels = 1;
2231 d = PA_CARD_PROFILE_DATA(p);
2233 create_ports_for_profile(u, &data, p);
2235 pa_hashmap_put(data.profiles, p->name, p);
2238 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2239 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2243 p->max_sink_channels = 1;
2244 p->max_source_channels = 1;
2246 d = PA_CARD_PROFILE_DATA(p);
2248 create_ports_for_profile(u, &data, p);
2250 pa_hashmap_put(data.profiles, p->name, p);
2253 pa_assert(!pa_hashmap_isempty(data.profiles));
2255 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2256 d = PA_CARD_PROFILE_DATA(p);
2258 pa_hashmap_put(data.profiles, p->name, p);
2260 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2261 if (pa_hashmap_get(data.profiles, default_profile))
2262 pa_card_new_data_set_profile(&data, default_profile);
2264 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2267 u->card = pa_card_new(u->core, &data);
2268 pa_card_new_data_done(&data);
2271 pa_log("Failed to allocate card.");
2275 u->card->userdata = u;
2276 u->card->set_profile = card_set_profile;
2278 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2280 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2281 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2282 (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) ||
2283 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2284 pa_log_warn("Default profile not connected, selecting off profile");
2285 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2286 u->card->save_profile = FALSE;
2289 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2292 if (USE_SCO_OVER_PCM(u))
2293 save_sco_volume_callbacks(u);
2298 /* Run from main thread */
2299 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2300 const pa_bluetooth_device *d = NULL;
2304 if (!address && !path) {
2305 pa_log_error("Failed to get device address/path from module arguments.");
2310 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2311 pa_log_error("%s is not a valid BlueZ audio device.", path);
2315 if (address && !(pa_streq(d->address, address))) {
2316 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2321 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2322 pa_log_error("%s is not known.", address);
2328 u->address = pa_xstrdup(d->address);
2329 u->path = pa_xstrdup(d->path);
2335 /* Run from main thread */
2336 static int setup_dbus(struct userdata *u) {
2339 dbus_error_init(&err);
2341 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2343 if (dbus_error_is_set(&err) || !u->connection) {
2344 pa_log("Failed to get D-Bus connection: %s", err.message);
2345 dbus_error_free(&err);
2352 int pa__init(pa_module* m) {
2356 const char *address, *path;
2358 char *mike, *speaker;
2359 const pa_bluetooth_device *device;
2363 dbus_error_init(&err);
2365 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2366 pa_log_error("Failed to parse module arguments");
2370 m->userdata = u = pa_xnew0(struct userdata, 1);
2374 u->sample_spec = m->core->default_sample_spec;
2377 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2378 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2379 pa_log("SCO sink not found");
2383 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2384 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2385 pa_log("SCO source not found");
2389 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2390 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2391 pa_log_error("Failed to get rate from module arguments");
2395 u->auto_connect = TRUE;
2396 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2397 pa_log("Failed to parse auto_connect= argument");
2401 channels = u->sample_spec.channels;
2402 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2403 channels <= 0 || channels > PA_CHANNELS_MAX) {
2404 pa_log_error("Failed to get channels from module arguments");
2407 u->sample_spec.channels = (uint8_t) channels;
2408 u->requested_sample_spec = u->sample_spec;
2410 address = pa_modargs_get_value(ma, "address", NULL);
2411 path = pa_modargs_get_value(ma, "path", NULL);
2413 if (setup_dbus(u) < 0)
2416 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2419 if (!(device = find_device(u, address, path)))
2422 /* Add the card structure. This will also initialize the default profile */
2423 if (add_card(u, device) < 0)
2426 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2429 u->msg->parent.process_msg = device_process_msg;
2430 u->msg->card = u->card;
2432 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2433 pa_log_error("Failed to add filter function");
2436 u->filter_added = TRUE;
2438 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2439 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2441 if (pa_dbus_add_matches(
2442 pa_dbus_connection_get(u->connection), &err,
2445 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2446 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2452 pa_log("Failed to add D-Bus matches: %s", err.message);
2459 if (u->profile != PROFILE_OFF)
2460 if (init_profile(u) < 0)
2463 if (u->sink || u->source)
2464 if (start_thread(u) < 0)
2473 dbus_error_free(&err);
2478 int pa__get_n_used(pa_module *m) {
2482 pa_assert_se(u = m->userdata);
2485 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2486 (u->source ? pa_source_linked_by(u->source) : 0);
2489 void pa__done(pa_module *m) {
2494 if (!(u = m->userdata))
2497 if (u->sink && !USE_SCO_OVER_PCM(u))
2498 pa_sink_unlink(u->sink);
2500 if (u->source && !USE_SCO_OVER_PCM(u))
2501 pa_source_unlink(u->source);
2505 if (USE_SCO_OVER_PCM(u))
2506 restore_sco_volume_callbacks(u);
2508 if (u->connection) {
2511 char *speaker, *mike;
2512 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2513 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2515 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
2516 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2517 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2524 if (u->filter_added)
2525 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2527 pa_dbus_connection_unref(u->connection);
2534 pa_card_free(u->card);
2536 if (u->read_smoother)
2537 pa_smoother_free(u->read_smoother);
2540 pa_xfree(u->a2dp.buffer);
2542 sbc_finish(&u->a2dp.sbc);
2545 pa_modargs_free(u->modargs);
2547 pa_xfree(u->address);
2551 bt_transport_release(u);
2552 pa_xfree(u->transport);
2556 pa_bluetooth_discovery_unref(u->discovery);