bluetooth: Check return value of start_thread()
[pulseaudio-raopUDP/pulseaudio-raop-alac.git] / src / modules / bluetooth / module-bluetooth-device.c
blob4b98108ae96d5813f73fd220bd2f4b70632ddc42
1 /***
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
20 USA.
21 ***/
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
27 #include <string.h>
28 #include <errno.h>
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 <sbc/sbc.h>
55 #include "module-bluetooth-device-symdef.h"
56 #include "a2dp-codecs.h"
57 #include "rtp.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);
68 PA_MODULE_USAGE(
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> "
78 "rate=<sample rate> "
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[] = {
88 "name",
89 "card_name",
90 "card_properties",
91 "sink_name",
92 "sink_properties",
93 "source_name",
94 "source_properties",
95 "address",
96 "profile",
97 "rate",
98 "channels",
99 "path",
100 "auto_connect",
101 "sco_sink",
102 "sco_source",
103 NULL
106 struct a2dp_info {
107 sbc_t sbc; /* Codec data */
108 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
109 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
111 void* buffer; /* Codec transfer buffer */
112 size_t buffer_size; /* Size of the buffer */
114 uint16_t seq_num; /* Cumulative packet sequence */
115 uint8_t min_bitpool;
116 uint8_t max_bitpool;
119 struct hsp_info {
120 pa_sink *sco_sink;
121 void (*sco_sink_set_volume)(pa_sink *s);
122 pa_source *sco_source;
123 void (*sco_source_set_volume)(pa_source *s);
124 pa_hook_slot *sink_state_changed_slot;
125 pa_hook_slot *source_state_changed_slot;
126 pa_hook_slot *nrec_changed_slot;
129 struct bluetooth_msg {
130 pa_msgobject parent;
131 pa_card *card;
134 typedef struct bluetooth_msg bluetooth_msg;
135 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
136 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
138 struct userdata {
139 pa_core *core;
140 pa_module *module;
142 char *address;
143 char *path;
144 char *transport;
145 char *accesstype;
147 pa_bluetooth_discovery *discovery;
148 pa_bool_t auto_connect;
150 pa_dbus_connection *connection;
152 pa_card *card;
153 pa_sink *sink;
154 pa_source *source;
156 pa_thread_mq thread_mq;
157 pa_rtpoll *rtpoll;
158 pa_rtpoll_item *rtpoll_item;
159 pa_thread *thread;
160 bluetooth_msg *msg;
162 uint64_t read_index, write_index;
163 pa_usec_t started_at;
164 pa_smoother *read_smoother;
166 pa_memchunk write_memchunk;
168 pa_sample_spec sample_spec, requested_sample_spec;
170 int stream_fd;
172 size_t read_link_mtu;
173 size_t read_block_size;
175 size_t write_link_mtu;
176 size_t write_block_size;
178 struct a2dp_info a2dp;
179 struct hsp_info hsp;
181 enum profile profile;
183 pa_modargs *modargs;
185 int stream_write_type;
187 pa_bool_t filter_added;
190 enum {
191 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
192 BLUETOOTH_MESSAGE_MAX
195 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
196 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
197 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
198 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
200 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
202 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
204 static int init_profile(struct userdata *u);
206 /* from IO thread */
207 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
209 struct a2dp_info *a2dp;
211 pa_assert(u);
213 a2dp = &u->a2dp;
215 if (a2dp->sbc.bitpool == bitpool)
216 return;
218 if (bitpool > a2dp->max_bitpool)
219 bitpool = a2dp->max_bitpool;
220 else if (bitpool < a2dp->min_bitpool)
221 bitpool = a2dp->min_bitpool;
223 a2dp->sbc.bitpool = bitpool;
225 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
226 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
228 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
230 u->read_block_size =
231 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
232 / a2dp->frame_length * a2dp->codesize;
234 u->write_block_size =
235 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
236 / a2dp->frame_length * a2dp->codesize;
238 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
239 pa_sink_set_fixed_latency_within_thread(u->sink,
240 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
243 /* from IO thread, except in SCO over PCM */
244 static void bt_transport_config_mtu(struct userdata *u) {
245 /* Calculate block sizes */
246 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
247 u->read_block_size = u->read_link_mtu;
248 u->write_block_size = u->write_link_mtu;
249 } else {
250 u->read_block_size =
251 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
252 / u->a2dp.frame_length * u->a2dp.codesize;
254 u->write_block_size =
255 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
256 / u->a2dp.frame_length * u->a2dp.codesize;
259 if (USE_SCO_OVER_PCM(u))
260 return;
262 if (u->sink) {
263 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
264 pa_sink_set_fixed_latency_within_thread(u->sink,
265 (u->profile == PROFILE_A2DP ?
266 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
267 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
270 if (u->source)
271 pa_source_set_fixed_latency_within_thread(u->source,
272 (u->profile == PROFILE_A2DP_SOURCE ?
273 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
274 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
277 /* from IO thread, except in SCO over PCM */
279 static void setup_stream(struct userdata *u) {
280 struct pollfd *pollfd;
281 int one;
283 bt_transport_config_mtu(u);
285 pa_make_fd_nonblock(u->stream_fd);
286 pa_make_socket_low_delay(u->stream_fd);
288 one = 1;
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 == PROFILE_A2DP)
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;
303 u->started_at = 0;
305 if (u->source)
306 u->read_smoother = pa_smoother_new(
307 PA_USEC_PER_SEC,
308 PA_USEC_PER_SEC*2,
309 TRUE,
310 TRUE,
312 pa_rtclock_now(),
313 TRUE);
316 static bool bt_transport_is_acquired(struct userdata *u) {
317 if (u->accesstype == NULL) {
318 pa_assert(u->stream_fd < 0);
319 return FALSE;
320 } else {
321 /* During IO thread HUP stream_fd can be -1 */
322 return TRUE;
326 static void teardown_stream(struct userdata *u) {
327 if (u->rtpoll_item) {
328 pa_rtpoll_item_free(u->rtpoll_item);
329 u->rtpoll_item = NULL;
332 if (u->stream_fd >= 0) {
333 pa_close(u->stream_fd);
334 u->stream_fd = -1;
337 if (u->read_smoother) {
338 pa_smoother_free(u->read_smoother);
339 u->read_smoother = NULL;
342 pa_log_debug("Audio stream torn down");
345 static void bt_transport_release(struct userdata *u) {
346 const char *accesstype = "rw";
347 const pa_bluetooth_transport *t;
349 /* Ignore if already released */
350 if (!bt_transport_is_acquired(u))
351 return;
353 pa_log_debug("Releasing transport %s", u->transport);
355 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
356 if (t)
357 pa_bluetooth_transport_release(t, accesstype);
359 pa_xfree(u->accesstype);
360 u->accesstype = NULL;
362 teardown_stream(u);
365 static pa_bt_audio_state_t get_profile_audio_state(const struct userdata *u, const pa_bluetooth_device *d) {
366 switch(u->profile) {
367 case PROFILE_HSP:
368 return d->headset_state;
369 case PROFILE_A2DP:
370 return d->audio_sink_state;
371 case PROFILE_A2DP_SOURCE:
372 return d->audio_source_state;
373 case PROFILE_HFGW:
374 return d->hfgw_state;
375 case PROFILE_OFF:
376 break;
379 pa_assert_not_reached();
382 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
383 const char *accesstype = "rw";
384 const pa_bluetooth_device *d;
385 const pa_bluetooth_transport *t;
387 if (u->transport == NULL) {
388 pa_log("Transport no longer available.");
389 return -1;
392 if (bt_transport_is_acquired(u)) {
393 if (start)
394 goto done;
395 return 0;
398 pa_log_debug("Acquiring transport %s", u->transport);
400 d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path);
401 if (!d) {
402 pa_log_error("Failed to get device object.");
403 return -1;
406 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
407 if (!t) {
408 pa_log("Transport %s no longer available", u->transport);
409 pa_xfree(u->transport);
410 u->transport = NULL;
411 return -1;
414 if (!start) {
415 /* FIXME: we are trying to acquire the transport only if the stream is
416 playing, without actually initiating the stream request from our side
417 (which is typically undesireable specially for hfgw use-cases.
418 However this approach is racy, since the stream could have been
419 suspended in the meantime, so we can't really guarantee that the
420 stream will not be requested until BlueZ's API supports this
421 atomically. */
422 if (get_profile_audio_state(u, d) < PA_BT_AUDIO_STATE_PLAYING) {
423 pa_log_info("Failed optional acquire of transport %s", u->transport);
424 return -1;
428 u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, &u->read_link_mtu, &u->write_link_mtu);
429 if (u->stream_fd < 0) {
430 if (start)
431 pa_log("Failed to acquire transport %s", u->transport);
432 else
433 pa_log_info("Failed optional acquire of transport %s", u->transport);
435 return -1;
438 u->accesstype = pa_xstrdup(accesstype);
439 pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
441 if (!start)
442 return 0;
444 done:
445 pa_log_info("Transport %s resuming", u->transport);
446 setup_stream(u);
448 return 0;
451 /* Run from IO thread */
452 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
453 struct userdata *u = PA_SINK(o)->userdata;
454 pa_bool_t failed = FALSE;
455 int r;
457 pa_assert(u->sink == PA_SINK(o));
458 pa_assert(u->transport);
460 switch (code) {
462 case PA_SINK_MESSAGE_SET_STATE:
464 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
466 case PA_SINK_SUSPENDED:
467 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
468 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
469 break;
471 /* Stop the device if the source is suspended as well */
472 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
473 /* We deliberately ignore whether stopping
474 * actually worked. Since the stream_fd is
475 * closed it doesn't really matter */
476 bt_transport_release(u);
478 break;
480 case PA_SINK_IDLE:
481 case PA_SINK_RUNNING:
482 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
483 break;
485 /* Resume the device if the source was suspended as well */
486 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
487 if (bt_transport_acquire(u, TRUE) < 0)
488 failed = TRUE;
490 break;
492 case PA_SINK_UNLINKED:
493 case PA_SINK_INIT:
494 case PA_SINK_INVALID_STATE:
497 break;
499 case PA_SINK_MESSAGE_GET_LATENCY: {
501 if (u->read_smoother) {
502 pa_usec_t wi, ri;
504 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
505 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
507 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
508 } else {
509 pa_usec_t ri, wi;
511 ri = pa_rtclock_now() - u->started_at;
512 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
514 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
517 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
518 return 0;
522 r = pa_sink_process_msg(o, code, data, offset, chunk);
524 return (r < 0 || !failed) ? r : -1;
527 /* Run from IO thread */
528 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
529 struct userdata *u = PA_SOURCE(o)->userdata;
530 pa_bool_t failed = FALSE;
531 int r;
533 pa_assert(u->source == PA_SOURCE(o));
534 pa_assert(u->transport);
536 switch (code) {
538 case PA_SOURCE_MESSAGE_SET_STATE:
540 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
542 case PA_SOURCE_SUSPENDED:
543 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
544 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
545 break;
547 /* Stop the device if the sink is suspended as well */
548 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
549 bt_transport_release(u);
551 if (u->read_smoother)
552 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
553 break;
555 case PA_SOURCE_IDLE:
556 case PA_SOURCE_RUNNING:
557 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
558 break;
560 /* Resume the device if the sink was suspended as well */
561 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
562 if (bt_transport_acquire(u, TRUE) < 0)
563 failed = TRUE;
565 /* We don't resume the smoother here. Instead we
566 * wait until the first packet arrives */
567 break;
569 case PA_SOURCE_UNLINKED:
570 case PA_SOURCE_INIT:
571 case PA_SOURCE_INVALID_STATE:
574 break;
576 case PA_SOURCE_MESSAGE_GET_LATENCY: {
577 pa_usec_t wi, ri;
579 if (u->read_smoother) {
580 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
581 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
583 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
584 } else
585 *((pa_usec_t*) data) = 0;
587 return 0;
592 r = pa_source_process_msg(o, code, data, offset, chunk);
594 return (r < 0 || !failed) ? r : -1;
597 /* Called from main thread context */
598 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
599 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
601 switch (code) {
602 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
603 if (u->card->module->unload_requested)
604 break;
606 pa_log_debug("Switching the profile to off due to IO thread failure.");
608 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
609 break;
612 return 0;
615 /* Run from IO thread */
616 static int hsp_process_render(struct userdata *u) {
617 int ret = 0;
619 pa_assert(u);
620 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
621 pa_assert(u->sink);
623 /* First, render some data */
624 if (!u->write_memchunk.memblock)
625 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
627 pa_assert(u->write_memchunk.length == u->write_block_size);
629 for (;;) {
630 ssize_t l;
631 const void *p;
633 /* Now write that data to the socket. The socket is of type
634 * SEQPACKET, and we generated the data of the MTU size, so this
635 * should just work. */
637 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
638 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
639 pa_memblock_release(u->write_memchunk.memblock);
641 pa_assert(l != 0);
643 if (l < 0) {
645 if (errno == EINTR)
646 /* Retry right away if we got interrupted */
647 continue;
649 else if (errno == EAGAIN)
650 /* Hmm, apparently the socket was not writable, give up for now */
651 break;
653 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
654 ret = -1;
655 break;
658 pa_assert((size_t) l <= u->write_memchunk.length);
660 if ((size_t) l != u->write_memchunk.length) {
661 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
662 (unsigned long long) l,
663 (unsigned long long) u->write_memchunk.length);
664 ret = -1;
665 break;
668 u->write_index += (uint64_t) u->write_memchunk.length;
669 pa_memblock_unref(u->write_memchunk.memblock);
670 pa_memchunk_reset(&u->write_memchunk);
672 ret = 1;
673 break;
676 return ret;
679 /* Run from IO thread */
680 static int hsp_process_push(struct userdata *u) {
681 int ret = 0;
682 pa_memchunk memchunk;
684 pa_assert(u);
685 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
686 pa_assert(u->source);
687 pa_assert(u->read_smoother);
689 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
690 memchunk.index = memchunk.length = 0;
692 for (;;) {
693 ssize_t l;
694 void *p;
695 struct msghdr m;
696 struct cmsghdr *cm;
697 uint8_t aux[1024];
698 struct iovec iov;
699 pa_bool_t found_tstamp = FALSE;
700 pa_usec_t tstamp;
702 memset(&m, 0, sizeof(m));
703 memset(&aux, 0, sizeof(aux));
704 memset(&iov, 0, sizeof(iov));
706 m.msg_iov = &iov;
707 m.msg_iovlen = 1;
708 m.msg_control = aux;
709 m.msg_controllen = sizeof(aux);
711 p = pa_memblock_acquire(memchunk.memblock);
712 iov.iov_base = p;
713 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
714 l = recvmsg(u->stream_fd, &m, 0);
715 pa_memblock_release(memchunk.memblock);
717 if (l <= 0) {
719 if (l < 0 && errno == EINTR)
720 /* Retry right away if we got interrupted */
721 continue;
723 else if (l < 0 && errno == EAGAIN)
724 /* Hmm, apparently the socket was not readable, give up for now. */
725 break;
727 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
728 ret = -1;
729 break;
732 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
734 memchunk.length = (size_t) l;
735 u->read_index += (uint64_t) l;
737 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
738 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
739 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
740 pa_rtclock_from_wallclock(tv);
741 tstamp = pa_timeval_load(tv);
742 found_tstamp = TRUE;
743 break;
746 if (!found_tstamp) {
747 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
748 tstamp = pa_rtclock_now();
751 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
752 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
754 pa_source_post(u->source, &memchunk);
756 ret = l;
757 break;
760 pa_memblock_unref(memchunk.memblock);
762 return ret;
765 /* Run from IO thread */
766 static void a2dp_prepare_buffer(struct userdata *u) {
767 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
769 pa_assert(u);
771 if (u->a2dp.buffer_size >= min_buffer_size)
772 return;
774 u->a2dp.buffer_size = 2 * min_buffer_size;
775 pa_xfree(u->a2dp.buffer);
776 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
779 /* Run from IO thread */
780 static int a2dp_process_render(struct userdata *u) {
781 struct a2dp_info *a2dp;
782 struct rtp_header *header;
783 struct rtp_payload *payload;
784 size_t nbytes;
785 void *d;
786 const void *p;
787 size_t to_write, to_encode;
788 unsigned frame_count;
789 int ret = 0;
791 pa_assert(u);
792 pa_assert(u->profile == PROFILE_A2DP);
793 pa_assert(u->sink);
795 /* First, render some data */
796 if (!u->write_memchunk.memblock)
797 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
799 pa_assert(u->write_memchunk.length == u->write_block_size);
801 a2dp_prepare_buffer(u);
803 a2dp = &u->a2dp;
804 header = a2dp->buffer;
805 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
807 frame_count = 0;
809 /* Try to create a packet of the full MTU */
811 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
812 to_encode = u->write_memchunk.length;
814 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
815 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
817 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
818 ssize_t written;
819 ssize_t encoded;
821 encoded = sbc_encode(&a2dp->sbc,
822 p, to_encode,
823 d, to_write,
824 &written);
826 if (PA_UNLIKELY(encoded <= 0)) {
827 pa_log_error("SBC encoding error (%li)", (long) encoded);
828 pa_memblock_release(u->write_memchunk.memblock);
829 return -1;
832 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
833 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
835 pa_assert_fp((size_t) encoded <= to_encode);
836 pa_assert_fp((size_t) encoded == a2dp->codesize);
838 pa_assert_fp((size_t) written <= to_write);
839 pa_assert_fp((size_t) written == a2dp->frame_length);
841 p = (const uint8_t*) p + encoded;
842 to_encode -= encoded;
844 d = (uint8_t*) d + written;
845 to_write -= written;
847 frame_count++;
850 pa_memblock_release(u->write_memchunk.memblock);
852 pa_assert(to_encode == 0);
854 PA_ONCE_BEGIN {
855 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
856 } PA_ONCE_END;
858 /* write it to the fifo */
859 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
860 header->v = 2;
861 header->pt = 1;
862 header->sequence_number = htons(a2dp->seq_num++);
863 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
864 header->ssrc = htonl(1);
865 payload->frame_count = frame_count;
867 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
869 for (;;) {
870 ssize_t l;
872 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
874 pa_assert(l != 0);
876 if (l < 0) {
878 if (errno == EINTR)
879 /* Retry right away if we got interrupted */
880 continue;
882 else if (errno == EAGAIN)
883 /* Hmm, apparently the socket was not writable, give up for now */
884 break;
886 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
887 ret = -1;
888 break;
891 pa_assert((size_t) l <= nbytes);
893 if ((size_t) l != nbytes) {
894 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
895 (unsigned long long) l,
896 (unsigned long long) nbytes);
897 ret = -1;
898 break;
901 u->write_index += (uint64_t) u->write_memchunk.length;
902 pa_memblock_unref(u->write_memchunk.memblock);
903 pa_memchunk_reset(&u->write_memchunk);
905 ret = 1;
907 break;
910 return ret;
913 static int a2dp_process_push(struct userdata *u) {
914 int ret = 0;
915 pa_memchunk memchunk;
917 pa_assert(u);
918 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
919 pa_assert(u->source);
920 pa_assert(u->read_smoother);
922 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
923 memchunk.index = memchunk.length = 0;
925 for (;;) {
926 pa_bool_t found_tstamp = FALSE;
927 pa_usec_t tstamp;
928 struct a2dp_info *a2dp;
929 struct rtp_header *header;
930 struct rtp_payload *payload;
931 const void *p;
932 void *d;
933 ssize_t l;
934 size_t to_write, to_decode;
936 a2dp_prepare_buffer(u);
938 a2dp = &u->a2dp;
939 header = a2dp->buffer;
940 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
942 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
944 if (l <= 0) {
946 if (l < 0 && errno == EINTR)
947 /* Retry right away if we got interrupted */
948 continue;
950 else if (l < 0 && errno == EAGAIN)
951 /* Hmm, apparently the socket was not readable, give up for now. */
952 break;
954 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
955 ret = -1;
956 break;
959 pa_assert((size_t) l <= a2dp->buffer_size);
961 u->read_index += (uint64_t) l;
963 /* TODO: get timestamp from rtp */
964 if (!found_tstamp) {
965 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
966 tstamp = pa_rtclock_now();
969 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
970 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
972 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
973 to_decode = l - sizeof(*header) - sizeof(*payload);
975 d = pa_memblock_acquire(memchunk.memblock);
976 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
978 while (PA_LIKELY(to_decode > 0)) {
979 size_t written;
980 ssize_t decoded;
982 decoded = sbc_decode(&a2dp->sbc,
983 p, to_decode,
984 d, to_write,
985 &written);
987 if (PA_UNLIKELY(decoded <= 0)) {
988 pa_log_error("SBC decoding error (%li)", (long) decoded);
989 pa_memblock_release(memchunk.memblock);
990 pa_memblock_unref(memchunk.memblock);
991 return -1;
994 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
995 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
997 /* Reset frame length, it can be changed due to bitpool change */
998 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1000 pa_assert_fp((size_t) decoded <= to_decode);
1001 pa_assert_fp((size_t) decoded == a2dp->frame_length);
1003 pa_assert_fp((size_t) written == a2dp->codesize);
1005 p = (const uint8_t*) p + decoded;
1006 to_decode -= decoded;
1008 d = (uint8_t*) d + written;
1009 to_write -= written;
1012 memchunk.length -= to_write;
1014 pa_memblock_release(memchunk.memblock);
1016 pa_source_post(u->source, &memchunk);
1018 ret = l;
1019 break;
1022 pa_memblock_unref(memchunk.memblock);
1024 return ret;
1027 static void a2dp_reduce_bitpool(struct userdata *u)
1029 struct a2dp_info *a2dp;
1030 uint8_t bitpool;
1032 pa_assert(u);
1034 a2dp = &u->a2dp;
1036 /* Check if bitpool is already at its limit */
1037 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1038 return;
1040 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1042 if (bitpool < BITPOOL_DEC_LIMIT)
1043 bitpool = BITPOOL_DEC_LIMIT;
1045 a2dp_set_bitpool(u, bitpool);
1048 static void thread_func(void *userdata) {
1049 struct userdata *u = userdata;
1050 unsigned do_write = 0;
1051 unsigned pending_read_bytes = 0;
1052 pa_bool_t writable = FALSE;
1054 pa_assert(u);
1055 pa_assert(u->transport);
1057 pa_log_debug("IO Thread starting up");
1059 if (u->core->realtime_scheduling)
1060 pa_make_realtime(u->core->realtime_priority);
1062 pa_thread_mq_install(&u->thread_mq);
1064 /* Setup the stream only if the transport was already acquired */
1065 if (bt_transport_is_acquired(u))
1066 bt_transport_acquire(u, TRUE);
1068 for (;;) {
1069 struct pollfd *pollfd;
1070 int ret;
1071 pa_bool_t disable_timer = TRUE;
1073 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1075 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1077 /* We should send two blocks to the device before we expect
1078 * a response. */
1080 if (u->write_index == 0 && u->read_index <= 0)
1081 do_write = 2;
1083 if (pollfd && (pollfd->revents & POLLIN)) {
1084 int n_read;
1086 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1087 n_read = hsp_process_push(u);
1088 else
1089 n_read = a2dp_process_push(u);
1091 if (n_read < 0)
1092 goto io_fail;
1094 /* We just read something, so we are supposed to write something, too */
1095 pending_read_bytes += n_read;
1096 do_write += pending_read_bytes / u->write_block_size;
1097 pending_read_bytes = pending_read_bytes % u->write_block_size;
1101 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1103 if (u->sink->thread_info.rewind_requested)
1104 pa_sink_process_rewind(u->sink, 0);
1106 if (pollfd) {
1107 if (pollfd->revents & POLLOUT)
1108 writable = TRUE;
1110 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1111 pa_usec_t time_passed;
1112 pa_usec_t audio_sent;
1114 /* Hmm, there is no input stream we could synchronize
1115 * to. So let's do things by time */
1117 time_passed = pa_rtclock_now() - u->started_at;
1118 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1120 if (audio_sent <= time_passed) {
1121 pa_usec_t audio_to_send = time_passed - audio_sent;
1123 /* Never try to catch up for more than 100ms */
1124 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1125 pa_usec_t skip_usec;
1126 uint64_t skip_bytes;
1128 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1129 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1131 if (skip_bytes > 0) {
1132 pa_memchunk tmp;
1134 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1135 (unsigned long long) skip_usec,
1136 (unsigned long long) skip_bytes);
1138 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1139 pa_memblock_unref(tmp.memblock);
1140 u->write_index += skip_bytes;
1142 if (u->profile == PROFILE_A2DP)
1143 a2dp_reduce_bitpool(u);
1147 do_write = 1;
1148 pending_read_bytes = 0;
1152 if (writable && do_write > 0) {
1153 int n_written;
1155 if (u->write_index <= 0)
1156 u->started_at = pa_rtclock_now();
1158 if (u->profile == PROFILE_A2DP) {
1159 if ((n_written = a2dp_process_render(u)) < 0)
1160 goto io_fail;
1161 } else {
1162 if ((n_written = hsp_process_render(u)) < 0)
1163 goto io_fail;
1166 if (n_written == 0)
1167 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1169 do_write -= n_written;
1170 writable = FALSE;
1173 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1174 pa_usec_t sleep_for;
1175 pa_usec_t time_passed, next_write_at;
1177 if (writable) {
1178 /* Hmm, there is no input stream we could synchronize
1179 * to. So let's estimate when we need to wake up the latest */
1180 time_passed = pa_rtclock_now() - u->started_at;
1181 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1182 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1183 /* 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); */
1184 } else
1185 /* drop stream every 500 ms */
1186 sleep_for = PA_USEC_PER_MSEC * 500;
1188 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1189 disable_timer = FALSE;
1194 if (disable_timer)
1195 pa_rtpoll_set_timer_disabled(u->rtpoll);
1197 /* Hmm, nothing to do. Let's sleep */
1198 if (pollfd)
1199 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1200 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1202 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
1203 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1204 goto fail;
1206 if (ret == 0) {
1207 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1208 bt_transport_release(u);
1209 goto finish;
1212 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1214 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1215 pa_log_info("FD error: %s%s%s%s",
1216 pollfd->revents & POLLERR ? "POLLERR " :"",
1217 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1218 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1219 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1220 goto io_fail;
1223 continue;
1225 io_fail:
1226 /* In case of HUP, just tear down the streams */
1227 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1228 goto fail;
1230 do_write = 0;
1231 pending_read_bytes = 0;
1232 writable = FALSE;
1234 teardown_stream(u);
1237 fail:
1238 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1239 pa_log_debug("IO thread failed");
1240 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1241 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1243 finish:
1244 pa_log_debug("IO thread shutting down");
1247 static pa_bt_audio_state_t parse_state_property_change(DBusMessage *m) {
1248 DBusMessageIter iter;
1249 DBusMessageIter variant;
1250 const char *key;
1251 const char *value;
1252 pa_bt_audio_state_t state;
1254 if (!dbus_message_iter_init(m, &iter)) {
1255 pa_log("Failed to parse PropertyChanged");
1256 return PA_BT_AUDIO_STATE_INVALID;
1259 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
1260 pa_log("Property name not a string");
1261 return PA_BT_AUDIO_STATE_INVALID;
1264 dbus_message_iter_get_basic(&iter, &key);
1266 if (!pa_streq(key, "State"))
1267 return PA_BT_AUDIO_STATE_INVALID;
1269 if (!dbus_message_iter_next(&iter)) {
1270 pa_log("Property value missing");
1271 return PA_BT_AUDIO_STATE_INVALID;
1274 dbus_message_iter_recurse(&iter, &variant);
1276 if (dbus_message_iter_get_arg_type(&variant) != DBUS_TYPE_STRING) {
1277 pa_log("Property value not a string");
1278 return PA_BT_AUDIO_STATE_INVALID;
1281 dbus_message_iter_get_basic(&variant, &value);
1283 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m), value);
1285 state = pa_bt_audio_state_from_string(value);
1287 if (state == PA_BT_AUDIO_STATE_INVALID)
1288 pa_log("Unexpected value for property 'State': '%s'", value);
1290 return state;
1293 static pa_port_available_t audio_state_to_availability(pa_bt_audio_state_t state) {
1294 if (state < PA_BT_AUDIO_STATE_CONNECTED)
1295 return PA_PORT_AVAILABLE_NO;
1296 else if (state >= PA_BT_AUDIO_STATE_PLAYING)
1297 return PA_PORT_AVAILABLE_YES;
1298 else
1299 return PA_PORT_AVAILABLE_UNKNOWN;
1302 /* Run from main thread */
1303 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1304 DBusError err;
1305 struct userdata *u;
1306 bool acquire = FALSE;
1307 bool release = FALSE;
1309 pa_assert(bus);
1310 pa_assert(m);
1311 pa_assert_se(u = userdata);
1313 dbus_error_init(&err);
1315 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1316 dbus_message_get_interface(m),
1317 dbus_message_get_path(m),
1318 dbus_message_get_member(m));
1320 if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1321 goto fail;
1323 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1324 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1326 dbus_uint16_t gain;
1327 pa_cvolume v;
1329 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > HSP_MAX_GAIN) {
1330 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1331 goto fail;
1334 if (u->profile == PROFILE_HSP) {
1335 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1336 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1338 /* increment volume by one to correct rounding errors */
1339 if (volume < PA_VOLUME_NORM)
1340 volume++;
1342 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1343 pa_sink_volume_changed(u->sink, &v);
1345 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1346 pa_volume_t volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1348 /* increment volume by one to correct rounding errors */
1349 if (volume < PA_VOLUME_NORM)
1350 volume++;
1352 pa_cvolume_set(&v, u->sample_spec.channels, volume);
1353 pa_source_volume_changed(u->source, &v);
1356 } else if (dbus_message_is_signal(m, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1357 pa_bt_audio_state_t state = parse_state_property_change(m);
1359 if (state != PA_BT_AUDIO_STATE_INVALID && pa_hashmap_get(u->card->profiles, "hfgw")) {
1360 pa_device_port *port;
1361 pa_port_available_t available = audio_state_to_availability(state);
1363 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1364 pa_device_port_set_available(port, available);
1366 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1367 pa_device_port_set_available(port, available);
1369 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1370 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1372 } else if (dbus_message_is_signal(m, "org.bluez.Headset", "PropertyChanged")) {
1373 pa_bt_audio_state_t state = parse_state_property_change(m);
1375 if (state != PA_BT_AUDIO_STATE_INVALID && pa_hashmap_get(u->card->profiles, "hsp")) {
1376 pa_device_port *port;
1377 pa_port_available_t available = audio_state_to_availability(state);
1379 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1380 pa_device_port_set_available(port, available);
1382 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1383 pa_device_port_set_available(port, available);
1385 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HSP);
1386 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_HSP);
1388 } else if (dbus_message_is_signal(m, "org.bluez.AudioSource", "PropertyChanged")) {
1389 pa_bt_audio_state_t state = parse_state_property_change(m);
1391 if (state != PA_BT_AUDIO_STATE_INVALID && pa_hashmap_get(u->card->profiles, "a2dp_source")) {
1392 pa_device_port *port;
1393 pa_port_available_t available = audio_state_to_availability(state);
1395 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1396 pa_device_port_set_available(port, available);
1398 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1399 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1401 } else if (dbus_message_is_signal(m, "org.bluez.AudioSink", "PropertyChanged")) {
1402 pa_bt_audio_state_t state = parse_state_property_change(m);
1404 if (state != PA_BT_AUDIO_STATE_INVALID && pa_hashmap_get(u->card->profiles, "a2dp")) {
1405 pa_device_port *port;
1406 pa_port_available_t available = audio_state_to_availability(state);
1408 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1409 pa_device_port_set_available(port, available);
1411 acquire = (available == PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1412 release = (available != PA_PORT_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1416 if (acquire)
1417 if (bt_transport_acquire(u, FALSE) >= 0) {
1418 if (u->source)
1419 pa_source_suspend(u->source, FALSE, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1421 if (u->sink)
1422 pa_sink_suspend(u->sink, FALSE, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1425 if (release && bt_transport_is_acquired(u)) {
1426 /* FIXME: this release is racy, since the audio stream might have
1427 been set up again in the meantime (but not processed yet by PA).
1428 BlueZ should probably release the transport automatically, and
1429 in that case we would just mark the transport as released */
1431 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1432 if (u->source)
1433 pa_source_suspend(u->source, TRUE, PA_SUSPEND_USER);
1435 if (u->sink)
1436 pa_sink_suspend(u->sink, TRUE, PA_SUSPEND_USER);
1439 fail:
1440 dbus_error_free(&err);
1442 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1445 /* Run from main thread */
1446 static void sink_set_volume_cb(pa_sink *s) {
1447 DBusMessage *m;
1448 dbus_uint16_t gain;
1449 pa_volume_t volume;
1450 struct userdata *u;
1451 char *k;
1453 pa_assert(s);
1454 pa_assert(s->core);
1456 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1457 u = pa_shared_get(s->core, k);
1458 pa_xfree(k);
1460 pa_assert(u);
1461 pa_assert(u->sink == s);
1462 pa_assert(u->profile == PROFILE_HSP);
1464 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1466 if (gain > HSP_MAX_GAIN)
1467 gain = HSP_MAX_GAIN;
1469 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1471 /* increment volume by one to correct rounding errors */
1472 if (volume < PA_VOLUME_NORM)
1473 volume++;
1475 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1477 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1478 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1479 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1480 dbus_message_unref(m);
1483 /* Run from main thread */
1484 static void source_set_volume_cb(pa_source *s) {
1485 DBusMessage *m;
1486 dbus_uint16_t gain;
1487 pa_volume_t volume;
1488 struct userdata *u;
1489 char *k;
1491 pa_assert(s);
1492 pa_assert(s->core);
1494 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1495 u = pa_shared_get(s->core, k);
1496 pa_xfree(k);
1498 pa_assert(u);
1499 pa_assert(u->source == s);
1500 pa_assert(u->profile == PROFILE_HSP);
1502 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1504 if (gain > HSP_MAX_GAIN)
1505 gain = HSP_MAX_GAIN;
1507 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1509 /* increment volume by one to correct rounding errors */
1510 if (volume < PA_VOLUME_NORM)
1511 volume++;
1513 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1515 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1516 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1517 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1518 dbus_message_unref(m);
1521 /* Run from main thread */
1522 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1523 char *t;
1524 const char *n;
1526 pa_assert(type);
1527 pa_assert(ma);
1528 pa_assert(device_id);
1529 pa_assert(namereg_fail);
1531 t = pa_sprintf_malloc("%s_name", type);
1532 n = pa_modargs_get_value(ma, t, NULL);
1533 pa_xfree(t);
1535 if (n) {
1536 *namereg_fail = TRUE;
1537 return pa_xstrdup(n);
1540 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1541 *namereg_fail = TRUE;
1542 else {
1543 n = device_id;
1544 *namereg_fail = FALSE;
1547 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1550 static int sco_over_pcm_state_update(struct userdata *u, pa_bool_t changed) {
1551 pa_assert(u);
1552 pa_assert(USE_SCO_OVER_PCM(u));
1554 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1555 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1557 if (u->stream_fd >= 0)
1558 return 0;
1560 pa_log_debug("Resuming SCO over PCM");
1561 if (init_profile(u) < 0) {
1562 pa_log("Can't resume SCO over PCM");
1563 return -1;
1566 return bt_transport_acquire(u, TRUE);
1569 if (changed) {
1570 if (u->stream_fd < 0)
1571 return 0;
1573 pa_log_debug("Closing SCO over PCM");
1575 bt_transport_release(u);
1578 return 0;
1581 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1582 pa_assert(c);
1583 pa_sink_assert_ref(s);
1584 pa_assert(u);
1586 if (s != u->hsp.sco_sink)
1587 return PA_HOOK_OK;
1589 sco_over_pcm_state_update(u, TRUE);
1591 return PA_HOOK_OK;
1594 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1595 pa_assert(c);
1596 pa_source_assert_ref(s);
1597 pa_assert(u);
1599 if (s != u->hsp.sco_source)
1600 return PA_HOOK_OK;
1602 sco_over_pcm_state_update(u, TRUE);
1604 return PA_HOOK_OK;
1607 static pa_hook_result_t nrec_changed_cb(pa_bluetooth_transport *t, void *call_data, struct userdata *u) {
1608 pa_proplist *p;
1610 pa_assert(t);
1611 pa_assert(u);
1613 p = pa_proplist_new();
1614 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1615 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1616 pa_proplist_free(p);
1618 return PA_HOOK_OK;
1621 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1622 union {
1623 pa_sink_new_data *sink_new_data;
1624 pa_source_new_data *source_new_data;
1625 } data;
1626 pa_device_port *port;
1628 if (direction == PA_DIRECTION_OUTPUT)
1629 data.sink_new_data = sink_or_source_new_data;
1630 else
1631 data.source_new_data = sink_or_source_new_data;
1633 switch (u->profile) {
1634 case PROFILE_A2DP:
1635 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-output"));
1636 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1637 pa_device_port_ref(port);
1638 break;
1640 case PROFILE_A2DP_SOURCE:
1641 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1642 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1643 pa_device_port_ref(port);
1644 break;
1646 case PROFILE_HSP:
1647 if (direction == PA_DIRECTION_OUTPUT) {
1648 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-output"));
1649 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1650 } else {
1651 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1652 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1654 pa_device_port_ref(port);
1655 break;
1657 case PROFILE_HFGW:
1658 if (direction == PA_DIRECTION_OUTPUT) {
1659 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1660 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1661 } else {
1662 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1663 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1665 pa_device_port_ref(port);
1666 break;
1668 default:
1669 pa_assert_not_reached();
1673 static const char *profile_to_string(enum profile profile) {
1674 switch(profile) {
1675 case PROFILE_A2DP:
1676 return "a2dp";
1677 case PROFILE_A2DP_SOURCE:
1678 return "a2dp_source";
1679 case PROFILE_HSP:
1680 return "hsp";
1681 case PROFILE_HFGW:
1682 return "hfgw";
1683 default:
1684 pa_assert_not_reached();
1688 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1689 return 0;
1692 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1693 return 0;
1696 /* Run from main thread */
1697 static int add_sink(struct userdata *u) {
1698 char *k;
1700 if (USE_SCO_OVER_PCM(u)) {
1701 pa_proplist *p;
1703 u->sink = u->hsp.sco_sink;
1704 p = pa_proplist_new();
1705 pa_proplist_sets(p, "bluetooth.protocol", profile_to_string(u->profile));
1706 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1707 pa_proplist_free(p);
1709 if (!u->hsp.sink_state_changed_slot)
1710 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);
1712 } else {
1713 pa_sink_new_data data;
1714 pa_bool_t b;
1716 pa_sink_new_data_init(&data);
1717 data.driver = __FILE__;
1718 data.module = u->module;
1719 pa_sink_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");
1723 data.card = u->card;
1724 data.name = get_name("sink", u->modargs, u->address, &b);
1725 data.namereg_fail = b;
1727 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1728 pa_log("Invalid properties");
1729 pa_sink_new_data_done(&data);
1730 return -1;
1732 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1734 if (!bt_transport_is_acquired(u))
1735 switch (u->profile) {
1736 case PROFILE_A2DP:
1737 case PROFILE_HSP:
1738 data.suspend_cause = PA_SUSPEND_IDLE;
1739 break;
1740 case PROFILE_HFGW:
1741 data.suspend_cause = PA_SUSPEND_USER;
1742 break;
1743 case PROFILE_A2DP_SOURCE:
1744 case PROFILE_OFF:
1745 pa_assert_not_reached();
1748 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1749 pa_sink_new_data_done(&data);
1751 if (!u->sink) {
1752 pa_log_error("Failed to create sink");
1753 return -1;
1756 u->sink->userdata = u;
1757 u->sink->parent.process_msg = sink_process_msg;
1758 u->sink->set_port = sink_set_port_cb;
1761 if (u->profile == PROFILE_HSP) {
1762 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1763 u->sink->n_volume_steps = 16;
1765 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1766 pa_shared_set(u->core, k, u);
1767 pa_xfree(k);
1770 return 0;
1773 /* Run from main thread */
1774 static int add_source(struct userdata *u) {
1775 char *k;
1777 if (USE_SCO_OVER_PCM(u)) {
1778 u->source = u->hsp.sco_source;
1779 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", profile_to_string(u->profile));
1781 if (!u->hsp.source_state_changed_slot)
1782 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);
1784 } else {
1785 pa_source_new_data data;
1786 pa_bool_t b;
1788 pa_source_new_data_init(&data);
1789 data.driver = __FILE__;
1790 data.module = u->module;
1791 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1792 pa_proplist_sets(data.proplist, "bluetooth.protocol", profile_to_string(u->profile));
1793 if (u->profile == PROFILE_HSP)
1794 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1796 data.card = u->card;
1797 data.name = get_name("source", u->modargs, u->address, &b);
1798 data.namereg_fail = b;
1800 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1801 pa_log("Invalid properties");
1802 pa_source_new_data_done(&data);
1803 return -1;
1806 connect_ports(u, &data, PA_DIRECTION_INPUT);
1808 if (!bt_transport_is_acquired(u))
1809 switch (u->profile) {
1810 case PROFILE_HSP:
1811 data.suspend_cause = PA_SUSPEND_IDLE;
1812 break;
1813 case PROFILE_A2DP_SOURCE:
1814 case PROFILE_HFGW:
1815 data.suspend_cause = PA_SUSPEND_USER;
1816 break;
1817 case PROFILE_A2DP:
1818 case PROFILE_OFF:
1819 pa_assert_not_reached();
1822 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1823 pa_source_new_data_done(&data);
1825 if (!u->source) {
1826 pa_log_error("Failed to create source");
1827 return -1;
1830 u->source->userdata = u;
1831 u->source->parent.process_msg = source_process_msg;
1832 u->source->set_port = source_set_port_cb;
1835 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1836 pa_bluetooth_transport *t;
1837 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1838 pa_assert(t);
1839 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1841 if (!u->hsp.nrec_changed_slot)
1842 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);
1845 if (u->profile == PROFILE_HSP) {
1846 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1847 u->source->n_volume_steps = 16;
1849 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1850 pa_shared_set(u->core, k, u);
1851 pa_xfree(k);
1854 return 0;
1857 static void bt_transport_config_a2dp(struct userdata *u) {
1858 const pa_bluetooth_transport *t;
1859 struct a2dp_info *a2dp = &u->a2dp;
1860 a2dp_sbc_t *config;
1862 t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1863 pa_assert(t);
1865 config = (a2dp_sbc_t *) t->config;
1867 u->sample_spec.format = PA_SAMPLE_S16LE;
1869 if (a2dp->sbc_initialized)
1870 sbc_reinit(&a2dp->sbc, 0);
1871 else
1872 sbc_init(&a2dp->sbc, 0);
1873 a2dp->sbc_initialized = TRUE;
1875 switch (config->frequency) {
1876 case SBC_SAMPLING_FREQ_16000:
1877 a2dp->sbc.frequency = SBC_FREQ_16000;
1878 u->sample_spec.rate = 16000U;
1879 break;
1880 case SBC_SAMPLING_FREQ_32000:
1881 a2dp->sbc.frequency = SBC_FREQ_32000;
1882 u->sample_spec.rate = 32000U;
1883 break;
1884 case SBC_SAMPLING_FREQ_44100:
1885 a2dp->sbc.frequency = SBC_FREQ_44100;
1886 u->sample_spec.rate = 44100U;
1887 break;
1888 case SBC_SAMPLING_FREQ_48000:
1889 a2dp->sbc.frequency = SBC_FREQ_48000;
1890 u->sample_spec.rate = 48000U;
1891 break;
1892 default:
1893 pa_assert_not_reached();
1896 switch (config->channel_mode) {
1897 case SBC_CHANNEL_MODE_MONO:
1898 a2dp->sbc.mode = SBC_MODE_MONO;
1899 u->sample_spec.channels = 1;
1900 break;
1901 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1902 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1903 u->sample_spec.channels = 2;
1904 break;
1905 case SBC_CHANNEL_MODE_STEREO:
1906 a2dp->sbc.mode = SBC_MODE_STEREO;
1907 u->sample_spec.channels = 2;
1908 break;
1909 case SBC_CHANNEL_MODE_JOINT_STEREO:
1910 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1911 u->sample_spec.channels = 2;
1912 break;
1913 default:
1914 pa_assert_not_reached();
1917 switch (config->allocation_method) {
1918 case SBC_ALLOCATION_SNR:
1919 a2dp->sbc.allocation = SBC_AM_SNR;
1920 break;
1921 case SBC_ALLOCATION_LOUDNESS:
1922 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1923 break;
1924 default:
1925 pa_assert_not_reached();
1928 switch (config->subbands) {
1929 case SBC_SUBBANDS_4:
1930 a2dp->sbc.subbands = SBC_SB_4;
1931 break;
1932 case SBC_SUBBANDS_8:
1933 a2dp->sbc.subbands = SBC_SB_8;
1934 break;
1935 default:
1936 pa_assert_not_reached();
1939 switch (config->block_length) {
1940 case SBC_BLOCK_LENGTH_4:
1941 a2dp->sbc.blocks = SBC_BLK_4;
1942 break;
1943 case SBC_BLOCK_LENGTH_8:
1944 a2dp->sbc.blocks = SBC_BLK_8;
1945 break;
1946 case SBC_BLOCK_LENGTH_12:
1947 a2dp->sbc.blocks = SBC_BLK_12;
1948 break;
1949 case SBC_BLOCK_LENGTH_16:
1950 a2dp->sbc.blocks = SBC_BLK_16;
1951 break;
1952 default:
1953 pa_assert_not_reached();
1956 a2dp->min_bitpool = config->min_bitpool;
1957 a2dp->max_bitpool = config->max_bitpool;
1959 /* Set minimum bitpool for source to get the maximum possible block_size */
1960 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1961 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1962 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1964 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1965 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1968 static void bt_transport_config(struct userdata *u) {
1969 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1970 u->sample_spec.format = PA_SAMPLE_S16LE;
1971 u->sample_spec.channels = 1;
1972 u->sample_spec.rate = 8000;
1973 } else
1974 bt_transport_config_a2dp(u);
1977 /* Run from main thread */
1978 static int setup_transport(struct userdata *u) {
1979 const pa_bluetooth_device *d;
1980 const pa_bluetooth_transport *t;
1982 pa_assert(u);
1984 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1985 pa_log_error("Failed to get device object.");
1986 return -1;
1989 /* check if profile has a transport */
1990 t = pa_bluetooth_device_get_transport(d, u->profile);
1991 if (t == NULL) {
1992 pa_log_warn("Profile has no transport");
1993 return -1;
1996 u->transport = pa_xstrdup(t->path);
1998 bt_transport_acquire(u, FALSE);
2000 bt_transport_config(u);
2002 return 0;
2005 /* Run from main thread */
2006 static int init_profile(struct userdata *u) {
2007 int r = 0;
2008 pa_assert(u);
2009 pa_assert(u->profile != PROFILE_OFF);
2011 if (setup_transport(u) < 0)
2012 return -1;
2014 if (u->profile == PROFILE_A2DP ||
2015 u->profile == PROFILE_HSP ||
2016 u->profile == PROFILE_HFGW)
2017 if (add_sink(u) < 0)
2018 r = -1;
2020 if (u->profile == PROFILE_HSP ||
2021 u->profile == PROFILE_A2DP_SOURCE ||
2022 u->profile == PROFILE_HFGW)
2023 if (add_source(u) < 0)
2024 r = -1;
2026 return r;
2029 /* Run from main thread */
2030 static void stop_thread(struct userdata *u) {
2031 char *k;
2033 pa_assert(u);
2035 if (u->sink && !USE_SCO_OVER_PCM(u))
2036 pa_sink_unlink(u->sink);
2038 if (u->source && !USE_SCO_OVER_PCM(u))
2039 pa_source_unlink(u->source);
2041 if (u->thread) {
2042 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2043 pa_thread_free(u->thread);
2044 u->thread = NULL;
2047 if (u->rtpoll_item) {
2048 pa_rtpoll_item_free(u->rtpoll_item);
2049 u->rtpoll_item = NULL;
2052 if (u->hsp.sink_state_changed_slot) {
2053 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2054 u->hsp.sink_state_changed_slot = NULL;
2057 if (u->hsp.source_state_changed_slot) {
2058 pa_hook_slot_free(u->hsp.source_state_changed_slot);
2059 u->hsp.source_state_changed_slot = NULL;
2062 if (u->hsp.nrec_changed_slot) {
2063 pa_hook_slot_free(u->hsp.nrec_changed_slot);
2064 u->hsp.nrec_changed_slot = NULL;
2067 if (u->transport) {
2068 bt_transport_release(u);
2069 pa_xfree(u->transport);
2070 u->transport = NULL;
2073 if (u->sink) {
2074 if (u->profile == PROFILE_HSP) {
2075 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2076 pa_shared_remove(u->core, k);
2077 pa_xfree(k);
2080 pa_sink_unref(u->sink);
2081 u->sink = NULL;
2084 if (u->source) {
2085 if (u->profile == PROFILE_HSP) {
2086 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2087 pa_shared_remove(u->core, k);
2088 pa_xfree(k);
2091 pa_source_unref(u->source);
2092 u->source = NULL;
2095 if (u->rtpoll) {
2096 pa_thread_mq_done(&u->thread_mq);
2098 pa_rtpoll_free(u->rtpoll);
2099 u->rtpoll = NULL;
2102 if (u->read_smoother) {
2103 pa_smoother_free(u->read_smoother);
2104 u->read_smoother = NULL;
2108 /* Run from main thread */
2109 static int start_thread(struct userdata *u) {
2110 pa_assert(u);
2111 pa_assert(!u->thread);
2112 pa_assert(!u->rtpoll);
2113 pa_assert(!u->rtpoll_item);
2115 u->rtpoll = pa_rtpoll_new();
2116 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2118 if (USE_SCO_OVER_PCM(u)) {
2119 if (sco_over_pcm_state_update(u, FALSE) < 0) {
2120 char *k;
2122 if (u->sink) {
2123 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2124 pa_shared_remove(u->core, k);
2125 pa_xfree(k);
2126 u->sink = NULL;
2128 if (u->source) {
2129 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2130 pa_shared_remove(u->core, k);
2131 pa_xfree(k);
2132 u->source = NULL;
2134 return -1;
2137 pa_sink_ref(u->sink);
2138 pa_source_ref(u->source);
2139 /* FIXME: monitor stream_fd error */
2140 return 0;
2143 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2144 pa_log_error("Failed to create IO thread");
2145 return -1;
2148 if (u->sink) {
2149 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2150 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2151 pa_sink_put(u->sink);
2153 if (u->sink->set_volume)
2154 u->sink->set_volume(u->sink);
2157 if (u->source) {
2158 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2159 pa_source_set_rtpoll(u->source, u->rtpoll);
2160 pa_source_put(u->source);
2162 if (u->source->set_volume)
2163 u->source->set_volume(u->source);
2166 return 0;
2169 static void save_sco_volume_callbacks(struct userdata *u) {
2170 pa_assert(u);
2171 pa_assert(USE_SCO_OVER_PCM(u));
2173 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2174 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2177 static void restore_sco_volume_callbacks(struct userdata *u) {
2178 pa_assert(u);
2179 pa_assert(USE_SCO_OVER_PCM(u));
2181 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2182 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2185 /* Run from main thread */
2186 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2187 struct userdata *u;
2188 enum profile *d;
2190 pa_assert(c);
2191 pa_assert(new_profile);
2192 pa_assert_se(u = c->userdata);
2194 d = PA_CARD_PROFILE_DATA(new_profile);
2196 if (*d != PROFILE_OFF) {
2197 const pa_bluetooth_device *device;
2199 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2200 pa_log_error("Failed to get device object.");
2201 return -PA_ERR_IO;
2204 if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2205 pa_log_warn("HSP is not connected, refused to switch profile");
2206 return -PA_ERR_IO;
2207 } else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2208 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2209 return -PA_ERR_IO;
2210 } else if (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) {
2211 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2212 return -PA_ERR_IO;
2213 } else if (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2214 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2215 return -PA_ERR_IO;
2219 stop_thread(u);
2221 if (USE_SCO_OVER_PCM(u))
2222 restore_sco_volume_callbacks(u);
2224 u->profile = *d;
2225 u->sample_spec = u->requested_sample_spec;
2227 if (USE_SCO_OVER_PCM(u))
2228 save_sco_volume_callbacks(u);
2230 if (u->profile != PROFILE_OFF)
2231 if (init_profile(u) < 0)
2232 goto off;
2234 if (u->sink || u->source)
2235 if (start_thread(u) < 0)
2236 goto off;
2238 return 0;
2240 off:
2241 stop_thread(u);
2243 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
2245 return -PA_ERR_IO;
2248 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) {
2249 pa_device_port *port;
2250 enum profile *d;
2252 d = PA_CARD_PROFILE_DATA(profile);
2254 switch (*d) {
2255 case PROFILE_A2DP:
2256 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2257 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2258 port->is_output = 1;
2259 port->is_input = 0;
2260 port->priority = profile->priority * 100;
2261 port->available = audio_state_to_availability(device->audio_sink_state);
2262 pa_hashmap_put(port->profiles, profile->name, profile);
2263 break;
2265 case PROFILE_A2DP_SOURCE:
2266 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2267 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2268 port->is_output = 0;
2269 port->is_input = 1;
2270 port->priority = profile->priority * 100;
2271 port->available = audio_state_to_availability(device->audio_source_state);
2272 pa_hashmap_put(port->profiles, profile->name, profile);
2273 break;
2275 case PROFILE_HSP:
2276 pa_assert_se(port = pa_device_port_new(u->core, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2277 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2278 port->is_output = 1;
2279 port->is_input = 0;
2280 port->priority = profile->priority * 100;
2281 port->available = audio_state_to_availability(device->headset_state);
2282 pa_hashmap_put(port->profiles, profile->name, profile);
2284 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2285 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2286 port->is_output = 0;
2287 port->is_input = 1;
2288 port->priority = profile->priority * 100;
2289 port->available = audio_state_to_availability(device->headset_state);
2290 pa_hashmap_put(port->profiles, profile->name, profile);
2291 break;
2293 case PROFILE_HFGW:
2294 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2295 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2296 port->is_output = 1;
2297 port->is_input = 0;
2298 port->priority = profile->priority * 100;
2299 port->available = audio_state_to_availability(device->hfgw_state);
2300 pa_hashmap_put(port->profiles, profile->name, profile);
2302 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2303 pa_assert_se(pa_hashmap_put(card_new_data->ports, port->name, port) >= 0);
2304 port->is_output = 0;
2305 port->is_input = 1;
2306 port->priority = profile->priority * 100;
2307 port->available = audio_state_to_availability(device->hfgw_state);
2308 pa_hashmap_put(port->profiles, profile->name, profile);
2309 break;
2311 default:
2312 pa_assert_not_reached();
2317 /* Run from main thread */
2318 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2319 pa_card_new_data data;
2320 pa_bool_t b;
2321 pa_card_profile *p;
2322 enum profile *d;
2323 const char *ff;
2324 char *n;
2325 const char *default_profile;
2327 pa_assert(u);
2328 pa_assert(device);
2330 pa_card_new_data_init(&data);
2331 data.driver = __FILE__;
2332 data.module = u->module;
2334 n = pa_bluetooth_cleanup_name(device->name);
2335 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2336 pa_xfree(n);
2337 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2338 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2339 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2340 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2341 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2342 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2343 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2344 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2345 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2346 data.name = get_name("card", u->modargs, device->address, &b);
2347 data.namereg_fail = b;
2349 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2350 pa_log("Invalid properties");
2351 pa_card_new_data_done(&data);
2352 return -1;
2355 /* we base hsp/a2dp availability on UUIDs.
2356 Ideally, it would be based on "Connected" state, but
2357 we can't afford to wait for this information when
2358 we are loaded with profile="hsp", for instance */
2359 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2360 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2361 p->priority = 10;
2362 p->n_sinks = 1;
2363 p->n_sources = 0;
2364 p->max_sink_channels = 2;
2365 p->max_source_channels = 0;
2367 d = PA_CARD_PROFILE_DATA(p);
2368 *d = PROFILE_A2DP;
2369 create_ports_for_profile(u, device, &data, p);
2371 pa_hashmap_put(data.profiles, p->name, p);
2374 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2375 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2376 p->priority = 10;
2377 p->n_sinks = 0;
2378 p->n_sources = 1;
2379 p->max_sink_channels = 0;
2380 p->max_source_channels = 2;
2382 d = PA_CARD_PROFILE_DATA(p);
2383 *d = PROFILE_A2DP_SOURCE;
2384 create_ports_for_profile(u, device, &data, p);
2386 pa_hashmap_put(data.profiles, p->name, p);
2389 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2390 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2391 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2392 p->priority = 20;
2393 p->n_sinks = 1;
2394 p->n_sources = 1;
2395 p->max_sink_channels = 1;
2396 p->max_source_channels = 1;
2398 d = PA_CARD_PROFILE_DATA(p);
2399 *d = PROFILE_HSP;
2400 create_ports_for_profile(u, device, &data, p);
2402 pa_hashmap_put(data.profiles, p->name, p);
2405 if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2406 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2407 p->priority = 20;
2408 p->n_sinks = 1;
2409 p->n_sources = 1;
2410 p->max_sink_channels = 1;
2411 p->max_source_channels = 1;
2413 d = PA_CARD_PROFILE_DATA(p);
2414 *d = PROFILE_HFGW;
2415 create_ports_for_profile(u, device, &data, p);
2417 pa_hashmap_put(data.profiles, p->name, p);
2420 pa_assert(!pa_hashmap_isempty(data.profiles));
2422 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2423 d = PA_CARD_PROFILE_DATA(p);
2424 *d = PROFILE_OFF;
2425 pa_hashmap_put(data.profiles, p->name, p);
2427 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2428 if (pa_hashmap_get(data.profiles, default_profile))
2429 pa_card_new_data_set_profile(&data, default_profile);
2430 else
2431 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2434 u->card = pa_card_new(u->core, &data);
2435 pa_card_new_data_done(&data);
2437 if (!u->card) {
2438 pa_log("Failed to allocate card.");
2439 return -1;
2442 u->card->userdata = u;
2443 u->card->set_profile = card_set_profile;
2445 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2447 if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2448 (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2449 (device->audio_source_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP_SOURCE) ||
2450 (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2451 pa_log_warn("Default profile not connected, selecting off profile");
2452 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2453 u->card->save_profile = FALSE;
2456 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2457 u->profile = *d;
2459 if (USE_SCO_OVER_PCM(u))
2460 save_sco_volume_callbacks(u);
2462 return 0;
2465 /* Run from main thread */
2466 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2467 const pa_bluetooth_device *d = NULL;
2469 pa_assert(u);
2471 if (!address && !path) {
2472 pa_log_error("Failed to get device address/path from module arguments.");
2473 return NULL;
2476 if (path) {
2477 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2478 pa_log_error("%s is not a valid BlueZ audio device.", path);
2479 return NULL;
2482 if (address && !(pa_streq(d->address, address))) {
2483 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2484 return NULL;
2487 } else {
2488 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2489 pa_log_error("%s is not known.", address);
2490 return NULL;
2494 if (d) {
2495 u->address = pa_xstrdup(d->address);
2496 u->path = pa_xstrdup(d->path);
2499 return d;
2502 /* Run from main thread */
2503 static int setup_dbus(struct userdata *u) {
2504 DBusError err;
2506 dbus_error_init(&err);
2508 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2510 if (dbus_error_is_set(&err) || !u->connection) {
2511 pa_log("Failed to get D-Bus connection: %s", err.message);
2512 dbus_error_free(&err);
2513 return -1;
2516 return 0;
2519 int pa__init(pa_module* m) {
2520 pa_modargs *ma;
2521 uint32_t channels;
2522 struct userdata *u;
2523 const char *address, *path;
2524 DBusError err;
2525 char *mike, *speaker;
2526 const pa_bluetooth_device *device;
2528 pa_assert(m);
2530 dbus_error_init(&err);
2532 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2533 pa_log_error("Failed to parse module arguments");
2534 goto fail;
2537 m->userdata = u = pa_xnew0(struct userdata, 1);
2538 u->module = m;
2539 u->core = m->core;
2540 u->stream_fd = -1;
2541 u->sample_spec = m->core->default_sample_spec;
2542 u->modargs = ma;
2544 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2545 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2546 pa_log("SCO sink not found");
2547 goto fail;
2550 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2551 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2552 pa_log("SCO source not found");
2553 goto fail;
2556 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2557 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2558 pa_log_error("Failed to get rate from module arguments");
2559 goto fail;
2562 u->auto_connect = TRUE;
2563 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2564 pa_log("Failed to parse auto_connect= argument");
2565 goto fail;
2568 channels = u->sample_spec.channels;
2569 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2570 channels <= 0 || channels > PA_CHANNELS_MAX) {
2571 pa_log_error("Failed to get channels from module arguments");
2572 goto fail;
2574 u->sample_spec.channels = (uint8_t) channels;
2575 u->requested_sample_spec = u->sample_spec;
2577 address = pa_modargs_get_value(ma, "address", NULL);
2578 path = pa_modargs_get_value(ma, "path", NULL);
2580 if (setup_dbus(u) < 0)
2581 goto fail;
2583 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2584 goto fail;
2586 if (!(device = find_device(u, address, path)))
2587 goto fail;
2589 /* Add the card structure. This will also initialize the default profile */
2590 if (add_card(u, device) < 0)
2591 goto fail;
2593 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2594 goto fail;
2596 u->msg->parent.process_msg = device_process_msg;
2597 u->msg->card = u->card;
2599 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2600 pa_log_error("Failed to add filter function");
2601 goto fail;
2603 u->filter_added = TRUE;
2605 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2606 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2608 if (pa_dbus_add_matches(
2609 pa_dbus_connection_get(u->connection), &err,
2610 speaker,
2611 mike,
2612 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2613 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2614 "type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged'",
2615 "type='signal',sender='org.bluez',interface='org.bluez.AudioSource',member='PropertyChanged'",
2616 "type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged'",
2617 NULL) < 0) {
2619 pa_xfree(speaker);
2620 pa_xfree(mike);
2622 pa_log("Failed to add D-Bus matches: %s", err.message);
2623 goto fail;
2626 pa_xfree(speaker);
2627 pa_xfree(mike);
2629 if (u->profile != PROFILE_OFF)
2630 if (init_profile(u) < 0)
2631 goto fail;
2633 if (u->sink || u->source)
2634 if (start_thread(u) < 0)
2635 goto fail;
2637 return 0;
2639 fail:
2641 pa__done(m);
2643 dbus_error_free(&err);
2645 return -1;
2648 int pa__get_n_used(pa_module *m) {
2649 struct userdata *u;
2651 pa_assert(m);
2652 pa_assert_se(u = m->userdata);
2654 return
2655 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2656 (u->source ? pa_source_linked_by(u->source) : 0);
2659 void pa__done(pa_module *m) {
2660 struct userdata *u;
2662 pa_assert(m);
2664 if (!(u = m->userdata))
2665 return;
2667 stop_thread(u);
2669 if (USE_SCO_OVER_PCM(u))
2670 restore_sco_volume_callbacks(u);
2672 if (u->connection) {
2674 if (u->path) {
2675 char *speaker, *mike;
2676 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2677 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2679 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike,
2680 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2681 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2682 NULL);
2684 pa_xfree(speaker);
2685 pa_xfree(mike);
2688 if (u->filter_added)
2689 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2691 pa_dbus_connection_unref(u->connection);
2694 if (u->msg)
2695 pa_xfree(u->msg);
2697 if (u->card)
2698 pa_card_free(u->card);
2700 if (u->read_smoother)
2701 pa_smoother_free(u->read_smoother);
2703 if (u->a2dp.buffer)
2704 pa_xfree(u->a2dp.buffer);
2706 sbc_finish(&u->a2dp.sbc);
2708 if (u->modargs)
2709 pa_modargs_free(u->modargs);
2711 pa_xfree(u->address);
2712 pa_xfree(u->path);
2714 if (u->discovery)
2715 pa_bluetooth_discovery_unref(u->discovery);
2717 pa_xfree(u);