2 This file is part of PulseAudio.
4 Copyright 2008-2013 João Paulo Rechi Vita
5 Copyright 2011-2013 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, see <http://www.gnu.org/licenses/>.
28 #include <linux/sockios.h>
29 #include <arpa/inet.h>
31 #include <pulse/rtclock.h>
32 #include <pulse/sample.h>
33 #include <pulse/timeval.h>
34 #include <pulse/utf8.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>
54 #include "a2dp-codecs.h"
56 #include "bluez4-util.h"
58 #define BITPOOL_DEC_LIMIT 32
59 #define BITPOOL_DEC_STEP 5
61 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("BlueZ 4 Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION);
64 PA_MODULE_LOAD_ONCE(false);
66 "name=<name for the card/sink/source, to be prefixed> "
67 "card_name=<name for the card> "
68 "card_properties=<properties for the card> "
69 "sink_name=<name for the sink> "
70 "sink_properties=<properties for the sink> "
71 "source_name=<name for the source> "
72 "source_properties=<properties for the source> "
73 "address=<address of the device> "
74 "profile=<a2dp|hsp|hfgw> "
76 "channels=<number of channels> "
77 "path=<device object path> "
78 "sco_sink=<SCO over PCM sink name> "
79 "sco_source=<SCO over PCM source name>");
81 /* TODO: not close fd when entering suspend mode in a2dp */
83 static const char* const valid_modargs[] = {
102 sbc_t sbc; /* Codec data */
103 bool sbc_initialized; /* Keep track if the encoder is initialized */
104 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
106 void* buffer; /* Codec transfer buffer */
107 size_t buffer_size; /* Size of the buffer */
109 uint16_t seq_num; /* Cumulative packet sequence */
116 void (*sco_sink_set_volume)(pa_sink *s);
117 pa_source *sco_source;
118 void (*sco_source_set_volume)(pa_source *s);
121 struct bluetooth_msg {
126 typedef struct bluetooth_msg bluetooth_msg;
127 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
128 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
134 pa_bluez4_device *device;
135 pa_hook_slot *uuid_added_slot;
138 pa_bluez4_transport *transport;
139 bool transport_acquired;
140 pa_hook_slot *discovery_slot;
141 pa_hook_slot *sink_state_changed_slot;
142 pa_hook_slot *source_state_changed_slot;
143 pa_hook_slot *transport_state_changed_slot;
144 pa_hook_slot *transport_nrec_changed_slot;
145 pa_hook_slot *transport_microphone_changed_slot;
146 pa_hook_slot *transport_speaker_changed_slot;
148 pa_bluez4_discovery *discovery;
150 char *output_port_name;
151 char *input_port_name;
157 pa_thread_mq thread_mq;
159 pa_rtpoll_item *rtpoll_item;
163 uint64_t read_index, write_index;
164 pa_usec_t started_at;
165 pa_smoother *read_smoother;
167 pa_memchunk write_memchunk;
169 pa_sample_spec sample_spec, requested_sample_spec;
173 size_t read_link_mtu;
174 size_t read_block_size;
176 size_t write_link_mtu;
177 size_t write_block_size;
179 struct a2dp_info a2dp;
182 pa_bluez4_profile_t profile;
186 int stream_write_type;
190 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
191 BLUETOOTH_MESSAGE_MAX
194 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
195 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
196 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
197 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
199 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
201 #define USE_SCO_OVER_PCM(u) (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT && (u->hsp.sco_sink && u->hsp.sco_source))
203 static int init_profile(struct userdata *u);
206 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
207 struct a2dp_info *a2dp;
213 if (a2dp->sbc.bitpool == bitpool)
216 if (bitpool > a2dp->max_bitpool)
217 bitpool = a2dp->max_bitpool;
218 else if (bitpool < a2dp->min_bitpool)
219 bitpool = a2dp->min_bitpool;
221 a2dp->sbc.bitpool = bitpool;
223 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
224 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
226 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
229 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
230 / a2dp->frame_length * a2dp->codesize;
232 u->write_block_size =
233 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
234 / a2dp->frame_length * a2dp->codesize;
236 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
237 pa_sink_set_fixed_latency_within_thread(u->sink,
238 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
241 /* from IO thread, except in SCO over PCM */
242 static void bt_transport_config_mtu(struct userdata *u) {
243 /* Calculate block sizes */
244 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY) {
245 u->read_block_size = u->read_link_mtu;
246 u->write_block_size = u->write_link_mtu;
249 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
250 / u->a2dp.frame_length * u->a2dp.codesize;
252 u->write_block_size =
253 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
254 / u->a2dp.frame_length * u->a2dp.codesize;
257 if (USE_SCO_OVER_PCM(u))
261 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
262 pa_sink_set_fixed_latency_within_thread(u->sink,
263 (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ?
264 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
265 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
269 pa_source_set_fixed_latency_within_thread(u->source,
270 (u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE ?
271 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
272 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
275 /* from IO thread, except in SCO over PCM */
277 static void setup_stream(struct userdata *u) {
278 struct pollfd *pollfd;
281 pa_log_info("Transport %s resuming", u->transport->path);
283 bt_transport_config_mtu(u);
285 pa_make_fd_nonblock(u->stream_fd);
286 pa_make_socket_low_delay(u->stream_fd);
289 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
290 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
292 pa_log_debug("Stream properly set up, we're ready to roll!");
294 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK)
295 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
297 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
298 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
299 pollfd->fd = u->stream_fd;
300 pollfd->events = pollfd->revents = 0;
302 u->read_index = u->write_index = 0;
306 u->read_smoother = pa_smoother_new(
316 static void teardown_stream(struct userdata *u) {
317 if (u->rtpoll_item) {
318 pa_rtpoll_item_free(u->rtpoll_item);
319 u->rtpoll_item = NULL;
322 if (u->stream_fd >= 0) {
323 pa_close(u->stream_fd);
327 if (u->read_smoother) {
328 pa_smoother_free(u->read_smoother);
329 u->read_smoother = NULL;
332 if (u->write_memchunk.memblock) {
333 pa_memblock_unref(u->write_memchunk.memblock);
334 pa_memchunk_reset(&u->write_memchunk);
337 pa_log_debug("Audio stream torn down");
340 static void bt_transport_release(struct userdata *u) {
341 pa_assert(u->transport);
343 /* Ignore if already released */
344 if (!u->transport_acquired)
347 pa_log_debug("Releasing transport %s", u->transport->path);
349 pa_bluez4_transport_release(u->transport);
351 u->transport_acquired = false;
356 static int bt_transport_acquire(struct userdata *u, bool optional) {
357 pa_assert(u->transport);
359 if (u->transport_acquired)
362 pa_log_debug("Acquiring transport %s", u->transport->path);
364 u->stream_fd = pa_bluez4_transport_acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
365 if (u->stream_fd < 0) {
367 pa_log("Failed to acquire transport %s", u->transport->path);
369 pa_log_info("Failed optional acquire of transport %s", u->transport->path);
374 u->transport_acquired = true;
375 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
380 /* Run from IO thread */
381 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
382 struct userdata *u = PA_SINK(o)->userdata;
384 pa_assert(u->sink == PA_SINK(o));
385 pa_assert(u->transport);
389 case PA_SINK_MESSAGE_GET_LATENCY: {
391 if (u->read_smoother) {
394 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
395 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
397 *((int64_t*) data) = wi - ri;
401 ri = pa_rtclock_now() - u->started_at;
402 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
404 *((int64_t*) data) = wi - ri;
407 *((int64_t*) data) += u->sink->thread_info.fixed_latency;
412 return pa_sink_process_msg(o, code, data, offset, chunk);
415 /* Called from the IO thread. */
416 static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
420 pa_assert_se(u = s->userdata);
424 case PA_SINK_SUSPENDED:
425 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
426 if (!PA_SINK_IS_OPENED(s->thread_info.state))
429 /* Stop the device if the source is suspended as well */
430 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
431 /* We deliberately ignore whether stopping
432 * actually worked. Since the stream_fd is
433 * closed it doesn't really matter */
434 bt_transport_release(u);
439 case PA_SINK_RUNNING:
440 if (s->thread_info.state != PA_SINK_SUSPENDED)
443 /* Resume the device if the source was suspended as well */
444 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
445 if (bt_transport_acquire(u, false) < 0)
452 case PA_SINK_UNLINKED:
454 case PA_SINK_INVALID_STATE:
461 /* Run from IO thread */
462 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
463 struct userdata *u = PA_SOURCE(o)->userdata;
465 pa_assert(u->source == PA_SOURCE(o));
466 pa_assert(u->transport);
470 case PA_SOURCE_MESSAGE_GET_LATENCY: {
473 if (u->read_smoother) {
474 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
475 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
477 *((int64_t*) data) = wi - ri + u->source->thread_info.fixed_latency;
479 *((int64_t*) data) = 0;
486 return pa_source_process_msg(o, code, data, offset, chunk);
489 /* Called from the IO thread. */
490 static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
494 pa_assert_se(u = s->userdata);
498 case PA_SOURCE_SUSPENDED:
499 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
500 if (!PA_SOURCE_IS_OPENED(s->thread_info.state))
503 /* Stop the device if the sink is suspended as well */
504 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
505 bt_transport_release(u);
507 if (u->read_smoother)
508 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
512 case PA_SOURCE_RUNNING:
513 if (s->thread_info.state != PA_SOURCE_SUSPENDED)
516 /* Resume the device if the sink was suspended as well */
517 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
518 if (bt_transport_acquire(u, false) < 0)
523 /* We don't resume the smoother here. Instead we
524 * wait until the first packet arrives */
527 case PA_SOURCE_UNLINKED:
529 case PA_SOURCE_INVALID_STATE:
536 /* Called from main thread context */
537 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
538 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
541 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
542 if (u->card->module->unload_requested)
545 pa_log_debug("Switching the profile to off due to IO thread failure.");
547 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
554 /* Run from IO thread */
555 static int hsp_process_render(struct userdata *u) {
559 pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY);
562 /* First, render some data */
563 if (!u->write_memchunk.memblock)
564 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
566 pa_assert(u->write_memchunk.length == u->write_block_size);
572 /* Now write that data to the socket. The socket is of type
573 * SEQPACKET, and we generated the data of the MTU size, so this
574 * should just work. */
576 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
577 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
578 pa_memblock_release(u->write_memchunk.memblock);
585 /* Retry right away if we got interrupted */
588 else if (errno == EAGAIN)
589 /* Hmm, apparently the socket was not writable, give up for now */
592 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
597 pa_assert((size_t) l <= u->write_memchunk.length);
599 if ((size_t) l != u->write_memchunk.length) {
600 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
601 (unsigned long long) l,
602 (unsigned long long) u->write_memchunk.length);
607 u->write_index += (uint64_t) u->write_memchunk.length;
608 pa_memblock_unref(u->write_memchunk.memblock);
609 pa_memchunk_reset(&u->write_memchunk);
618 /* Run from IO thread */
619 static int hsp_process_push(struct userdata *u) {
621 pa_memchunk memchunk;
624 pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY);
625 pa_assert(u->source);
626 pa_assert(u->read_smoother);
628 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
629 memchunk.index = memchunk.length = 0;
638 bool found_tstamp = false;
641 memset(&m, 0, sizeof(m));
642 memset(&aux, 0, sizeof(aux));
643 memset(&iov, 0, sizeof(iov));
648 m.msg_controllen = sizeof(aux);
650 p = pa_memblock_acquire(memchunk.memblock);
652 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
653 l = recvmsg(u->stream_fd, &m, 0);
654 pa_memblock_release(memchunk.memblock);
658 if (l < 0 && errno == EINTR)
659 /* Retry right away if we got interrupted */
662 else if (l < 0 && errno == EAGAIN)
663 /* Hmm, apparently the socket was not readable, give up for now. */
666 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
671 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
673 /* In some rare occasions, we might receive packets of a very strange
674 * size. This could potentially be possible if the SCO packet was
675 * received partially over-the-air, or more probably due to hardware
676 * issues in our Bluetooth adapter. In these cases, in order to avoid
677 * an assertion failure due to unaligned data, just discard the whole
679 if (!pa_frame_aligned(l, &u->sample_spec)) {
680 pa_log_warn("SCO packet received of unaligned size: %zu", l);
684 memchunk.length = (size_t) l;
685 u->read_index += (uint64_t) l;
687 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
688 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
689 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
690 pa_rtclock_from_wallclock(tv);
691 tstamp = pa_timeval_load(tv);
697 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
698 tstamp = pa_rtclock_now();
701 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
702 pa_smoother_resume(u->read_smoother, tstamp, true);
704 pa_source_post(u->source, &memchunk);
710 pa_memblock_unref(memchunk.memblock);
715 /* Run from IO thread */
716 static void a2dp_prepare_buffer(struct userdata *u) {
717 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
721 if (u->a2dp.buffer_size >= min_buffer_size)
724 u->a2dp.buffer_size = 2 * min_buffer_size;
725 pa_xfree(u->a2dp.buffer);
726 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
729 /* Run from IO thread */
730 static int a2dp_process_render(struct userdata *u) {
731 struct a2dp_info *a2dp;
732 struct rtp_header *header;
733 struct rtp_payload *payload;
737 size_t to_write, to_encode;
738 unsigned frame_count;
742 pa_assert(u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK);
745 /* First, render some data */
746 if (!u->write_memchunk.memblock)
747 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
749 pa_assert(u->write_memchunk.length == u->write_block_size);
751 a2dp_prepare_buffer(u);
754 header = a2dp->buffer;
755 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
759 /* Try to create a packet of the full MTU */
761 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
762 to_encode = u->write_memchunk.length;
764 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
765 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
767 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
771 encoded = sbc_encode(&a2dp->sbc,
776 if (PA_UNLIKELY(encoded <= 0)) {
777 pa_log_error("SBC encoding error (%li)", (long) encoded);
778 pa_memblock_release(u->write_memchunk.memblock);
782 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
783 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
785 pa_assert_fp((size_t) encoded <= to_encode);
786 pa_assert_fp((size_t) encoded == a2dp->codesize);
788 pa_assert_fp((size_t) written <= to_write);
789 pa_assert_fp((size_t) written == a2dp->frame_length);
791 p = (const uint8_t*) p + encoded;
792 to_encode -= encoded;
794 d = (uint8_t*) d + written;
800 pa_memblock_release(u->write_memchunk.memblock);
802 pa_assert(to_encode == 0);
805 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
808 /* write it to the fifo */
809 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
812 header->sequence_number = htons(a2dp->seq_num++);
813 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
814 header->ssrc = htonl(1);
815 payload->frame_count = frame_count;
817 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
822 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
829 /* Retry right away if we got interrupted */
832 else if (errno == EAGAIN)
833 /* Hmm, apparently the socket was not writable, give up for now */
836 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
841 pa_assert((size_t) l <= nbytes);
843 if ((size_t) l != nbytes) {
844 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
845 (unsigned long long) l,
846 (unsigned long long) nbytes);
851 u->write_index += (uint64_t) u->write_memchunk.length;
852 pa_memblock_unref(u->write_memchunk.memblock);
853 pa_memchunk_reset(&u->write_memchunk);
863 static int a2dp_process_push(struct userdata *u) {
865 pa_memchunk memchunk;
868 pa_assert(u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE);
869 pa_assert(u->source);
870 pa_assert(u->read_smoother);
872 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
873 memchunk.index = memchunk.length = 0;
876 bool found_tstamp = false;
878 struct a2dp_info *a2dp;
879 struct rtp_header *header;
880 struct rtp_payload *payload;
884 size_t to_write, to_decode;
885 size_t total_written = 0;
887 a2dp_prepare_buffer(u);
890 header = a2dp->buffer;
891 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
893 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
897 if (l < 0 && errno == EINTR)
898 /* Retry right away if we got interrupted */
901 else if (l < 0 && errno == EAGAIN)
902 /* Hmm, apparently the socket was not readable, give up for now. */
905 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
910 pa_assert((size_t) l <= a2dp->buffer_size);
912 /* TODO: get timestamp from rtp */
914 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
915 tstamp = pa_rtclock_now();
918 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
919 to_decode = l - sizeof(*header) - sizeof(*payload);
921 d = pa_memblock_acquire(memchunk.memblock);
922 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
924 while (PA_LIKELY(to_decode > 0)) {
928 decoded = sbc_decode(&a2dp->sbc,
933 if (PA_UNLIKELY(decoded <= 0)) {
934 pa_log_error("SBC decoding error (%li)", (long) decoded);
935 pa_memblock_release(memchunk.memblock);
936 pa_memblock_unref(memchunk.memblock);
940 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
941 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
943 total_written += written;
945 /* Reset frame length, it can be changed due to bitpool change */
946 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
948 pa_assert_fp((size_t) decoded <= to_decode);
949 pa_assert_fp((size_t) decoded == a2dp->frame_length);
951 pa_assert_fp((size_t) written == a2dp->codesize);
953 p = (const uint8_t*) p + decoded;
954 to_decode -= decoded;
956 d = (uint8_t*) d + written;
960 u->read_index += (uint64_t) total_written;
961 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
962 pa_smoother_resume(u->read_smoother, tstamp, true);
964 memchunk.length -= to_write;
966 pa_memblock_release(memchunk.memblock);
968 pa_source_post(u->source, &memchunk);
974 pa_memblock_unref(memchunk.memblock);
979 static void a2dp_reduce_bitpool(struct userdata *u) {
980 struct a2dp_info *a2dp;
987 /* Check if bitpool is already at its limit */
988 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
991 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
993 if (bitpool < BITPOOL_DEC_LIMIT)
994 bitpool = BITPOOL_DEC_LIMIT;
996 a2dp_set_bitpool(u, bitpool);
999 static void thread_func(void *userdata) {
1000 struct userdata *u = userdata;
1001 unsigned do_write = 0;
1002 unsigned pending_read_bytes = 0;
1003 bool writable = false;
1006 pa_assert(u->transport);
1008 pa_log_debug("IO Thread starting up");
1010 if (u->core->realtime_scheduling)
1011 pa_make_realtime(u->core->realtime_priority);
1013 pa_thread_mq_install(&u->thread_mq);
1015 /* Setup the stream only if the transport was already acquired */
1016 if (u->transport_acquired)
1020 struct pollfd *pollfd;
1022 bool disable_timer = true;
1024 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1026 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1028 /* We should send two blocks to the device before we expect
1031 if (u->write_index == 0 && u->read_index <= 0)
1034 if (pollfd && (pollfd->revents & POLLIN)) {
1037 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1038 n_read = hsp_process_push(u);
1040 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;
1054 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1056 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1057 pa_sink_process_rewind(u->sink, 0);
1060 if (pollfd->revents & POLLOUT)
1063 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1064 pa_usec_t time_passed;
1065 pa_usec_t audio_sent;
1067 /* Hmm, there is no input stream we could synchronize
1068 * to. So let's do things by time */
1070 time_passed = pa_rtclock_now() - u->started_at;
1071 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1073 if (audio_sent <= time_passed) {
1074 pa_usec_t audio_to_send = time_passed - audio_sent;
1076 /* Never try to catch up for more than 100ms */
1077 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1078 pa_usec_t skip_usec;
1079 uint64_t skip_bytes;
1081 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1082 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1084 if (skip_bytes > 0) {
1087 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1088 (unsigned long long) skip_usec,
1089 (unsigned long long) skip_bytes);
1091 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1092 pa_memblock_unref(tmp.memblock);
1093 u->write_index += skip_bytes;
1095 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK)
1096 a2dp_reduce_bitpool(u);
1101 pending_read_bytes = 0;
1105 if (writable && do_write > 0) {
1108 if (u->write_index <= 0)
1109 u->started_at = pa_rtclock_now();
1111 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK) {
1112 if ((n_written = a2dp_process_render(u)) < 0)
1115 if ((n_written = hsp_process_render(u)) < 0)
1120 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1122 do_write -= n_written;
1126 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1127 pa_usec_t sleep_for;
1128 pa_usec_t time_passed, next_write_at;
1131 /* Hmm, there is no input stream we could synchronize
1132 * to. So let's estimate when we need to wake up the latest */
1133 time_passed = pa_rtclock_now() - u->started_at;
1134 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1135 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1136 /* 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); */
1138 /* drop stream every 500 ms */
1139 sleep_for = PA_USEC_PER_MSEC * 500;
1141 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1142 disable_timer = false;
1148 pa_rtpoll_set_timer_disabled(u->rtpoll);
1150 /* Hmm, nothing to do. Let's sleep */
1152 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1153 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1155 if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1156 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1160 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1161 bt_transport_release(u);
1165 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1167 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1168 pa_log_info("FD error: %s%s%s%s",
1169 pollfd->revents & POLLERR ? "POLLERR " :"",
1170 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1171 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1172 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1179 /* In case of HUP, just tear down the streams */
1180 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1184 pending_read_bytes = 0;
1191 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1192 pa_log_debug("IO thread failed");
1193 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1194 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1197 pa_log_debug("IO thread shutting down");
1200 static pa_available_t transport_state_to_availability(pa_bluez4_transport_state_t state) {
1201 if (state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)
1202 return PA_AVAILABLE_NO;
1203 else if (state >= PA_BLUEZ4_TRANSPORT_STATE_PLAYING)
1204 return PA_AVAILABLE_YES;
1206 return PA_AVAILABLE_UNKNOWN;
1209 static pa_direction_t get_profile_direction(pa_bluez4_profile_t p) {
1210 static const pa_direction_t profile_direction[] = {
1211 [PA_BLUEZ4_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1212 [PA_BLUEZ4_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1213 [PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1214 [PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1215 [PA_BLUEZ4_PROFILE_OFF] = 0
1218 return profile_direction[p];
1221 /* Run from main thread */
1222 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1223 pa_available_t result = PA_AVAILABLE_NO;
1227 pa_assert(u->device);
1229 for (i = 0; i < PA_BLUEZ4_PROFILE_COUNT; i++) {
1230 pa_bluez4_transport *transport;
1232 if (!(get_profile_direction(i) & direction))
1235 if (!(transport = u->device->transports[i]))
1238 switch(transport->state) {
1239 case PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED:
1242 case PA_BLUEZ4_TRANSPORT_STATE_IDLE:
1243 if (result == PA_AVAILABLE_NO)
1244 result = PA_AVAILABLE_UNKNOWN;
1248 case PA_BLUEZ4_TRANSPORT_STATE_PLAYING:
1249 return PA_AVAILABLE_YES;
1256 /* Run from main thread */
1257 static void handle_transport_state_change(struct userdata *u, struct pa_bluez4_transport *transport) {
1258 bool acquire = false;
1259 bool release = false;
1260 pa_bluez4_profile_t profile;
1261 pa_card_profile *cp;
1262 pa_bluez4_transport_state_t state;
1263 pa_device_port *port;
1266 pa_assert(transport);
1268 profile = transport->profile;
1269 state = transport->state;
1271 /* Update profile availability */
1272 if (!(cp = pa_hashmap_get(u->card->profiles, pa_bluez4_profile_to_string(profile))))
1275 pa_card_profile_set_available(cp, transport_state_to_availability(state));
1277 /* Update port availability */
1278 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
1279 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
1281 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
1282 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
1284 /* Acquire or release transport as needed */
1285 acquire = (state == PA_BLUEZ4_TRANSPORT_STATE_PLAYING && u->profile == profile);
1286 release = (state != PA_BLUEZ4_TRANSPORT_STATE_PLAYING && u->profile == profile);
1289 if (bt_transport_acquire(u, true) >= 0) {
1291 pa_log_debug("Resuming source %s, because the bluetooth audio state changed to 'playing'.", u->source->name);
1292 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1296 pa_log_debug("Resuming sink %s, because the bluetooth audio state changed to 'playing'.", u->sink->name);
1297 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1301 if (release && u->transport_acquired) {
1302 /* FIXME: this release is racy, since the audio stream might have
1303 been set up again in the meantime (but not processed yet by PA).
1304 BlueZ should probably release the transport automatically, and
1305 in that case we would just mark the transport as released */
1307 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1309 pa_log_debug("Suspending source %s, because the remote end closed the stream.", u->source->name);
1310 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
1314 pa_log_debug("Suspending sink %s, because the remote end closed the stream.", u->sink->name);
1315 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
1320 /* Run from main thread */
1321 static void sink_set_volume_cb(pa_sink *s) {
1330 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1331 u = pa_shared_get(s->core, k);
1335 pa_assert(u->sink == s);
1336 pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT);
1337 pa_assert(u->transport);
1339 gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1340 volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1342 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1344 pa_bluez4_transport_set_speaker_gain(u->transport, gain);
1347 /* Run from main thread */
1348 static void source_set_volume_cb(pa_source *s) {
1357 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1358 u = pa_shared_get(s->core, k);
1362 pa_assert(u->source == s);
1363 pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT);
1364 pa_assert(u->transport);
1366 gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1367 volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1369 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1371 pa_bluez4_transport_set_microphone_gain(u->transport, gain);
1374 /* Run from main thread */
1375 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, const char *profile, bool *namereg_fail) {
1381 pa_assert(device_id);
1382 pa_assert(namereg_fail);
1384 t = pa_sprintf_malloc("%s_name", type);
1385 n = pa_modargs_get_value(ma, t, NULL);
1389 *namereg_fail = true;
1390 return pa_xstrdup(n);
1393 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1394 *namereg_fail = true;
1397 *namereg_fail = false;
1401 return pa_sprintf_malloc("bluez_%s.%s.%s", type, n, profile);
1403 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1406 static int sco_over_pcm_state_update(struct userdata *u, bool changed) {
1408 pa_assert(USE_SCO_OVER_PCM(u));
1410 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1411 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1413 if (u->stream_fd >= 0)
1416 pa_log_debug("Resuming SCO over PCM");
1417 if (init_profile(u) < 0) {
1418 pa_log("Can't resume SCO over PCM");
1422 if (bt_transport_acquire(u, false) < 0)
1431 if (u->stream_fd < 0)
1434 pa_log_debug("Closing SCO over PCM");
1436 bt_transport_release(u);
1442 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1444 pa_sink_assert_ref(s);
1447 if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_sink)
1450 sco_over_pcm_state_update(u, true);
1455 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1457 pa_source_assert_ref(s);
1460 if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_source)
1463 sco_over_pcm_state_update(u, true);
1468 static pa_hook_result_t transport_nrec_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t, struct userdata *u) {
1474 if (t != u->transport)
1477 p = pa_proplist_new();
1478 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1479 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1480 pa_proplist_free(p);
1485 static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t,
1486 struct userdata *u) {
1492 if (t != u->transport)
1495 pa_assert(u->source);
1497 pa_cvolume_set(&v, u->sample_spec.channels,
1498 (pa_volume_t) round((double) t->microphone_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1499 pa_source_volume_changed(u->source, &v);
1504 static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t,
1505 struct userdata *u) {
1511 if (t != u->transport)
1516 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) round((double) t->speaker_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1517 pa_sink_volume_changed(u->sink, &v);
1522 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1523 pa_device_port *port;
1525 if (direction == PA_DIRECTION_OUTPUT) {
1526 pa_sink_new_data *sink_new_data = sink_or_source_new_data;
1528 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
1529 pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
1530 pa_device_port_ref(port);
1532 pa_source_new_data *source_new_data = sink_or_source_new_data;
1534 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
1535 pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
1536 pa_device_port_ref(port);
1540 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1544 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1548 /* Run from main thread */
1549 static int add_sink(struct userdata *u) {
1552 pa_assert(u->transport);
1554 if (USE_SCO_OVER_PCM(u)) {
1557 u->sink = u->hsp.sco_sink;
1558 p = pa_proplist_new();
1559 pa_proplist_sets(p, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1560 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1561 pa_proplist_free(p);
1563 pa_sink_new_data data;
1566 pa_sink_new_data_init(&data);
1567 data.driver = __FILE__;
1568 data.module = u->module;
1569 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1570 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1571 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT)
1572 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1573 data.card = u->card;
1574 data.name = get_name("sink", u->modargs, u->address, pa_bluez4_profile_to_string(u->profile), &b);
1575 data.namereg_fail = b;
1577 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1578 pa_log("Invalid properties");
1579 pa_sink_new_data_done(&data);
1582 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1584 if (!u->transport_acquired)
1585 switch (u->profile) {
1586 case PA_BLUEZ4_PROFILE_A2DP_SINK:
1587 case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
1588 pa_assert_not_reached(); /* Profile switch should have failed */
1590 case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
1591 data.suspend_cause = PA_SUSPEND_USER;
1593 case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
1594 case PA_BLUEZ4_PROFILE_OFF:
1595 pa_assert_not_reached();
1598 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1599 pa_sink_new_data_done(&data);
1602 pa_log_error("Failed to create sink");
1606 u->sink->userdata = u;
1607 u->sink->parent.process_msg = sink_process_msg;
1608 u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1609 u->sink->set_port = sink_set_port_cb;
1612 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1613 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1614 u->sink->n_volume_steps = 16;
1616 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1617 pa_shared_set(u->core, k, u);
1624 /* Run from main thread */
1625 static int add_source(struct userdata *u) {
1628 pa_assert(u->transport);
1630 if (USE_SCO_OVER_PCM(u)) {
1631 u->source = u->hsp.sco_source;
1632 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1634 pa_source_new_data data;
1637 pa_source_new_data_init(&data);
1638 data.driver = __FILE__;
1639 data.module = u->module;
1640 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1641 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1642 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT)
1643 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1645 data.card = u->card;
1646 data.name = get_name("source", u->modargs, u->address, pa_bluez4_profile_to_string(u->profile), &b);
1647 data.namereg_fail = b;
1649 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1650 pa_log("Invalid properties");
1651 pa_source_new_data_done(&data);
1655 connect_ports(u, &data, PA_DIRECTION_INPUT);
1657 if (!u->transport_acquired)
1658 switch (u->profile) {
1659 case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
1660 pa_assert_not_reached(); /* Profile switch should have failed */
1662 case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
1663 case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
1664 data.suspend_cause = PA_SUSPEND_USER;
1666 case PA_BLUEZ4_PROFILE_A2DP_SINK:
1667 case PA_BLUEZ4_PROFILE_OFF:
1668 pa_assert_not_reached();
1671 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1672 pa_source_new_data_done(&data);
1675 pa_log_error("Failed to create source");
1679 u->source->userdata = u;
1680 u->source->parent.process_msg = source_process_msg;
1681 u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
1682 u->source->set_port = source_set_port_cb;
1685 if ((u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) || (u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)) {
1686 pa_bluez4_transport *t = u->transport;
1687 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1690 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1691 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1692 u->source->n_volume_steps = 16;
1694 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1695 pa_shared_set(u->core, k, u);
1702 static void bt_transport_config_a2dp(struct userdata *u) {
1703 const pa_bluez4_transport *t;
1704 struct a2dp_info *a2dp = &u->a2dp;
1710 config = (a2dp_sbc_t *) t->config;
1712 u->sample_spec.format = PA_SAMPLE_S16LE;
1714 if (a2dp->sbc_initialized)
1715 sbc_reinit(&a2dp->sbc, 0);
1717 sbc_init(&a2dp->sbc, 0);
1718 a2dp->sbc_initialized = true;
1720 switch (config->frequency) {
1721 case SBC_SAMPLING_FREQ_16000:
1722 a2dp->sbc.frequency = SBC_FREQ_16000;
1723 u->sample_spec.rate = 16000U;
1725 case SBC_SAMPLING_FREQ_32000:
1726 a2dp->sbc.frequency = SBC_FREQ_32000;
1727 u->sample_spec.rate = 32000U;
1729 case SBC_SAMPLING_FREQ_44100:
1730 a2dp->sbc.frequency = SBC_FREQ_44100;
1731 u->sample_spec.rate = 44100U;
1733 case SBC_SAMPLING_FREQ_48000:
1734 a2dp->sbc.frequency = SBC_FREQ_48000;
1735 u->sample_spec.rate = 48000U;
1738 pa_assert_not_reached();
1741 switch (config->channel_mode) {
1742 case SBC_CHANNEL_MODE_MONO:
1743 a2dp->sbc.mode = SBC_MODE_MONO;
1744 u->sample_spec.channels = 1;
1746 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1747 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1748 u->sample_spec.channels = 2;
1750 case SBC_CHANNEL_MODE_STEREO:
1751 a2dp->sbc.mode = SBC_MODE_STEREO;
1752 u->sample_spec.channels = 2;
1754 case SBC_CHANNEL_MODE_JOINT_STEREO:
1755 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1756 u->sample_spec.channels = 2;
1759 pa_assert_not_reached();
1762 switch (config->allocation_method) {
1763 case SBC_ALLOCATION_SNR:
1764 a2dp->sbc.allocation = SBC_AM_SNR;
1766 case SBC_ALLOCATION_LOUDNESS:
1767 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1770 pa_assert_not_reached();
1773 switch (config->subbands) {
1774 case SBC_SUBBANDS_4:
1775 a2dp->sbc.subbands = SBC_SB_4;
1777 case SBC_SUBBANDS_8:
1778 a2dp->sbc.subbands = SBC_SB_8;
1781 pa_assert_not_reached();
1784 switch (config->block_length) {
1785 case SBC_BLOCK_LENGTH_4:
1786 a2dp->sbc.blocks = SBC_BLK_4;
1788 case SBC_BLOCK_LENGTH_8:
1789 a2dp->sbc.blocks = SBC_BLK_8;
1791 case SBC_BLOCK_LENGTH_12:
1792 a2dp->sbc.blocks = SBC_BLK_12;
1794 case SBC_BLOCK_LENGTH_16:
1795 a2dp->sbc.blocks = SBC_BLK_16;
1798 pa_assert_not_reached();
1801 a2dp->min_bitpool = config->min_bitpool;
1802 a2dp->max_bitpool = config->max_bitpool;
1804 /* Set minimum bitpool for source to get the maximum possible block_size */
1805 a2dp->sbc.bitpool = u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ? a2dp->max_bitpool : a2dp->min_bitpool;
1806 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1807 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1809 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u",
1810 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1813 static void bt_transport_config(struct userdata *u) {
1814 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY) {
1815 u->sample_spec.format = PA_SAMPLE_S16LE;
1816 u->sample_spec.channels = 1;
1817 u->sample_spec.rate = 8000;
1819 bt_transport_config_a2dp(u);
1822 /* Run from main thread */
1823 static pa_hook_result_t transport_state_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t, struct userdata *u) {
1827 if (t == u->transport && t->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)
1828 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
1830 if (t->device == u->device)
1831 handle_transport_state_change(u, t);
1836 /* Run from main thread */
1837 static int setup_transport(struct userdata *u) {
1838 pa_bluez4_transport *t;
1841 pa_assert(!u->transport);
1842 pa_assert(u->profile != PA_BLUEZ4_PROFILE_OFF);
1844 /* check if profile has a transport */
1845 t = u->device->transports[u->profile];
1846 if (!t || t->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED) {
1847 pa_log_warn("Profile has no transport");
1853 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1854 bt_transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1855 else if (bt_transport_acquire(u, false) < 0)
1856 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1858 bt_transport_config(u);
1863 /* Run from main thread */
1864 static int init_profile(struct userdata *u) {
1867 pa_assert(u->profile != PA_BLUEZ4_PROFILE_OFF);
1869 if (setup_transport(u) < 0)
1872 pa_assert(u->transport);
1874 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ||
1875 u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT ||
1876 u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1877 if (add_sink(u) < 0)
1880 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT ||
1881 u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE ||
1882 u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1883 if (add_source(u) < 0)
1889 /* Run from main thread */
1890 static void stop_thread(struct userdata *u) {
1895 if (u->sink && !USE_SCO_OVER_PCM(u))
1896 pa_sink_unlink(u->sink);
1898 if (u->source && !USE_SCO_OVER_PCM(u))
1899 pa_source_unlink(u->source);
1902 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1903 pa_thread_free(u->thread);
1907 if (u->rtpoll_item) {
1908 pa_rtpoll_item_free(u->rtpoll_item);
1909 u->rtpoll_item = NULL;
1913 pa_thread_mq_done(&u->thread_mq);
1915 pa_rtpoll_free(u->rtpoll);
1920 bt_transport_release(u);
1921 u->transport = NULL;
1925 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1926 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1927 pa_shared_remove(u->core, k);
1931 pa_sink_unref(u->sink);
1936 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1937 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1938 pa_shared_remove(u->core, k);
1942 pa_source_unref(u->source);
1946 if (u->read_smoother) {
1947 pa_smoother_free(u->read_smoother);
1948 u->read_smoother = NULL;
1952 /* Run from main thread */
1953 static int start_thread(struct userdata *u) {
1955 pa_assert(!u->thread);
1956 pa_assert(!u->rtpoll);
1957 pa_assert(!u->rtpoll_item);
1959 u->rtpoll = pa_rtpoll_new();
1961 if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1962 pa_log("pa_thread_mq_init() failed.");
1966 if (USE_SCO_OVER_PCM(u)) {
1967 if (sco_over_pcm_state_update(u, false) < 0) {
1971 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1972 pa_shared_remove(u->core, k);
1977 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1978 pa_shared_remove(u->core, k);
1985 pa_sink_ref(u->sink);
1986 pa_source_ref(u->source);
1987 /* FIXME: monitor stream_fd error */
1991 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1992 pa_log_error("Failed to create IO thread");
1997 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1998 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1999 pa_sink_put(u->sink);
2001 if (u->sink->set_volume)
2002 u->sink->set_volume(u->sink);
2006 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2007 pa_source_set_rtpoll(u->source, u->rtpoll);
2008 pa_source_put(u->source);
2010 if (u->source->set_volume)
2011 u->source->set_volume(u->source);
2017 static void save_sco_volume_callbacks(struct userdata *u) {
2019 pa_assert(USE_SCO_OVER_PCM(u));
2021 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2022 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2025 static void restore_sco_volume_callbacks(struct userdata *u) {
2027 pa_assert(USE_SCO_OVER_PCM(u));
2029 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2030 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2033 /* Run from main thread */
2034 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2036 pa_bluez4_profile_t *d;
2039 pa_assert(new_profile);
2040 pa_assert_se(u = c->userdata);
2042 d = PA_CARD_PROFILE_DATA(new_profile);
2044 if (*d != PA_BLUEZ4_PROFILE_OFF) {
2045 const pa_bluez4_device *device = u->device;
2047 if (!device->transports[*d] || device->transports[*d]->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED) {
2048 pa_log_warn("Profile not connected, refused to switch profile to %s", new_profile->name);
2055 if (USE_SCO_OVER_PCM(u))
2056 restore_sco_volume_callbacks(u);
2059 u->sample_spec = u->requested_sample_spec;
2061 if (USE_SCO_OVER_PCM(u))
2062 save_sco_volume_callbacks(u);
2064 if (u->profile != PA_BLUEZ4_PROFILE_OFF)
2065 if (init_profile(u) < 0)
2068 if (u->sink || u->source)
2069 if (start_thread(u) < 0)
2077 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2082 /* Run from main thread */
2083 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
2084 pa_device_port *port;
2085 pa_device_port_new_data port_data;
2087 const char *name_prefix = NULL;
2088 const char *input_description = NULL;
2089 const char *output_description = NULL;
2093 pa_assert(u->device);
2095 switch (pa_bluez4_get_form_factor(u->device->class)) {
2096 case PA_BLUEZ4_FORM_FACTOR_UNKNOWN:
2099 case PA_BLUEZ4_FORM_FACTOR_HEADSET:
2100 name_prefix = "headset";
2101 input_description = output_description = _("Headset");
2104 case PA_BLUEZ4_FORM_FACTOR_HANDSFREE:
2105 name_prefix = "handsfree";
2106 input_description = output_description = _("Handsfree");
2109 case PA_BLUEZ4_FORM_FACTOR_MICROPHONE:
2110 name_prefix = "microphone";
2111 input_description = _("Microphone");
2114 case PA_BLUEZ4_FORM_FACTOR_SPEAKER:
2115 name_prefix = "speaker";
2116 output_description = _("Speaker");
2119 case PA_BLUEZ4_FORM_FACTOR_HEADPHONE:
2120 name_prefix = "headphone";
2121 output_description = _("Headphone");
2124 case PA_BLUEZ4_FORM_FACTOR_PORTABLE:
2125 name_prefix = "portable";
2126 input_description = output_description = _("Portable");
2129 case PA_BLUEZ4_FORM_FACTOR_CAR:
2130 name_prefix = "car";
2131 input_description = output_description = _("Car");
2134 case PA_BLUEZ4_FORM_FACTOR_HIFI:
2135 name_prefix = "hifi";
2136 input_description = output_description = _("HiFi");
2139 case PA_BLUEZ4_FORM_FACTOR_PHONE:
2140 name_prefix = "phone";
2141 input_description = output_description = _("Phone");
2146 name_prefix = "unknown";
2148 if (!output_description)
2149 output_description = _("Bluetooth Output");
2151 if (!input_description)
2152 input_description = _("Bluetooth Input");
2154 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
2155 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
2157 pa_device_port_new_data_init(&port_data);
2158 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
2159 pa_device_port_new_data_set_description(&port_data, output_description);
2160 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
2161 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
2162 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2163 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2164 pa_device_port_new_data_done(&port_data);
2166 pa_device_port_new_data_init(&port_data);
2167 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
2168 pa_device_port_new_data_set_description(&port_data, input_description);
2169 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
2170 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
2171 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2172 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2173 pa_device_port_new_data_done(&port_data);
2176 /* Run from main thread */
2177 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluez4_profile_t profile, pa_hashmap *ports) {
2178 pa_device_port *input_port, *output_port;
2180 pa_card_profile *p = NULL;
2181 pa_bluez4_profile_t *d = NULL;
2182 pa_bluez4_transport *t;
2184 pa_assert(u->input_port_name);
2185 pa_assert(u->output_port_name);
2186 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2187 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2189 name = pa_bluez4_profile_to_string(profile);
2192 case PA_BLUEZ4_PROFILE_A2DP_SINK:
2193 p = pa_card_profile_new(name, _("High Fidelity Playback (A2DP)"), sizeof(pa_bluez4_profile_t));
2197 p->max_sink_channels = 2;
2198 p->max_source_channels = 0;
2199 pa_hashmap_put(output_port->profiles, p->name, p);
2201 d = PA_CARD_PROFILE_DATA(p);
2204 case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
2205 p = pa_card_profile_new(name, _("High Fidelity Capture (A2DP)"), sizeof(pa_bluez4_profile_t));
2209 p->max_sink_channels = 0;
2210 p->max_source_channels = 2;
2211 pa_hashmap_put(input_port->profiles, p->name, p);
2213 d = PA_CARD_PROFILE_DATA(p);
2216 case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
2217 p = pa_card_profile_new(name, _("Telephony Duplex (HSP/HFP)"), sizeof(pa_bluez4_profile_t));
2221 p->max_sink_channels = 1;
2222 p->max_source_channels = 1;
2223 pa_hashmap_put(input_port->profiles, p->name, p);
2224 pa_hashmap_put(output_port->profiles, p->name, p);
2226 d = PA_CARD_PROFILE_DATA(p);
2229 case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
2230 p = pa_card_profile_new(name, _("Handsfree Gateway"), sizeof(pa_bluez4_profile_t));
2234 p->max_sink_channels = 1;
2235 p->max_source_channels = 1;
2236 pa_hashmap_put(input_port->profiles, p->name, p);
2237 pa_hashmap_put(output_port->profiles, p->name, p);
2239 d = PA_CARD_PROFILE_DATA(p);
2242 case PA_BLUEZ4_PROFILE_OFF:
2243 pa_assert_not_reached();
2248 if ((t = u->device->transports[*d]))
2249 p->available = transport_state_to_availability(t->state);
2254 static int uuid_to_profile(const char *uuid, pa_bluez4_profile_t *_r) {
2255 if (pa_streq(uuid, PA_BLUEZ4_UUID_A2DP_SINK))
2256 *_r = PA_BLUEZ4_PROFILE_A2DP_SINK;
2257 else if (pa_streq(uuid, PA_BLUEZ4_UUID_A2DP_SOURCE))
2258 *_r = PA_BLUEZ4_PROFILE_A2DP_SOURCE;
2259 else if (pa_streq(uuid, PA_BLUEZ4_UUID_HSP_HS) || pa_streq(uuid, PA_BLUEZ4_UUID_HFP_HF))
2260 *_r = PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT;
2261 else if (pa_streq(uuid, PA_BLUEZ4_UUID_HSP_AG) || pa_streq(uuid, PA_BLUEZ4_UUID_HFP_AG))
2262 *_r = PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY;
2264 return -PA_ERR_INVALID;
2269 /* Run from main thread */
2270 static int add_card(struct userdata *u) {
2271 pa_card_new_data data;
2274 pa_bluez4_profile_t *d;
2275 pa_bluez4_form_factor_t ff;
2277 const char *profile_str;
2278 const pa_bluez4_device *device;
2283 pa_assert(u->device);
2287 pa_card_new_data_init(&data);
2288 data.driver = __FILE__;
2289 data.module = u->module;
2291 n = pa_utf8_filter(device->alias);
2292 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2294 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2295 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2296 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2297 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2299 if ((ff = pa_bluez4_get_form_factor(device->class)) != PA_BLUEZ4_FORM_FACTOR_UNKNOWN)
2300 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, pa_bluez4_form_factor_to_string(ff));
2302 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2303 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2304 pa_proplist_sets(data.proplist, "bluez.alias", device->alias);
2305 data.name = get_name("card", u->modargs, device->address, NULL, &b);
2306 data.namereg_fail = b;
2308 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2309 pa_log("Invalid properties");
2310 pa_card_new_data_done(&data);
2314 create_card_ports(u, data.ports);
2316 PA_HASHMAP_FOREACH(uuid, device->uuids, state) {
2317 pa_bluez4_profile_t profile;
2319 if (uuid_to_profile(uuid, &profile) < 0)
2322 if (pa_hashmap_get(data.profiles, pa_bluez4_profile_to_string(profile)))
2325 p = create_card_profile(u, profile, data.ports);
2326 pa_hashmap_put(data.profiles, p->name, p);
2329 pa_assert(!pa_hashmap_isempty(data.profiles));
2331 p = pa_card_profile_new("off", _("Off"), sizeof(pa_bluez4_profile_t));
2332 p->available = PA_AVAILABLE_YES;
2333 d = PA_CARD_PROFILE_DATA(p);
2334 *d = PA_BLUEZ4_PROFILE_OFF;
2335 pa_hashmap_put(data.profiles, p->name, p);
2337 u->card = pa_card_new(u->core, &data);
2338 pa_card_new_data_done(&data);
2341 pa_log("Failed to allocate card.");
2345 u->card->userdata = u;
2346 u->card->set_profile = card_set_profile;
2348 pa_card_choose_initial_profile(u->card);
2350 /* If the "profile" modarg is given, we have to override whatever the usual
2351 * policy chose in pa_card_choose_initial_profile(). */
2352 profile_str = pa_modargs_get_value(u->modargs, "profile", NULL);
2354 pa_card_profile *profile;
2356 profile = pa_hashmap_get(u->card->profiles, profile_str);
2358 pa_log("No such profile: %s", profile_str);
2362 pa_card_set_profile(u->card, profile, false);
2365 pa_card_put(u->card);
2367 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2369 if (*d != PA_BLUEZ4_PROFILE_OFF && (!device->transports[*d] ||
2370 device->transports[*d]->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)) {
2371 pa_log_warn("Default profile not connected, selecting off profile");
2372 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2373 u->card->save_profile = false;
2376 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2379 if (USE_SCO_OVER_PCM(u))
2380 save_sco_volume_callbacks(u);
2385 /* Run from main thread */
2386 static pa_bluez4_device* find_device(struct userdata *u, const char *address, const char *path) {
2387 pa_bluez4_device *d = NULL;
2391 if (!address && !path) {
2392 pa_log_error("Failed to get device address/path from module arguments.");
2397 if (!(d = pa_bluez4_discovery_get_by_path(u->discovery, path))) {
2398 pa_log_error("%s is not a valid BlueZ audio device.", path);
2402 if (address && !(pa_streq(d->address, address))) {
2403 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2408 if (!(d = pa_bluez4_discovery_get_by_address(u->discovery, address))) {
2409 pa_log_error("%s is not known.", address);
2415 u->address = pa_xstrdup(d->address);
2416 u->path = pa_xstrdup(d->path);
2422 /* Run from main thread */
2423 static pa_hook_result_t uuid_added_cb(pa_bluez4_discovery *y, const struct pa_bluez4_hook_uuid_data *data,
2424 struct userdata *u) {
2425 pa_bluez4_profile_t profile;
2429 pa_assert(data->device);
2430 pa_assert(data->uuid);
2433 if (data->device != u->device)
2436 if (uuid_to_profile(data->uuid, &profile) < 0)
2439 if (pa_hashmap_get(u->card->profiles, pa_bluez4_profile_to_string(profile)))
2442 p = create_card_profile(u, profile, u->card->ports);
2443 pa_card_add_profile(u->card, p);
2448 /* Run from main thread */
2449 static pa_hook_result_t discovery_hook_cb(pa_bluez4_discovery *y, const pa_bluez4_device *d, struct userdata *u) {
2457 pa_log_debug("Device %s removed: unloading module", d->path);
2458 else if (!pa_bluez4_device_any_audio_connected(d))
2459 pa_log_debug("Unloading module, because device %s doesn't have any audio profiles connected anymore.", d->path);
2463 pa_module_unload(u->module, true);
2468 int pa__init(pa_module *m) {
2472 const char *address, *path;
2473 pa_bluez4_device *device;
2477 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2478 pa_log_error("Failed to parse module arguments");
2482 m->userdata = u = pa_xnew0(struct userdata, 1);
2486 u->sample_spec = m->core->default_sample_spec;
2489 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2490 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2491 pa_log("SCO sink not found");
2495 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2496 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2497 pa_log("SCO source not found");
2501 if (pa_modargs_get_sample_rate(ma, &u->sample_spec.rate) < 0) {
2502 pa_log_error("Failed to get rate from module arguments");
2506 channels = u->sample_spec.channels;
2507 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2508 !pa_channels_valid(channels)) {
2509 pa_log_error("Failed to get channels from module arguments");
2512 u->sample_spec.channels = (uint8_t) channels;
2513 u->requested_sample_spec = u->sample_spec;
2515 address = pa_modargs_get_value(ma, "address", NULL);
2516 path = pa_modargs_get_value(ma, "path", NULL);
2518 if (!(u->discovery = pa_bluez4_discovery_get(m->core)))
2521 if (!(device = find_device(u, address, path)))
2527 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_DEVICE_CONNECTION_CHANGED),
2528 PA_HOOK_NORMAL, (pa_hook_cb_t) discovery_hook_cb, u);
2530 u->uuid_added_slot =
2531 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_DEVICE_UUID_ADDED),
2532 PA_HOOK_NORMAL, (pa_hook_cb_t) uuid_added_cb, u);
2534 u->sink_state_changed_slot =
2535 pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED],
2536 PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
2538 u->source_state_changed_slot =
2539 pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED],
2540 PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2542 u->transport_state_changed_slot =
2543 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_STATE_CHANGED),
2544 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2546 u->transport_nrec_changed_slot =
2547 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_NREC_CHANGED),
2548 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_nrec_changed_cb, u);
2550 u->transport_microphone_changed_slot =
2551 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED),
2552 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2554 u->transport_speaker_changed_slot =
2555 pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED),
2556 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2558 /* Add the card structure. This will also initialize the default profile */
2559 if (add_card(u) < 0)
2562 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2565 u->msg->parent.process_msg = device_process_msg;
2566 u->msg->card = u->card;
2568 if (u->profile != PA_BLUEZ4_PROFILE_OFF)
2569 if (init_profile(u) < 0)
2572 if (u->sink || u->source)
2573 if (start_thread(u) < 0)
2581 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2592 int pa__get_n_used(pa_module *m) {
2596 pa_assert_se(u = m->userdata);
2599 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2600 (u->source ? pa_source_linked_by(u->source) : 0);
2603 void pa__done(pa_module *m) {
2608 if (!(u = m->userdata))
2613 if (u->discovery_slot)
2614 pa_hook_slot_free(u->discovery_slot);
2616 if (u->uuid_added_slot)
2617 pa_hook_slot_free(u->uuid_added_slot);
2619 if (u->sink_state_changed_slot)
2620 pa_hook_slot_free(u->sink_state_changed_slot);
2622 if (u->source_state_changed_slot)
2623 pa_hook_slot_free(u->source_state_changed_slot);
2625 if (u->transport_state_changed_slot)
2626 pa_hook_slot_free(u->transport_state_changed_slot);
2628 if (u->transport_nrec_changed_slot)
2629 pa_hook_slot_free(u->transport_nrec_changed_slot);
2631 if (u->transport_microphone_changed_slot)
2632 pa_hook_slot_free(u->transport_microphone_changed_slot);
2634 if (u->transport_speaker_changed_slot)
2635 pa_hook_slot_free(u->transport_speaker_changed_slot);
2637 if (USE_SCO_OVER_PCM(u))
2638 restore_sco_volume_callbacks(u);
2644 pa_card_free(u->card);
2647 pa_xfree(u->a2dp.buffer);
2649 sbc_finish(&u->a2dp.sbc);
2652 pa_modargs_free(u->modargs);
2654 pa_xfree(u->output_port_name);
2655 pa_xfree(u->input_port_name);
2657 pa_xfree(u->address);
2661 pa_bluez4_discovery_unref(u->discovery);