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 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1524 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1528 /* Run from main thread */
1529 static int add_sink(struct userdata *u) {
1532 if (USE_SCO_OVER_PCM(u)) {
1535 u->sink = u->hsp.sco_sink;
1536 p = pa_proplist_new();
1537 pa_proplist_sets(p, "bluetooth.protocol", profile_to_string(u->profile));
1538 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1539 pa_proplist_free(p);
1541 if (!u->hsp.sink_state_changed_slot)
1542 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);
1545 pa_sink_new_data data;
1548 pa_sink_new_data_init(&data);
1549 data.driver = __FILE__;
1550 data.module = u->module;
1551 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1552 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1553 if (u->profile == PROFILE_HSP)
1554 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1555 data.card = u->card;
1556 data.name = get_name("sink", u->modargs, u->address, &b);
1557 data.namereg_fail = b;
1559 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1560 pa_log("Invalid properties");
1561 pa_sink_new_data_done(&data);
1564 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1566 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1567 pa_sink_new_data_done(&data);
1570 pa_log_error("Failed to create sink");
1574 u->sink->userdata = u;
1575 u->sink->parent.process_msg = sink_process_msg;
1576 u->sink->set_port = sink_set_port_cb;
1578 pa_sink_set_max_request(u->sink, u->write_block_size);
1579 pa_sink_set_fixed_latency(u->sink,
1580 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1581 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
1584 if (u->profile == PROFILE_HSP) {
1585 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1586 u->sink->n_volume_steps = 16;
1588 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1589 pa_shared_set(u->core, k, u);
1596 /* Run from main thread */
1597 static int add_source(struct userdata *u) {
1600 if (USE_SCO_OVER_PCM(u)) {
1601 u->source = u->hsp.sco_source;
1602 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", profile_to_string(u->profile));
1604 if (!u->hsp.source_state_changed_slot)
1605 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);
1608 pa_source_new_data data;
1611 pa_source_new_data_init(&data);
1612 data.driver = __FILE__;
1613 data.module = u->module;
1614 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1615 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1616 if (u->profile == PROFILE_HSP)
1617 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1619 data.card = u->card;
1620 data.name = get_name("source", u->modargs, u->address, &b);
1621 data.namereg_fail = b;
1623 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1624 pa_log("Invalid properties");
1625 pa_source_new_data_done(&data);
1629 connect_ports(u, &data, PA_DIRECTION_INPUT);
1630 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1631 pa_source_new_data_done(&data);
1634 pa_log_error("Failed to create source");
1638 u->source->userdata = u;
1639 u->source->parent.process_msg = source_process_msg;
1640 u->source->set_port = source_set_port_cb;
1642 pa_source_set_fixed_latency(u->source,
1643 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
1644 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
1647 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1648 pa_bluetooth_transport *t;
1649 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1651 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1653 if (!u->hsp.nrec_changed_slot)
1654 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);
1657 if (u->profile == PROFILE_HSP) {
1658 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1659 u->source->n_volume_steps = 16;
1661 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1662 pa_shared_set(u->core, k, u);
1669 static void bt_transport_config_a2dp(struct userdata *u) {
1670 const pa_bluetooth_transport *t;
1671 struct a2dp_info *a2dp = &u->a2dp;
1674 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1677 config = (a2dp_sbc_t *) t->config;
1679 u->sample_spec.format = PA_SAMPLE_S16LE;
1681 if (a2dp->sbc_initialized)
1682 sbc_reinit(&a2dp->sbc, 0);
1684 sbc_init(&a2dp->sbc, 0);
1685 a2dp->sbc_initialized = TRUE;
1687 switch (config->frequency) {
1688 case BT_SBC_SAMPLING_FREQ_16000:
1689 a2dp->sbc.frequency = SBC_FREQ_16000;
1690 u->sample_spec.rate = 16000U;
1692 case BT_SBC_SAMPLING_FREQ_32000:
1693 a2dp->sbc.frequency = SBC_FREQ_32000;
1694 u->sample_spec.rate = 32000U;
1696 case BT_SBC_SAMPLING_FREQ_44100:
1697 a2dp->sbc.frequency = SBC_FREQ_44100;
1698 u->sample_spec.rate = 44100U;
1700 case BT_SBC_SAMPLING_FREQ_48000:
1701 a2dp->sbc.frequency = SBC_FREQ_48000;
1702 u->sample_spec.rate = 48000U;
1705 pa_assert_not_reached();
1708 switch (config->channel_mode) {
1709 case BT_A2DP_CHANNEL_MODE_MONO:
1710 a2dp->sbc.mode = SBC_MODE_MONO;
1711 u->sample_spec.channels = 1;
1713 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
1714 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1715 u->sample_spec.channels = 2;
1717 case BT_A2DP_CHANNEL_MODE_STEREO:
1718 a2dp->sbc.mode = SBC_MODE_STEREO;
1719 u->sample_spec.channels = 2;
1721 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
1722 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1723 u->sample_spec.channels = 2;
1726 pa_assert_not_reached();
1729 switch (config->allocation_method) {
1730 case BT_A2DP_ALLOCATION_SNR:
1731 a2dp->sbc.allocation = SBC_AM_SNR;
1733 case BT_A2DP_ALLOCATION_LOUDNESS:
1734 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1737 pa_assert_not_reached();
1740 switch (config->subbands) {
1741 case BT_A2DP_SUBBANDS_4:
1742 a2dp->sbc.subbands = SBC_SB_4;
1744 case BT_A2DP_SUBBANDS_8:
1745 a2dp->sbc.subbands = SBC_SB_8;
1748 pa_assert_not_reached();
1751 switch (config->block_length) {
1752 case BT_A2DP_BLOCK_LENGTH_4:
1753 a2dp->sbc.blocks = SBC_BLK_4;
1755 case BT_A2DP_BLOCK_LENGTH_8:
1756 a2dp->sbc.blocks = SBC_BLK_8;
1758 case BT_A2DP_BLOCK_LENGTH_12:
1759 a2dp->sbc.blocks = SBC_BLK_12;
1761 case BT_A2DP_BLOCK_LENGTH_16:
1762 a2dp->sbc.blocks = SBC_BLK_16;
1765 pa_assert_not_reached();
1768 a2dp->min_bitpool = config->min_bitpool;
1769 a2dp->max_bitpool = config->max_bitpool;
1771 /* Set minimum bitpool for source to get the maximum possible block_size */
1772 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1773 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1774 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1776 u->read_block_size =
1777 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1778 / a2dp->frame_length * a2dp->codesize;
1780 u->write_block_size =
1781 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1782 / a2dp->frame_length * a2dp->codesize;
1784 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1785 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1788 static void bt_transport_config(struct userdata *u) {
1789 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1790 u->read_block_size = u->read_link_mtu;
1791 u->write_block_size = u->write_link_mtu;
1792 u->sample_spec.format = PA_SAMPLE_S16LE;
1793 u->sample_spec.channels = 1;
1794 u->sample_spec.rate = 8000;
1796 bt_transport_config_a2dp(u);
1799 /* Run from main thread */
1800 static int setup_bt(struct userdata *u) {
1801 const pa_bluetooth_device *d;
1802 const pa_bluetooth_transport *t;
1806 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1807 pa_log_error("Failed to get device object.");
1811 /* release transport if exist */
1813 bt_transport_release(u);
1814 pa_xfree(u->transport);
1815 u->transport = NULL;
1818 /* check if profile has a transport */
1819 t = pa_bluetooth_device_get_transport(d, u->profile);
1821 pa_log_warn("Profile has no transport");
1825 u->transport = pa_xstrdup(t->path);
1827 if (bt_transport_acquire(u, FALSE) < 0)
1830 bt_transport_config(u);
1835 /* Run from main thread */
1836 static int init_profile(struct userdata *u) {
1839 pa_assert(u->profile != PROFILE_OFF);
1841 if (setup_bt(u) < 0)
1844 if (u->profile == PROFILE_A2DP ||
1845 u->profile == PROFILE_HSP ||
1846 u->profile == PROFILE_HFGW)
1847 if (add_sink(u) < 0)
1850 if (u->profile == PROFILE_HSP ||
1851 u->profile == PROFILE_A2DP_SOURCE ||
1852 u->profile == PROFILE_HFGW)
1853 if (add_source(u) < 0)
1859 /* Run from main thread */
1860 static void stop_thread(struct userdata *u) {
1866 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1867 pa_thread_free(u->thread);
1871 if (u->rtpoll_item) {
1872 pa_rtpoll_item_free(u->rtpoll_item);
1873 u->rtpoll_item = NULL;
1876 if (u->hsp.sink_state_changed_slot) {
1877 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1878 u->hsp.sink_state_changed_slot = NULL;
1881 if (u->hsp.source_state_changed_slot) {
1882 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1883 u->hsp.source_state_changed_slot = NULL;
1886 if (u->hsp.nrec_changed_slot) {
1887 pa_hook_slot_free(u->hsp.nrec_changed_slot);
1888 u->hsp.nrec_changed_slot = NULL;
1892 if (u->profile == PROFILE_HSP) {
1893 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1894 pa_shared_remove(u->core, k);
1898 pa_sink_unref(u->sink);
1903 if (u->profile == PROFILE_HSP) {
1904 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1905 pa_shared_remove(u->core, k);
1909 pa_source_unref(u->source);
1914 pa_thread_mq_done(&u->thread_mq);
1916 pa_rtpoll_free(u->rtpoll);
1920 if (u->read_smoother) {
1921 pa_smoother_free(u->read_smoother);
1922 u->read_smoother = NULL;
1926 /* Run from main thread */
1927 static int start_thread(struct userdata *u) {
1929 pa_assert(!u->thread);
1930 pa_assert(!u->rtpoll);
1931 pa_assert(!u->rtpoll_item);
1933 u->rtpoll = pa_rtpoll_new();
1934 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1936 if (USE_SCO_OVER_PCM(u)) {
1937 if (sco_over_pcm_state_update(u, FALSE) < 0) {
1941 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1942 pa_shared_remove(u->core, k);
1947 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1948 pa_shared_remove(u->core, k);
1955 pa_sink_ref(u->sink);
1956 pa_source_ref(u->source);
1957 /* FIXME: monitor stream_fd error */
1961 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1962 pa_log_error("Failed to create IO thread");
1968 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1969 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1970 pa_sink_put(u->sink);
1972 if (u->sink->set_volume)
1973 u->sink->set_volume(u->sink);
1977 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1978 pa_source_set_rtpoll(u->source, u->rtpoll);
1979 pa_source_put(u->source);
1981 if (u->source->set_volume)
1982 u->source->set_volume(u->source);
1988 static void save_sco_volume_callbacks(struct userdata *u) {
1990 pa_assert(USE_SCO_OVER_PCM(u));
1992 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
1993 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
1996 static void restore_sco_volume_callbacks(struct userdata *u) {
1998 pa_assert(USE_SCO_OVER_PCM(u));
2000 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2001 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2004 /* Run from main thread */
2005 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2008 pa_queue *inputs = NULL, *outputs = NULL;
2009 const pa_bluetooth_device *device;
2012 pa_assert(new_profile);
2013 pa_assert_se(u = c->userdata);
2015 d = PA_CARD_PROFILE_DATA(new_profile);
2017 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2018 pa_log_error("Failed to get device object.");
2022 /* The state signal is sent by bluez, so it is racy to check
2023 strictly for CONNECTED, we should also accept STREAMING state
2024 as being good enough. However, if the profile is used
2025 concurrently (which is unlikely), ipc will fail later on, and
2026 module will be unloaded. */
2027 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2028 pa_log_warn("HSP is not connected, refused to switch profile");
2030 } else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2031 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2033 } else if (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) {
2034 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2036 } else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2037 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2042 inputs = pa_sink_move_all_start(u->sink, NULL);
2044 if (!USE_SCO_OVER_PCM(u))
2045 pa_sink_unlink(u->sink);
2049 outputs = pa_source_move_all_start(u->source, NULL);
2051 if (!USE_SCO_OVER_PCM(u))
2052 pa_source_unlink(u->source);
2057 if (u->profile != PROFILE_OFF && u->transport) {
2058 bt_transport_release(u);
2059 pa_xfree(u->transport);
2060 u->transport = NULL;
2063 if (USE_SCO_OVER_PCM(u))
2064 restore_sco_volume_callbacks(u);
2067 u->sample_spec = u->requested_sample_spec;
2069 if (USE_SCO_OVER_PCM(u))
2070 save_sco_volume_callbacks(u);
2072 if (u->profile != PROFILE_OFF)
2075 if (u->sink || u->source)
2080 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2082 pa_sink_move_all_fail(inputs);
2087 pa_source_move_all_finish(u->source, outputs, FALSE);
2089 pa_source_move_all_fail(outputs);
2095 static void create_ports_for_profile(struct userdata *u, pa_card_new_data *card_new_data, pa_card_profile *profile) {
2096 pa_device_port *port;
2099 d = PA_CARD_PROFILE_DATA(profile);
2103 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2104 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2105 port->is_output = 1;
2107 port->priority = profile->priority * 100;
2108 pa_hashmap_put(port->profiles, profile->name, profile);
2111 case PROFILE_A2DP_SOURCE:
2112 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2113 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2114 port->is_output = 0;
2116 port->priority = profile->priority * 100;
2117 pa_hashmap_put(port->profiles, profile->name, profile);
2121 pa_assert_se(port = pa_device_port_new(u->core, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2122 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2123 port->is_output = 1;
2125 port->priority = profile->priority * 100;
2126 pa_hashmap_put(port->profiles, profile->name, profile);
2128 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2129 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2130 port->is_output = 0;
2132 port->priority = profile->priority * 100;
2133 pa_hashmap_put(port->profiles, profile->name, profile);
2137 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2138 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2139 port->is_output = 1;
2141 port->priority = profile->priority * 100;
2142 pa_hashmap_put(port->profiles, profile->name, profile);
2144 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2145 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2146 port->is_output = 0;
2148 port->priority = profile->priority * 100;
2149 pa_hashmap_put(port->profiles, profile->name, profile);
2153 pa_assert_not_reached();
2158 /* Run from main thread */
2159 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2160 pa_card_new_data data;
2166 const char *default_profile;
2171 pa_card_new_data_init(&data);
2172 data.driver = __FILE__;
2173 data.module = u->module;
2175 n = pa_bluetooth_cleanup_name(device->name);
2176 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2178 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2179 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2180 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2181 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2182 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2183 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2184 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2185 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2186 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2187 data.name = get_name("card", u->modargs, device->address, &b);
2188 data.namereg_fail = b;
2190 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2191 pa_log("Invalid properties");
2192 pa_card_new_data_done(&data);
2196 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2198 /* we base hsp/a2dp availability on UUIDs.
2199 Ideally, it would be based on "Connected" state, but
2200 we can't afford to wait for this information when
2201 we are loaded with profile="hsp", for instance */
2202 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2203 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2207 p->max_sink_channels = 2;
2208 p->max_source_channels = 0;
2210 d = PA_CARD_PROFILE_DATA(p);
2212 create_ports_for_profile(u, &data, p);
2214 pa_hashmap_put(data.profiles, p->name, p);
2217 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2218 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2222 p->max_sink_channels = 0;
2223 p->max_source_channels = 2;
2225 d = PA_CARD_PROFILE_DATA(p);
2226 *d = PROFILE_A2DP_SOURCE;
2227 create_ports_for_profile(u, &data, p);
2229 pa_hashmap_put(data.profiles, p->name, p);
2232 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2233 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2234 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2238 p->max_sink_channels = 1;
2239 p->max_source_channels = 1;
2241 d = PA_CARD_PROFILE_DATA(p);
2243 create_ports_for_profile(u, &data, p);
2245 pa_hashmap_put(data.profiles, p->name, p);
2248 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2249 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2253 p->max_sink_channels = 1;
2254 p->max_source_channels = 1;
2256 d = PA_CARD_PROFILE_DATA(p);
2258 create_ports_for_profile(u, &data, p);
2260 pa_hashmap_put(data.profiles, p->name, p);
2263 pa_assert(!pa_hashmap_isempty(data.profiles));
2265 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2266 d = PA_CARD_PROFILE_DATA(p);
2268 pa_hashmap_put(data.profiles, p->name, p);
2270 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2271 if (pa_hashmap_get(data.profiles, default_profile))
2272 pa_card_new_data_set_profile(&data, default_profile);
2274 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2277 u->card = pa_card_new(u->core, &data);
2278 pa_card_new_data_done(&data);
2281 pa_log("Failed to allocate card.");
2285 u->card->userdata = u;
2286 u->card->set_profile = card_set_profile;
2288 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2290 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2291 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2292 (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) ||
2293 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2294 pa_log_warn("Default profile not connected, selecting off profile");
2295 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2296 u->card->save_profile = FALSE;
2299 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2302 if (USE_SCO_OVER_PCM(u))
2303 save_sco_volume_callbacks(u);
2308 /* Run from main thread */
2309 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2310 const pa_bluetooth_device *d = NULL;
2314 if (!address && !path) {
2315 pa_log_error("Failed to get device address/path from module arguments.");
2320 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2321 pa_log_error("%s is not a valid BlueZ audio device.", path);
2325 if (address && !(pa_streq(d->address, address))) {
2326 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2331 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2332 pa_log_error("%s is not known.", address);
2338 u->address = pa_xstrdup(d->address);
2339 u->path = pa_xstrdup(d->path);
2345 /* Run from main thread */
2346 static int setup_dbus(struct userdata *u) {
2349 dbus_error_init(&err);
2351 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2353 if (dbus_error_is_set(&err) || !u->connection) {
2354 pa_log("Failed to get D-Bus connection: %s", err.message);
2355 dbus_error_free(&err);
2362 int pa__init(pa_module* m) {
2366 const char *address, *path;
2368 char *mike, *speaker;
2369 const pa_bluetooth_device *device;
2373 dbus_error_init(&err);
2375 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2376 pa_log_error("Failed to parse module arguments");
2380 m->userdata = u = pa_xnew0(struct userdata, 1);
2384 u->sample_spec = m->core->default_sample_spec;
2387 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2388 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2389 pa_log("SCO sink not found");
2393 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2394 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2395 pa_log("SCO source not found");
2399 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2400 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2401 pa_log_error("Failed to get rate from module arguments");
2405 u->auto_connect = TRUE;
2406 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2407 pa_log("Failed to parse auto_connect= argument");
2411 channels = u->sample_spec.channels;
2412 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2413 channels <= 0 || channels > PA_CHANNELS_MAX) {
2414 pa_log_error("Failed to get channels from module arguments");
2417 u->sample_spec.channels = (uint8_t) channels;
2418 u->requested_sample_spec = u->sample_spec;
2420 address = pa_modargs_get_value(ma, "address", NULL);
2421 path = pa_modargs_get_value(ma, "path", NULL);
2423 if (setup_dbus(u) < 0)
2426 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2429 if (!(device = find_device(u, address, path)))
2432 /* Add the card structure. This will also initialize the default profile */
2433 if (add_card(u, device) < 0)
2436 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2439 u->msg->parent.process_msg = device_process_msg;
2440 u->msg->card = u->card;
2442 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2443 pa_log_error("Failed to add filter function");
2446 u->filter_added = TRUE;
2448 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2449 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2451 if (pa_dbus_add_matches(
2452 pa_dbus_connection_get(u->connection), &err,
2455 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2456 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2462 pa_log("Failed to add D-Bus matches: %s", err.message);
2469 if (u->profile != PROFILE_OFF)
2470 if (init_profile(u) < 0)
2473 if (u->sink || u->source)
2474 if (start_thread(u) < 0)
2483 dbus_error_free(&err);
2488 int pa__get_n_used(pa_module *m) {
2492 pa_assert_se(u = m->userdata);
2495 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2496 (u->source ? pa_source_linked_by(u->source) : 0);
2499 void pa__done(pa_module *m) {
2504 if (!(u = m->userdata))
2507 if (u->sink && !USE_SCO_OVER_PCM(u))
2508 pa_sink_unlink(u->sink);
2510 if (u->source && !USE_SCO_OVER_PCM(u))
2511 pa_source_unlink(u->source);
2515 if (USE_SCO_OVER_PCM(u))
2516 restore_sco_volume_callbacks(u);
2518 if (u->connection) {
2521 char *speaker, *mike;
2522 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2523 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2525 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
2526 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2527 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2534 if (u->filter_added)
2535 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2537 pa_dbus_connection_unref(u->connection);
2544 pa_card_free(u->card);
2546 if (u->read_smoother)
2547 pa_smoother_free(u->read_smoother);
2550 pa_xfree(u->a2dp.buffer);
2552 sbc_finish(&u->a2dp.sbc);
2555 pa_modargs_free(u->modargs);
2557 pa_xfree(u->address);
2561 bt_transport_release(u);
2562 pa_xfree(u->transport);
2566 pa_bluetooth_discovery_unref(u->discovery);