2 This file is part of PulseAudio.
4 Copyright 2008-2013 João Paulo Rechi Vita
5 Copyright 2011-2013 BMW Car IT GmbH.
7 PulseAudio is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 PulseAudio is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with PulseAudio; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
29 #include <arpa/inet.h>
32 #ifdef BLUETOOTH_APTX_SUPPORT
36 #include <pulse/rtclock.h>
37 #include <pulse/timeval.h>
39 #include <pulsecore/core-error.h>
40 #include <pulsecore/core-rtclock.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/i18n.h>
43 #include <pulsecore/module.h>
44 #include <pulsecore/modargs.h>
45 #include <pulsecore/poll.h>
46 #include <pulsecore/rtpoll.h>
47 #include <pulsecore/shared.h>
48 #include <pulsecore/socket-util.h>
49 #include <pulsecore/thread.h>
50 #include <pulsecore/thread-mq.h>
51 #include <pulsecore/time-smoother.h>
53 #include "a2dp-codecs.h"
54 #include "bluez5-util.h"
57 #include "module-bluez5-device-symdef.h"
59 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
60 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
61 PA_MODULE_VERSION(PACKAGE_VERSION);
62 PA_MODULE_LOAD_ONCE(false);
63 PA_MODULE_USAGE("path=<device object path>");
65 #define MAX_PLAYBACK_CATCH_UP_USEC (100 * PA_USEC_PER_MSEC)
66 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
67 #define FIXED_LATENCY_PLAYBACK_SCO (125 * PA_USEC_PER_MSEC)
68 #define FIXED_LATENCY_RECORD_A2DP (25 * PA_USEC_PER_MSEC)
69 #define FIXED_LATENCY_RECORD_SCO (25 * PA_USEC_PER_MSEC)
71 #define BITPOOL_DEC_LIMIT 32
72 #define BITPOOL_DEC_STEP 5
74 static const char* const valid_modargs[] = {
84 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
85 BLUETOOTH_MESSAGE_TRANSPORT_STATE_CHANGED,
89 typedef struct bluetooth_msg {
93 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
94 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
96 typedef struct sbc_info {
97 sbc_t sbc; /* Codec data */
98 bool sbc_initialized; /* Keep track if the encoder is initialized */
99 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
100 uint16_t seq_num; /* Cumulative packet sequence */
103 #ifdef BLUETOOTH_APTX_SUPPORT
104 bool aptx_initialized; /* Keep track if the encoder is initialized */
105 void *aptx; /* aptx Codec data */
107 void* buffer; /* Codec transfer buffer */
108 size_t buffer_size; /* Size of the buffer */
115 pa_hook_slot *device_connection_changed_slot;
116 pa_hook_slot *transport_state_changed_slot;
118 pa_hook_slot *sco_state_changed_slot;
121 pa_bluetooth_discovery *discovery;
122 pa_bluetooth_device *device;
123 pa_bluetooth_transport *transport;
124 bool transport_acquired;
127 bool transport_suspended_by_remote;
133 pa_bluetooth_profile_t profile;
134 char *output_port_name;
135 char *input_port_name;
138 pa_thread_mq thread_mq;
140 pa_rtpoll_item *rtpoll_item;
144 int stream_write_type;
145 size_t read_link_mtu;
146 size_t write_link_mtu;
147 size_t read_block_size;
148 size_t write_block_size;
150 uint64_t write_index;
151 pa_usec_t started_at;
152 pa_smoother *read_smoother;
153 pa_memchunk write_memchunk;
154 pa_sample_spec sample_spec;
155 struct sbc_info sbc_info;
162 typedef enum pa_bluetooth_form_factor {
163 PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
164 PA_BLUETOOTH_FORM_FACTOR_HEADSET,
165 PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
166 PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
167 PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
168 PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
169 PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
170 PA_BLUETOOTH_FORM_FACTOR_CAR,
171 PA_BLUETOOTH_FORM_FACTOR_HIFI,
172 PA_BLUETOOTH_FORM_FACTOR_PHONE,
173 } pa_bluetooth_form_factor_t;
175 /* Run from main thread */
176 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
177 unsigned major, minor;
178 pa_bluetooth_form_factor_t r;
180 static const pa_bluetooth_form_factor_t table[] = {
181 [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
182 [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
183 [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
184 [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
185 [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
186 [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
187 [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
188 [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
192 * See Bluetooth Assigned Numbers:
193 * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
195 major = (class_of_device >> 8) & 0x1F;
196 minor = (class_of_device >> 2) & 0x3F;
200 return PA_BLUETOOTH_FORM_FACTOR_PHONE;
204 pa_log_debug("Unknown Bluetooth major device class %u", major);
205 return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
208 r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
211 pa_log_debug("Unknown Bluetooth minor device class %u", minor);
216 /* Run from main thread */
217 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
219 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
221 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
223 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
225 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
227 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
229 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
231 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
233 case PA_BLUETOOTH_FORM_FACTOR_CAR:
235 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
237 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
241 pa_assert_not_reached();
244 #ifdef BLUETOOTH_APTX_SUPPORT
245 void* (*aptx_new)(short endian);
246 int (*aptx_encode)(void* _state, void* _pcmL, void* _pcmR, void* _buffer);
248 const char *aptx_new_name = "NewAptxEnc";
249 const char *aptx_encode_name = "aptxbtenc_encodestereo";
251 static bool pa_load_aptx_sym(void *handle )
256 aptx_new = (void* (*)(short endian))dlsym(handle, aptx_new_name);
259 pa_log_debug("Load Symbol(%s)", aptx_new_name);
261 pa_log_debug("Fail to Load Symbol(%s)", aptx_new_name);
265 aptx_encode = (int (*)(void* _state, void* _pcmL, void* _pcmR,
267 dlsym(handle, "aptxbtenc_encodestereo");
270 pa_log_debug("Load Symbol(%s)", aptx_encode_name);
272 pa_log_debug("Fail to Load Symbol(%s)", aptx_encode_name);
280 /* Run from main thread */
281 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
282 pa_device_port *port;
284 if (direction == PA_DIRECTION_OUTPUT) {
285 pa_sink_new_data *sink_new_data = new_data;
287 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
288 pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
289 pa_device_port_ref(port);
291 pa_source_new_data *source_new_data = new_data;
293 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
294 pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
295 pa_device_port_ref(port);
299 /* Run from IO thread */
300 static int sco_process_render(struct userdata *u) {
304 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
307 /* First, render some data */
308 if (!u->write_memchunk.memblock)
309 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
311 pa_assert(u->write_memchunk.length == u->write_block_size);
317 /* Now write that data to the socket. The socket is of type
318 * SEQPACKET, and we generated the data of the MTU size, so this
319 * should just work. */
321 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
322 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
323 pa_memblock_release(u->write_memchunk.memblock);
330 /* Retry right away if we got interrupted */
333 else if (errno == EAGAIN)
334 /* Hmm, apparently the socket was not writable, give up for now */
337 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
342 pa_assert((size_t) l <= u->write_memchunk.length);
344 if ((size_t) l != u->write_memchunk.length) {
345 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
346 (unsigned long long) l,
347 (unsigned long long) u->write_memchunk.length);
352 u->write_index += (uint64_t) u->write_memchunk.length;
353 pa_memblock_unref(u->write_memchunk.memblock);
354 pa_memchunk_reset(&u->write_memchunk);
363 /* Run from IO thread */
364 static int sco_process_push(struct userdata *u) {
366 pa_memchunk memchunk;
369 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
370 pa_assert(u->source);
371 pa_assert(u->read_smoother);
373 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
374 memchunk.index = memchunk.length = 0;
383 bool found_tstamp = false;
386 memset(&m, 0, sizeof(m));
387 memset(&aux, 0, sizeof(aux));
388 memset(&iov, 0, sizeof(iov));
393 m.msg_controllen = sizeof(aux);
395 p = pa_memblock_acquire(memchunk.memblock);
397 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
398 l = recvmsg(u->stream_fd, &m, 0);
399 pa_memblock_release(memchunk.memblock);
403 if (l < 0 && errno == EINTR)
404 /* Retry right away if we got interrupted */
407 else if (l < 0 && errno == EAGAIN)
408 /* Hmm, apparently the socket was not readable, give up for now. */
411 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
416 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
418 /* In some rare occasions, we might receive packets of a very strange
419 * size. This could potentially be possible if the SCO packet was
420 * received partially over-the-air, or more probably due to hardware
421 * issues in our Bluetooth adapter. In these cases, in order to avoid
422 * an assertion failure due to unaligned data, just discard the whole
424 if (!pa_frame_aligned(l, &u->sample_spec)) {
425 pa_log_warn("SCO packet received of unaligned size: %zu", l);
429 memchunk.length = (size_t) l;
430 u->read_index += (uint64_t) l;
432 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
433 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
434 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
435 pa_rtclock_from_wallclock(tv);
436 tstamp = pa_timeval_load(tv);
442 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
443 tstamp = pa_rtclock_now();
446 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
447 pa_smoother_resume(u->read_smoother, tstamp, true);
449 pa_source_post(u->source, &memchunk);
455 pa_memblock_unref(memchunk.memblock);
460 /* Run from IO thread */
461 static void a2dp_prepare_buffer(struct userdata *u) {
462 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
466 if (u->sbc_info.buffer_size >= min_buffer_size)
469 u->sbc_info.buffer_size = 2 * min_buffer_size;
470 pa_xfree(u->sbc_info.buffer);
471 u->sbc_info.buffer = pa_xmalloc(u->sbc_info.buffer_size);
474 /* Run from IO thread */
475 static int a2dp_process_render(struct userdata *u) {
476 struct sbc_info *sbc_info;
477 struct rtp_header *header;
478 struct rtp_payload *payload;
482 size_t to_write, to_encode;
483 unsigned frame_count;
487 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
490 /* First, render some data */
491 if (!u->write_memchunk.memblock)
492 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
494 pa_assert(u->write_memchunk.length == u->write_block_size);
496 a2dp_prepare_buffer(u);
498 sbc_info = &u->sbc_info;
499 header = sbc_info->buffer;
500 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
504 /* Try to create a packet of the full MTU */
506 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
507 to_encode = u->write_memchunk.length;
509 d = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
510 to_write = sbc_info->buffer_size - sizeof(*header) - sizeof(*payload);
512 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
516 encoded = sbc_encode(&sbc_info->sbc,
521 if (PA_UNLIKELY(encoded <= 0)) {
522 pa_log_error("SBC encoding error (%li)", (long) encoded);
523 pa_memblock_release(u->write_memchunk.memblock);
527 pa_assert_fp((size_t) encoded <= to_encode);
528 pa_assert_fp((size_t) encoded == sbc_info->codesize);
530 pa_assert_fp((size_t) written <= to_write);
531 pa_assert_fp((size_t) written == sbc_info->frame_length);
533 p = (const uint8_t*) p + encoded;
534 to_encode -= encoded;
536 d = (uint8_t*) d + written;
542 pa_memblock_release(u->write_memchunk.memblock);
544 pa_assert(to_encode == 0);
547 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
550 /* write it to the fifo */
551 memset(sbc_info->buffer, 0, sizeof(*header) + sizeof(*payload));
554 header->sequence_number = htons(sbc_info->seq_num++);
555 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
556 header->ssrc = htonl(1);
557 payload->frame_count = frame_count;
559 nbytes = (uint8_t*) d - (uint8_t*) sbc_info->buffer;
564 l = pa_write(u->stream_fd, sbc_info->buffer, nbytes, &u->stream_write_type);
571 /* Retry right away if we got interrupted */
574 else if (errno == EAGAIN)
575 /* Hmm, apparently the socket was not writable, give up for now */
578 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
583 pa_assert((size_t) l <= nbytes);
585 if ((size_t) l != nbytes) {
586 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
587 (unsigned long long) l,
588 (unsigned long long) nbytes);
593 u->write_index += (uint64_t) u->write_memchunk.length;
594 pa_memblock_unref(u->write_memchunk.memblock);
595 pa_memchunk_reset(&u->write_memchunk);
605 #ifdef BLUETOOTH_APTX_SUPPORT
606 /* Run from IO thread */
607 static int a2dp_aptx_process_render(struct userdata *u) {
608 struct sbc_info *a2dp;
612 size_t to_write, to_encode;
617 const uint8_t *mybuffer;
620 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_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 a2dp_prepare_buffer(u);
633 /* Try to create a packet of the full MTU */
634 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
635 to_encode = u->write_memchunk.length;
637 d = (uint8_t*) a2dp->buffer ;
638 to_write = a2dp->buffer_size;
640 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
644 mybuffer = (uint8_t *)p;
646 for (i = 0; i < 4; i += 1) {
647 pcmL[i] = mybuffer[2*i];
648 pcmR[i] = mybuffer[2*i+1];
650 /*(8 audio samples)16 bytes of audo data encoded to 4 bytes*/
651 aptx_encode(a2dp->aptx, pcmL, pcmR, (short*)d);
656 pa_assert_fp((size_t) encoded <= to_encode);
657 pa_assert_fp((size_t) written <= to_write);
659 p = (const uint8_t*) p + encoded;
660 to_encode -= encoded;
662 d = (uint8_t*) d + written;
667 pa_memblock_release(u->write_memchunk.memblock);
669 pa_assert(to_encode == 0);
672 pa_log_debug("Using APTX encoder implementation");
675 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
680 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
687 /* Retry right away if we got interrupted */
690 else if (errno == EAGAIN)
691 /* Hmm, apparently the socket was not writable, give up for now */
694 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
699 pa_assert((size_t) l <= nbytes);
701 if ((size_t) l != nbytes) {
702 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
703 (unsigned long long) l,
704 (unsigned long long) nbytes);
709 u->write_index += (uint64_t) u->write_memchunk.length;
710 pa_memblock_unref(u->write_memchunk.memblock);
711 pa_memchunk_reset(&u->write_memchunk);
721 /* Run from IO thread */
722 static int a2dp_process_null_render(struct userdata *u) {
724 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
727 /* First, render some data */
728 if (!u->write_memchunk.memblock)
729 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
731 pa_assert(u->write_memchunk.length == u->write_block_size);
733 u->write_index += (uint64_t) u->write_memchunk.length;
734 pa_memblock_unref(u->write_memchunk.memblock);
735 pa_memchunk_reset(&u->write_memchunk);
741 /* Run from IO thread */
742 static int a2dp_process_push(struct userdata *u) {
744 pa_memchunk memchunk;
747 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
748 pa_assert(u->source);
749 pa_assert(u->read_smoother);
751 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
752 memchunk.index = memchunk.length = 0;
755 bool found_tstamp = false;
757 struct sbc_info *sbc_info;
758 struct rtp_header *header;
759 struct rtp_payload *payload;
763 size_t to_write, to_decode;
765 a2dp_prepare_buffer(u);
767 sbc_info = &u->sbc_info;
768 header = sbc_info->buffer;
769 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
771 l = pa_read(u->stream_fd, sbc_info->buffer, sbc_info->buffer_size, &u->stream_write_type);
775 if (l < 0 && errno == EINTR)
776 /* Retry right away if we got interrupted */
779 else if (l < 0 && errno == EAGAIN)
780 /* Hmm, apparently the socket was not readable, give up for now. */
783 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
788 pa_assert((size_t) l <= sbc_info->buffer_size);
790 u->read_index += (uint64_t) l;
792 /* TODO: get timestamp from rtp */
794 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
795 tstamp = pa_rtclock_now();
798 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
799 pa_smoother_resume(u->read_smoother, tstamp, true);
801 p = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
802 to_decode = l - sizeof(*header) - sizeof(*payload);
804 d = pa_memblock_acquire(memchunk.memblock);
805 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
807 while (PA_LIKELY(to_decode > 0)) {
811 decoded = sbc_decode(&sbc_info->sbc,
816 if (PA_UNLIKELY(decoded <= 0)) {
817 pa_log_error("SBC decoding error (%li)", (long) decoded);
818 pa_memblock_release(memchunk.memblock);
819 pa_memblock_unref(memchunk.memblock);
823 /* Reset frame length, it can be changed due to bitpool change */
824 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
826 pa_assert_fp((size_t) decoded <= to_decode);
827 pa_assert_fp((size_t) decoded == sbc_info->frame_length);
829 pa_assert_fp((size_t) written == sbc_info->codesize);
831 p = (const uint8_t*) p + decoded;
832 to_decode -= decoded;
834 d = (uint8_t*) d + written;
838 memchunk.length -= to_write;
840 pa_memblock_release(memchunk.memblock);
842 pa_source_post(u->source, &memchunk);
848 pa_memblock_unref(memchunk.memblock);
853 /* Run from I/O thread */
854 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
855 struct sbc_info *sbc_info;
859 sbc_info = &u->sbc_info;
861 if (sbc_info->sbc.bitpool == bitpool)
864 if (bitpool > sbc_info->max_bitpool)
865 bitpool = sbc_info->max_bitpool;
866 else if (bitpool < sbc_info->min_bitpool)
867 bitpool = sbc_info->min_bitpool;
869 sbc_info->sbc.bitpool = bitpool;
871 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
872 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
874 pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
877 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
878 / sbc_info->frame_length * sbc_info->codesize;
880 u->write_block_size =
881 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
882 / sbc_info->frame_length * sbc_info->codesize;
884 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
885 pa_sink_set_fixed_latency_within_thread(u->sink,
886 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
889 /* Run from I/O thread */
890 static void a2dp_reduce_bitpool(struct userdata *u) {
891 struct sbc_info *sbc_info;
896 sbc_info = &u->sbc_info;
898 /* Check if bitpool is already at its limit */
899 if (sbc_info->sbc.bitpool <= BITPOOL_DEC_LIMIT)
902 bitpool = sbc_info->sbc.bitpool - BITPOOL_DEC_STEP;
904 if (bitpool < BITPOOL_DEC_LIMIT)
905 bitpool = BITPOOL_DEC_LIMIT;
907 a2dp_set_bitpool(u, bitpool);
910 static void teardown_stream(struct userdata *u) {
911 if (u->rtpoll_item) {
912 pa_rtpoll_item_free(u->rtpoll_item);
913 u->rtpoll_item = NULL;
916 if (u->stream_fd >= 0) {
917 pa_close(u->stream_fd);
921 if (u->read_smoother) {
922 pa_smoother_free(u->read_smoother);
923 u->read_smoother = NULL;
926 if (u->write_memchunk.memblock) {
927 pa_memblock_unref(u->write_memchunk.memblock);
928 pa_memchunk_reset(&u->write_memchunk);
931 pa_log_debug("Audio stream torn down");
934 static int transport_acquire(struct userdata *u, bool optional) {
935 pa_assert(u->transport);
937 if (u->transport_acquired)
940 pa_log_debug("Acquiring transport %s", u->transport->path);
942 u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
943 if (u->stream_fd < 0)
946 u->transport_acquired = true;
949 u->transport_suspended_by_remote = false;
951 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
956 static void transport_release(struct userdata *u) {
957 pa_assert(u->transport);
959 /* Ignore if already released */
960 if (!u->transport_acquired)
963 pa_log_debug("Releasing transport %s", u->transport->path);
965 u->transport->release(u->transport);
967 u->transport_acquired = false;
970 /* The below code would be less effect for most of case */
971 if (u->transport_suspended_by_remote)
972 pa_log_info("Released by remote suspend request");
975 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
976 u->transport->state = PA_BLUETOOTH_TRANSPORT_STATE_IDLE;
977 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_TRANSPORT_STATE_CHANGED, u, 0,
984 /* Run from I/O thread */
985 static void transport_config_mtu(struct userdata *u) {
986 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
987 u->read_block_size = u->read_link_mtu;
988 u->write_block_size = u->write_link_mtu;
990 } else if(u->sbc_info.sbc_initialized) {
995 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
996 / u->sbc_info.frame_length * u->sbc_info.codesize;
998 u->write_block_size =
999 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1000 / u->sbc_info.frame_length * u->sbc_info.codesize;
1004 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
1005 pa_sink_set_fixed_latency_within_thread(u->sink,
1006 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
1007 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
1008 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
1012 pa_source_set_fixed_latency_within_thread(u->source,
1013 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
1014 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
1015 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
1018 /* Run from I/O thread */
1019 static void setup_stream(struct userdata *u) {
1020 struct pollfd *pollfd;
1023 pa_log_info("Transport %s resuming", u->transport->path);
1025 transport_config_mtu(u);
1027 pa_make_fd_nonblock(u->stream_fd);
1028 pa_make_socket_low_delay(u->stream_fd);
1031 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
1032 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
1034 pa_log_debug("Stream properly set up, we're ready to roll!");
1036 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1037 a2dp_set_bitpool(u, u->sbc_info.max_bitpool);
1039 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
1040 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
1041 pollfd->fd = u->stream_fd;
1042 pollfd->events = pollfd->revents = 0;
1044 u->read_index = u->write_index = 0;
1048 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
1051 /* Run from IO thread */
1052 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1053 struct userdata *u = PA_SOURCE(o)->userdata;
1054 bool failed = false;
1057 pa_assert(u->source == PA_SOURCE(o));
1058 pa_assert(u->transport);
1062 case PA_SOURCE_MESSAGE_SET_STATE:
1064 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1066 case PA_SOURCE_SUSPENDED:
1067 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
1068 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1071 /* Stop the device if the sink is suspended as well */
1072 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
1073 transport_release(u);
1075 if (u->read_smoother)
1076 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1080 case PA_SOURCE_IDLE:
1081 case PA_SOURCE_RUNNING:
1082 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1085 /* Resume the device if the sink was suspended as well */
1086 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
1087 if (transport_acquire(u, false) < 0)
1093 /* We don't resume the smoother here. Instead we
1094 * wait until the first packet arrives */
1098 case PA_SOURCE_UNLINKED:
1099 case PA_SOURCE_INIT:
1100 case PA_SOURCE_INVALID_STATE:
1106 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1109 if (u->read_smoother) {
1110 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1111 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1113 *((pa_usec_t*) data) = FIXED_LATENCY_RECORD_A2DP + wi > ri ? FIXED_LATENCY_RECORD_A2DP + wi - ri : 0;
1115 *((pa_usec_t*) data) = 0;
1122 r = pa_source_process_msg(o, code, data, offset, chunk);
1124 return (r < 0 || !failed) ? r : -1;
1127 /* Run from main thread */
1128 static int add_source(struct userdata *u) {
1129 pa_source_new_data data;
1131 pa_assert(u->transport);
1133 pa_source_new_data_init(&data);
1134 data.module = u->module;
1135 data.card = u->card;
1136 data.driver = __FILE__;
1137 data.name = pa_sprintf_malloc("bluez_source.%s", u->device->address);
1138 data.namereg_fail = false;
1139 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1140 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1141 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1142 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1144 connect_ports(u, &data, PA_DIRECTION_INPUT);
1146 if (!u->transport_acquired)
1147 switch (u->profile) {
1148 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1149 case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1150 data.suspend_cause = PA_SUSPEND_USER;
1152 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1153 case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1154 case PA_BLUETOOTH_PROFILE_OFF:
1155 pa_assert_not_reached();
1159 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1160 pa_source_new_data_done(&data);
1162 pa_log_error("Failed to create source");
1166 u->source->userdata = u;
1167 u->source->parent.process_msg = source_process_msg;
1172 /* Run from IO thread */
1173 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1174 struct userdata *u = PA_SINK(o)->userdata;
1175 bool failed = false;
1178 pa_assert(u->sink == PA_SINK(o));
1179 pa_assert(u->transport);
1183 case PA_SINK_MESSAGE_SET_STATE:
1185 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
1187 case PA_SINK_SUSPENDED:
1188 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1189 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
1192 /* Stop the device if the source is suspended as well */
1193 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1194 /* We deliberately ignore whether stopping
1195 * actually worked. Since the stream_fd is
1196 * closed it doesn't really matter */
1197 transport_release(u);
1202 case PA_SINK_RUNNING:
1203 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1206 /* Wait until PA_BLUETOOTH_TRANSPORT_IDLE */
1207 if ((u->transport != NULL) && (u->transport->state ==
1208 PA_BLUETOOTH_TRANSPORT_STATE_IDLE))
1209 pa_log_info("This is good time for(%d)",
1210 (pa_sink_state_t) PA_PTR_TO_UINT(data));
1212 pa_log_info("Wait for PA_BLUETOOTH_TRANSPORT_STATE_IDLE");
1214 /* Resume the device if the source was suspended as well */
1215 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
1216 if (transport_acquire(u, false) < 0)
1224 case PA_SINK_UNLINKED:
1226 case PA_SINK_INVALID_STATE:
1232 case PA_SINK_MESSAGE_GET_LATENCY: {
1235 if (u->read_smoother) {
1236 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1237 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
1239 ri = pa_rtclock_now() - u->started_at;
1240 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1243 *((pa_usec_t*) data) = FIXED_LATENCY_PLAYBACK_A2DP + wi > ri ? FIXED_LATENCY_PLAYBACK_A2DP + wi - ri : 0;
1249 r = pa_sink_process_msg(o, code, data, offset, chunk);
1251 return (r < 0 || !failed) ? r : -1;
1254 /* Run from main thread */
1255 static int add_sink(struct userdata *u) {
1256 pa_sink_new_data data;
1258 pa_assert(u->transport);
1260 pa_sink_new_data_init(&data);
1261 data.module = u->module;
1262 data.card = u->card;
1263 data.driver = __FILE__;
1264 data.name = pa_sprintf_malloc("bluez_sink.%s", u->device->address);
1265 data.namereg_fail = false;
1266 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1267 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1268 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1269 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1271 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1273 if (!u->transport_acquired)
1274 switch (u->profile) {
1275 case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1276 data.suspend_cause = PA_SUSPEND_USER;
1278 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1279 /* Profile switch should have failed */
1280 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1281 case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1282 case PA_BLUETOOTH_PROFILE_OFF:
1283 pa_assert_not_reached();
1287 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1288 pa_sink_new_data_done(&data);
1290 pa_log_error("Failed to create sink");
1294 u->sink->userdata = u;
1295 u->sink->parent.process_msg = sink_process_msg;
1300 #ifdef BLUETOOTH_APTX_SUPPORT
1301 /* should be implemeted */
1302 static void bt_transport_config_a2dp_for_aptx(struct userdata *u) {
1303 const pa_bluetooth_transport *t;
1304 struct sbc_info *a2dp = &u->sbc_info;
1309 u->sample_spec.format = PA_SAMPLE_S16LE;
1311 if (!a2dp->aptx_initialized) {
1312 #if __BYTE_ORDER==__LITTLE_ENDIAN
1313 a2dp->aptx = aptx_new(1);
1314 #elif __BYTE_ORDER==__BIG_ENDIAN
1315 a2dp->aptx = aptx_new(0);
1317 #error "Unknown byte order"
1319 a2dp->aptx_initialized = true;
1322 pa_log_debug("aptx Encoder is intialized !!");
1324 u->write_block_size =(size_t)(u->write_link_mtu/(size_t)16) *16*4 ;
1325 pa_log_info("APTX parameters block_size(%d),link_mtu(%d)",u->write_block_size,u->write_link_mtu);
1330 /* Run from main thread */
1331 static void transport_config(struct userdata *u) {
1332 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1333 u->sample_spec.format = PA_SAMPLE_S16LE;
1334 u->sample_spec.channels = 1;
1335 u->sample_spec.rate = 8000;
1337 sbc_info_t *sbc_info = &u->sbc_info;
1339 #ifdef BLUETOOTH_APTX_SUPPORT
1340 const pa_bluetooth_transport *t;
1341 a2dp_aptx_t *aptx_config;
1344 pa_assert(u->transport);
1346 #ifdef BLUETOOTH_APTX_SUPPORT
1348 if (t->codec == A2DP_CODEC_VENDOR) {
1349 aptx_config = (a2dp_aptx_t *) t->config;
1350 if (aptx_config->vendor_id[0] == APTX_VENDOR_ID0 &&
1351 aptx_config->vendor_id[1] == APTX_VENDOR_ID1 &&
1352 aptx_config->vendor_id[2] == APTX_VENDOR_ID2 &&
1353 aptx_config->vendor_id[3] == APTX_VENDOR_ID3 &&
1354 aptx_config->codec_id[0] == APTX_CODEC_ID0 &&
1355 aptx_config->codec_id[1] == APTX_CODEC_ID1 ){
1356 pa_log("A2DP_CODEC_NON_A2DP and this is APTX Codec");
1358 bt_transport_config_a2dp_for_aptx(u);
1361 pa_log("A2DP_CODEC_NON_A2DP but this is not APTX Codec");
1367 u->sample_spec.format = PA_SAMPLE_S16LE;
1368 config = (a2dp_sbc_t *) u->transport->config;
1370 if (sbc_info->sbc_initialized)
1371 sbc_reinit(&sbc_info->sbc, 0);
1373 sbc_init(&sbc_info->sbc, 0);
1374 sbc_info->sbc_initialized = true;
1376 switch (config->frequency) {
1377 case SBC_SAMPLING_FREQ_16000:
1378 sbc_info->sbc.frequency = SBC_FREQ_16000;
1379 u->sample_spec.rate = 16000U;
1381 case SBC_SAMPLING_FREQ_32000:
1382 sbc_info->sbc.frequency = SBC_FREQ_32000;
1383 u->sample_spec.rate = 32000U;
1385 case SBC_SAMPLING_FREQ_44100:
1386 sbc_info->sbc.frequency = SBC_FREQ_44100;
1387 u->sample_spec.rate = 44100U;
1389 case SBC_SAMPLING_FREQ_48000:
1390 sbc_info->sbc.frequency = SBC_FREQ_48000;
1391 u->sample_spec.rate = 48000U;
1394 pa_assert_not_reached();
1397 switch (config->channel_mode) {
1398 case SBC_CHANNEL_MODE_MONO:
1399 sbc_info->sbc.mode = SBC_MODE_MONO;
1400 u->sample_spec.channels = 1;
1402 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1403 sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1404 u->sample_spec.channels = 2;
1406 case SBC_CHANNEL_MODE_STEREO:
1407 sbc_info->sbc.mode = SBC_MODE_STEREO;
1408 u->sample_spec.channels = 2;
1410 case SBC_CHANNEL_MODE_JOINT_STEREO:
1411 sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
1412 u->sample_spec.channels = 2;
1415 pa_assert_not_reached();
1418 switch (config->allocation_method) {
1419 case SBC_ALLOCATION_SNR:
1420 sbc_info->sbc.allocation = SBC_AM_SNR;
1422 case SBC_ALLOCATION_LOUDNESS:
1423 sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
1426 pa_assert_not_reached();
1429 switch (config->subbands) {
1430 case SBC_SUBBANDS_4:
1431 sbc_info->sbc.subbands = SBC_SB_4;
1433 case SBC_SUBBANDS_8:
1434 sbc_info->sbc.subbands = SBC_SB_8;
1437 pa_assert_not_reached();
1440 switch (config->block_length) {
1441 case SBC_BLOCK_LENGTH_4:
1442 sbc_info->sbc.blocks = SBC_BLK_4;
1444 case SBC_BLOCK_LENGTH_8:
1445 sbc_info->sbc.blocks = SBC_BLK_8;
1447 case SBC_BLOCK_LENGTH_12:
1448 sbc_info->sbc.blocks = SBC_BLK_12;
1450 case SBC_BLOCK_LENGTH_16:
1451 sbc_info->sbc.blocks = SBC_BLK_16;
1454 pa_assert_not_reached();
1457 sbc_info->min_bitpool = config->min_bitpool;
1458 sbc_info->max_bitpool = config->max_bitpool;
1460 /* Set minimum bitpool for source to get the maximum possible block_size */
1461 sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
1462 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
1463 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
1465 pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
1466 sbc_info->sbc.allocation, sbc_info->sbc.subbands, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
1470 /* Run from main thread */
1471 static int setup_transport(struct userdata *u) {
1472 pa_bluetooth_transport *t;
1475 pa_assert(!u->transport);
1476 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1478 /* check if profile has a transport */
1479 t = u->device->transports[u->profile];
1480 if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1481 pa_log_warn("Profile has no transport");
1487 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1488 transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1489 else if (transport_acquire(u, false) < 0)
1490 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1492 transport_config(u);
1497 /* Run from main thread */
1498 static int init_profile(struct userdata *u) {
1501 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1503 if (setup_transport(u) < 0)
1506 pa_assert(u->transport);
1508 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
1509 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1510 if (add_sink(u) < 0)
1513 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
1514 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1515 if (add_source(u) < 0)
1521 /* I/O thread function */
1522 static void thread_func(void *userdata) {
1523 struct userdata *u = userdata;
1524 unsigned do_write = 0;
1525 unsigned pending_read_bytes = 0;
1526 bool writable = false;
1529 pa_assert(u->transport);
1531 pa_log_debug("IO Thread starting up");
1533 if (u->core->realtime_scheduling)
1534 pa_make_realtime(u->core->realtime_priority);
1536 pa_thread_mq_install(&u->thread_mq);
1538 /* Setup the stream only if the transport was already acquired */
1539 if (u->transport_acquired)
1543 struct pollfd *pollfd;
1545 bool disable_timer = true;
1547 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1549 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1550 pa_log_info("FD error: %s%s%s%s",
1551 pollfd->revents & POLLERR ? "POLLERR " :"",
1552 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1553 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1554 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1555 if (pollfd->revents & POLLHUP) {
1558 pending_read_bytes = 0;
1560 transport_release(u);
1565 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1567 /* We should send two blocks to the device before we expect
1570 if (u->write_index == 0 && u->read_index <= 0)
1573 if (pollfd && (pollfd->revents & POLLIN)) {
1576 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1577 n_read = sco_process_push(u);
1579 n_read = a2dp_process_push(u);
1588 /* We just read something, so we are supposed to write something, too */
1589 pending_read_bytes += n_read;
1590 do_write += pending_read_bytes / u->write_block_size;
1591 pending_read_bytes = pending_read_bytes % u->write_block_size;
1595 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1597 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1598 pa_sink_process_rewind(u->sink, 0);
1601 if (pollfd->revents & POLLOUT)
1604 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1605 pa_usec_t time_passed;
1606 pa_usec_t audio_sent;
1608 /* Hmm, there is no input stream we could synchronize
1609 * to. So let's do things by time */
1611 time_passed = pa_rtclock_now() - u->started_at;
1612 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1614 if (audio_sent <= time_passed) {
1615 pa_usec_t audio_to_send = time_passed - audio_sent;
1617 /* Never try to catch up for more than 100ms */
1618 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1619 pa_usec_t skip_usec;
1620 uint64_t skip_bytes;
1622 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1623 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1625 if (skip_bytes > 0) {
1628 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1629 (unsigned long long) skip_usec,
1630 (unsigned long long) skip_bytes);
1632 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1633 pa_memblock_unref(tmp.memblock);
1634 u->write_index += skip_bytes;
1636 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1637 a2dp_reduce_bitpool(u);
1642 pending_read_bytes = 0;
1646 if (writable && do_write > 0) {
1649 if (u->write_index <= 0)
1650 u->started_at = pa_rtclock_now();
1652 if ((u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) &&
1653 !u->transport_suspended_by_remote) {
1654 if(u->sbc_info.sbc_initialized) {
1655 if ((n_written = a2dp_process_render(u)) < 0)
1658 if ((n_written = a2dp_aptx_process_render(u)) < 0)
1661 } else if ((u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) &&
1662 u->transport_suspended_by_remote) {
1663 a2dp_process_null_render(u);
1665 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ) {
1666 if ((n_written = a2dp_process_render(u)) < 0)
1670 if ((n_written = sco_process_render(u)) < 0)
1679 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1681 do_write -= n_written;
1685 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1686 pa_usec_t sleep_for;
1687 pa_usec_t time_passed, next_write_at;
1690 /* Hmm, there is no input stream we could synchronize
1691 * to. So let's estimate when we need to wake up the latest */
1692 time_passed = pa_rtclock_now() - u->started_at;
1693 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1694 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1695 /* 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); */
1697 /* drop stream every 500 ms */
1698 sleep_for = PA_USEC_PER_MSEC * 500;
1700 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1701 disable_timer = false;
1707 pa_rtpoll_set_timer_disabled(u->rtpoll);
1709 /* Hmm, nothing to do. Let's sleep */
1711 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1712 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1714 if ((ret = pa_rtpoll_run(u->rtpoll, true)) < 0) {
1715 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1720 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1721 transport_release(u);
1725 #ifndef __TIZEN_BT__
1726 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1728 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1729 pa_log_info("FD error: %s%s%s%s",
1730 pollfd->revents & POLLERR ? "POLLERR " :"",
1731 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1732 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1733 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1740 /* In case of HUP, just tear down the streams */
1741 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1745 pending_read_bytes = 0;
1748 transport_release(u);
1754 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1755 pa_log_debug("IO thread failed");
1756 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1757 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1760 pa_log_debug("IO thread shutting down");
1763 /* Run from main thread */
1764 static int start_thread(struct userdata *u) {
1766 pa_assert(!u->thread);
1767 pa_assert(!u->rtpoll);
1768 pa_assert(!u->rtpoll_item);
1770 u->rtpoll = pa_rtpoll_new();
1771 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1773 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1774 pa_log_error("Failed to create IO thread");
1779 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1780 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1781 pa_sink_put(u->sink);
1783 if (u->sink->set_volume)
1784 u->sink->set_volume(u->sink);
1788 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1789 pa_source_set_rtpoll(u->source, u->rtpoll);
1790 pa_source_put(u->source);
1792 if (u->source->set_volume)
1793 u->source->set_volume(u->source);
1799 /* Run from main thread */
1800 static void stop_thread(struct userdata *u) {
1804 pa_sink_unlink(u->sink);
1807 pa_source_unlink(u->source);
1810 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1811 pa_thread_free(u->thread);
1815 if (u->rtpoll_item) {
1816 pa_rtpoll_item_free(u->rtpoll_item);
1817 u->rtpoll_item = NULL;
1821 pa_rtpoll_free(u->rtpoll);
1823 pa_thread_mq_done(&u->thread_mq);
1827 transport_release(u);
1828 u->transport = NULL;
1832 pa_sink_unref(u->sink);
1837 pa_source_unref(u->source);
1841 if (u->read_smoother) {
1842 pa_smoother_free(u->read_smoother);
1843 u->read_smoother = NULL;
1847 /* Run from main thread */
1848 static char *cleanup_name(const char *name) {
1854 while ((*name >= 1 && *name <= 32) || *name >= 127)
1857 t = pa_xstrdup(name);
1859 for (s = d = t; *s; s++) {
1861 if (*s <= 32 || *s >= 127 || *s == '_') {
1879 /* Run from main thread */
1880 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1881 static const pa_direction_t profile_direction[] = {
1882 [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1883 [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1884 [PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1885 [PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1886 [PA_BLUETOOTH_PROFILE_OFF] = 0
1889 return profile_direction[p];
1892 /* Run from main thread */
1893 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1894 pa_available_t result = PA_AVAILABLE_NO;
1898 pa_assert(u->device);
1900 for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1901 pa_bluetooth_transport *transport;
1903 if (!(get_profile_direction(i) & direction))
1906 if (!(transport = u->device->transports[i]))
1909 switch(transport->state) {
1910 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1913 case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1914 if (result == PA_AVAILABLE_NO)
1915 result = PA_AVAILABLE_UNKNOWN;
1919 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1920 return PA_AVAILABLE_YES;
1927 /* Run from main thread */
1928 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1930 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1931 return PA_AVAILABLE_NO;
1932 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1933 return PA_AVAILABLE_YES;
1935 return PA_AVAILABLE_UNKNOWN;
1939 /* Run from main thread */
1940 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1941 pa_device_port *port;
1942 pa_device_port_new_data port_data;
1944 const char *name_prefix, *input_description, *output_description;
1948 pa_assert(u->device);
1950 name_prefix = "unknown";
1951 input_description = _("Bluetooth Input");
1952 output_description = _("Bluetooth Output");
1954 switch (form_factor_from_class(u->device->class_of_device)) {
1955 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1956 name_prefix = "headset";
1957 input_description = output_description = _("Headset");
1960 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1961 name_prefix = "handsfree";
1962 input_description = output_description = _("Handsfree");
1965 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1966 name_prefix = "microphone";
1967 input_description = _("Microphone");
1968 output_description = _("Bluetooth Output");
1971 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1972 name_prefix = "speaker";
1973 input_description = _("Bluetooth Input");
1974 output_description = _("Speaker");
1977 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1978 name_prefix = "headphone";
1979 input_description = _("Bluetooth Input");
1980 output_description = _("Headphone");
1983 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1984 name_prefix = "portable";
1985 input_description = output_description = _("Portable");
1988 case PA_BLUETOOTH_FORM_FACTOR_CAR:
1989 name_prefix = "car";
1990 input_description = output_description = _("Car");
1993 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1994 name_prefix = "hifi";
1995 input_description = output_description = _("HiFi");
1998 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1999 name_prefix = "phone";
2000 input_description = output_description = _("Phone");
2003 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
2004 name_prefix = "unknown";
2005 input_description = _("Bluetooth Input");
2006 output_description = _("Bluetooth Output");
2010 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
2011 pa_device_port_new_data_init(&port_data);
2012 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
2013 pa_device_port_new_data_set_description(&port_data, output_description);
2014 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
2015 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
2016 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2017 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2018 pa_device_port_new_data_done(&port_data);
2020 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
2021 pa_device_port_new_data_init(&port_data);
2022 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
2023 pa_device_port_new_data_set_description(&port_data, input_description);
2024 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
2025 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
2026 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2027 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2028 pa_device_port_new_data_done(&port_data);
2031 /* Run from main thread */
2032 static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid, pa_hashmap *ports) {
2033 pa_device_port *input_port, *output_port;
2034 pa_card_profile *cp = NULL;
2035 pa_bluetooth_profile_t *p;
2037 pa_assert(u->input_port_name);
2038 pa_assert(u->output_port_name);
2039 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2040 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2042 if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
2043 /* TODO: Change this profile's name to a2dp_sink, to reflect the remote
2044 * device's role and be consistent with the a2dp source profile */
2045 cp = pa_card_profile_new("a2dp_sink", _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
2049 cp->max_sink_channels = 2;
2050 cp->max_source_channels = 0;
2051 pa_hashmap_put(output_port->profiles, cp->name, cp);
2053 p = PA_CARD_PROFILE_DATA(cp);
2054 *p = PA_BLUETOOTH_PROFILE_A2DP_SINK;
2055 } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
2056 cp = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
2060 cp->max_sink_channels = 0;
2061 cp->max_source_channels = 2;
2062 pa_hashmap_put(input_port->profiles, cp->name, cp);
2064 p = PA_CARD_PROFILE_DATA(cp);
2065 *p = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
2066 #ifndef __TIZEN_BT__
2067 } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_HS) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF)) {
2068 /* TODO: Change this profile's name to headset_head_unit, to reflect the remote
2069 * device's role and be consistent with the other profiles */
2070 cp = pa_card_profile_new("hsp", _("Headset Head Unit (HSP/HFP)"), sizeof(enum profile));
2074 cp->max_sink_channels = 1;
2075 cp->max_source_channels = 1;
2076 pa_hashmap_put(input_port->profiles, cp->name, cp);
2077 pa_hashmap_put(output_port->profiles, cp->name, cp);
2079 p = PA_CARD_PROFILE_DATA(cp);
2080 *p = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
2081 } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG)) {
2082 /* TODO: Change this profile's name to headset_audio_gateway, to reflect the remote
2083 * device's role and be consistent with the other profiles */
2084 cp = pa_card_profile_new("hfgw", _("Headset Audio Gateway (HSP/HFP)"), sizeof(enum profile));
2088 cp->max_sink_channels = 1;
2089 cp->max_source_channels = 1;
2090 pa_hashmap_put(input_port->profiles, cp->name, cp);
2091 pa_hashmap_put(output_port->profiles, cp->name, cp);
2093 p = PA_CARD_PROFILE_DATA(cp);
2094 *p = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
2098 if (cp && u->device->transports[*p])
2099 cp->available = transport_state_to_availability(u->device->transports[*p]->state);
2104 /* Run from main thread */
2105 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
2107 pa_bluetooth_profile_t *p;
2110 pa_assert(new_profile);
2111 pa_assert_se(u = c->userdata);
2113 p = PA_CARD_PROFILE_DATA(new_profile);
2115 if (*p != PA_BLUETOOTH_PROFILE_OFF) {
2116 const pa_bluetooth_device *d = u->device;
2118 if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2119 pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
2128 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2129 if (init_profile(u) < 0)
2132 if (u->sink || u->source)
2133 if (start_thread(u) < 0)
2141 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2146 /* Run from main thread */
2147 static int add_card(struct userdata *u) {
2148 const pa_bluetooth_device *d;
2149 pa_card_new_data data;
2151 pa_bluetooth_form_factor_t ff;
2152 pa_card_profile *cp;
2153 pa_bluetooth_profile_t *p;
2157 const char *default_profile;
2161 pa_assert(u->device);
2165 pa_card_new_data_init(&data);
2166 data.driver = __FILE__;
2167 data.module = u->module;
2169 alias = cleanup_name(d->alias);
2170 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2173 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2174 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2175 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2176 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2178 if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2179 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2181 pa_proplist_sets(data.proplist, "bluez.path", d->path);
2182 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2183 pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2184 data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2185 data.namereg_fail = false;
2187 create_card_ports(u, data.ports);
2189 PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2190 cp = create_card_profile(u, uuid, data.ports);
2195 if (pa_hashmap_get(data.profiles, cp->name)) {
2196 pa_card_profile_free(cp);
2200 pa_hashmap_put(data.profiles, cp->name, cp);
2203 pa_assert(!pa_hashmap_isempty(data.profiles));
2205 cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2206 cp->available = PA_AVAILABLE_YES;
2207 p = PA_CARD_PROFILE_DATA(cp);
2208 *p = PA_BLUETOOTH_PROFILE_OFF;
2209 pa_hashmap_put(data.profiles, cp->name, cp);
2210 pa_card_new_data_set_profile(&data, "off");
2213 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2214 pa_log_debug("default_profile: %s", default_profile);
2216 if (pa_hashmap_get(data.profiles, default_profile))
2217 pa_card_new_data_set_profile(&data, default_profile);
2219 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2223 u->card = pa_card_new(u->core, &data);
2224 pa_card_new_data_done(&data);
2226 pa_log("Failed to allocate card.");
2230 u->card->userdata = u;
2231 u->card->set_profile = set_profile_cb;
2233 p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2239 /* Run from main thread */
2240 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2241 bool acquire = false;
2242 bool release = false;
2243 pa_card_profile *cp;
2244 pa_device_port *port;
2249 /* Update profile availability */
2250 if (!(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile))))
2252 pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2254 /* Update port availability */
2255 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2256 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2257 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2258 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2260 /* Acquire or release transport as needed */
2261 acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2262 release = (t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2264 if (acquire && transport_acquire(u, true) >= 0) {
2266 pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2268 /* We remove the IDLE suspend cause, because otherwise
2269 * module-loopback doesn't uncork its streams. FIXME: Messing with
2270 * the IDLE suspend cause here is wrong, the correct way to handle
2271 * this would probably be to uncork the loopback streams not only
2272 * when the other end is unsuspended, but also when the other end's
2273 * suspend cause changes to IDLE only (currently there's no
2274 * notification mechanism for suspend cause changes, though). */
2275 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2279 pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2282 u->transport_suspended_by_remote = false;
2284 /* FIXME: See the previous comment. */
2285 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2289 if (release && u->transport_acquired) {
2290 /* FIXME: this release is racy, since the audio stream might have
2291 * been set up again in the meantime (but not processed yet by PA).
2292 * BlueZ should probably release the transport automatically, and in
2293 * that case we would just mark the transport as released */
2295 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2297 pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2298 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2302 pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2304 /* if we change PA state as Suspend, PA client application
2305 * such as music app would face lock-up */
2306 u->transport_suspended_by_remote = true;
2308 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2314 /* Run from main thread */
2315 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2319 if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
2322 pa_log_debug("Unloading module for device %s", d->path);
2323 pa_module_unload(u->core, u->module, true);
2329 void dbus_sco_open_handler(struct userdata *u, struct pa_bluetooth_transport *t)
2332 pa_log_info("Suspending sink %s to handle the SCO connection", u->sink->name);
2334 pa_sink *sink_null = NULL;
2338 if (pa_sink_check_suspend(u->sink) > 0) {
2339 sink_null = (pa_sink *)pa_namereg_get(u->core, "null", 0);
2343 PA_IDXSET_FOREACH(si, u->core->sink_inputs, idx) {
2344 pa_sink_input_move_to(si, sink_null, false);
2349 pa_sink_suspend(u->sink, true, PA_SUSPEND_INTERNAL);
2353 /* Run from main thread */
2354 static pa_hook_result_t sco_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2358 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2361 if (t->device == u->device)
2362 dbus_sco_open_handler(u, t);
2368 /* Run from main thread */
2369 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2373 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2374 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2376 if (t->device == u->device)
2377 handle_transport_state_change(u, t);
2382 /* Run from main thread context */
2383 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2384 struct bluetooth_msg *b = BLUETOOTH_MSG(obj);
2385 struct userdata *u = data;
2388 case BLUETOOTH_MESSAGE_TRANSPORT_STATE_CHANGED:
2389 handle_transport_state_change(u, u->transport);
2391 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2392 if (b->card->module->unload_requested)
2395 pa_log_debug("Switching the profile to off due to IO thread failure.");
2396 pa_assert_se(pa_card_set_profile(b->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2403 int pa__init(pa_module* m) {
2407 #ifdef BLUETOOTH_APTX_SUPPORT
2413 m->userdata = u = pa_xnew0(struct userdata, 1);
2417 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2418 pa_log_error("Failed to parse module arguments");
2423 u->sample_spec = m->core->default_sample_spec;
2427 if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2428 pa_log_error("Failed to get device path from module arguments");
2432 if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2433 pa_bluetooth_discovery_ref(u->discovery);
2435 pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2439 if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2440 pa_log_error("%s is unknown", path);
2444 #ifndef __TIZEN_BT__
2445 pa_modargs_free(ma);
2448 u->device_connection_changed_slot =
2449 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2450 PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2452 u->transport_state_changed_slot =
2453 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2454 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2456 u->sco_state_changed_slot =
2457 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_SCO_STATE_CHANGED),
2458 PA_HOOK_NORMAL, (pa_hook_cb_t) sco_state_changed_cb, u);
2461 if (add_card(u) < 0)
2465 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2468 u->msg->parent.process_msg = device_process_msg;
2469 u->msg->card = u->card;
2471 #ifdef BLUETOOTH_APTX_SUPPORT
2472 handle = pa_aptx_get_handle();
2475 pa_log_debug("Aptx Library loaded\n");
2476 pa_load_aptx_sym(handle);
2480 pa_modargs_free(ma);
2483 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2484 if (init_profile(u) < 0)
2487 if (u->sink || u->source)
2488 if (start_thread(u) < 0)
2496 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2503 pa_modargs_free(ma);
2510 void pa__done(pa_module *m) {
2515 if (!(u = m->userdata))
2520 if (u->device_connection_changed_slot)
2521 pa_hook_slot_free(u->device_connection_changed_slot);
2523 if (u->transport_state_changed_slot)
2524 pa_hook_slot_free(u->transport_state_changed_slot);
2526 if (u->sco_state_changed_slot)
2527 pa_hook_slot_free(u->sco_state_changed_slot);
2530 if (u->sbc_info.buffer)
2531 pa_xfree(u->sbc_info.buffer);
2533 if (u->sbc_info.sbc_initialized)
2534 sbc_finish(&u->sbc_info.sbc);
2540 pa_card_free(u->card);
2543 pa_bluetooth_discovery_unref(u->discovery);
2545 pa_xfree(u->output_port_name);
2546 pa_xfree(u->input_port_name);
2551 int pa__get_n_used(pa_module *m) {
2555 pa_assert_se(u = m->userdata);
2557 return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);