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 */
246 static void bt_transport_config_mtu(struct userdata *u) {
247 /* Calculate block sizes */
248 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
249 u->read_block_size = u->read_link_mtu;
250 u->write_block_size = u->write_link_mtu;
253 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
254 / u->a2dp.frame_length * u->a2dp.codesize;
256 u->write_block_size =
257 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
258 / u->a2dp.frame_length * u->a2dp.codesize;
261 if (USE_SCO_OVER_PCM(u))
265 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
266 pa_sink_set_fixed_latency_within_thread(u->sink,
267 (u->profile == PROFILE_A2DP ?
268 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
269 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
273 pa_source_set_fixed_latency_within_thread(u->source,
274 (u->profile == PROFILE_A2DP_SOURCE ?
275 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
276 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
279 /* from IO thread, except in SCO over PCM */
281 static void setup_stream(struct userdata *u) {
282 struct pollfd *pollfd;
285 bt_transport_config_mtu(u);
287 pa_make_fd_nonblock(u->stream_fd);
288 pa_make_socket_low_delay(u->stream_fd);
291 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
292 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
294 pa_log_debug("Stream properly set up, we're ready to roll!");
296 if (u->profile == PROFILE_A2DP)
297 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
299 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
300 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
301 pollfd->fd = u->stream_fd;
302 pollfd->events = pollfd->revents = 0;
304 u->read_index = u->write_index = 0;
308 u->read_smoother = pa_smoother_new(
318 static bool bt_transport_is_acquired(struct userdata *u) {
319 if (u->accesstype == NULL) {
320 pa_assert(u->stream_fd < 0);
323 pa_assert(u->stream_fd >= 0);
328 static void bt_transport_release(struct userdata *u) {
329 const char *accesstype = "rw";
330 const pa_bluetooth_transport *t;
332 /* Ignore if already released */
333 if (!bt_transport_is_acquired(u))
336 pa_log_debug("Releasing transport %s", u->transport);
338 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
340 pa_bluetooth_transport_release(t, accesstype);
342 pa_xfree(u->accesstype);
343 u->accesstype = NULL;
345 if (u->rtpoll_item) {
346 pa_rtpoll_item_free(u->rtpoll_item);
347 u->rtpoll_item = NULL;
350 if (u->stream_fd >= 0) {
351 pa_close(u->stream_fd);
355 if (u->read_smoother) {
356 pa_smoother_free(u->read_smoother);
357 u->read_smoother = NULL;
361 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
362 const char *accesstype = "rw";
363 const pa_bluetooth_transport *t;
365 if (u->transport == NULL) {
366 pa_log("Transport no longer available.");
370 if (bt_transport_is_acquired(u)) {
376 pa_log_debug("Acquiring transport %s", u->transport);
378 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
380 pa_log("Transport %s no longer available", u->transport);
381 pa_xfree(u->transport);
386 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, &u->read_link_mtu, &u->write_link_mtu);
387 if (u->stream_fd < 0)
390 u->accesstype = pa_xstrdup(accesstype);
391 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
397 pa_log_info("Transport %s resuming", u->transport);
403 /* Run from IO thread */
404 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
405 struct userdata *u = PA_SINK(o)->userdata;
406 pa_bool_t failed = FALSE;
409 pa_assert(u->sink == PA_SINK(o));
410 pa_assert(u->transport);
414 case PA_SINK_MESSAGE_SET_STATE:
416 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
418 case PA_SINK_SUSPENDED:
419 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
420 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
423 /* Stop the device if the source is suspended as well */
424 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
425 /* We deliberately ignore whether stopping
426 * actually worked. Since the stream_fd is
427 * closed it doesn't really matter */
428 bt_transport_release(u);
433 case PA_SINK_RUNNING:
434 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
437 /* Resume the device if the source was suspended as well */
438 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
439 if (bt_transport_acquire(u, TRUE) < 0)
444 case PA_SINK_UNLINKED:
446 case PA_SINK_INVALID_STATE:
451 case PA_SINK_MESSAGE_GET_LATENCY: {
453 if (u->read_smoother) {
456 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
457 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
459 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
463 ri = pa_rtclock_now() - u->started_at;
464 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
466 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
469 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
474 r = pa_sink_process_msg(o, code, data, offset, chunk);
476 return (r < 0 || !failed) ? r : -1;
479 /* Run from IO thread */
480 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
481 struct userdata *u = PA_SOURCE(o)->userdata;
482 pa_bool_t failed = FALSE;
485 pa_assert(u->source == PA_SOURCE(o));
486 pa_assert(u->transport);
490 case PA_SOURCE_MESSAGE_SET_STATE:
492 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
494 case PA_SOURCE_SUSPENDED:
495 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
496 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
499 /* Stop the device if the sink is suspended as well */
500 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
501 bt_transport_release(u);
503 if (u->read_smoother)
504 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
508 case PA_SOURCE_RUNNING:
509 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
512 /* Resume the device if the sink was suspended as well */
513 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
514 if (bt_transport_acquire(u, TRUE) < 0)
517 /* We don't resume the smoother here. Instead we
518 * wait until the first packet arrives */
521 case PA_SOURCE_UNLINKED:
523 case PA_SOURCE_INVALID_STATE:
528 case PA_SOURCE_MESSAGE_GET_LATENCY: {
531 if (u->read_smoother) {
532 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
533 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
535 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
537 *((pa_usec_t*) data) = 0;
544 r = pa_source_process_msg(o, code, data, offset, chunk);
546 return (r < 0 || !failed) ? r : -1;
549 /* Called from main thread context */
550 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
551 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
554 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
555 if (u->card->module->unload_requested)
558 pa_log_debug("Switching the profile to off due to IO thread failure.");
560 if (pa_card_set_profile(u->card, "off", FALSE) < 0)
561 pa_log_debug("Failed to switch profile to off");
568 /* Run from IO thread */
569 static int hsp_process_render(struct userdata *u) {
573 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
576 /* First, render some data */
577 if (!u->write_memchunk.memblock)
578 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
580 pa_assert(u->write_memchunk.length == u->write_block_size);
586 /* Now write that data to the socket. The socket is of type
587 * SEQPACKET, and we generated the data of the MTU size, so this
588 * should just work. */
590 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
591 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
592 pa_memblock_release(u->write_memchunk.memblock);
599 /* Retry right away if we got interrupted */
602 else if (errno == EAGAIN)
603 /* Hmm, apparently the socket was not writable, give up for now */
606 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
611 pa_assert((size_t) l <= u->write_memchunk.length);
613 if ((size_t) l != u->write_memchunk.length) {
614 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
615 (unsigned long long) l,
616 (unsigned long long) u->write_memchunk.length);
621 u->write_index += (uint64_t) u->write_memchunk.length;
622 pa_memblock_unref(u->write_memchunk.memblock);
623 pa_memchunk_reset(&u->write_memchunk);
632 /* Run from IO thread */
633 static int hsp_process_push(struct userdata *u) {
635 pa_memchunk memchunk;
638 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
639 pa_assert(u->source);
640 pa_assert(u->read_smoother);
642 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
643 memchunk.index = memchunk.length = 0;
652 pa_bool_t found_tstamp = FALSE;
655 memset(&m, 0, sizeof(m));
656 memset(&aux, 0, sizeof(aux));
657 memset(&iov, 0, sizeof(iov));
662 m.msg_controllen = sizeof(aux);
664 p = pa_memblock_acquire(memchunk.memblock);
666 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
667 l = recvmsg(u->stream_fd, &m, 0);
668 pa_memblock_release(memchunk.memblock);
672 if (l < 0 && errno == EINTR)
673 /* Retry right away if we got interrupted */
676 else if (l < 0 && errno == EAGAIN)
677 /* Hmm, apparently the socket was not readable, give up for now. */
680 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
685 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
687 memchunk.length = (size_t) l;
688 u->read_index += (uint64_t) l;
690 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
691 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
692 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
693 pa_rtclock_from_wallclock(tv);
694 tstamp = pa_timeval_load(tv);
700 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
701 tstamp = pa_rtclock_now();
704 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
705 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
707 pa_source_post(u->source, &memchunk);
713 pa_memblock_unref(memchunk.memblock);
718 /* Run from IO thread */
719 static void a2dp_prepare_buffer(struct userdata *u) {
720 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
724 if (u->a2dp.buffer_size >= min_buffer_size)
727 u->a2dp.buffer_size = 2 * min_buffer_size;
728 pa_xfree(u->a2dp.buffer);
729 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
732 /* Run from IO thread */
733 static int a2dp_process_render(struct userdata *u) {
734 struct a2dp_info *a2dp;
735 struct rtp_header *header;
736 struct rtp_payload *payload;
740 size_t to_write, to_encode;
741 unsigned frame_count;
745 pa_assert(u->profile == PROFILE_A2DP);
748 /* First, render some data */
749 if (!u->write_memchunk.memblock)
750 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
752 pa_assert(u->write_memchunk.length == u->write_block_size);
754 a2dp_prepare_buffer(u);
757 header = a2dp->buffer;
758 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
762 /* Try to create a packet of the full MTU */
764 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
765 to_encode = u->write_memchunk.length;
767 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
768 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
770 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
774 encoded = sbc_encode(&a2dp->sbc,
779 if (PA_UNLIKELY(encoded <= 0)) {
780 pa_log_error("SBC encoding error (%li)", (long) encoded);
781 pa_memblock_release(u->write_memchunk.memblock);
785 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
786 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
788 pa_assert_fp((size_t) encoded <= to_encode);
789 pa_assert_fp((size_t) encoded == a2dp->codesize);
791 pa_assert_fp((size_t) written <= to_write);
792 pa_assert_fp((size_t) written == a2dp->frame_length);
794 p = (const uint8_t*) p + encoded;
795 to_encode -= encoded;
797 d = (uint8_t*) d + written;
803 pa_memblock_release(u->write_memchunk.memblock);
805 pa_assert(to_encode == 0);
808 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
811 /* write it to the fifo */
812 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
815 header->sequence_number = htons(a2dp->seq_num++);
816 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
817 header->ssrc = htonl(1);
818 payload->frame_count = frame_count;
820 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
825 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
832 /* Retry right away if we got interrupted */
835 else if (errno == EAGAIN)
836 /* Hmm, apparently the socket was not writable, give up for now */
839 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
844 pa_assert((size_t) l <= nbytes);
846 if ((size_t) l != nbytes) {
847 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
848 (unsigned long long) l,
849 (unsigned long long) nbytes);
854 u->write_index += (uint64_t) u->write_memchunk.length;
855 pa_memblock_unref(u->write_memchunk.memblock);
856 pa_memchunk_reset(&u->write_memchunk);
866 static int a2dp_process_push(struct userdata *u) {
868 pa_memchunk memchunk;
871 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
872 pa_assert(u->source);
873 pa_assert(u->read_smoother);
875 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
876 memchunk.index = memchunk.length = 0;
879 pa_bool_t found_tstamp = FALSE;
881 struct a2dp_info *a2dp;
882 struct rtp_header *header;
883 struct rtp_payload *payload;
887 size_t to_write, to_decode;
889 a2dp_prepare_buffer(u);
892 header = a2dp->buffer;
893 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
895 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
899 if (l < 0 && errno == EINTR)
900 /* Retry right away if we got interrupted */
903 else if (l < 0 && errno == EAGAIN)
904 /* Hmm, apparently the socket was not readable, give up for now. */
907 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
912 pa_assert((size_t) l <= a2dp->buffer_size);
914 u->read_index += (uint64_t) l;
916 /* TODO: get timestamp from rtp */
918 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
919 tstamp = pa_rtclock_now();
922 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
923 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
925 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
926 to_decode = l - sizeof(*header) - sizeof(*payload);
928 d = pa_memblock_acquire(memchunk.memblock);
929 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
931 while (PA_LIKELY(to_decode > 0)) {
935 decoded = sbc_decode(&a2dp->sbc,
940 if (PA_UNLIKELY(decoded <= 0)) {
941 pa_log_error("SBC decoding error (%li)", (long) decoded);
942 pa_memblock_release(memchunk.memblock);
943 pa_memblock_unref(memchunk.memblock);
947 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
948 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
950 /* Reset frame length, it can be changed due to bitpool change */
951 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
953 pa_assert_fp((size_t) decoded <= to_decode);
954 pa_assert_fp((size_t) decoded == a2dp->frame_length);
956 pa_assert_fp((size_t) written == a2dp->codesize);
958 p = (const uint8_t*) p + decoded;
959 to_decode -= decoded;
961 d = (uint8_t*) d + written;
965 memchunk.length -= to_write;
967 pa_memblock_release(memchunk.memblock);
969 pa_source_post(u->source, &memchunk);
975 pa_memblock_unref(memchunk.memblock);
980 static void a2dp_reduce_bitpool(struct userdata *u)
982 struct a2dp_info *a2dp;
989 /* Check if bitpool is already at its limit */
990 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
993 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
995 if (bitpool < BITPOOL_DEC_LIMIT)
996 bitpool = BITPOOL_DEC_LIMIT;
998 a2dp_set_bitpool(u, bitpool);
1001 static void thread_func(void *userdata) {
1002 struct userdata *u = userdata;
1003 unsigned do_write = 0;
1004 unsigned pending_read_bytes = 0;
1005 pa_bool_t writable = FALSE;
1008 pa_assert(u->transport);
1010 pa_log_debug("IO Thread starting up");
1012 if (u->core->realtime_scheduling)
1013 pa_make_realtime(u->core->realtime_priority);
1015 pa_thread_mq_install(&u->thread_mq);
1017 if (bt_transport_acquire(u, TRUE) < 0)
1021 struct pollfd *pollfd;
1023 pa_bool_t disable_timer = TRUE;
1025 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1027 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1029 /* We should send two blocks to the device before we expect
1032 if (u->write_index == 0 && u->read_index <= 0)
1035 if (pollfd && (pollfd->revents & POLLIN)) {
1038 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1039 n_read = hsp_process_push(u);
1041 n_read = a2dp_process_push(u);
1046 /* We just read something, so we are supposed to write something, too */
1047 pending_read_bytes += n_read;
1048 do_write += pending_read_bytes / u->write_block_size;
1049 pending_read_bytes = pending_read_bytes % u->write_block_size;
1053 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1055 if (u->sink->thread_info.rewind_requested)
1056 pa_sink_process_rewind(u->sink, 0);
1059 if (pollfd->revents & POLLOUT)
1062 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1063 pa_usec_t time_passed;
1064 pa_usec_t audio_sent;
1066 /* Hmm, there is no input stream we could synchronize
1067 * to. So let's do things by time */
1069 time_passed = pa_rtclock_now() - u->started_at;
1070 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1072 if (audio_sent <= time_passed) {
1073 pa_usec_t audio_to_send = time_passed - audio_sent;
1075 /* Never try to catch up for more than 100ms */
1076 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1077 pa_usec_t skip_usec;
1078 uint64_t skip_bytes;
1080 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1081 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1083 if (skip_bytes > 0) {
1086 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1087 (unsigned long long) skip_usec,
1088 (unsigned long long) skip_bytes);
1090 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1091 pa_memblock_unref(tmp.memblock);
1092 u->write_index += skip_bytes;
1094 if (u->profile == PROFILE_A2DP)
1095 a2dp_reduce_bitpool(u);
1100 pending_read_bytes = 0;
1104 if (writable && do_write > 0) {
1107 if (u->write_index <= 0)
1108 u->started_at = pa_rtclock_now();
1110 if (u->profile == PROFILE_A2DP) {
1111 if ((n_written = a2dp_process_render(u)) < 0)
1114 if ((n_written = hsp_process_render(u)) < 0)
1119 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1121 do_write -= n_written;
1125 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1126 pa_usec_t sleep_for;
1127 pa_usec_t time_passed, next_write_at;
1130 /* Hmm, there is no input stream we could synchronize
1131 * to. So let's estimate when we need to wake up the latest */
1132 time_passed = pa_rtclock_now() - u->started_at;
1133 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1134 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1135 /* 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); */
1137 /* drop stream every 500 ms */
1138 sleep_for = PA_USEC_PER_MSEC * 500;
1140 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1141 disable_timer = FALSE;
1147 pa_rtpoll_set_timer_disabled(u->rtpoll);
1149 /* Hmm, nothing to do. Let's sleep */
1151 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1152 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1154 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
1155 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1159 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1160 bt_transport_release(u);
1164 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1166 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1167 pa_log_info("FD error: %s%s%s%s",
1168 pollfd->revents & POLLERR ? "POLLERR " :"",
1169 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1170 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1171 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1177 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1178 pa_log_debug("IO thread failed");
1179 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1180 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1183 pa_log_debug("IO thread shutting down");
1186 static pa_bt_audio_state_t parse_state_property_change(DBusMessage *m) {
1187 DBusMessageIter iter;
1188 DBusMessageIter variant;
1191 pa_bt_audio_state_t state;
1193 if (!dbus_message_iter_init(m, &iter)) {
1194 pa_log("Failed to parse PropertyChanged");
1195 return PA_BT_AUDIO_STATE_INVALID;
1198 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1199 pa_log("Property name not a string");
1200 return PA_BT_AUDIO_STATE_INVALID;
1203 dbus_message_iter_get_basic(&iter, &key);
1205 if (!pa_streq(key, "State"))
1206 return PA_BT_AUDIO_STATE_INVALID;
1208 if (!dbus_message_iter_next(&iter)) {
1209 pa_log("Property value missing");
1210 return PA_BT_AUDIO_STATE_INVALID;
1213 dbus_message_iter_recurse(&iter, &variant);
1215 if (dbus_message_iter_get_arg_type(&variant) != DBUS_TYPE_STRING) {
1216 pa_log("Property value not a string");
1217 return PA_BT_AUDIO_STATE_INVALID;
1220 dbus_message_iter_get_basic(&variant, &value);
1222 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m), value);
1224 state = pa_bt_audio_state_from_string(value);
1226 if (state == PA_BT_AUDIO_STATE_INVALID)
1227 pa_log("Unexpected value for property 'State': '%s'", value);
1232 static pa_port_available_t audio_state_to_availability(pa_bt_audio_state_t state) {
1233 if (state < PA_BT_AUDIO_STATE_CONNECTED)
1234 return PA_PORT_AVAILABLE_NO;
1235 else if (state >= PA_BT_AUDIO_STATE_PLAYING)
1236 return PA_PORT_AVAILABLE_YES;
1238 return PA_PORT_AVAILABLE_UNKNOWN;
1241 /* Run from main thread */
1242 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1245 bool acquire = FALSE;
1246 bool release = FALSE;
1250 pa_assert_se(u = userdata);
1252 dbus_error_init(&err);
1254 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1255 dbus_message_get_interface(m),
1256 dbus_message_get_path(m),
1257 dbus_message_get_member(m));
1259 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1262 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1263 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1268 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1269 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1273 if (u->profile == PROFILE_HSP) {
1274 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1275 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1277 /* increment volume by one to correct rounding errors */
1278 if (volume < PA_VOLUME_NORM)
1281 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1282 pa_sink_volume_changed(u->sink, &v);
1284 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1285 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1287 /* increment volume by one to correct rounding errors */
1288 if (volume < PA_VOLUME_NORM)
1291 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1292 pa_source_volume_changed(u->source, &v);
1295 } else if (dbus_message_is_signal(m, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1296 pa_bt_audio_state_t state = parse_state_property_change(m);
1298 if (state != PA_BT_AUDIO_STATE_INVALID) {
1299 pa_device_port *port;
1300 pa_port_available_t available = audio_state_to_availability(state);
1302 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1303 pa_device_port_set_available(port, available);
1305 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1306 pa_device_port_set_available(port, available);
1308 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1309 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1311 } else if (dbus_message_is_signal(m, "org.bluez.Headset", "PropertyChanged")) {
1312 pa_bt_audio_state_t state = parse_state_property_change(m);
1314 if (state != PA_BT_AUDIO_STATE_INVALID) {
1315 pa_device_port *port;
1316 pa_port_available_t available = audio_state_to_availability(state);
1318 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1319 pa_device_port_set_available(port, available);
1321 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1322 pa_device_port_set_available(port, available);
1324 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HSP);
1325 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HSP);
1327 } else if (dbus_message_is_signal(m, "org.bluez.AudioSource", "PropertyChanged")) {
1328 pa_bt_audio_state_t state = parse_state_property_change(m);
1330 if (state != PA_BT_AUDIO_STATE_INVALID) {
1331 pa_device_port *port;
1332 pa_port_available_t available = audio_state_to_availability(state);
1334 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1335 pa_device_port_set_available(port, available);
1337 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1338 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1340 } else if (dbus_message_is_signal(m, "org.bluez.AudioSink", "PropertyChanged")) {
1341 pa_bt_audio_state_t state = parse_state_property_change(m);
1343 if (state != PA_BT_AUDIO_STATE_INVALID) {
1344 pa_device_port *port;
1345 pa_port_available_t available = audio_state_to_availability(state);
1347 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1348 pa_device_port_set_available(port, available);
1350 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1351 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1356 if (bt_transport_acquire(u, FALSE) >= 0) {
1358 pa_source_suspend(u->source, FALSE, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1361 pa_sink_suspend(u->sink, FALSE, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1364 if (release && bt_transport_is_acquired(u)) {
1365 /* FIXME: this release is racy, since the audio stream might have
1366 been set up again in the meantime (but not processed yet by PA).
1367 BlueZ should probably release the transport automatically, and
1368 in that case we would just mark the transport as released */
1370 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1372 pa_source_suspend(u->source, TRUE, PA_SUSPEND_USER);
1375 pa_sink_suspend(u->sink, TRUE, PA_SUSPEND_USER);
1379 dbus_error_free(&err);
1381 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1384 /* Run from main thread */
1385 static void sink_set_volume_cb(pa_sink *s) {
1395 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1396 u = pa_shared_get(s->core, k);
1400 pa_assert(u->sink == s);
1401 pa_assert(u->profile == PROFILE_HSP);
1403 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1405 if (gain > HSP_MAX_GAIN)
1406 gain = HSP_MAX_GAIN;
1408 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1410 /* increment volume by one to correct rounding errors */
1411 if (volume < PA_VOLUME_NORM)
1414 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1416 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1417 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1418 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1419 dbus_message_unref(m);
1422 /* Run from main thread */
1423 static void source_set_volume_cb(pa_source *s) {
1433 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1434 u = pa_shared_get(s->core, k);
1438 pa_assert(u->source == s);
1439 pa_assert(u->profile == PROFILE_HSP);
1441 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1443 if (gain > HSP_MAX_GAIN)
1444 gain = HSP_MAX_GAIN;
1446 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1448 /* increment volume by one to correct rounding errors */
1449 if (volume < PA_VOLUME_NORM)
1452 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1454 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1455 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1456 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1457 dbus_message_unref(m);
1460 /* Run from main thread */
1461 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1467 pa_assert(device_id);
1468 pa_assert(namereg_fail);
1470 t = pa_sprintf_malloc("%s_name", type);
1471 n = pa_modargs_get_value(ma, t, NULL);
1475 *namereg_fail = TRUE;
1476 return pa_xstrdup(n);
1479 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1480 *namereg_fail = TRUE;
1483 *namereg_fail = FALSE;
1486 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1489 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1491 pa_assert(USE_SCO_OVER_PCM(u));
1493 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1494 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1496 if (u->stream_fd >= 0)
1499 pa_log_debug("Resuming SCO over PCM");
1500 if (init_profile(u) < 0) {
1501 pa_log("Can't resume SCO over PCM");
1505 return bt_transport_acquire(u, TRUE);
1509 if (u->stream_fd < 0)
1512 pa_log_debug("Closing SCO over PCM");
1514 bt_transport_release(u);
1520 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1522 pa_sink_assert_ref(s);
1525 if (s != u->hsp.sco_sink)
1528 sco_over_pcm_state_update(u, TRUE);
1533 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1535 pa_source_assert_ref(s);
1538 if (s != u->hsp.sco_source)
1541 sco_over_pcm_state_update(u, TRUE);
1546 static pa_hook_result_t nrec_changed_cb(pa_bluetooth_transport *t, void *call_data, struct userdata *u) {
1552 p = pa_proplist_new();
1553 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1554 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1555 pa_proplist_free(p);
1560 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1562 pa_sink_new_data *sink_new_data;
1563 pa_source_new_data *source_new_data;
1565 pa_device_port *port;
1567 if (direction == PA_DIRECTION_OUTPUT) {
1568 data.sink_new_data = sink_or_source_new_data;
1569 data.sink_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1571 data.source_new_data = sink_or_source_new_data;
1572 data.source_new_data->ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1575 switch (u->profile) {
1577 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1578 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1579 pa_device_port_ref(port);
1582 case PROFILE_A2DP_SOURCE:
1583 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1584 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1585 pa_device_port_ref(port);
1589 if (direction == PA_DIRECTION_OUTPUT) {
1590 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1591 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1593 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1594 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1596 pa_device_port_ref(port);
1600 if (direction == PA_DIRECTION_OUTPUT) {
1601 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1602 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1604 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1605 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1607 pa_device_port_ref(port);
1611 pa_assert_not_reached();
1615 static const char *profile_to_string(enum profile profile) {
1619 case PROFILE_A2DP_SOURCE:
1620 return "a2dp_source";
1626 pa_assert_not_reached();
1630 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1634 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1638 /* Run from main thread */
1639 static int add_sink(struct userdata *u) {
1642 if (USE_SCO_OVER_PCM(u)) {
1645 u->sink = u->hsp.sco_sink;
1646 p = pa_proplist_new();
1647 pa_proplist_sets(p, "bluetooth.protocol", profile_to_string(u->profile));
1648 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1649 pa_proplist_free(p);
1651 if (!u->hsp.sink_state_changed_slot)
1652 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);
1655 pa_sink_new_data data;
1658 pa_sink_new_data_init(&data);
1659 data.driver = __FILE__;
1660 data.module = u->module;
1661 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1662 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1663 if (u->profile == PROFILE_HSP)
1664 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1665 data.card = u->card;
1666 data.name = get_name("sink", u->modargs, u->address, &b);
1667 data.namereg_fail = b;
1669 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1670 pa_log("Invalid properties");
1671 pa_sink_new_data_done(&data);
1674 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1676 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1677 pa_sink_new_data_done(&data);
1680 pa_log_error("Failed to create sink");
1684 u->sink->userdata = u;
1685 u->sink->parent.process_msg = sink_process_msg;
1686 u->sink->set_port = sink_set_port_cb;
1689 if (u->profile == PROFILE_HSP) {
1690 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1691 u->sink->n_volume_steps = 16;
1693 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1694 pa_shared_set(u->core, k, u);
1701 /* Run from main thread */
1702 static int add_source(struct userdata *u) {
1705 if (USE_SCO_OVER_PCM(u)) {
1706 u->source = u->hsp.sco_source;
1707 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", profile_to_string(u->profile));
1709 if (!u->hsp.source_state_changed_slot)
1710 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);
1713 pa_source_new_data data;
1716 pa_source_new_data_init(&data);
1717 data.driver = __FILE__;
1718 data.module = u->module;
1719 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1720 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1721 if (u->profile == PROFILE_HSP)
1722 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1724 data.card = u->card;
1725 data.name = get_name("source", u->modargs, u->address, &b);
1726 data.namereg_fail = b;
1728 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1729 pa_log("Invalid properties");
1730 pa_source_new_data_done(&data);
1734 connect_ports(u, &data, PA_DIRECTION_INPUT);
1735 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1736 pa_source_new_data_done(&data);
1739 pa_log_error("Failed to create source");
1743 u->source->userdata = u;
1744 u->source->parent.process_msg = source_process_msg;
1745 u->source->set_port = source_set_port_cb;
1748 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1749 pa_bluetooth_transport *t;
1750 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1752 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1754 if (!u->hsp.nrec_changed_slot)
1755 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);
1758 if (u->profile == PROFILE_HSP) {
1759 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1760 u->source->n_volume_steps = 16;
1762 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1763 pa_shared_set(u->core, k, u);
1770 static void bt_transport_config_a2dp(struct userdata *u) {
1771 const pa_bluetooth_transport *t;
1772 struct a2dp_info *a2dp = &u->a2dp;
1775 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1778 config = (a2dp_sbc_t *) t->config;
1780 u->sample_spec.format = PA_SAMPLE_S16LE;
1782 if (a2dp->sbc_initialized)
1783 sbc_reinit(&a2dp->sbc, 0);
1785 sbc_init(&a2dp->sbc, 0);
1786 a2dp->sbc_initialized = TRUE;
1788 switch (config->frequency) {
1789 case BT_SBC_SAMPLING_FREQ_16000:
1790 a2dp->sbc.frequency = SBC_FREQ_16000;
1791 u->sample_spec.rate = 16000U;
1793 case BT_SBC_SAMPLING_FREQ_32000:
1794 a2dp->sbc.frequency = SBC_FREQ_32000;
1795 u->sample_spec.rate = 32000U;
1797 case BT_SBC_SAMPLING_FREQ_44100:
1798 a2dp->sbc.frequency = SBC_FREQ_44100;
1799 u->sample_spec.rate = 44100U;
1801 case BT_SBC_SAMPLING_FREQ_48000:
1802 a2dp->sbc.frequency = SBC_FREQ_48000;
1803 u->sample_spec.rate = 48000U;
1806 pa_assert_not_reached();
1809 switch (config->channel_mode) {
1810 case BT_A2DP_CHANNEL_MODE_MONO:
1811 a2dp->sbc.mode = SBC_MODE_MONO;
1812 u->sample_spec.channels = 1;
1814 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
1815 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1816 u->sample_spec.channels = 2;
1818 case BT_A2DP_CHANNEL_MODE_STEREO:
1819 a2dp->sbc.mode = SBC_MODE_STEREO;
1820 u->sample_spec.channels = 2;
1822 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
1823 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1824 u->sample_spec.channels = 2;
1827 pa_assert_not_reached();
1830 switch (config->allocation_method) {
1831 case BT_A2DP_ALLOCATION_SNR:
1832 a2dp->sbc.allocation = SBC_AM_SNR;
1834 case BT_A2DP_ALLOCATION_LOUDNESS:
1835 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1838 pa_assert_not_reached();
1841 switch (config->subbands) {
1842 case BT_A2DP_SUBBANDS_4:
1843 a2dp->sbc.subbands = SBC_SB_4;
1845 case BT_A2DP_SUBBANDS_8:
1846 a2dp->sbc.subbands = SBC_SB_8;
1849 pa_assert_not_reached();
1852 switch (config->block_length) {
1853 case BT_A2DP_BLOCK_LENGTH_4:
1854 a2dp->sbc.blocks = SBC_BLK_4;
1856 case BT_A2DP_BLOCK_LENGTH_8:
1857 a2dp->sbc.blocks = SBC_BLK_8;
1859 case BT_A2DP_BLOCK_LENGTH_12:
1860 a2dp->sbc.blocks = SBC_BLK_12;
1862 case BT_A2DP_BLOCK_LENGTH_16:
1863 a2dp->sbc.blocks = SBC_BLK_16;
1866 pa_assert_not_reached();
1869 a2dp->min_bitpool = config->min_bitpool;
1870 a2dp->max_bitpool = config->max_bitpool;
1872 /* Set minimum bitpool for source to get the maximum possible block_size */
1873 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1874 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1875 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1877 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1878 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1881 static void bt_transport_config(struct userdata *u) {
1882 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1883 u->sample_spec.format = PA_SAMPLE_S16LE;
1884 u->sample_spec.channels = 1;
1885 u->sample_spec.rate = 8000;
1887 bt_transport_config_a2dp(u);
1890 /* Run from main thread */
1891 static int setup_bt(struct userdata *u) {
1892 const pa_bluetooth_device *d;
1893 const pa_bluetooth_transport *t;
1897 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1898 pa_log_error("Failed to get device object.");
1902 /* release transport if exist */
1904 bt_transport_release(u);
1905 pa_xfree(u->transport);
1906 u->transport = NULL;
1909 /* check if profile has a transport */
1910 t = pa_bluetooth_device_get_transport(d, u->profile);
1912 pa_log_warn("Profile has no transport");
1916 u->transport = pa_xstrdup(t->path);
1918 if (bt_transport_acquire(u, FALSE) < 0)
1921 bt_transport_config(u);
1926 /* Run from main thread */
1927 static int init_profile(struct userdata *u) {
1930 pa_assert(u->profile != PROFILE_OFF);
1932 if (setup_bt(u) < 0)
1935 if (u->profile == PROFILE_A2DP ||
1936 u->profile == PROFILE_HSP ||
1937 u->profile == PROFILE_HFGW)
1938 if (add_sink(u) < 0)
1941 if (u->profile == PROFILE_HSP ||
1942 u->profile == PROFILE_A2DP_SOURCE ||
1943 u->profile == PROFILE_HFGW)
1944 if (add_source(u) < 0)
1950 /* Run from main thread */
1951 static void stop_thread(struct userdata *u) {
1957 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1958 pa_thread_free(u->thread);
1962 if (u->rtpoll_item) {
1963 pa_rtpoll_item_free(u->rtpoll_item);
1964 u->rtpoll_item = NULL;
1967 if (u->hsp.sink_state_changed_slot) {
1968 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1969 u->hsp.sink_state_changed_slot = NULL;
1972 if (u->hsp.source_state_changed_slot) {
1973 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1974 u->hsp.source_state_changed_slot = NULL;
1977 if (u->hsp.nrec_changed_slot) {
1978 pa_hook_slot_free(u->hsp.nrec_changed_slot);
1979 u->hsp.nrec_changed_slot = NULL;
1983 if (u->profile == PROFILE_HSP) {
1984 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1985 pa_shared_remove(u->core, k);
1989 pa_sink_unref(u->sink);
1994 if (u->profile == PROFILE_HSP) {
1995 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1996 pa_shared_remove(u->core, k);
2000 pa_source_unref(u->source);
2005 pa_thread_mq_done(&u->thread_mq);
2007 pa_rtpoll_free(u->rtpoll);
2011 if (u->read_smoother) {
2012 pa_smoother_free(u->read_smoother);
2013 u->read_smoother = NULL;
2017 /* Run from main thread */
2018 static int start_thread(struct userdata *u) {
2020 pa_assert(!u->thread);
2021 pa_assert(!u->rtpoll);
2022 pa_assert(!u->rtpoll_item);
2024 u->rtpoll = pa_rtpoll_new();
2025 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2027 if (USE_SCO_OVER_PCM(u)) {
2028 if (sco_over_pcm_state_update(u, FALSE) < 0) {
2032 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2033 pa_shared_remove(u->core, k);
2038 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2039 pa_shared_remove(u->core, k);
2046 pa_sink_ref(u->sink);
2047 pa_source_ref(u->source);
2048 /* FIXME: monitor stream_fd error */
2052 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2053 pa_log_error("Failed to create IO thread");
2059 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2060 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2061 pa_sink_put(u->sink);
2063 if (u->sink->set_volume)
2064 u->sink->set_volume(u->sink);
2068 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2069 pa_source_set_rtpoll(u->source, u->rtpoll);
2070 pa_source_put(u->source);
2072 if (u->source->set_volume)
2073 u->source->set_volume(u->source);
2079 static void save_sco_volume_callbacks(struct userdata *u) {
2081 pa_assert(USE_SCO_OVER_PCM(u));
2083 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2084 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2087 static void restore_sco_volume_callbacks(struct userdata *u) {
2089 pa_assert(USE_SCO_OVER_PCM(u));
2091 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2092 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2095 /* Run from main thread */
2096 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2099 pa_queue *inputs = NULL, *outputs = NULL;
2100 const pa_bluetooth_device *device;
2103 pa_assert(new_profile);
2104 pa_assert_se(u = c->userdata);
2106 d = PA_CARD_PROFILE_DATA(new_profile);
2108 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2109 pa_log_error("Failed to get device object.");
2113 /* The state signal is sent by bluez, so it is racy to check
2114 strictly for CONNECTED, we should also accept STREAMING state
2115 as being good enough. However, if the profile is used
2116 concurrently (which is unlikely), ipc will fail later on, and
2117 module will be unloaded. */
2118 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2119 pa_log_warn("HSP is not connected, refused to switch profile");
2121 } else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2122 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2124 } else if (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) {
2125 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2127 } else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2128 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2133 inputs = pa_sink_move_all_start(u->sink, NULL);
2135 if (!USE_SCO_OVER_PCM(u))
2136 pa_sink_unlink(u->sink);
2140 outputs = pa_source_move_all_start(u->source, NULL);
2142 if (!USE_SCO_OVER_PCM(u))
2143 pa_source_unlink(u->source);
2148 if (u->profile != PROFILE_OFF && u->transport) {
2149 bt_transport_release(u);
2150 pa_xfree(u->transport);
2151 u->transport = NULL;
2154 if (USE_SCO_OVER_PCM(u))
2155 restore_sco_volume_callbacks(u);
2158 u->sample_spec = u->requested_sample_spec;
2160 if (USE_SCO_OVER_PCM(u))
2161 save_sco_volume_callbacks(u);
2163 if (u->profile != PROFILE_OFF)
2166 if (u->sink || u->source)
2171 pa_sink_move_all_finish(u->sink, inputs, FALSE);
2173 pa_sink_move_all_fail(inputs);
2178 pa_source_move_all_finish(u->source, outputs, FALSE);
2180 pa_source_move_all_fail(outputs);
2186 static void create_ports_for_profile(struct userdata *u, const pa_bluetooth_device *device, pa_card_new_data *card_new_data, pa_card_profile *profile) {
2187 pa_device_port *port;
2190 d = PA_CARD_PROFILE_DATA(profile);
2194 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2195 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2196 port->is_output = 1;
2198 port->priority = profile->priority * 100;
2199 port->available = audio_state_to_availability(device->audio_sink_state);
2200 pa_hashmap_put(port->profiles, profile->name, profile);
2203 case PROFILE_A2DP_SOURCE:
2204 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2205 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2206 port->is_output = 0;
2208 port->priority = profile->priority * 100;
2209 port->available = audio_state_to_availability(device->audio_source_state);
2210 pa_hashmap_put(port->profiles, profile->name, profile);
2214 pa_assert_se(port = pa_device_port_new(u->core, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2215 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2216 port->is_output = 1;
2218 port->priority = profile->priority * 100;
2219 port->available = audio_state_to_availability(device->headset_state);
2220 pa_hashmap_put(port->profiles, profile->name, profile);
2222 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2223 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2224 port->is_output = 0;
2226 port->priority = profile->priority * 100;
2227 port->available = audio_state_to_availability(device->headset_state);
2228 pa_hashmap_put(port->profiles, profile->name, profile);
2232 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2233 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2234 port->is_output = 1;
2236 port->priority = profile->priority * 100;
2237 port->available = audio_state_to_availability(device->hfgw_state);
2238 pa_hashmap_put(port->profiles, profile->name, profile);
2240 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2241 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2242 port->is_output = 0;
2244 port->priority = profile->priority * 100;
2245 port->available = audio_state_to_availability(device->hfgw_state);
2246 pa_hashmap_put(port->profiles, profile->name, profile);
2250 pa_assert_not_reached();
2255 /* Run from main thread */
2256 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2257 pa_card_new_data data;
2263 const char *default_profile;
2268 pa_card_new_data_init(&data);
2269 data.driver = __FILE__;
2270 data.module = u->module;
2272 n = pa_bluetooth_cleanup_name(device->name);
2273 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2275 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2276 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2277 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2278 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2279 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2280 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2281 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2282 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2283 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2284 data.name = get_name("card", u->modargs, device->address, &b);
2285 data.namereg_fail = b;
2287 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2288 pa_log("Invalid properties");
2289 pa_card_new_data_done(&data);
2293 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2295 /* we base hsp/a2dp availability on UUIDs.
2296 Ideally, it would be based on "Connected" state, but
2297 we can't afford to wait for this information when
2298 we are loaded with profile="hsp", for instance */
2299 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2300 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2301 p->priority = device->audio_sink_state * 10;
2304 p->max_sink_channels = 2;
2305 p->max_source_channels = 0;
2307 d = PA_CARD_PROFILE_DATA(p);
2309 create_ports_for_profile(u, device, &data, p);
2311 pa_hashmap_put(data.profiles, p->name, p);
2314 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2315 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2316 p->priority = device->audio_source_state * 10;
2320 p->max_sink_channels = 0;
2321 p->max_source_channels = 2;
2323 d = PA_CARD_PROFILE_DATA(p);
2324 *d = PROFILE_A2DP_SOURCE;
2325 create_ports_for_profile(u, device, &data, p);
2327 pa_hashmap_put(data.profiles, p->name, p);
2330 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2331 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2332 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2333 p->priority = device->headset_state * 10;
2336 p->max_sink_channels = 1;
2337 p->max_source_channels = 1;
2339 d = PA_CARD_PROFILE_DATA(p);
2341 create_ports_for_profile(u, device, &data, p);
2343 pa_hashmap_put(data.profiles, p->name, p);
2346 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2347 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2348 p->priority = device->hfgw_state * 10;
2351 p->max_sink_channels = 1;
2352 p->max_source_channels = 1;
2354 d = PA_CARD_PROFILE_DATA(p);
2356 create_ports_for_profile(u, device, &data, p);
2358 pa_hashmap_put(data.profiles, p->name, p);
2361 pa_assert(!pa_hashmap_isempty(data.profiles));
2363 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2364 p->priority = PA_BT_AUDIO_STATE_CONNECTED * 10 + 1;
2365 d = PA_CARD_PROFILE_DATA(p);
2367 pa_hashmap_put(data.profiles, p->name, p);
2369 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2370 if (pa_hashmap_get(data.profiles, default_profile))
2371 pa_card_new_data_set_profile(&data, default_profile);
2373 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2376 u->card = pa_card_new(u->core, &data);
2377 pa_card_new_data_done(&data);
2380 pa_log("Failed to allocate card.");
2384 u->card->userdata = u;
2385 u->card->set_profile = card_set_profile;
2387 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2389 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2390 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2391 (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) ||
2392 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2393 pa_log_warn("Default profile not connected, selecting off profile");
2394 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2395 u->card->save_profile = FALSE;
2398 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2401 if (USE_SCO_OVER_PCM(u))
2402 save_sco_volume_callbacks(u);
2407 /* Run from main thread */
2408 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2409 const pa_bluetooth_device *d = NULL;
2413 if (!address && !path) {
2414 pa_log_error("Failed to get device address/path from module arguments.");
2419 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2420 pa_log_error("%s is not a valid BlueZ audio device.", path);
2424 if (address && !(pa_streq(d->address, address))) {
2425 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2430 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2431 pa_log_error("%s is not known.", address);
2437 u->address = pa_xstrdup(d->address);
2438 u->path = pa_xstrdup(d->path);
2444 /* Run from main thread */
2445 static int setup_dbus(struct userdata *u) {
2448 dbus_error_init(&err);
2450 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2452 if (dbus_error_is_set(&err) || !u->connection) {
2453 pa_log("Failed to get D-Bus connection: %s", err.message);
2454 dbus_error_free(&err);
2461 int pa__init(pa_module* m) {
2465 const char *address, *path;
2467 char *mike, *speaker;
2468 const pa_bluetooth_device *device;
2472 dbus_error_init(&err);
2474 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2475 pa_log_error("Failed to parse module arguments");
2479 m->userdata = u = pa_xnew0(struct userdata, 1);
2483 u->sample_spec = m->core->default_sample_spec;
2486 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2487 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2488 pa_log("SCO sink not found");
2492 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2493 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2494 pa_log("SCO source not found");
2498 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2499 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2500 pa_log_error("Failed to get rate from module arguments");
2504 u->auto_connect = TRUE;
2505 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2506 pa_log("Failed to parse auto_connect= argument");
2510 channels = u->sample_spec.channels;
2511 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2512 channels <= 0 || channels > PA_CHANNELS_MAX) {
2513 pa_log_error("Failed to get channels from module arguments");
2516 u->sample_spec.channels = (uint8_t) channels;
2517 u->requested_sample_spec = u->sample_spec;
2519 address = pa_modargs_get_value(ma, "address", NULL);
2520 path = pa_modargs_get_value(ma, "path", NULL);
2522 if (setup_dbus(u) < 0)
2525 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2528 if (!(device = find_device(u, address, path)))
2531 /* Add the card structure. This will also initialize the default profile */
2532 if (add_card(u, device) < 0)
2535 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2538 u->msg->parent.process_msg = device_process_msg;
2539 u->msg->card = u->card;
2541 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2542 pa_log_error("Failed to add filter function");
2545 u->filter_added = TRUE;
2547 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2548 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2550 if (pa_dbus_add_matches(
2551 pa_dbus_connection_get(u->connection), &err,
2554 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2555 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2556 "type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged'",
2557 "type='signal',sender='org.bluez',interface='org.bluez.AudioSource',member='PropertyChanged'",
2558 "type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged'",
2564 pa_log("Failed to add D-Bus matches: %s", err.message);
2571 if (u->profile != PROFILE_OFF)
2572 if (init_profile(u) < 0)
2575 if (u->sink || u->source)
2576 if (start_thread(u) < 0)
2585 dbus_error_free(&err);
2590 int pa__get_n_used(pa_module *m) {
2594 pa_assert_se(u = m->userdata);
2597 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2598 (u->source ? pa_source_linked_by(u->source) : 0);
2601 void pa__done(pa_module *m) {
2606 if (!(u = m->userdata))
2609 if (u->sink && !USE_SCO_OVER_PCM(u))
2610 pa_sink_unlink(u->sink);
2612 if (u->source && !USE_SCO_OVER_PCM(u))
2613 pa_source_unlink(u->source);
2617 if (USE_SCO_OVER_PCM(u))
2618 restore_sco_volume_callbacks(u);
2620 if (u->connection) {
2623 char *speaker, *mike;
2624 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2625 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2627 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
2628 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2629 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2636 if (u->filter_added)
2637 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2639 pa_dbus_connection_unref(u->connection);
2646 pa_card_free(u->card);
2648 if (u->read_smoother)
2649 pa_smoother_free(u->read_smoother);
2652 pa_xfree(u->a2dp.buffer);
2654 sbc_finish(&u->a2dp.sbc);
2657 pa_modargs_free(u->modargs);
2659 pa_xfree(u->address);
2663 bt_transport_release(u);
2664 pa_xfree(u->transport);
2668 pa_bluetooth_discovery_unref(u->discovery);