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 int 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(
284 static void bt_transport_release(struct userdata *u) {
285 const char *accesstype = "rw";
286 const pa_bluetooth_transport *t;
288 /* Ignore if already released */
292 pa_log_debug("Releasing transport %s", u->transport);
294 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
296 pa_bluetooth_transport_release(t, accesstype);
298 pa_xfree(u->accesstype);
299 u->accesstype = NULL;
301 if (u->rtpoll_item) {
302 pa_rtpoll_item_free(u->rtpoll_item);
303 u->rtpoll_item = NULL;
306 if (u->stream_fd >= 0) {
307 pa_close(u->stream_fd);
311 if (u->read_smoother) {
312 pa_smoother_free(u->read_smoother);
313 u->read_smoother = NULL;
317 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
318 const char *accesstype = "rw";
319 const pa_bluetooth_transport *t;
327 pa_log_debug("Acquiring transport %s", u->transport);
329 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
331 pa_log("Transport %s no longer available", u->transport);
332 pa_xfree(u->transport);
337 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, &u->read_link_mtu, &u->write_link_mtu);
338 if (u->stream_fd < 0)
341 u->accesstype = pa_xstrdup(accesstype);
342 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
348 pa_log_info("Transport %s resuming", u->transport);
349 return setup_stream(u);
352 /* Run from IO thread */
353 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
354 struct userdata *u = PA_SINK(o)->userdata;
355 pa_bool_t failed = FALSE;
358 pa_assert(u->sink == PA_SINK(o));
359 pa_assert(u->transport);
363 case PA_SINK_MESSAGE_SET_STATE:
365 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
367 case PA_SINK_SUSPENDED:
368 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
370 /* Stop the device if the source is suspended as well */
371 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
372 /* We deliberately ignore whether stopping
373 * actually worked. Since the stream_fd is
374 * closed it doesn't really matter */
375 bt_transport_release(u);
380 case PA_SINK_RUNNING:
381 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
384 /* Resume the device if the source was suspended as well */
385 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
386 if (bt_transport_acquire(u, TRUE) < 0)
391 case PA_SINK_UNLINKED:
393 case PA_SINK_INVALID_STATE:
398 case PA_SINK_MESSAGE_GET_LATENCY: {
400 if (u->read_smoother) {
403 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
404 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
406 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
410 ri = pa_rtclock_now() - u->started_at;
411 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
413 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
416 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
421 r = pa_sink_process_msg(o, code, data, offset, chunk);
423 return (r < 0 || !failed) ? r : -1;
426 /* Run from IO thread */
427 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
428 struct userdata *u = PA_SOURCE(o)->userdata;
429 pa_bool_t failed = FALSE;
432 pa_assert(u->source == PA_SOURCE(o));
433 pa_assert(u->transport);
437 case PA_SOURCE_MESSAGE_SET_STATE:
439 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
441 case PA_SOURCE_SUSPENDED:
442 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
444 /* Stop the device if the sink is suspended as well */
445 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
446 bt_transport_release(u);
448 if (u->read_smoother)
449 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
453 case PA_SOURCE_RUNNING:
454 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
457 /* Resume the device if the sink was suspended as well */
458 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
459 if (bt_transport_acquire(u, TRUE) < 0)
462 /* We don't resume the smoother here. Instead we
463 * wait until the first packet arrives */
466 case PA_SOURCE_UNLINKED:
468 case PA_SOURCE_INVALID_STATE:
473 case PA_SOURCE_MESSAGE_GET_LATENCY: {
476 if (u->read_smoother) {
477 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
478 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
480 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
482 *((pa_usec_t*) data) = 0;
489 r = pa_source_process_msg(o, code, data, offset, chunk);
491 return (r < 0 || !failed) ? r : -1;
494 /* Called from main thread context */
495 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
496 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
499 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
500 if (u->card->module->unload_requested)
503 pa_log_debug("Switching the profile to off due to IO thread failure.");
505 if (pa_card_set_profile(u->card, "off", FALSE) < 0)
506 pa_log_debug("Failed to switch profile to off");
513 /* Run from IO thread */
514 static int hsp_process_render(struct userdata *u) {
518 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
521 /* First, render some data */
522 if (!u->write_memchunk.memblock)
523 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
525 pa_assert(u->write_memchunk.length == u->write_block_size);
531 /* Now write that data to the socket. The socket is of type
532 * SEQPACKET, and we generated the data of the MTU size, so this
533 * should just work. */
535 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
536 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
537 pa_memblock_release(u->write_memchunk.memblock);
544 /* Retry right away if we got interrupted */
547 else if (errno == EAGAIN)
548 /* Hmm, apparently the socket was not writable, give up for now */
551 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
556 pa_assert((size_t) l <= u->write_memchunk.length);
558 if ((size_t) l != u->write_memchunk.length) {
559 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
560 (unsigned long long) l,
561 (unsigned long long) u->write_memchunk.length);
566 u->write_index += (uint64_t) u->write_memchunk.length;
567 pa_memblock_unref(u->write_memchunk.memblock);
568 pa_memchunk_reset(&u->write_memchunk);
577 /* Run from IO thread */
578 static int hsp_process_push(struct userdata *u) {
580 pa_memchunk memchunk;
583 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
584 pa_assert(u->source);
585 pa_assert(u->read_smoother);
587 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
588 memchunk.index = memchunk.length = 0;
597 pa_bool_t found_tstamp = FALSE;
600 memset(&m, 0, sizeof(m));
601 memset(&aux, 0, sizeof(aux));
602 memset(&iov, 0, sizeof(iov));
607 m.msg_controllen = sizeof(aux);
609 p = pa_memblock_acquire(memchunk.memblock);
611 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
612 l = recvmsg(u->stream_fd, &m, 0);
613 pa_memblock_release(memchunk.memblock);
617 if (l < 0 && errno == EINTR)
618 /* Retry right away if we got interrupted */
621 else if (l < 0 && errno == EAGAIN)
622 /* Hmm, apparently the socket was not readable, give up for now. */
625 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
630 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
632 memchunk.length = (size_t) l;
633 u->read_index += (uint64_t) l;
635 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
636 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
637 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
638 pa_rtclock_from_wallclock(tv);
639 tstamp = pa_timeval_load(tv);
645 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
646 tstamp = pa_rtclock_now();
649 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
650 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
652 pa_source_post(u->source, &memchunk);
658 pa_memblock_unref(memchunk.memblock);
663 /* Run from IO thread */
664 static void a2dp_prepare_buffer(struct userdata *u) {
665 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
669 if (u->a2dp.buffer_size >= min_buffer_size)
672 u->a2dp.buffer_size = 2 * min_buffer_size;
673 pa_xfree(u->a2dp.buffer);
674 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
677 /* Run from IO thread */
678 static int a2dp_process_render(struct userdata *u) {
679 struct a2dp_info *a2dp;
680 struct rtp_header *header;
681 struct rtp_payload *payload;
685 size_t to_write, to_encode;
686 unsigned frame_count;
690 pa_assert(u->profile == PROFILE_A2DP);
693 /* First, render some data */
694 if (!u->write_memchunk.memblock)
695 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
697 pa_assert(u->write_memchunk.length == u->write_block_size);
699 a2dp_prepare_buffer(u);
702 header = a2dp->buffer;
703 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
707 /* Try to create a packet of the full MTU */
709 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
710 to_encode = u->write_memchunk.length;
712 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
713 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
715 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
719 encoded = sbc_encode(&a2dp->sbc,
724 if (PA_UNLIKELY(encoded <= 0)) {
725 pa_log_error("SBC encoding error (%li)", (long) encoded);
726 pa_memblock_release(u->write_memchunk.memblock);
730 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
731 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
733 pa_assert_fp((size_t) encoded <= to_encode);
734 pa_assert_fp((size_t) encoded == a2dp->codesize);
736 pa_assert_fp((size_t) written <= to_write);
737 pa_assert_fp((size_t) written == a2dp->frame_length);
739 p = (const uint8_t*) p + encoded;
740 to_encode -= encoded;
742 d = (uint8_t*) d + written;
748 pa_memblock_release(u->write_memchunk.memblock);
750 pa_assert(to_encode == 0);
753 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
756 /* write it to the fifo */
757 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
760 header->sequence_number = htons(a2dp->seq_num++);
761 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
762 header->ssrc = htonl(1);
763 payload->frame_count = frame_count;
765 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
770 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
777 /* Retry right away if we got interrupted */
780 else if (errno == EAGAIN)
781 /* Hmm, apparently the socket was not writable, give up for now */
784 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
789 pa_assert((size_t) l <= nbytes);
791 if ((size_t) l != nbytes) {
792 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
793 (unsigned long long) l,
794 (unsigned long long) nbytes);
799 u->write_index += (uint64_t) u->write_memchunk.length;
800 pa_memblock_unref(u->write_memchunk.memblock);
801 pa_memchunk_reset(&u->write_memchunk);
811 static int a2dp_process_push(struct userdata *u) {
813 pa_memchunk memchunk;
816 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
817 pa_assert(u->source);
818 pa_assert(u->read_smoother);
820 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
821 memchunk.index = memchunk.length = 0;
824 pa_bool_t found_tstamp = FALSE;
826 struct a2dp_info *a2dp;
827 struct rtp_header *header;
828 struct rtp_payload *payload;
832 size_t to_write, to_decode;
834 a2dp_prepare_buffer(u);
837 header = a2dp->buffer;
838 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
840 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
844 if (l < 0 && errno == EINTR)
845 /* Retry right away if we got interrupted */
848 else if (l < 0 && errno == EAGAIN)
849 /* Hmm, apparently the socket was not readable, give up for now. */
852 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
857 pa_assert((size_t) l <= a2dp->buffer_size);
859 u->read_index += (uint64_t) l;
861 /* TODO: get timestamp from rtp */
863 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
864 tstamp = pa_rtclock_now();
867 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
868 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
870 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
871 to_decode = l - sizeof(*header) - sizeof(*payload);
873 d = pa_memblock_acquire(memchunk.memblock);
874 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
876 while (PA_LIKELY(to_decode > 0)) {
880 decoded = sbc_decode(&a2dp->sbc,
885 if (PA_UNLIKELY(decoded <= 0)) {
886 pa_log_error("SBC decoding error (%li)", (long) decoded);
887 pa_memblock_release(memchunk.memblock);
888 pa_memblock_unref(memchunk.memblock);
892 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
893 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
895 /* Reset frame length, it can be changed due to bitpool change */
896 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
898 pa_assert_fp((size_t) decoded <= to_decode);
899 pa_assert_fp((size_t) decoded == a2dp->frame_length);
901 pa_assert_fp((size_t) written == a2dp->codesize);
903 p = (const uint8_t*) p + decoded;
904 to_decode -= decoded;
906 d = (uint8_t*) d + written;
910 memchunk.length -= to_write;
912 pa_memblock_release(memchunk.memblock);
914 pa_source_post(u->source, &memchunk);
920 pa_memblock_unref(memchunk.memblock);
925 static void a2dp_reduce_bitpool(struct userdata *u)
927 struct a2dp_info *a2dp;
934 /* Check if bitpool is already at its limit */
935 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
938 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
940 if (bitpool < BITPOOL_DEC_LIMIT)
941 bitpool = BITPOOL_DEC_LIMIT;
943 a2dp_set_bitpool(u, bitpool);
946 static void thread_func(void *userdata) {
947 struct userdata *u = userdata;
948 unsigned do_write = 0;
949 unsigned pending_read_bytes = 0;
950 pa_bool_t writable = FALSE;
953 pa_assert(u->transport);
955 pa_log_debug("IO Thread starting up");
957 if (u->core->realtime_scheduling)
958 pa_make_realtime(u->core->realtime_priority);
960 pa_thread_mq_install(&u->thread_mq);
962 if (bt_transport_acquire(u, TRUE) < 0)
966 struct pollfd *pollfd;
968 pa_bool_t disable_timer = TRUE;
970 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
972 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
974 /* We should send two blocks to the device before we expect
977 if (u->write_index == 0 && u->read_index <= 0)
980 if (pollfd && (pollfd->revents & POLLIN)) {
983 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
984 n_read = hsp_process_push(u);
986 n_read = a2dp_process_push(u);
991 /* We just read something, so we are supposed to write something, too */
992 pending_read_bytes += n_read;
993 do_write += pending_read_bytes / u->write_block_size;
994 pending_read_bytes = pending_read_bytes % u->write_block_size;
998 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1000 if (u->sink->thread_info.rewind_requested)
1001 pa_sink_process_rewind(u->sink, 0);
1004 if (pollfd->revents & POLLOUT)
1007 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1008 pa_usec_t time_passed;
1009 pa_usec_t audio_sent;
1011 /* Hmm, there is no input stream we could synchronize
1012 * to. So let's do things by time */
1014 time_passed = pa_rtclock_now() - u->started_at;
1015 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1017 if (audio_sent <= time_passed) {
1018 pa_usec_t audio_to_send = time_passed - audio_sent;
1020 /* Never try to catch up for more than 100ms */
1021 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1022 pa_usec_t skip_usec;
1023 uint64_t skip_bytes;
1025 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1026 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1028 if (skip_bytes > 0) {
1031 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1032 (unsigned long long) skip_usec,
1033 (unsigned long long) skip_bytes);
1035 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1036 pa_memblock_unref(tmp.memblock);
1037 u->write_index += skip_bytes;
1039 if (u->profile == PROFILE_A2DP)
1040 a2dp_reduce_bitpool(u);
1045 pending_read_bytes = 0;
1049 if (writable && do_write > 0) {
1052 if (u->write_index <= 0)
1053 u->started_at = pa_rtclock_now();
1055 if (u->profile == PROFILE_A2DP) {
1056 if ((n_written = a2dp_process_render(u)) < 0)
1059 if ((n_written = hsp_process_render(u)) < 0)
1064 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1066 do_write -= n_written;
1070 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1071 pa_usec_t sleep_for;
1072 pa_usec_t time_passed, next_write_at;
1075 /* Hmm, there is no input stream we could synchronize
1076 * to. So let's estimate when we need to wake up the latest */
1077 time_passed = pa_rtclock_now() - u->started_at;
1078 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1079 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1080 /* 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); */
1082 /* drop stream every 500 ms */
1083 sleep_for = PA_USEC_PER_MSEC * 500;
1085 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1086 disable_timer = FALSE;
1092 pa_rtpoll_set_timer_disabled(u->rtpoll);
1094 /* Hmm, nothing to do. Let's sleep */
1096 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1097 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1099 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
1100 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1104 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1105 bt_transport_release(u);
1109 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1111 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1112 pa_log_info("FD error: %s%s%s%s",
1113 pollfd->revents & POLLERR ? "POLLERR " :"",
1114 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1115 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1116 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1122 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1123 pa_log_debug("IO thread failed");
1124 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1125 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1128 pa_log_debug("IO thread shutting down");
1131 /* Run from main thread */
1132 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1138 pa_assert_se(u = userdata);
1140 dbus_error_init(&err);
1142 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1143 dbus_message_get_interface(m),
1144 dbus_message_get_path(m),
1145 dbus_message_get_member(m));
1147 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1150 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1151 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1156 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1157 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1161 if (u->profile == PROFILE_HSP) {
1162 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1163 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1165 /* increment volume by one to correct rounding errors */
1166 if (volume < PA_VOLUME_NORM)
1169 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1170 pa_sink_volume_changed(u->sink, &v);
1172 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1173 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1175 /* increment volume by one to correct rounding errors */
1176 if (volume < PA_VOLUME_NORM)
1179 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1180 pa_source_volume_changed(u->source, &v);
1183 } else if (dbus_message_is_signal(m, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1185 DBusMessageIter iter;
1186 DBusMessageIter variant;
1187 pa_bt_audio_state_t state = PA_BT_AUDIO_STATE_INVALID;
1189 if (!dbus_message_iter_init(m, &iter)) {
1190 pa_log("Failed to parse PropertyChanged: %s", err.message);
1194 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1195 pa_log("Property name not a string.");
1199 dbus_message_iter_get_basic(&iter, &key);
1201 if (!dbus_message_iter_next(&iter)) {
1202 pa_log("Property value missing");
1206 dbus_message_iter_recurse(&iter, &variant);
1208 if (dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_STRING) {
1210 dbus_message_iter_get_basic(&variant, &value);
1212 if (pa_streq(key, "State")) {
1213 pa_log_debug("dbus: HSHFAG property 'State' changed to value '%s'", value);
1214 state = pa_bt_audio_state_from_string(value);
1219 case PA_BT_AUDIO_STATE_INVALID:
1220 case PA_BT_AUDIO_STATE_DISCONNECTED:
1221 case PA_BT_AUDIO_STATE_CONNECTED:
1222 case PA_BT_AUDIO_STATE_CONNECTING:
1225 case PA_BT_AUDIO_STATE_PLAYING:
1227 pa_log_debug("Changing profile to hfgw");
1228 if (pa_card_set_profile(u->card, "hfgw", FALSE) < 0)
1229 pa_log("Failed to change profile to hfgw");
1236 dbus_error_free(&err);
1238 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1241 /* Run from main thread */
1242 static void sink_set_volume_cb(pa_sink *s) {
1252 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1253 u = pa_shared_get(s->core, k);
1257 pa_assert(u->sink == s);
1258 pa_assert(u->profile == PROFILE_HSP);
1260 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1262 if (gain > HSP_MAX_GAIN)
1263 gain = HSP_MAX_GAIN;
1265 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1267 /* increment volume by one to correct rounding errors */
1268 if (volume < PA_VOLUME_NORM)
1271 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1273 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1274 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1275 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1276 dbus_message_unref(m);
1279 /* Run from main thread */
1280 static void source_set_volume_cb(pa_source *s) {
1290 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1291 u = pa_shared_get(s->core, k);
1295 pa_assert(u->source == s);
1296 pa_assert(u->profile == PROFILE_HSP);
1298 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1300 if (gain > HSP_MAX_GAIN)
1301 gain = HSP_MAX_GAIN;
1303 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1305 /* increment volume by one to correct rounding errors */
1306 if (volume < PA_VOLUME_NORM)
1309 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1311 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1312 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1313 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1314 dbus_message_unref(m);
1317 /* Run from main thread */
1318 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1324 pa_assert(device_id);
1325 pa_assert(namereg_fail);
1327 t = pa_sprintf_malloc("%s_name", type);
1328 n = pa_modargs_get_value(ma, t, NULL);
1332 *namereg_fail = TRUE;
1333 return pa_xstrdup(n);
1336 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1337 *namereg_fail = TRUE;
1340 *namereg_fail = FALSE;
1343 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1346 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1348 pa_assert(USE_SCO_OVER_PCM(u));
1350 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1351 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1353 if (u->stream_fd >= 0)
1356 pa_log_debug("Resuming SCO over PCM");
1357 if (init_profile(u) < 0) {
1358 pa_log("Can't resume SCO over PCM");
1362 return bt_transport_acquire(u, TRUE);
1366 if (u->stream_fd < 0)
1369 pa_log_debug("Closing SCO over PCM");
1371 bt_transport_release(u);
1377 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1379 pa_sink_assert_ref(s);
1382 if (s != u->hsp.sco_sink)
1385 sco_over_pcm_state_update(u, TRUE);
1390 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1392 pa_source_assert_ref(s);
1395 if (s != u->hsp.sco_source)
1398 sco_over_pcm_state_update(u, TRUE);
1403 static pa_hook_result_t nrec_changed_cb(pa_bluetooth_transport *t, void *call_data, struct userdata *u) {
1409 p = pa_proplist_new();
1410 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1411 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1412 pa_proplist_free(p);
1417 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1419 pa_sink_new_data *sink_new_data;
1420 pa_source_new_data *source_new_data;
1422 pa_device_port *port;
1424 if (direction == PA_DIRECTION_OUTPUT) {
1425 data.sink_new_data = sink_or_source_new_data;
1426 data.sink_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1428 data.source_new_data = sink_or_source_new_data;
1429 data.source_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1432 switch (u->profile) {
1434 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1435 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1436 pa_device_port_ref(port);
1439 case PROFILE_A2DP_SOURCE:
1440 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1441 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1442 pa_device_port_ref(port);
1446 if (direction == PA_DIRECTION_OUTPUT) {
1447 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1448 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1450 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1451 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1453 pa_device_port_ref(port);
1457 if (direction == PA_DIRECTION_OUTPUT) {
1458 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1459 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1461 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1462 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1464 pa_device_port_ref(port);
1468 pa_assert_not_reached();
1472 static const char *profile_to_string(enum profile profile) {
1476 case PROFILE_A2DP_SOURCE:
1477 return "a2dp_source";
1483 pa_assert_not_reached();
1487 /* Run from main thread */
1488 static int add_sink(struct userdata *u) {
1491 if (USE_SCO_OVER_PCM(u)) {
1494 u->sink = u->hsp.sco_sink;
1495 p = pa_proplist_new();
1496 pa_proplist_sets(p, "bluetooth.protocol", profile_to_string(u->profile));
1497 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1498 pa_proplist_free(p);
1500 if (!u->hsp.sink_state_changed_slot)
1501 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);
1504 pa_sink_new_data data;
1507 pa_sink_new_data_init(&data);
1508 data.driver = __FILE__;
1509 data.module = u->module;
1510 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1511 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1512 if (u->profile == PROFILE_HSP)
1513 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1514 data.card = u->card;
1515 data.name = get_name("sink", u->modargs, u->address, &b);
1516 data.namereg_fail = b;
1518 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1519 pa_log("Invalid properties");
1520 pa_sink_new_data_done(&data);
1523 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1525 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1526 pa_sink_new_data_done(&data);
1529 pa_log_error("Failed to create sink");
1533 u->sink->userdata = u;
1534 u->sink->parent.process_msg = sink_process_msg;
1536 pa_sink_set_max_request(u->sink, u->write_block_size);
1537 pa_sink_set_fixed_latency(u->sink,
1538 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1539 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
1542 if (u->profile == PROFILE_HSP) {
1543 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1544 u->sink->n_volume_steps = 16;
1546 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1547 pa_shared_set(u->core, k, u);
1554 /* Run from main thread */
1555 static int add_source(struct userdata *u) {
1558 if (USE_SCO_OVER_PCM(u)) {
1559 u->source = u->hsp.sco_source;
1560 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", profile_to_string(u->profile));
1562 if (!u->hsp.source_state_changed_slot)
1563 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);
1566 pa_source_new_data data;
1569 pa_source_new_data_init(&data);
1570 data.driver = __FILE__;
1571 data.module = u->module;
1572 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1573 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1574 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
1575 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1577 data.card = u->card;
1578 data.name = get_name("source", u->modargs, u->address, &b);
1579 data.namereg_fail = b;
1581 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1582 pa_log("Invalid properties");
1583 pa_source_new_data_done(&data);
1587 connect_ports(u, &data, PA_DIRECTION_INPUT);
1588 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1589 pa_source_new_data_done(&data);
1592 pa_log_error("Failed to create source");
1596 u->source->userdata = u;
1597 u->source->parent.process_msg = source_process_msg;
1599 pa_source_set_fixed_latency(u->source,
1600 (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
1601 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
1604 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1605 pa_bluetooth_transport *t;
1606 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1608 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1610 if (!u->hsp.nrec_changed_slot)
1611 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);
1614 if (u->profile == PROFILE_HSP) {
1615 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1616 u->source->n_volume_steps = 16;
1618 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1619 pa_shared_set(u->core, k, u);
1626 static int bt_transport_config_a2dp(struct userdata *u) {
1627 const pa_bluetooth_transport *t;
1628 struct a2dp_info *a2dp = &u->a2dp;
1631 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1634 config = (a2dp_sbc_t *) t->config;
1636 u->sample_spec.format = PA_SAMPLE_S16LE;
1638 if (a2dp->sbc_initialized)
1639 sbc_reinit(&a2dp->sbc, 0);
1641 sbc_init(&a2dp->sbc, 0);
1642 a2dp->sbc_initialized = TRUE;
1644 switch (config->frequency) {
1645 case BT_SBC_SAMPLING_FREQ_16000:
1646 a2dp->sbc.frequency = SBC_FREQ_16000;
1647 u->sample_spec.rate = 16000U;
1649 case BT_SBC_SAMPLING_FREQ_32000:
1650 a2dp->sbc.frequency = SBC_FREQ_32000;
1651 u->sample_spec.rate = 32000U;
1653 case BT_SBC_SAMPLING_FREQ_44100:
1654 a2dp->sbc.frequency = SBC_FREQ_44100;
1655 u->sample_spec.rate = 44100U;
1657 case BT_SBC_SAMPLING_FREQ_48000:
1658 a2dp->sbc.frequency = SBC_FREQ_48000;
1659 u->sample_spec.rate = 48000U;
1662 pa_assert_not_reached();
1665 switch (config->channel_mode) {
1666 case BT_A2DP_CHANNEL_MODE_MONO:
1667 a2dp->sbc.mode = SBC_MODE_MONO;
1668 u->sample_spec.channels = 1;
1670 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
1671 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1672 u->sample_spec.channels = 2;
1674 case BT_A2DP_CHANNEL_MODE_STEREO:
1675 a2dp->sbc.mode = SBC_MODE_STEREO;
1676 u->sample_spec.channels = 2;
1678 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
1679 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1680 u->sample_spec.channels = 2;
1683 pa_assert_not_reached();
1686 switch (config->allocation_method) {
1687 case BT_A2DP_ALLOCATION_SNR:
1688 a2dp->sbc.allocation = SBC_AM_SNR;
1690 case BT_A2DP_ALLOCATION_LOUDNESS:
1691 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1694 pa_assert_not_reached();
1697 switch (config->subbands) {
1698 case BT_A2DP_SUBBANDS_4:
1699 a2dp->sbc.subbands = SBC_SB_4;
1701 case BT_A2DP_SUBBANDS_8:
1702 a2dp->sbc.subbands = SBC_SB_8;
1705 pa_assert_not_reached();
1708 switch (config->block_length) {
1709 case BT_A2DP_BLOCK_LENGTH_4:
1710 a2dp->sbc.blocks = SBC_BLK_4;
1712 case BT_A2DP_BLOCK_LENGTH_8:
1713 a2dp->sbc.blocks = SBC_BLK_8;
1715 case BT_A2DP_BLOCK_LENGTH_12:
1716 a2dp->sbc.blocks = SBC_BLK_12;
1718 case BT_A2DP_BLOCK_LENGTH_16:
1719 a2dp->sbc.blocks = SBC_BLK_16;
1722 pa_assert_not_reached();
1725 a2dp->min_bitpool = config->min_bitpool;
1726 a2dp->max_bitpool = config->max_bitpool;
1728 /* Set minimum bitpool for source to get the maximum possible block_size */
1729 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1730 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1731 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1733 u->read_block_size =
1734 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1735 / a2dp->frame_length * a2dp->codesize;
1737 u->write_block_size =
1738 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1739 / a2dp->frame_length * a2dp->codesize;
1741 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1742 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1747 static int bt_transport_config(struct userdata *u) {
1748 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1749 u->read_block_size = u->read_link_mtu;
1750 u->write_block_size = u->write_link_mtu;
1751 u->sample_spec.format = PA_SAMPLE_S16LE;
1752 u->sample_spec.channels = 1;
1753 u->sample_spec.rate = 8000;
1757 return bt_transport_config_a2dp(u);
1760 /* Run from main thread */
1761 static int setup_bt(struct userdata *u) {
1762 const pa_bluetooth_device *d;
1763 const pa_bluetooth_transport *t;
1767 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1768 pa_log_error("Failed to get device object.");
1772 /* release transport if exist */
1774 bt_transport_release(u);
1775 pa_xfree(u->transport);
1776 u->transport = NULL;
1779 /* check if profile has a transport */
1780 t = pa_bluetooth_device_get_transport(d, u->profile);
1782 pa_log_warn("Profile has no transport");
1786 u->transport = pa_xstrdup(t->path);
1788 if (bt_transport_acquire(u, FALSE) < 0)
1791 return bt_transport_config(u);
1794 /* Run from main thread */
1795 static int init_profile(struct userdata *u) {
1798 pa_assert(u->profile != PROFILE_OFF);
1800 if (setup_bt(u) < 0)
1803 if (u->profile == PROFILE_A2DP ||
1804 u->profile == PROFILE_HSP ||
1805 u->profile == PROFILE_HFGW)
1806 if (add_sink(u) < 0)
1809 if (u->profile == PROFILE_HSP ||
1810 u->profile == PROFILE_A2DP_SOURCE ||
1811 u->profile == PROFILE_HFGW)
1812 if (add_source(u) < 0)
1818 /* Run from main thread */
1819 static void stop_thread(struct userdata *u) {
1825 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1826 pa_thread_free(u->thread);
1830 if (u->rtpoll_item) {
1831 pa_rtpoll_item_free(u->rtpoll_item);
1832 u->rtpoll_item = NULL;
1835 if (u->hsp.sink_state_changed_slot) {
1836 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1837 u->hsp.sink_state_changed_slot = NULL;
1840 if (u->hsp.source_state_changed_slot) {
1841 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1842 u->hsp.source_state_changed_slot = NULL;
1845 if (u->hsp.nrec_changed_slot) {
1846 pa_hook_slot_free(u->hsp.nrec_changed_slot);
1847 u->hsp.nrec_changed_slot = NULL;
1851 if (u->profile == PROFILE_HSP) {
1852 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1853 pa_shared_remove(u->core, k);
1857 pa_sink_unref(u->sink);
1862 if (u->profile == PROFILE_HSP) {
1863 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1864 pa_shared_remove(u->core, k);
1868 pa_source_unref(u->source);
1873 pa_thread_mq_done(&u->thread_mq);
1875 pa_rtpoll_free(u->rtpoll);
1879 if (u->read_smoother) {
1880 pa_smoother_free(u->read_smoother);
1881 u->read_smoother = NULL;
1885 /* Run from main thread */
1886 static int start_thread(struct userdata *u) {
1888 pa_assert(!u->thread);
1889 pa_assert(!u->rtpoll);
1890 pa_assert(!u->rtpoll_item);
1892 u->rtpoll = pa_rtpoll_new();
1893 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1895 if (USE_SCO_OVER_PCM(u)) {
1896 if (sco_over_pcm_state_update(u, FALSE) < 0) {
1900 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1901 pa_shared_remove(u->core, k);
1906 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1907 pa_shared_remove(u->core, k);
1914 pa_sink_ref(u->sink);
1915 pa_source_ref(u->source);
1916 /* FIXME: monitor stream_fd error */
1920 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1921 pa_log_error("Failed to create IO thread");
1927 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1928 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1929 pa_sink_put(u->sink);
1931 if (u->sink->set_volume)
1932 u->sink->set_volume(u->sink);
1936 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1937 pa_source_set_rtpoll(u->source, u->rtpoll);
1938 pa_source_put(u->source);
1940 if (u->source->set_volume)
1941 u->source->set_volume(u->source);
1947 static void save_sco_volume_callbacks(struct userdata *u) {
1949 pa_assert(USE_SCO_OVER_PCM(u));
1951 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
1952 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
1955 static void restore_sco_volume_callbacks(struct userdata *u) {
1957 pa_assert(USE_SCO_OVER_PCM(u));
1959 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
1960 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
1963 /* Run from main thread */
1964 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1967 pa_queue *inputs = NULL, *outputs = NULL;
1968 const pa_bluetooth_device *device;
1971 pa_assert(new_profile);
1972 pa_assert_se(u = c->userdata);
1974 d = PA_CARD_PROFILE_DATA(new_profile);
1976 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1977 pa_log_error("Failed to get device object.");
1981 /* The state signal is sent by bluez, so it is racy to check
1982 strictly for CONNECTED, we should also accept STREAMING state
1983 as being good enough. However, if the profile is used
1984 concurrently (which is unlikely), ipc will fail later on, and
1985 module will be unloaded. */
1986 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
1987 pa_log_warn("HSP is not connected, refused to switch profile");
1989 } else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
1990 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
1992 } else if (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) {
1993 pa_log_warn("A2DP Source is not connected, refused to switch profile");
1995 } else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
1996 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2001 inputs = pa_sink_move_all_start(u->sink, NULL);
2003 if (!USE_SCO_OVER_PCM(u))
2004 pa_sink_unlink(u->sink);
2008 outputs = pa_source_move_all_start(u->source, NULL);
2010 if (!USE_SCO_OVER_PCM(u))
2011 pa_source_unlink(u->source);
2016 if (u->profile != PROFILE_OFF && u->transport) {
2017 bt_transport_release(u);
2018 pa_xfree(u->transport);
2019 u->transport = NULL;
2022 if (USE_SCO_OVER_PCM(u))
2023 restore_sco_volume_callbacks(u);
2026 u->sample_spec = u->requested_sample_spec;
2028 if (USE_SCO_OVER_PCM(u))
2029 save_sco_volume_callbacks(u);
2031 if (u->profile != PROFILE_OFF)
2034 if (u->sink || u->source)
2039 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2041 pa_sink_move_all_fail(inputs);
2046 pa_source_move_all_finish(u->source, outputs, FALSE);
2048 pa_source_move_all_fail(outputs);
2054 static void create_ports_for_profile(struct userdata *u, pa_card_new_data *card_new_data, pa_card_profile *profile) {
2055 pa_device_port *port;
2058 d = PA_CARD_PROFILE_DATA(profile);
2062 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2063 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2064 port->is_output = 1;
2066 port->priority = profile->priority * 100;
2067 pa_hashmap_put(port->profiles, profile->name, profile);
2070 case PROFILE_A2DP_SOURCE:
2071 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2072 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2073 port->is_output = 0;
2075 port->priority = profile->priority * 100;
2076 pa_hashmap_put(port->profiles, profile->name, profile);
2080 pa_assert_se(port = pa_device_port_new(u->core, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2081 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2082 port->is_output = 1;
2084 port->priority = profile->priority * 100;
2085 pa_hashmap_put(port->profiles, profile->name, profile);
2087 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2088 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2089 port->is_output = 0;
2091 port->priority = profile->priority * 100;
2092 pa_hashmap_put(port->profiles, profile->name, profile);
2096 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2097 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2098 port->is_output = 1;
2100 port->priority = profile->priority * 100;
2101 pa_hashmap_put(port->profiles, profile->name, profile);
2103 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2104 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2105 port->is_output = 0;
2107 port->priority = profile->priority * 100;
2108 pa_hashmap_put(port->profiles, profile->name, profile);
2112 pa_assert_not_reached();
2117 /* Run from main thread */
2118 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2119 pa_card_new_data data;
2125 const char *default_profile;
2130 pa_card_new_data_init(&data);
2131 data.driver = __FILE__;
2132 data.module = u->module;
2134 n = pa_bluetooth_cleanup_name(device->name);
2135 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2137 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2138 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2139 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2140 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2141 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2142 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2143 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2144 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2145 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2146 data.name = get_name("card", u->modargs, device->address, &b);
2147 data.namereg_fail = b;
2149 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2150 pa_log("Invalid properties");
2151 pa_card_new_data_done(&data);
2155 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2157 /* we base hsp/a2dp availability on UUIDs.
2158 Ideally, it would be based on "Connected" state, but
2159 we can't afford to wait for this information when
2160 we are loaded with profile="hsp", for instance */
2161 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2162 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2166 p->max_sink_channels = 2;
2167 p->max_source_channels = 0;
2169 d = PA_CARD_PROFILE_DATA(p);
2171 create_ports_for_profile(u, &data, p);
2173 pa_hashmap_put(data.profiles, p->name, p);
2176 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2177 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2181 p->max_sink_channels = 0;
2182 p->max_source_channels = 2;
2184 d = PA_CARD_PROFILE_DATA(p);
2185 *d = PROFILE_A2DP_SOURCE;
2186 create_ports_for_profile(u, &data, p);
2188 pa_hashmap_put(data.profiles, p->name, p);
2191 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2192 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2193 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2197 p->max_sink_channels = 1;
2198 p->max_source_channels = 1;
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, HFP_AG_UUID)) {
2208 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2212 p->max_sink_channels = 1;
2213 p->max_source_channels = 1;
2215 d = PA_CARD_PROFILE_DATA(p);
2217 create_ports_for_profile(u, &data, p);
2219 pa_hashmap_put(data.profiles, p->name, p);
2222 pa_assert(!pa_hashmap_isempty(data.profiles));
2224 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2225 d = PA_CARD_PROFILE_DATA(p);
2227 pa_hashmap_put(data.profiles, p->name, p);
2229 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2230 if (pa_hashmap_get(data.profiles, default_profile))
2231 pa_card_new_data_set_profile(&data, default_profile);
2233 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2236 u->card = pa_card_new(u->core, &data);
2237 pa_card_new_data_done(&data);
2240 pa_log("Failed to allocate card.");
2244 u->card->userdata = u;
2245 u->card->set_profile = card_set_profile;
2247 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2249 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2250 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2251 (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) ||
2252 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2253 pa_log_warn("Default profile not connected, selecting off profile");
2254 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2255 u->card->save_profile = FALSE;
2258 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2261 if (USE_SCO_OVER_PCM(u))
2262 save_sco_volume_callbacks(u);
2267 /* Run from main thread */
2268 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2269 const pa_bluetooth_device *d = NULL;
2273 if (!address && !path) {
2274 pa_log_error("Failed to get device address/path from module arguments.");
2279 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2280 pa_log_error("%s is not a valid BlueZ audio device.", path);
2284 if (address && !(pa_streq(d->address, address))) {
2285 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2290 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2291 pa_log_error("%s is not known.", address);
2297 u->address = pa_xstrdup(d->address);
2298 u->path = pa_xstrdup(d->path);
2304 /* Run from main thread */
2305 static int setup_dbus(struct userdata *u) {
2308 dbus_error_init(&err);
2310 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2312 if (dbus_error_is_set(&err) || !u->connection) {
2313 pa_log("Failed to get D-Bus connection: %s", err.message);
2314 dbus_error_free(&err);
2321 int pa__init(pa_module* m) {
2325 const char *address, *path;
2327 char *mike, *speaker;
2328 const pa_bluetooth_device *device;
2332 dbus_error_init(&err);
2334 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2335 pa_log_error("Failed to parse module arguments");
2339 m->userdata = u = pa_xnew0(struct userdata, 1);
2343 u->sample_spec = m->core->default_sample_spec;
2346 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2347 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2348 pa_log("SCO sink not found");
2352 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2353 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2354 pa_log("SCO source not found");
2358 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2359 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2360 pa_log_error("Failed to get rate from module arguments");
2364 u->auto_connect = TRUE;
2365 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2366 pa_log("Failed to parse auto_connect= argument");
2370 channels = u->sample_spec.channels;
2371 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2372 channels <= 0 || channels > PA_CHANNELS_MAX) {
2373 pa_log_error("Failed to get channels from module arguments");
2376 u->sample_spec.channels = (uint8_t) channels;
2377 u->requested_sample_spec = u->sample_spec;
2379 address = pa_modargs_get_value(ma, "address", NULL);
2380 path = pa_modargs_get_value(ma, "path", NULL);
2382 if (setup_dbus(u) < 0)
2385 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2388 if (!(device = find_device(u, address, path)))
2391 /* Add the card structure. This will also initialize the default profile */
2392 if (add_card(u, device) < 0)
2395 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2398 u->msg->parent.process_msg = device_process_msg;
2399 u->msg->card = u->card;
2401 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2402 pa_log_error("Failed to add filter function");
2405 u->filter_added = TRUE;
2407 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2408 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2410 if (pa_dbus_add_matches(
2411 pa_dbus_connection_get(u->connection), &err,
2414 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2415 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2421 pa_log("Failed to add D-Bus matches: %s", err.message);
2428 if (u->profile != PROFILE_OFF)
2429 if (init_profile(u) < 0)
2432 if (u->sink || u->source)
2433 if (start_thread(u) < 0)
2442 dbus_error_free(&err);
2447 int pa__get_n_used(pa_module *m) {
2451 pa_assert_se(u = m->userdata);
2454 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2455 (u->source ? pa_source_linked_by(u->source) : 0);
2458 void pa__done(pa_module *m) {
2463 if (!(u = m->userdata))
2466 if (u->sink && !USE_SCO_OVER_PCM(u))
2467 pa_sink_unlink(u->sink);
2469 if (u->source && !USE_SCO_OVER_PCM(u))
2470 pa_source_unlink(u->source);
2474 if (USE_SCO_OVER_PCM(u))
2475 restore_sco_volume_callbacks(u);
2477 if (u->connection) {
2480 char *speaker, *mike;
2481 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2482 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2484 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
2485 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2486 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2493 if (u->filter_added)
2494 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2496 pa_dbus_connection_unref(u->connection);
2503 pa_card_free(u->card);
2505 if (u->read_smoother)
2506 pa_smoother_free(u->read_smoother);
2509 pa_xfree(u->a2dp.buffer);
2511 sbc_finish(&u->a2dp.sbc);
2514 pa_modargs_free(u->modargs);
2516 pa_xfree(u->address);
2520 bt_transport_release(u);
2521 pa_xfree(u->transport);
2525 pa_bluetooth_discovery_unref(u->discovery);