2 This file is part of PulseAudio.
4 Copyright 2008-2013 João Paulo Rechi Vita
5 Copyright 2011-2013 BMW Car IT GmbH.
6 Copyright 2018-2019 Pali Rohár <pali.rohar@gmail.com>
8 PulseAudio is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as
10 published by the Free Software Foundation; either version 2.1 of the
11 License, or (at your option) any later version.
13 PulseAudio is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
28 #include <arpa/inet.h>
30 #include <pulse/rtclock.h>
31 #include <pulse/timeval.h>
32 #include <pulse/utf8.h>
33 #include <pulse/util.h>
35 #include <pulsecore/core-error.h>
36 #include <pulsecore/core-rtclock.h>
37 #include <pulsecore/core-util.h>
38 #include <pulsecore/i18n.h>
39 #include <pulsecore/json.h>
40 #include <pulsecore/message-handler.h>
41 #include <pulsecore/module.h>
42 #include <pulsecore/modargs.h>
43 #include <pulsecore/poll.h>
44 #include <pulsecore/rtpoll.h>
45 #include <pulsecore/shared.h>
46 #include <pulsecore/socket-util.h>
47 #include <pulsecore/thread.h>
48 #include <pulsecore/thread-mq.h>
49 #include <pulsecore/time-smoother.h>
52 #include <pulsecore/sink.h>
53 #include <pulsecore/namereg.h>
58 #include "a2dp-codecs.h"
59 #include "a2dp-codec-util.h"
60 #include "bluez5-util.h"
62 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
63 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
64 PA_MODULE_VERSION(PACKAGE_VERSION);
65 PA_MODULE_LOAD_ONCE(false);
67 "path=<device object path>"
68 "autodetect_mtu=<boolean>"
69 "output_rate_refresh_interval_ms=<interval between attempts to improve output rate in milliseconds>"
70 "avrcp_absolute_volume=<synchronize volume with peer, true by default>"
73 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
74 #define FIXED_LATENCY_PLAYBACK_SCO (25 * PA_USEC_PER_MSEC)
75 #define FIXED_LATENCY_RECORD_A2DP (25 * PA_USEC_PER_MSEC)
76 #define FIXED_LATENCY_RECORD_SCO (25 * PA_USEC_PER_MSEC)
78 static const char* const valid_modargs[] = {
81 "output_rate_refresh_interval_ms",
82 "avrcp_absolute_volume",
91 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
92 BLUETOOTH_MESSAGE_STREAM_FD_HUP,
93 BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING,
98 PA_SOURCE_MESSAGE_SETUP_STREAM = PA_SOURCE_MESSAGE_MAX,
102 PA_SINK_MESSAGE_SETUP_STREAM = PA_SINK_MESSAGE_MAX,
105 typedef struct bluetooth_msg {
109 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
110 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
116 pa_hook_slot *device_connection_changed_slot;
117 pa_hook_slot *transport_state_changed_slot;
118 pa_hook_slot *transport_sink_volume_changed_slot;
119 pa_hook_slot *transport_source_volume_changed_slot;
121 pa_hook_slot *sink_volume_changed_slot;
122 pa_hook_slot *source_volume_changed_slot;
125 pa_hook_slot *transport_delay_changed_slot;
126 pa_hook_slot *sco_state_changed_slot;
129 pa_bluetooth_discovery *discovery;
130 pa_bluetooth_device *device;
131 pa_bluetooth_transport *transport;
132 bool transport_acquired;
133 bool stream_setup_done;
136 bool transport_suspended_by_remote;
141 pa_bluetooth_profile_t profile;
142 char *output_port_name;
143 char *input_port_name;
146 pa_thread_mq thread_mq;
148 pa_rtpoll_item *rtpoll_item;
152 size_t read_link_mtu;
153 size_t write_link_mtu;
154 size_t read_block_size;
155 size_t write_block_size;
157 uint64_t write_index;
158 pa_usec_t started_at;
159 pa_smoother *read_smoother;
160 pa_memchunk write_memchunk;
162 const pa_bt_codec *bt_codec;
165 pa_sample_spec encoder_sample_spec;
166 void *encoder_buffer; /* Codec transfer buffer */
167 size_t encoder_buffer_size; /* Size of the buffer */
168 size_t encoder_buffer_used; /* Used space in the buffer */
171 pa_sample_spec decoder_sample_spec;
172 void *decoder_buffer; /* Codec transfer buffer */
173 size_t decoder_buffer_size; /* Size of the buffer */
175 bool message_handler_registered;
178 typedef enum pa_bluetooth_form_factor {
179 PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
180 PA_BLUETOOTH_FORM_FACTOR_HEADSET,
181 PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
182 PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
183 PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
184 PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
185 PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
186 PA_BLUETOOTH_FORM_FACTOR_CAR,
187 PA_BLUETOOTH_FORM_FACTOR_HIFI,
188 PA_BLUETOOTH_FORM_FACTOR_PHONE,
189 } pa_bluetooth_form_factor_t;
191 /* Run from main thread */
192 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
193 unsigned major, minor;
194 pa_bluetooth_form_factor_t r;
196 static const pa_bluetooth_form_factor_t table[] = {
197 [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
198 [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
199 [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
200 [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
201 [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
202 [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
203 [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
204 [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
208 * See Bluetooth Assigned Numbers:
209 * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
211 major = (class_of_device >> 8) & 0x1F;
212 minor = (class_of_device >> 2) & 0x3F;
216 return PA_BLUETOOTH_FORM_FACTOR_PHONE;
220 pa_log_debug("Unknown Bluetooth major device class %u", major);
221 return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
224 r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
227 pa_log_debug("Unknown Bluetooth minor device class %u", minor);
232 /* Run from main thread */
233 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
235 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
237 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
239 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
241 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
243 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
245 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
247 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
249 case PA_BLUETOOTH_FORM_FACTOR_CAR:
251 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
253 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
257 pa_assert_not_reached();
260 /* Run from main thread */
261 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
262 pa_device_port *port;
264 if (direction == PA_DIRECTION_OUTPUT) {
265 pa_sink_new_data *sink_new_data = new_data;
267 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
268 pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
269 pa_device_port_ref(port);
271 pa_source_new_data *source_new_data = new_data;
273 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
274 pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
275 pa_device_port_ref(port);
279 static bool bt_prepare_encoder_buffer(struct userdata *u)
281 size_t encoded_size, reserved_size;
283 pa_assert(u->bt_codec);
285 /* If socket write MTU is less than encoded frame size, there could be
286 * up to one write MTU of data left in encoder buffer from previous round.
288 * Reserve space for 2 encoded frames to cover that.
290 * Note for A2DP codecs it is expected that size of encoded frame is less
291 * than write link MTU. Therefore each encoded frame is sent out completely
292 * and there is no used space in encoder buffer before next encoder call.
294 if (u->bt_codec->get_encoded_block_size)
295 encoded_size = u->bt_codec->get_encoded_block_size(u->encoder_info, u->write_block_size);
297 encoded_size = u->write_block_size;
299 reserved_size = 2 * encoded_size;
301 if (u->encoder_buffer_size < reserved_size) {
302 u->encoder_buffer = pa_xrealloc(u->encoder_buffer, reserved_size);
303 u->encoder_buffer_size = reserved_size;
305 if (u->encoder_buffer_used > reserved_size) {
306 u->encoder_buffer_used = 0;
310 /* Report if there is still not enough space for new block */
311 if (u->encoder_buffer_size < u->encoder_buffer_used + encoded_size)
317 /* Run from IO thread */
318 static int bt_write_buffer(struct userdata *u) {
322 pa_assert(u->transport);
323 pa_assert(u->bt_codec);
325 written = u->transport->write(u->transport, u->stream_fd, u->encoder_buffer, u->encoder_buffer_used, u->write_link_mtu);
328 /* calculate remainder */
329 u->encoder_buffer_used -= written;
331 /* move any remainder back to start of u->encoder_buffer */
332 if (u->encoder_buffer_used)
333 memmove(u->encoder_buffer, u->encoder_buffer + written, u->encoder_buffer_used);
336 } else if (written == 0) {
337 /* Not enough data in encoder buffer */
340 /* Reset encoder sequence number and buffer positions */
341 u->bt_codec->reset(u->encoder_info);
342 u->encoder_buffer_used = 0;
347 /* Run from IO thread */
348 static int bt_process_render(struct userdata *u) {
357 pa_assert(u->bt_codec);
359 if (!bt_prepare_encoder_buffer(u))
362 /* First, render some data */
363 if (!u->write_memchunk.memblock)
364 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
366 pa_assert(u->write_memchunk.length == u->write_block_size);
368 ptr = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
370 length = u->bt_codec->encode_buffer(u->encoder_info, u->write_index / pa_frame_size(&u->encoder_sample_spec),
371 ptr, u->write_memchunk.length,
372 u->encoder_buffer + u->encoder_buffer_used, u->encoder_buffer_size - u->encoder_buffer_used,
375 pa_memblock_release(u->write_memchunk.memblock);
377 if (processed != u->write_memchunk.length) {
378 pa_log_error("Encoding error");
379 pa_memblock_unref(u->write_memchunk.memblock);
380 pa_memchunk_reset(&u->write_memchunk);
384 /* Encoder function of BT codec may provide empty buffer, in this case do
385 * not post any empty buffer via BT socket. It may be because of codec
386 * internal state, e.g. encoder is waiting for more samples so it can
387 * provide encoded data. */
389 if (PA_LIKELY(length)) {
390 u->encoder_buffer_used += length;
395 u->write_index += (uint64_t) u->write_memchunk.length;
396 pa_memblock_unref(u->write_memchunk.memblock);
397 pa_memchunk_reset(&u->write_memchunk);
402 static void bt_prepare_decoder_buffer(struct userdata *u) {
405 if (u->decoder_buffer_size < u->read_link_mtu) {
406 pa_xfree(u->decoder_buffer);
407 u->decoder_buffer = pa_xmalloc(u->read_link_mtu);
410 /* Decoder buffer cannot be larger then link MTU, otherwise
411 * decode method would produce larger output then read_block_size */
412 u->decoder_buffer_size = u->read_link_mtu;
415 /* Run from IO thread */
416 static ssize_t bt_transport_read(pa_bluetooth_transport *t, int fd, void *buffer, size_t size, pa_usec_t *p_timestamp) {
417 ssize_t received = 0;
425 bool found_tstamp = false;
434 m.msg_controllen = sizeof(aux);
436 iov.iov_base = buffer;
439 received = recvmsg(fd, &m, 0);
443 if (received < 0 && errno == EINTR)
444 /* Retry right away if we got interrupted */
447 else if (received < 0 && errno == EAGAIN)
448 /* Hmm, apparently the socket was not readable, give up for now. */
451 pa_log_error("Failed to read data from socket: %s", received < 0 ? pa_cstrerror(errno) : "EOF");
455 pa_assert((size_t) received <= size);
457 /* allow write side to find out size of last read packet */
458 t->last_read_size = received;
461 /* TODO: get timestamp from rtp */
463 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm)) {
464 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
465 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
466 pa_rtclock_from_wallclock(tv);
467 *p_timestamp = pa_timeval_load(tv);
475 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
477 *p_timestamp = pa_rtclock_now();
487 /* Run from IO thread */
488 /* Read incoming data, decode it and post result (if any) to source output.
489 * Returns number of bytes posted to source output. */
490 static int bt_process_push(struct userdata *u) {
494 size_t processed = 0;
497 pa_assert(u->source);
498 pa_assert(u->read_smoother);
499 pa_assert(u->bt_codec);
500 pa_assert(u->transport);
502 bt_prepare_decoder_buffer(u);
504 received = bt_transport_read(u->transport, u->stream_fd, u->decoder_buffer, u->decoder_buffer_size, &tstamp);
510 pa_memchunk memchunk;
512 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
513 memchunk.index = memchunk.length = 0;
515 ptr = pa_memblock_acquire(memchunk.memblock);
516 memchunk.length = pa_memblock_get_length(memchunk.memblock);
518 memchunk.length = u->bt_codec->decode_buffer(u->decoder_info, u->decoder_buffer, received, ptr, memchunk.length, &processed);
520 pa_memblock_release(memchunk.memblock);
522 if (processed != (size_t) received) {
523 pa_log_error("Decoding error");
524 pa_memblock_unref(memchunk.memblock);
528 u->read_index += (uint64_t) memchunk.length;
529 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec));
530 pa_smoother_resume(u->read_smoother, tstamp, true);
532 /* Decoding of data may result in empty buffer, in this case
533 * do not post empty audio samples. It may happen due to algorithmic
534 * delay of audio codec. */
535 if (PA_LIKELY(memchunk.length))
536 pa_source_post(u->source, &memchunk);
538 /* report decoded size */
539 received = memchunk.length;
541 pa_memblock_unref(memchunk.memblock);
546 static void update_sink_buffer_size(struct userdata *u) {
548 socklen_t len = sizeof(int);
551 ret = getsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &old_bufsize, &len);
553 pa_log_warn("Changing bluetooth buffer size: Failed to getsockopt(SO_SNDBUF): %s", pa_cstrerror(errno));
557 /* Set send buffer size as small as possible. The minimum value is 1024 according to the
558 * socket man page. The data is written to the socket in chunks of write_block_size, so
559 * there should at least be room for two chunks in the buffer. Generally, write_block_size
560 * is larger than 512. If not, use the next multiple of write_block_size which is larger
562 new_bufsize = 2 * u->write_block_size;
563 if (new_bufsize < 1024)
564 new_bufsize = (1024 / u->write_block_size + 1) * u->write_block_size;
566 /* The kernel internally doubles the buffer size that was set by setsockopt and getsockopt
567 * returns the doubled value. */
568 if (new_bufsize != old_bufsize / 2) {
569 ret = setsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &new_bufsize, len);
571 pa_log_warn("Changing bluetooth buffer size: Failed to change from %d to %d: %s", old_bufsize / 2, new_bufsize, pa_cstrerror(errno));
573 pa_log_info("Changing bluetooth buffer size: Changed from %d to %d", old_bufsize / 2, new_bufsize);
578 static void teardown_stream(struct userdata *u) {
579 if (u->rtpoll_item) {
580 pa_rtpoll_item_free(u->rtpoll_item);
581 u->rtpoll_item = NULL;
584 if (u->stream_fd >= 0) {
585 pa_close(u->stream_fd);
589 if (u->read_smoother) {
590 pa_smoother_free(u->read_smoother);
591 u->read_smoother = NULL;
594 if (u->write_memchunk.memblock) {
595 pa_memblock_unref(u->write_memchunk.memblock);
596 pa_memchunk_reset(&u->write_memchunk);
599 pa_log_debug("Audio stream torn down");
600 u->stream_setup_done = false;
603 static int transport_acquire(struct userdata *u, bool optional) {
604 pa_assert(u->transport);
606 if (u->transport_acquired)
609 pa_log_debug("Acquiring transport %s", u->transport->path);
611 u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
612 if (u->stream_fd < 0)
615 /* transport_acquired must be set before calling
616 * pa_bluetooth_transport_set_state() */
617 u->transport_acquired = true;
619 u->transport_suspended_by_remote = false;
621 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
623 if (u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
624 if (pa_thread_mq_get() != NULL)
625 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING, NULL, 0, NULL, NULL);
627 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
633 static void transport_release(struct userdata *u) {
634 pa_assert(u->transport);
636 /* Ignore if already released */
637 if (!u->transport_acquired)
640 pa_log_debug("Releasing transport %s", u->transport->path);
642 u->transport->release(u->transport);
644 u->transport_acquired = false;
647 /* The below code would be less effect for most of case */
648 if (u->transport_suspended_by_remote)
649 pa_log_info("Released by remote suspend request");
654 /* Set transport state to idle if this was not already done by the remote end closing
655 * the file descriptor. Only do this when called from the I/O thread */
656 if (pa_thread_mq_get() != NULL && u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
657 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
660 /* Run from I/O thread */
661 static void handle_sink_block_size_change(struct userdata *u) {
662 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
663 pa_sink_set_fixed_latency_within_thread(u->sink,
664 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
665 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
666 pa_bytes_to_usec(u->write_block_size, &u->encoder_sample_spec));
668 /* If there is still data in the memchunk, we have to discard it
669 * because the write_block_size may have changed. */
670 if (u->write_memchunk.memblock) {
671 pa_memblock_unref(u->write_memchunk.memblock);
672 pa_memchunk_reset(&u->write_memchunk);
675 update_sink_buffer_size(u);
678 /* Run from I/O thread */
679 static void transport_config_mtu(struct userdata *u) {
680 pa_assert(u->bt_codec);
682 if (u->encoder_info) {
683 u->write_block_size = u->bt_codec->get_write_block_size(u->encoder_info, u->write_link_mtu);
685 if (!pa_frame_aligned(u->write_block_size, &u->sink->sample_spec)) {
687 pa_log_debug("Got invalid write MTU: %zu, rounding down", u->write_block_size);
689 pa_log_debug("Got invalid write MTU: %lu, rounding down", u->write_block_size);
691 u->write_block_size = pa_frame_align(u->write_block_size, &u->sink->sample_spec);
695 if (u->decoder_info) {
696 u->read_block_size = u->bt_codec->get_read_block_size(u->decoder_info, u->read_link_mtu);
698 if (!pa_frame_aligned(u->read_block_size, &u->source->sample_spec)) {
700 pa_log_debug("Got invalid read MTU: %zu, rounding down", u->read_block_size);
702 pa_log_debug("Got invalid read MTU: %lu, rounding down", u->read_block_size);
704 u->read_block_size = pa_frame_align(u->read_block_size, &u->source->sample_spec);
709 handle_sink_block_size_change(u);
712 pa_source_set_fixed_latency_within_thread(u->source,
713 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
714 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
715 pa_bytes_to_usec(u->read_block_size, &u->decoder_sample_spec));
718 /* Run from I/O thread */
719 static int setup_stream(struct userdata *u) {
720 struct pollfd *pollfd;
723 pa_assert(u->stream_fd >= 0);
725 /* return if stream is already set up */
726 if (u->stream_setup_done)
729 pa_log_info("Transport %s resuming", u->transport->path);
731 pa_assert(u->bt_codec);
733 if (u->encoder_info) {
734 if (u->bt_codec->reset(u->encoder_info) < 0)
738 if (u->decoder_info) {
739 if (u->bt_codec->reset(u->decoder_info) < 0)
743 transport_config_mtu(u);
745 pa_make_fd_nonblock(u->stream_fd);
746 pa_make_socket_low_delay(u->stream_fd);
749 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
750 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
752 pa_log_debug("Stream properly set up, we're ready to roll!");
754 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
755 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
756 pollfd->fd = u->stream_fd;
757 pollfd->events = pollfd->revents = 0;
759 u->read_index = u->write_index = 0;
761 u->stream_setup_done = true;
764 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
769 /* Called from I/O thread, returns true if the transport was acquired or
770 * a connection was requested successfully. */
771 static bool setup_transport_and_stream(struct userdata *u) {
774 transport_error = transport_acquire(u, false);
775 if (transport_error < 0) {
776 if (transport_error != -EAGAIN)
779 if (setup_stream(u) < 0)
785 /* Run from main thread */
786 static pa_hook_result_t sink_source_volume_changed_cb(void *hook_data, void *call_data, void *slot_data) {
787 struct userdata *u = slot_data;
788 const pa_cvolume *new_volume = NULL;
790 pa_bluetooth_transport_set_volume_cb notify_volume_change;
792 /* In the HS/HF role, notify the AG of a change in speaker/microphone gain.
793 * In the AG role the command to change HW volume on the remote is already
794 * sent by the hardware callback (if the peer supports it and the sink
795 * or source set_volume callback is attached. Otherwise nothing is sent).
797 pa_assert(pa_bluetooth_profile_should_attenuate_volume(u->profile));
799 if (u->sink == call_data) {
800 new_volume = pa_sink_get_volume(u->sink, false);
801 notify_volume_change = u->transport->set_sink_volume;
802 } else if (u->source == call_data) {
803 new_volume = pa_source_get_volume(u->source, false);
804 notify_volume_change = u->transport->set_source_volume;
809 /* Volume control/notifications are optional */
810 if (!notify_volume_change)
813 volume = pa_cvolume_max(new_volume);
815 notify_volume_change(u->transport, volume);
820 /* Run from IO thread */
821 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
822 struct userdata *u = PA_SOURCE(o)->userdata;
824 pa_assert(u->source == PA_SOURCE(o));
825 pa_assert(u->transport);
829 case PA_SOURCE_MESSAGE_GET_LATENCY: {
832 if (u->read_smoother) {
833 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
834 ri = pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec);
836 *((int64_t*) data) = u->source->thread_info.fixed_latency + wi - ri;
838 *((int64_t*) data) = 0;
843 case PA_SOURCE_MESSAGE_SETUP_STREAM:
844 /* Skip stream setup if stream_fd has been invalidated.
845 This can occur if the stream has already been set up and
846 then immediately received POLLHUP. If the stream has
847 already been set up earlier, then this setup_stream()
848 call is redundant anyway, but currently the code
849 is such that this kind of unnecessary setup_stream()
851 if (u->stream_fd < 0)
852 pa_log_debug("Skip source stream setup while closing");
859 return pa_source_process_msg(o, code, data, offset, chunk);
862 /* Called from the IO thread. */
863 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) {
867 pa_assert_se(u = s->userdata);
871 case PA_SOURCE_SUSPENDED:
872 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
873 if (!PA_SOURCE_IS_OPENED(s->thread_info.state))
876 /* Stop the device if the sink is suspended as well */
877 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
878 transport_release(u);
880 if (u->read_smoother)
881 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
886 case PA_SOURCE_RUNNING:
887 if (s->thread_info.state != PA_SOURCE_SUSPENDED)
890 /* Resume the device if the sink was suspended as well */
891 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state))
892 if (!setup_transport_and_stream(u))
895 /* We don't resume the smoother here. Instead we
896 * wait until the first packet arrives */
900 case PA_SOURCE_UNLINKED:
902 case PA_SOURCE_INVALID_STATE:
909 /* Run from main thread */
910 static void source_set_volume_cb(pa_source *s) {
920 pa_assert(u->source == s);
921 pa_assert(!pa_bluetooth_profile_should_attenuate_volume(u->profile));
922 pa_assert(u->transport);
923 pa_assert(u->transport->set_source_volume);
925 /* In the AG role, send a command to change microphone gain on the HS/HF */
926 volume = u->transport->set_source_volume(u->transport, pa_cvolume_max(&s->real_volume));
928 pa_cvolume_set(&s->real_volume, u->decoder_sample_spec.channels, volume);
931 /* Run from main thread */
932 static void source_setup_volume_callback(pa_source *s) {
940 pa_assert(u->source == s);
941 pa_assert(u->transport);
943 if (pa_bluetooth_profile_is_a2dp(u->profile) && !u->transport->device->avrcp_absolute_volume)
946 /* Remote volume control has to be supported for the callback to make sense,
947 * otherwise this source should continue performing attenuation in software
948 * without HW_VOLUME_CTL.
949 * If the peer is an AG however backend-native unconditionally provides this
950 * function, PA in the role of HS/HF is responsible for signalling support
951 * by emitting an initial volume command.
952 * For A2DP bluez-util also unconditionally provides this function to keep
953 * the peer informed about volume changes.
955 if (!u->transport->set_source_volume)
958 if (pa_bluetooth_profile_should_attenuate_volume(u->profile)) {
959 if (u->source_volume_changed_slot)
962 pa_log_debug("%s: Attaching volume hook to notify peer of changes", s->name);
964 u->source_volume_changed_slot = pa_hook_connect(&s->core->hooks[PA_CORE_HOOK_SOURCE_VOLUME_CHANGED],
965 PA_HOOK_NORMAL, sink_source_volume_changed_cb, u);
967 /* Send initial volume to peer, signalling support for volume control */
968 u->transport->set_source_volume(u->transport, pa_cvolume_max(&s->real_volume));
970 /* It is yet unknown how (if at all) volume is synchronized for bidirectional
971 * A2DP codecs. Disallow attaching callbacks (and using HFP n_volume_steps)
972 * below to a pa_source if the peer is in A2DP_SINK role. This assert should
973 * be replaced with the proper logic when bidirectional codecs are implemented.
975 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_A2DP_SINK);
977 if (s->set_volume == source_set_volume_cb)
980 pa_log_debug("%s: Resetting software volume for hardware attenuation by peer", s->name);
982 /* Reset local attenuation */
983 pa_source_set_soft_volume(s, NULL);
985 pa_source_set_set_volume_callback(s, source_set_volume_cb);
986 s->n_volume_steps = HSP_MAX_GAIN + 1;
990 /* Run from main thread */
991 static int add_source(struct userdata *u) {
992 pa_source_new_data data;
994 pa_assert(u->transport);
996 pa_source_new_data_init(&data);
997 data.module = u->module;
999 data.driver = __FILE__;
1000 data.name = pa_sprintf_malloc("bluez_source.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1001 data.namereg_fail = false;
1002 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1004 pa_proplist_sets(data.proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1005 pa_source_new_data_set_sample_spec(&data, &u->decoder_sample_spec);
1006 if (u->profile == PA_BLUETOOTH_PROFILE_HSP_HS
1007 || u->profile == PA_BLUETOOTH_PROFILE_HFP_HF)
1008 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1010 connect_ports(u, &data, PA_DIRECTION_INPUT);
1012 if (!u->transport_acquired)
1013 switch (u->profile) {
1014 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1015 case PA_BLUETOOTH_PROFILE_HFP_AG:
1016 case PA_BLUETOOTH_PROFILE_HSP_AG:
1017 data.suspend_cause = PA_SUSPEND_USER;
1019 case PA_BLUETOOTH_PROFILE_HSP_HS:
1020 case PA_BLUETOOTH_PROFILE_HFP_HF:
1021 /* u->stream_fd contains the error returned by the last transport_acquire()
1022 * EAGAIN means we are waiting for a NewConnection signal */
1023 if (u->stream_fd == -EAGAIN)
1024 data.suspend_cause = PA_SUSPEND_USER;
1026 pa_assert_not_reached();
1028 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1029 case PA_BLUETOOTH_PROFILE_OFF:
1030 pa_assert_not_reached();
1034 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1035 pa_source_new_data_done(&data);
1037 pa_log_error("Failed to create source");
1041 u->source->userdata = u;
1042 u->source->parent.process_msg = source_process_msg;
1043 u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
1045 source_setup_volume_callback(u->source);
1050 /* Run from IO thread */
1051 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1052 struct userdata *u = PA_SINK(o)->userdata;
1054 pa_assert(u->sink == PA_SINK(o));
1055 pa_assert(u->transport);
1059 case PA_SINK_MESSAGE_GET_LATENCY: {
1060 int64_t wi = 0, ri = 0;
1062 if (u->read_smoother) {
1063 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1064 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->encoder_sample_spec);
1065 } else if (u->started_at) {
1066 ri = pa_rtclock_now() - u->started_at;
1067 wi = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1070 *((int64_t*) data) = u->sink->thread_info.fixed_latency + wi - ri;
1075 case PA_SINK_MESSAGE_SETUP_STREAM:
1076 /* Skip stream setup if stream_fd has been invalidated.
1077 This can occur if the stream has already been set up and
1078 then immediately received POLLHUP. If the stream has
1079 already been set up earlier, then this setup_stream()
1080 call is redundant anyway, but currently the code
1081 is such that this kind of unnecessary setup_stream()
1082 calls can happen. */
1083 if (u->stream_fd < 0)
1084 pa_log_debug("Skip sink stream setup while closing");
1090 return pa_sink_process_msg(o, code, data, offset, chunk);
1093 /* Called from the IO thread. */
1094 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) {
1098 pa_assert_se(u = s->userdata);
1100 switch (new_state) {
1102 case PA_SINK_SUSPENDED:
1103 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1104 if (!PA_SINK_IS_OPENED(s->thread_info.state))
1107 /* Stop the device if the source is suspended as well */
1108 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1109 /* We deliberately ignore whether stopping
1110 * actually worked. Since the stream_fd is
1111 * closed it doesn't really matter */
1112 transport_release(u);
1117 case PA_SINK_RUNNING:
1118 if (s->thread_info.state != PA_SINK_SUSPENDED)
1121 /* Resume the device if the source was suspended as well */
1122 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1123 if (!setup_transport_and_stream(u))
1128 case PA_SINK_UNLINKED:
1130 case PA_SINK_INVALID_STATE:
1137 /* Run from main thread */
1138 static void sink_set_volume_cb(pa_sink *s) {
1148 pa_assert(u->sink == s);
1149 pa_assert(!pa_bluetooth_profile_should_attenuate_volume(u->profile));
1150 pa_assert(u->transport);
1151 pa_assert(u->transport->set_sink_volume);
1153 /* In the AG role, send a command to change speaker gain on the HS/HF */
1154 volume = u->transport->set_sink_volume(u->transport, pa_cvolume_max(&s->real_volume));
1156 pa_cvolume_set(&s->real_volume, u->encoder_sample_spec.channels, volume);
1159 /* Run from main thread */
1160 static void sink_setup_volume_callback(pa_sink *s) {
1168 pa_assert(u->sink == s);
1169 pa_assert(u->transport);
1171 if (pa_bluetooth_profile_is_a2dp(u->profile) && !u->transport->device->avrcp_absolute_volume)
1174 /* Remote volume control has to be supported for the callback to make sense,
1175 * otherwise this sink should continue performing attenuation in software
1176 * without HW_VOLUME_CTL.
1177 * If the peer is an AG however backend-native unconditionally provides this
1178 * function, PA in the role of HS/HF is responsible for signalling support
1179 * by emitting an initial volume command.
1181 if (!u->transport->set_sink_volume)
1184 if (pa_bluetooth_profile_should_attenuate_volume(u->profile)) {
1185 /* It is yet unknown how (if at all) volume is synchronized for bidirectional
1186 * A2DP codecs. Disallow attaching hooks to a pa_sink if the peer is in
1187 * A2DP_SOURCE role. This assert should be replaced with the proper logic
1188 * when bidirectional codecs are implemented.
1190 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
1192 if (u->sink_volume_changed_slot)
1195 pa_log_debug("%s: Attaching volume hook to notify peer of changes", s->name);
1197 u->sink_volume_changed_slot = pa_hook_connect(&s->core->hooks[PA_CORE_HOOK_SINK_VOLUME_CHANGED],
1198 PA_HOOK_NORMAL, sink_source_volume_changed_cb, u);
1200 /* Send initial volume to peer, signalling support for volume control */
1201 u->transport->set_sink_volume(u->transport, pa_cvolume_max(&s->real_volume));
1203 if (s->set_volume == sink_set_volume_cb)
1206 pa_log_debug("%s: Resetting software volume for hardware attenuation by peer", s->name);
1208 /* Reset local attenuation */
1209 pa_sink_set_soft_volume(s, NULL);
1211 pa_sink_set_set_volume_callback(s, sink_set_volume_cb);
1213 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1214 s->n_volume_steps = A2DP_MAX_GAIN + 1;
1216 s->n_volume_steps = HSP_MAX_GAIN + 1;
1220 /* Run from main thread */
1221 static int add_sink(struct userdata *u) {
1222 pa_sink_new_data data;
1224 pa_assert(u->transport);
1226 pa_sink_new_data_init(&data);
1227 data.module = u->module;
1228 data.card = u->card;
1229 data.driver = __FILE__;
1230 data.name = pa_sprintf_malloc("bluez_sink.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1231 data.namereg_fail = false;
1232 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1234 pa_proplist_sets(data.proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1235 pa_sink_new_data_set_sample_spec(&data, &u->encoder_sample_spec);
1236 if (u->profile == PA_BLUETOOTH_PROFILE_HSP_HS
1237 || u->profile == PA_BLUETOOTH_PROFILE_HFP_HF)
1238 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1240 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1242 if (!u->transport_acquired)
1243 switch (u->profile) {
1244 case PA_BLUETOOTH_PROFILE_HFP_AG:
1245 case PA_BLUETOOTH_PROFILE_HSP_AG:
1246 data.suspend_cause = PA_SUSPEND_USER;
1248 case PA_BLUETOOTH_PROFILE_HSP_HS:
1249 case PA_BLUETOOTH_PROFILE_HFP_HF:
1250 /* u->stream_fd contains the error returned by the last transport_acquire()
1251 * EAGAIN means we are waiting for a NewConnection signal */
1252 if (u->stream_fd == -EAGAIN)
1253 data.suspend_cause = PA_SUSPEND_USER;
1255 pa_assert_not_reached();
1257 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1258 /* Profile switch should have failed */
1259 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1260 case PA_BLUETOOTH_PROFILE_OFF:
1261 pa_assert_not_reached();
1265 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1266 pa_sink_new_data_done(&data);
1268 pa_log_error("Failed to create sink");
1272 u->sink->userdata = u;
1273 u->sink->parent.process_msg = sink_process_msg;
1274 u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1276 sink_setup_volume_callback(u->sink);
1279 pa_device_port_set_latency_offset(u->sink->active_port, u->transport->delay);
1280 pa_log_info("transport[%s], sink[%s], delay[%" PRIu64 "us]", u->transport->path, u->sink->name, u->transport->delay);
1286 /* Run from main thread */
1287 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1288 static const pa_direction_t profile_direction[] = {
1289 [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1290 [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1291 [PA_BLUETOOTH_PROFILE_HSP_HS] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1292 [PA_BLUETOOTH_PROFILE_HSP_AG] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1293 [PA_BLUETOOTH_PROFILE_HFP_HF] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1294 [PA_BLUETOOTH_PROFILE_HFP_AG] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1295 [PA_BLUETOOTH_PROFILE_OFF] = 0
1298 return profile_direction[p];
1301 /* Run from main thread */
1302 static int transport_config(struct userdata *u) {
1304 pa_assert(u->transport);
1305 pa_assert(!u->bt_codec);
1306 pa_assert(!u->encoder_info);
1307 pa_assert(!u->decoder_info);
1309 u->bt_codec = u->transport->bt_codec;
1310 pa_assert(u->bt_codec);
1312 /* reset encoder buffer contents */
1313 u->encoder_buffer_used = 0;
1315 if (get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT) {
1316 u->encoder_info = u->bt_codec->init(true, false, u->transport->config, u->transport->config_size, &u->encoder_sample_spec, u->core);
1318 if (!u->encoder_info)
1322 if (get_profile_direction(u->profile) & PA_DIRECTION_INPUT) {
1323 u->decoder_info = u->bt_codec->init(false, false, u->transport->config, u->transport->config_size, &u->decoder_sample_spec, u->core);
1325 if (!u->decoder_info) {
1326 if (u->encoder_info) {
1327 u->bt_codec->deinit(u->encoder_info);
1328 u->encoder_info = NULL;
1337 /* Run from main thread */
1338 static int setup_transport(struct userdata *u) {
1339 pa_bluetooth_transport *t;
1342 pa_assert(!u->transport);
1343 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1345 /* check if profile has a transport */
1346 t = u->device->transports[u->profile];
1347 if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1348 pa_log_warn("Profile %s has no transport", pa_bluetooth_profile_to_string(u->profile));
1354 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG)
1355 transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1357 int transport_error;
1359 transport_error = transport_acquire(u, false);
1360 if (transport_error < 0 && transport_error != -EAGAIN)
1361 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1364 return transport_config(u);
1367 /* Run from main thread */
1368 static int init_profile(struct userdata *u) {
1371 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1373 r = setup_transport(u);
1374 if (r == -EINPROGRESS)
1379 pa_assert(u->transport);
1381 if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
1382 if (add_sink(u) < 0)
1385 if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
1386 if (add_source(u) < 0)
1392 static int bt_render_block(struct userdata *u) {
1395 if (u->write_index <= 0)
1396 u->started_at = pa_rtclock_now();
1398 n_rendered = bt_process_render(u);
1406 /* I/O thread function */
1407 static void thread_func(void *userdata) {
1408 struct userdata *u = userdata;
1409 unsigned blocks_to_write = 0;
1410 unsigned bytes_to_write = 0;
1411 struct timeval tv_last_output_rate_change;
1414 pa_assert(u->transport);
1416 pa_log_debug("IO Thread starting up");
1418 if (u->core->realtime_scheduling)
1419 pa_thread_make_realtime(u->core->realtime_priority);
1421 pa_thread_mq_install(&u->thread_mq);
1423 /* Setup the stream only if the transport was already acquired */
1424 if (u->transport_acquired)
1427 pa_gettimeofday(&tv_last_output_rate_change);
1430 struct pollfd *pollfd;
1432 bool disable_timer = true;
1433 bool writable = false;
1434 bool have_source = u->source ? PA_SOURCE_IS_LINKED(u->source->thread_info.state) : false;
1435 bool have_sink = u->sink ? PA_SINK_IS_LINKED(u->sink->thread_info.state) : false;
1437 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1439 /* Check for stream error or close */
1440 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1441 pa_log_info("FD error: %s%s%s%s",
1442 pollfd->revents & POLLERR ? "POLLERR " :"",
1443 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1444 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1445 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1447 if (pollfd->revents & POLLHUP) {
1450 blocks_to_write = 0;
1452 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
1457 /* If there is a pollfd, the stream is set up and we need to do something */
1460 /* Handle source if present */
1463 /* We should send two blocks to the device before we expect a response. */
1464 if (have_sink && u->write_index == 0 && u->read_index <= 0)
1465 blocks_to_write = 2;
1467 /* If we got woken up by POLLIN let's do some reading */
1468 if (pollfd->revents & POLLIN) {
1471 n_read = bt_process_push(u);
1476 if (have_sink && n_read > 0) {
1477 /* We just read something, so we are supposed to write something, too
1479 * If source and sink sample specifications are not equal,
1480 * expected write size needs to be adjusted accordingly.
1482 if (pa_sample_spec_equal(&u->encoder_sample_spec, &u->decoder_sample_spec))
1483 bytes_to_write += n_read;
1485 bytes_to_write += pa_usec_to_bytes(pa_bytes_to_usec(n_read, &u->decoder_sample_spec), &u->encoder_sample_spec);
1486 blocks_to_write += bytes_to_write / u->write_block_size;
1487 bytes_to_write = bytes_to_write % u->write_block_size;
1492 /* Handle sink if present */
1495 /* Process rewinds */
1496 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1497 pa_sink_process_rewind(u->sink, 0);
1499 /* Test if the stream is writable */
1500 if (pollfd->revents & POLLOUT)
1503 /* If we have a source, we let the source determine the timing
1507 /* If the stream is writable, send some data if necessary */
1511 if (blocks_to_write > 0) {
1512 result = bt_render_block(u);
1515 blocks_to_write -= result;
1518 result = bt_write_buffer(u);
1527 /* writable controls whether we set POLLOUT when polling - we set it to
1528 * false to enable POLLOUT. If there are more blocks to write, we want to
1529 * be woken up immediately when the socket becomes writable. If there
1530 * aren't currently any more blocks to write, then we'll have to wait
1531 * until we've received more data, so in that case we only want to set
1532 * POLLIN. Note that when we are woken up the next time, POLLOUT won't be
1533 * set in revents even if the socket has meanwhile become writable, which
1534 * may seem bad, but in that case we'll set POLLOUT in the subsequent
1535 * poll, and the poll will return immediately, so our writes won't be
1537 if (blocks_to_write > 0)
1540 /* There is no source, we have to use the system clock for timing */
1542 bool have_written = false;
1543 pa_usec_t time_passed = 0;
1544 pa_usec_t audio_sent = 0;
1546 if (u->started_at) {
1547 time_passed = pa_rtclock_now() - u->started_at;
1548 audio_sent = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1551 /* A new block needs to be sent. */
1552 if (audio_sent <= time_passed) {
1553 size_t bytes_to_send = pa_usec_to_bytes(time_passed - audio_sent, &u->encoder_sample_spec);
1555 /* There are more than two blocks that need to be written. It seems that
1556 * the socket has not been accepting data fast enough (could be due to
1557 * hiccups in the wireless transmission). We need to discard everything
1558 * older than two block sizes to keep the latency from growing. */
1559 if (bytes_to_send > 2 * u->write_block_size) {
1560 uint64_t skip_bytes;
1562 size_t max_render_size = pa_frame_align(pa_mempool_block_size_max(u->core->mempool), &u->encoder_sample_spec);
1563 pa_usec_t skip_usec;
1565 skip_bytes = bytes_to_send - 2 * u->write_block_size;
1566 skip_usec = pa_bytes_to_usec(skip_bytes, &u->encoder_sample_spec);
1568 pa_log_debug("Skipping %llu us (= %llu bytes) in audio stream",
1569 (unsigned long long) skip_usec,
1570 (unsigned long long) skip_bytes);
1572 while (skip_bytes > 0) {
1573 size_t bytes_to_render;
1575 if (skip_bytes > max_render_size)
1576 bytes_to_render = max_render_size;
1578 bytes_to_render = skip_bytes;
1580 pa_sink_render_full(u->sink, bytes_to_render, &tmp);
1581 pa_memblock_unref(tmp.memblock);
1582 u->write_index += bytes_to_render;
1583 skip_bytes -= bytes_to_render;
1586 if (u->write_index > 0 && (get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT)) {
1587 size_t new_write_block_size = u->bt_codec->reduce_encoder_bitrate(u->encoder_info, u->write_link_mtu);
1588 if (new_write_block_size) {
1589 u->write_block_size = new_write_block_size;
1590 handle_sink_block_size_change(u);
1592 pa_gettimeofday(&tv_last_output_rate_change);
1596 blocks_to_write = 1;
1599 /* If the stream is writable, send some data if necessary */
1603 if (blocks_to_write > 0) {
1604 int result = bt_render_block(u);
1607 blocks_to_write -= result;
1610 result = bt_write_buffer(u);
1617 have_written = true;
1621 /* If nothing was written during this iteration, either the stream
1622 * is not writable or there was no write pending. Set up a timer that
1623 * will wake up the thread when the next data needs to be written. */
1624 if (!have_written) {
1625 pa_usec_t sleep_for;
1626 pa_usec_t next_write_at;
1629 /* There was no write pending on this iteration of the loop.
1630 * Let's estimate when we need to wake up next */
1631 next_write_at = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1632 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1633 /* 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); */
1635 if ((get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT) && u->write_memchunk.memblock == NULL) {
1636 /* bt_write_buffer() is keeping up with input, try increasing bitrate */
1637 if (u->bt_codec->increase_encoder_bitrate
1638 && pa_timeval_age(&tv_last_output_rate_change) >= u->device->output_rate_refresh_interval_ms * PA_USEC_PER_MSEC) {
1639 size_t new_write_block_size = u->bt_codec->increase_encoder_bitrate(u->encoder_info, u->write_link_mtu);
1640 if (new_write_block_size) {
1641 u->write_block_size = new_write_block_size;
1642 handle_sink_block_size_change(u);
1644 pa_gettimeofday(&tv_last_output_rate_change);
1648 /* We could not write because the stream was not ready. Let's try
1649 * again in 500 ms and drop audio if we still can't write. The
1650 * thread will also be woken up when we can write again. */
1651 sleep_for = PA_USEC_PER_MSEC * 500;
1653 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1654 disable_timer = false;
1659 /* Set events to wake up the thread */
1660 pollfd->events = (short) (((have_sink && !writable) ? POLLOUT : 0) | (have_source ? POLLIN : 0));
1665 pa_rtpoll_set_timer_disabled(u->rtpoll);
1667 if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1668 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1673 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1674 transport_release(u);
1680 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1681 pa_log_debug("IO thread failed");
1682 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1683 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1686 pa_log_debug("IO thread shutting down");
1689 /* Run from main thread */
1690 static int start_thread(struct userdata *u) {
1692 pa_assert(!u->thread);
1693 pa_assert(!u->rtpoll);
1694 pa_assert(!u->rtpoll_item);
1696 u->rtpoll = pa_rtpoll_new();
1698 if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1699 pa_log("pa_thread_mq_init() failed.");
1703 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1704 pa_log_error("Failed to create IO thread");
1709 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1710 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1712 /* If we are in the headset role, the sink should not become default
1713 * unless there is no other sound device available. */
1714 if (u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG)
1715 u->sink->priority = 1500;
1717 pa_sink_put(u->sink);
1719 if (u->sink->set_volume)
1720 u->sink->set_volume(u->sink);
1724 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1725 pa_source_set_rtpoll(u->source, u->rtpoll);
1727 /* If we are in the headset role or the device is an a2dp source,
1728 * the source should not become default unless there is no other
1729 * sound device available. */
1730 if (u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG || u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1731 u->source->priority = 1500;
1733 pa_source_put(u->source);
1735 if (u->source->set_volume)
1736 u->source->set_volume(u->source);
1739 if (u->sink || u->source)
1741 pa_proplist_sets(u->card->proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1743 /* Now that everything is set up we are ready to check for the Volume property.
1744 * Sometimes its initial "change" notification arrives too early when the sink
1745 * is not available or still in UNLINKED state; check it again here to know if
1746 * our sink peer supports Absolute Volume; in that case we should not perform
1747 * any attenuation but delegate all set_volume calls to the peer through this
1750 * Note that this works the other way around if the peer is in source profile:
1751 * we are rendering audio and hence responsible for applying attenuation. The
1752 * set_volume callback is always registered, and Volume is always passed to
1753 * BlueZ unconditionally. BlueZ only sends a notification to the peer if it
1754 * registered a notification request for absolute volume previously.
1756 if (u->transport && u->sink)
1757 pa_bluetooth_transport_load_a2dp_sink_volume(u->transport);
1762 /* Run from main thread */
1763 static void stop_thread(struct userdata *u) {
1766 if (u->sink || u->source)
1767 pa_proplist_unset(u->card->proplist, PA_PROP_BLUETOOTH_CODEC);
1770 pa_sink_unlink(u->sink);
1773 pa_source_unlink(u->source);
1776 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1777 pa_thread_free(u->thread);
1781 if (u->rtpoll_item) {
1782 pa_rtpoll_item_free(u->rtpoll_item);
1783 u->rtpoll_item = NULL;
1787 pa_rtpoll_free(u->rtpoll);
1789 pa_thread_mq_done(&u->thread_mq);
1793 transport_release(u);
1794 u->transport = NULL;
1797 if (u->sink_volume_changed_slot) {
1798 pa_hook_slot_free(u->sink_volume_changed_slot);
1799 u->sink_volume_changed_slot = NULL;
1802 if (u->source_volume_changed_slot) {
1803 pa_hook_slot_free(u->source_volume_changed_slot);
1804 u->source_volume_changed_slot = NULL;
1808 pa_sink_unref(u->sink);
1813 pa_source_unref(u->source);
1817 if (u->read_smoother) {
1818 pa_smoother_free(u->read_smoother);
1819 u->read_smoother = NULL;
1823 if (u->encoder_info) {
1824 u->bt_codec->deinit(u->encoder_info);
1825 u->encoder_info = NULL;
1828 if (u->decoder_info) {
1829 u->bt_codec->deinit(u->decoder_info);
1830 u->decoder_info = NULL;
1836 if (u->encoder_buffer) {
1837 pa_xfree(u->encoder_buffer);
1838 u->encoder_buffer = NULL;
1841 u->encoder_buffer_size = 0;
1842 u->encoder_buffer_used = 0;
1844 if (u->decoder_buffer) {
1845 pa_xfree(u->decoder_buffer);
1846 u->decoder_buffer = NULL;
1849 u->decoder_buffer_size = 0;
1852 /* Run from main thread */
1853 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1854 pa_available_t result = PA_AVAILABLE_NO;
1858 pa_assert(u->device);
1860 for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1861 pa_bluetooth_transport *transport;
1863 if (!(get_profile_direction(i) & direction))
1866 if (!(transport = u->device->transports[i]))
1869 switch(transport->state) {
1870 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1873 case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1874 if (result == PA_AVAILABLE_NO)
1875 result = PA_AVAILABLE_UNKNOWN;
1879 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1880 return PA_AVAILABLE_YES;
1887 /* Run from main thread */
1888 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1890 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1891 return PA_AVAILABLE_NO;
1892 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1893 return PA_AVAILABLE_YES;
1895 return PA_AVAILABLE_UNKNOWN;
1899 /* Run from main thread */
1900 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1901 pa_device_port *port;
1902 pa_device_port_new_data port_data;
1903 pa_device_port_type_t input_type, output_type;
1904 const char *name_prefix, *input_description, *output_description;
1908 pa_assert(u->device);
1910 name_prefix = "unknown";
1911 input_description = _("Bluetooth Input");
1912 output_description = _("Bluetooth Output");
1913 input_type = output_type = PA_DEVICE_PORT_TYPE_BLUETOOTH;
1915 switch (form_factor_from_class(u->device->class_of_device)) {
1916 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1917 name_prefix = "headset";
1918 input_description = output_description = _("Headset");
1919 input_type = output_type = PA_DEVICE_PORT_TYPE_HEADSET;
1922 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1923 name_prefix = "handsfree";
1924 input_description = output_description = _("Handsfree");
1925 input_type = output_type = PA_DEVICE_PORT_TYPE_HANDSFREE;
1928 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1929 name_prefix = "microphone";
1930 input_description = _("Microphone");
1931 output_description = _("Bluetooth Output");
1932 input_type = PA_DEVICE_PORT_TYPE_MIC;
1935 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1936 name_prefix = "speaker";
1937 input_description = _("Bluetooth Input");
1938 output_description = _("Speaker");
1939 output_type = PA_DEVICE_PORT_TYPE_SPEAKER;
1942 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1943 name_prefix = "headphone";
1944 input_description = _("Bluetooth Input");
1945 output_description = _("Headphone");
1946 output_type = PA_DEVICE_PORT_TYPE_HEADPHONES;
1949 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1950 name_prefix = "portable";
1951 input_description = output_description = _("Portable");
1952 input_type = output_type = PA_DEVICE_PORT_TYPE_PORTABLE;
1955 case PA_BLUETOOTH_FORM_FACTOR_CAR:
1956 name_prefix = "car";
1957 input_description = output_description = _("Car");
1958 input_type = output_type = PA_DEVICE_PORT_TYPE_CAR;
1961 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1962 name_prefix = "hifi";
1963 input_description = output_description = _("HiFi");
1964 input_type = output_type = PA_DEVICE_PORT_TYPE_HIFI;
1967 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1968 name_prefix = "phone";
1969 input_description = output_description = _("Phone");
1970 input_type = output_type = PA_DEVICE_PORT_TYPE_PHONE;
1973 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
1977 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
1978 pa_device_port_new_data_init(&port_data);
1979 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
1980 pa_device_port_new_data_set_description(&port_data, output_description);
1981 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
1982 pa_device_port_new_data_set_type(&port_data, output_type);
1983 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
1984 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1985 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1986 pa_device_port_new_data_done(&port_data);
1988 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
1989 pa_device_port_new_data_init(&port_data);
1990 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
1991 pa_device_port_new_data_set_description(&port_data, input_description);
1992 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
1993 pa_device_port_new_data_set_type(&port_data, input_type);
1994 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
1995 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1996 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1997 pa_device_port_new_data_done(&port_data);
2000 /* Run from main thread */
2001 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluetooth_profile_t profile, pa_hashmap *ports) {
2002 pa_device_port *input_port, *output_port;
2004 pa_card_profile *cp = NULL;
2005 pa_bluetooth_profile_t *p;
2007 pa_assert(u->input_port_name);
2008 pa_assert(u->output_port_name);
2009 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2010 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2012 name = pa_bluetooth_profile_to_string(profile);
2015 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
2016 cp = pa_card_profile_new(name, _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
2020 cp->max_sink_channels = 2;
2021 cp->max_source_channels = 0;
2022 pa_hashmap_put(output_port->profiles, cp->name, cp);
2024 p = PA_CARD_PROFILE_DATA(cp);
2027 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
2028 cp = pa_card_profile_new(name, _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
2032 cp->max_sink_channels = 0;
2033 cp->max_source_channels = 2;
2034 pa_hashmap_put(input_port->profiles, cp->name, cp);
2036 p = PA_CARD_PROFILE_DATA(cp);
2039 case PA_BLUETOOTH_PROFILE_HSP_HS:
2040 cp = pa_card_profile_new(name, _("Headset Head Unit (HSP)"), sizeof(pa_bluetooth_profile_t));
2044 cp->max_sink_channels = 1;
2045 cp->max_source_channels = 1;
2046 pa_hashmap_put(input_port->profiles, cp->name, cp);
2047 pa_hashmap_put(output_port->profiles, cp->name, cp);
2049 p = PA_CARD_PROFILE_DATA(cp);
2052 case PA_BLUETOOTH_PROFILE_HSP_AG:
2053 cp = pa_card_profile_new(name, _("Headset Audio Gateway (HSP)"), sizeof(pa_bluetooth_profile_t));
2057 cp->max_sink_channels = 1;
2058 cp->max_source_channels = 1;
2059 pa_hashmap_put(input_port->profiles, cp->name, cp);
2060 pa_hashmap_put(output_port->profiles, cp->name, cp);
2062 p = PA_CARD_PROFILE_DATA(cp);
2065 case PA_BLUETOOTH_PROFILE_HFP_HF:
2066 cp = pa_card_profile_new(name, _("Handsfree Head Unit (HFP)"), sizeof(pa_bluetooth_profile_t));
2070 cp->max_sink_channels = 1;
2071 cp->max_source_channels = 1;
2072 pa_hashmap_put(input_port->profiles, cp->name, cp);
2073 pa_hashmap_put(output_port->profiles, cp->name, cp);
2075 p = PA_CARD_PROFILE_DATA(cp);
2078 case PA_BLUETOOTH_PROFILE_HFP_AG:
2079 cp = pa_card_profile_new(name, _("Handsfree Audio Gateway (HFP)"), sizeof(pa_bluetooth_profile_t));
2083 cp->max_sink_channels = 1;
2084 cp->max_source_channels = 1;
2085 pa_hashmap_put(input_port->profiles, cp->name, cp);
2086 pa_hashmap_put(output_port->profiles, cp->name, cp);
2088 p = PA_CARD_PROFILE_DATA(cp);
2091 case PA_BLUETOOTH_PROFILE_OFF:
2092 pa_assert_not_reached();
2097 if (u->device->transports[*p])
2098 cp->available = transport_state_to_availability(u->device->transports[*p]->state);
2100 cp->available = PA_AVAILABLE_NO;
2105 /* Run from main thread */
2106 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
2108 pa_bluetooth_profile_t *p;
2111 pa_assert(new_profile);
2112 pa_assert_se(u = c->userdata);
2114 p = PA_CARD_PROFILE_DATA(new_profile);
2116 if (*p != PA_BLUETOOTH_PROFILE_OFF) {
2117 const pa_bluetooth_device *d = u->device;
2119 if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2120 pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
2129 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2130 if (init_profile(u) < 0)
2133 if (u->sink || u->source)
2134 if (start_thread(u) < 0)
2142 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2147 static int uuid_to_profile(const char *uuid, pa_bluetooth_profile_t *_r) {
2148 if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK))
2149 *_r = PA_BLUETOOTH_PROFILE_A2DP_SINK;
2150 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE))
2151 *_r = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
2152 else if (pa_bluetooth_uuid_is_hsp_hs(uuid))
2153 *_r = PA_BLUETOOTH_PROFILE_HSP_HS;
2154 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF))
2155 *_r = PA_BLUETOOTH_PROFILE_HFP_HF;
2156 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG))
2157 *_r = PA_BLUETOOTH_PROFILE_HSP_AG;
2158 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG))
2159 *_r = PA_BLUETOOTH_PROFILE_HFP_AG;
2161 return -PA_ERR_INVALID;
2166 /* Run from main thread */
2167 static int add_card(struct userdata *u) {
2168 const pa_bluetooth_device *d;
2169 pa_card_new_data data;
2171 pa_bluetooth_form_factor_t ff;
2172 pa_card_profile *cp;
2173 pa_bluetooth_profile_t *p;
2178 pa_assert(u->device);
2182 pa_card_new_data_init(&data);
2183 data.driver = __FILE__;
2184 data.module = u->module;
2186 alias = pa_utf8_filter(d->alias);
2187 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2190 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2191 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2192 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2193 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2195 if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2196 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2198 pa_proplist_sets(data.proplist, "bluez.path", d->path);
2199 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2200 pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2201 data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2202 data.namereg_fail = false;
2204 create_card_ports(u, data.ports);
2206 PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2207 pa_bluetooth_profile_t profile;
2209 if (uuid_to_profile(uuid, &profile) < 0)
2212 if (pa_hashmap_get(data.profiles, pa_bluetooth_profile_to_string(profile)))
2215 cp = create_card_profile(u, profile, data.ports);
2216 pa_hashmap_put(data.profiles, cp->name, cp);
2219 pa_assert(!pa_hashmap_isempty(data.profiles));
2221 cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2222 cp->available = PA_AVAILABLE_YES;
2223 p = PA_CARD_PROFILE_DATA(cp);
2224 *p = PA_BLUETOOTH_PROFILE_OFF;
2225 pa_hashmap_put(data.profiles, cp->name, cp);
2227 u->card = pa_card_new(u->core, &data);
2228 pa_card_new_data_done(&data);
2230 pa_log("Failed to allocate card.");
2234 u->card->userdata = u;
2235 u->card->set_profile = set_profile_cb;
2236 pa_card_choose_initial_profile(u->card);
2237 pa_card_put(u->card);
2239 p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2245 /* Run from main thread */
2246 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2247 bool acquire = false;
2248 bool release = false;
2249 pa_card_profile *cp;
2250 pa_device_port *port;
2251 pa_available_t oldavail;
2255 pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
2257 oldavail = cp->available;
2259 * If codec switching is in progress, transport state change should not
2260 * make profile unavailable.
2262 if (!t->device->codec_switching_in_progress)
2263 pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2265 /* Update port availability */
2266 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2267 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2268 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2269 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2271 /* Acquire or release transport as needed */
2272 acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2273 release = (oldavail != PA_AVAILABLE_NO && t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2275 if (acquire && transport_acquire(u, true) >= 0) {
2277 pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2279 /* When the ofono backend resumes source or sink when in the audio gateway role, the
2280 * state of source or sink may already be RUNNING before the transport is acquired via
2281 * hf_audio_agent_new_connection(), so the pa_source_suspend() call will not lead to a
2282 * state change message. In this case we explicitly need to signal the I/O thread to
2283 * set up the stream. */
2284 if (PA_SOURCE_IS_OPENED(u->source->state))
2285 pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), PA_SOURCE_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2287 /* We remove the IDLE suspend cause, because otherwise
2288 * module-loopback doesn't uncork its streams. FIXME: Messing with
2289 * the IDLE suspend cause here is wrong, the correct way to handle
2290 * this would probably be to uncork the loopback streams not only
2291 * when the other end is unsuspended, but also when the other end's
2292 * suspend cause changes to IDLE only (currently there's no
2293 * notification mechanism for suspend cause changes, though). */
2294 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2298 pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2301 u->transport_suspended_by_remote = false;
2303 /* Same comment as above */
2304 if (PA_SINK_IS_OPENED(u->sink->state))
2305 pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), PA_SINK_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2307 /* FIXME: See the previous comment. */
2308 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2312 if (release && u->transport_acquired) {
2313 /* FIXME: this release is racy, since the audio stream might have
2314 * been set up again in the meantime (but not processed yet by PA).
2315 * BlueZ should probably release the transport automatically, and in
2316 * that case we would just mark the transport as released */
2318 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2320 pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2321 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2325 pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2327 /* if we change PA state as Suspend, PA client application
2328 * such as music app would face lock-up */
2329 u->transport_suspended_by_remote = true;
2331 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2337 /* Run from main thread */
2338 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2342 if (d != u->device || pa_bluetooth_device_any_transport_connected(d) || d->codec_switching_in_progress)
2345 pa_log_debug("Unloading module for device %s", d->path);
2346 pa_module_unload(u->module, true);
2352 static void dbus_sco_open_handler(struct userdata *u, struct pa_bluetooth_transport *t)
2359 pa_log_info("Suspending sink %s to handle the SCO connection", u->sink->name);
2361 if (pa_sink_check_suspend(u->sink, NULL, NULL) > 0) {
2362 sink_null = (pa_sink *)pa_namereg_get(u->core, "null", 0);
2365 PA_IDXSET_FOREACH(si, u->core->sink_inputs, idx) {
2366 pa_sink_input_move_to(si, sink_null, false);
2371 pa_sink_suspend(u->sink, true, PA_SUSPEND_INTERNAL);
2375 /* Run from main thread */
2376 static pa_hook_result_t sco_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2380 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2383 if (t->device == u->device)
2384 dbus_sco_open_handler(u, t);
2389 /* Run from main thread */
2390 static pa_hook_result_t transport_delay_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2394 if (t == u->transport && t->device == u->device && u->sink) {
2395 pa_device_port_set_latency_offset(u->sink->active_port, u->transport->delay);
2396 pa_log_info("transport[%s], sink[%s], delay[%" PRIu64 "us]", u->transport->path, u->sink->name, u->transport->delay);
2403 /* Run from main thread */
2404 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2408 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2409 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2411 if (t->device == u->device)
2412 handle_transport_state_change(u, t);
2417 static pa_hook_result_t transport_sink_volume_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2424 if (t != u->transport)
2427 volume = t->sink_volume;
2430 pa_log_warn("Received peer transport volume change without connected sink");
2434 sink_setup_volume_callback(u->sink);
2436 pa_cvolume_set(&v, u->encoder_sample_spec.channels, volume);
2437 if (pa_bluetooth_profile_should_attenuate_volume(t->profile))
2438 pa_sink_set_volume(u->sink, &v, true, true);
2440 pa_sink_volume_changed(u->sink, &v);
2445 static pa_hook_result_t transport_source_volume_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2452 if (t != u->transport)
2455 volume = t->source_volume;
2458 pa_log_warn("Received peer transport volume change without connected source");
2462 source_setup_volume_callback(u->source);
2464 pa_cvolume_set(&v, u->decoder_sample_spec.channels, volume);
2466 if (pa_bluetooth_profile_should_attenuate_volume(t->profile))
2467 pa_source_set_volume(u->source, &v, true, true);
2469 pa_source_volume_changed(u->source, &v);
2474 static char* make_message_handler_path(const char *name) {
2475 return pa_sprintf_malloc("/card/%s/bluez", name);
2478 static void switch_codec_cb_handler(bool success, pa_bluetooth_profile_t profile, void *userdata)
2480 struct userdata *u = (struct userdata *) userdata;
2485 u->profile = profile;
2487 if (init_profile(u) < 0) {
2488 pa_log_info("Failed to initialise profile after codec switching");
2492 if (u->sink || u->source)
2493 if (start_thread(u) < 0) {
2494 pa_log_info("Failed to start thread after codec switching");
2498 pa_log_info("Codec successfully switched to %s with profile: %s",
2499 u->bt_codec->name, pa_bluetooth_profile_to_string(u->profile));
2504 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2507 static char *list_codecs(struct userdata *u) {
2508 const pa_a2dp_codec_capabilities *a2dp_capabilities;
2509 const pa_a2dp_codec_id *key;
2510 pa_hashmap *a2dp_endpoints;
2511 pa_json_encoder *encoder;
2516 encoder = pa_json_encoder_new();
2518 pa_json_encoder_begin_element_array(encoder);
2520 if (pa_bluetooth_profile_is_a2dp(u->profile)) {
2521 is_a2dp_sink = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK;
2523 a2dp_endpoints = is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints;
2525 PA_HASHMAP_FOREACH_KV(key, a2dp_capabilities, a2dp_endpoints, state) {
2526 for (i = 0; i < pa_bluetooth_a2dp_endpoint_conf_count(); i++) {
2527 const pa_a2dp_endpoint_conf *endpoint_conf;
2529 endpoint_conf = pa_bluetooth_a2dp_endpoint_conf_iter(i);
2531 if (memcmp(key, &endpoint_conf->id, sizeof(pa_a2dp_codec_id)) == 0) {
2532 if (endpoint_conf->can_be_supported(is_a2dp_sink)) {
2533 pa_json_encoder_begin_element_object(encoder);
2535 pa_json_encoder_add_member_string(encoder, "name", endpoint_conf->bt_codec.name);
2536 pa_json_encoder_add_member_string(encoder, "description", endpoint_conf->bt_codec.description);
2538 pa_json_encoder_end_object(encoder);
2544 /* find out active codec selection from device profile */
2545 for (i = 0; i < pa_bluetooth_hf_codec_count(); i++) {
2546 const pa_bt_codec *hf_codec;
2548 hf_codec = pa_bluetooth_hf_codec_iter(i);
2551 pa_json_encoder_begin_element_object(encoder);
2553 pa_json_encoder_add_member_string(encoder, "name", hf_codec->name);
2554 pa_json_encoder_add_member_string(encoder, "description", hf_codec->description);
2556 pa_json_encoder_end_object(encoder);
2561 pa_json_encoder_end_array(encoder);
2563 return pa_json_encoder_to_string_free(encoder);
2566 static int bluez5_device_message_handler(const char *object_path, const char *message, const pa_json_object *parameters, char **response, void *userdata) {
2567 char *message_handler_path;
2568 pa_hashmap *capabilities_hashmap;
2569 pa_bluetooth_profile_t profile;
2570 const pa_a2dp_endpoint_conf *endpoint_conf;
2571 const char *codec_name;
2575 pa_assert(u = (struct userdata *)userdata);
2577 pa_assert(response);
2579 message_handler_path = make_message_handler_path(u->card->name);
2581 if (!object_path || !pa_streq(object_path, message_handler_path)) {
2582 pa_xfree(message_handler_path);
2583 return -PA_ERR_NOENTITY;
2586 pa_xfree(message_handler_path);
2588 if (u->device->codec_switching_in_progress) {
2589 pa_log_info("Codec switching operation already in progress");
2590 return -PA_ERR_INVALID;
2593 if (!u->device->adapter->application_registered) {
2594 pa_log_info("Old BlueZ version was detected, only SBC codec supported.");
2595 return -PA_ERR_NOTIMPLEMENTED;
2598 if (u->profile == PA_BLUETOOTH_PROFILE_OFF) {
2599 pa_log_info("Bluetooth profile is off. Message cannot be handled.");
2600 return -PA_ERR_INVALID;
2603 if (pa_streq(message, "switch-codec")) {
2604 if (u->profile != PA_BLUETOOTH_PROFILE_A2DP_SINK &&
2605 u->profile != PA_BLUETOOTH_PROFILE_A2DP_SOURCE) {
2606 pa_log_info("Switching codecs only allowed for A2DP sink or source");
2607 return -PA_ERR_INVALID;
2611 pa_log_info("Codec switching operation requires codec name string parameter");
2612 return -PA_ERR_INVALID;
2615 if (pa_json_object_get_type(parameters) != PA_JSON_TYPE_STRING) {
2616 pa_log_info("Codec name object parameter must be a string");
2617 return -PA_ERR_INVALID;
2620 codec_name = pa_json_object_get_string(parameters);
2622 if (u->bt_codec && pa_streq(codec_name, u->bt_codec->name)) {
2623 pa_log_info("Requested codec is currently selected codec");
2624 return -PA_ERR_INVALID;
2627 endpoint_conf = pa_bluetooth_get_a2dp_endpoint_conf(codec_name);
2628 if (endpoint_conf == NULL) {
2629 pa_log_info("Invalid codec %s specified for switching", codec_name);
2630 return -PA_ERR_INVALID;
2633 is_a2dp_sink = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK;
2635 if (!endpoint_conf->can_be_supported(is_a2dp_sink)) {
2636 pa_log_info("Codec not found on system");
2637 return -PA_ERR_NOTSUPPORTED;
2641 * We need to check if we have valid sink or source endpoints which
2642 * were registered during the negotiation process. If we do, then we
2643 * check if the specified codec is present among the codecs supported
2644 * by the remote endpoint.
2646 if (pa_hashmap_isempty(is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints)) {
2647 pa_log_info("No device endpoints found. Codec switching not allowed.");
2648 return -PA_ERR_INVALID;
2651 capabilities_hashmap = pa_hashmap_get(is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints, &endpoint_conf->id);
2652 if (!capabilities_hashmap) {
2653 pa_log_info("No remote endpoint found for %s codec. Codec not supported by remote endpoint.",
2654 endpoint_conf->bt_codec.name);
2655 return -PA_ERR_INVALID;
2658 pa_log_info("Initiating codec switching process to %s", endpoint_conf->bt_codec.name);
2661 * The current profile needs to be saved before we stop the thread and
2662 * initiate the switch. u->profile will be changed in other places
2663 * depending on the state of transport and port availability.
2665 profile = u->profile;
2669 if (!pa_bluetooth_device_switch_codec(u->device, profile, capabilities_hashmap, endpoint_conf, switch_codec_cb_handler, userdata)
2670 && !u->device->codec_switching_in_progress)
2674 } else if (pa_streq(message, "list-codecs")) {
2675 *response = list_codecs(u);
2677 } else if (pa_streq(message, "get-codec")) {
2678 pa_json_encoder *encoder;
2679 encoder = pa_json_encoder_new();
2682 pa_json_encoder_add_element_string(encoder, u->bt_codec->name);
2684 pa_json_encoder_add_element_null(encoder);
2686 *response = pa_json_encoder_to_string_free(encoder);
2692 return -PA_ERR_NOTIMPLEMENTED;
2695 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2700 /* Run from main thread context */
2701 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2702 struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
2703 struct userdata *u = m->card->userdata;
2706 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2707 if (m->card->module->unload_requested)
2710 pa_log_debug("Switching the profile to off due to IO thread failure.");
2711 pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
2713 case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
2714 if (u->transport->state > PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2715 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
2717 case BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING:
2718 /* transport_acquired needs to be checked here, because a message could have been
2719 * pending when the profile was switched. If the new transport has been acquired
2720 * correctly, the call below will have no effect because the transport state is
2721 * already PLAYING. If transport_acquire() failed for the new profile, the transport
2722 * state should not be changed. If the transport has been released for other reasons
2723 * (I/O thread shutdown), transport_acquired will also be false. */
2724 if (u->transport_acquired)
2725 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
2732 int pa__init(pa_module* m) {
2736 bool autodetect_mtu, avrcp_absolute_volume;
2737 char *message_handler_path;
2738 uint32_t output_rate_refresh_interval_ms;
2742 m->userdata = u = pa_xnew0(struct userdata, 1);
2745 u->message_handler_registered = false;
2747 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2748 pa_log_error("Failed to parse module arguments");
2749 goto fail_free_modargs;
2753 u->decoder_sample_spec = m->core->default_sample_spec;
2756 if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2757 pa_log_error("Failed to get device path from module arguments");
2758 goto fail_free_modargs;
2761 if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2762 pa_bluetooth_discovery_ref(u->discovery);
2764 pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2765 goto fail_free_modargs;
2768 if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2769 pa_log_error("%s is unknown", path);
2770 goto fail_free_modargs;
2773 autodetect_mtu = false;
2774 if (pa_modargs_get_value_boolean(ma, "autodetect_mtu", &autodetect_mtu) < 0) {
2775 pa_log("Invalid boolean value for autodetect_mtu parameter");
2776 goto fail_free_modargs;
2779 u->device->autodetect_mtu = autodetect_mtu;
2781 output_rate_refresh_interval_ms = DEFAULT_OUTPUT_RATE_REFRESH_INTERVAL_MS;
2782 if (pa_modargs_get_value_u32(ma, "output_rate_refresh_interval_ms", &output_rate_refresh_interval_ms) < 0) {
2783 pa_log("Invalid value for output_rate_refresh_interval parameter.");
2784 goto fail_free_modargs;
2787 u->device->output_rate_refresh_interval_ms = output_rate_refresh_interval_ms;
2789 avrcp_absolute_volume = true;
2790 if (pa_modargs_get_value_boolean(ma, "avrcp_absolute_volume", &avrcp_absolute_volume) < 0) {
2791 pa_log("Invalid boolean value for avrcp_absolute_volume parameter");
2792 goto fail_free_modargs;
2795 u->device->avrcp_absolute_volume = avrcp_absolute_volume;
2797 pa_modargs_free(ma);
2799 u->device_connection_changed_slot =
2800 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2801 PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2803 u->transport_state_changed_slot =
2804 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2805 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2807 u->transport_sink_volume_changed_slot =
2808 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SINK_VOLUME_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_sink_volume_changed_cb, u);
2810 u->transport_source_volume_changed_slot =
2811 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SOURCE_VOLUME_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_source_volume_changed_cb, u);
2814 u->transport_delay_changed_slot =
2815 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_DELAY_CHANGED),
2816 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_delay_changed_cb, u);
2818 u->sco_state_changed_slot =
2819 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_SCO_STATE_CHANGED),
2820 PA_HOOK_NORMAL, (pa_hook_cb_t) sco_state_changed_cb, u);
2823 if (add_card(u) < 0)
2826 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2829 u->msg->parent.process_msg = device_process_msg;
2830 u->msg->card = u->card;
2831 u->stream_setup_done = false;
2833 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2834 if (init_profile(u) < 0)
2837 if (u->sink || u->source)
2838 if (start_thread(u) < 0)
2841 message_handler_path = make_message_handler_path(u->card->name);
2842 pa_message_handler_register(m->core, message_handler_path, "Bluez5 device message handler",
2843 bluez5_device_message_handler, (void *) u);
2844 pa_log_info("Bluez5 device message handler registered at path: %s", message_handler_path);
2845 pa_xfree(message_handler_path);
2846 u->message_handler_registered = true;
2853 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2860 pa_modargs_free(ma);
2869 void pa__done(pa_module *m) {
2870 char *message_handler_path;
2875 if (!(u = m->userdata))
2878 if (u->message_handler_registered) {
2879 message_handler_path = make_message_handler_path(u->card->name);
2880 pa_message_handler_unregister(m->core, message_handler_path);
2881 pa_xfree(message_handler_path);
2886 if (u->device_connection_changed_slot)
2887 pa_hook_slot_free(u->device_connection_changed_slot);
2889 if (u->transport_state_changed_slot)
2890 pa_hook_slot_free(u->transport_state_changed_slot);
2892 if (u->transport_sink_volume_changed_slot)
2893 pa_hook_slot_free(u->transport_sink_volume_changed_slot);
2895 if (u->transport_source_volume_changed_slot)
2896 pa_hook_slot_free(u->transport_source_volume_changed_slot);
2899 if (u->transport_delay_changed_slot)
2900 pa_hook_slot_free(u->transport_delay_changed_slot);
2902 if (u->sco_state_changed_slot)
2903 pa_hook_slot_free(u->sco_state_changed_slot);
2906 if (u->encoder_buffer)
2907 pa_xfree(u->encoder_buffer);
2909 if (u->decoder_buffer)
2910 pa_xfree(u->decoder_buffer);
2916 pa_card_free(u->card);
2919 pa_bluetooth_discovery_unref(u->discovery);
2921 pa_xfree(u->output_port_name);
2922 pa_xfree(u->input_port_name);
2927 int pa__get_n_used(pa_module *m) {
2931 pa_assert_se(u = m->userdata);
2933 return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);