2 This file is part of PulseAudio.
4 Copyright 2008-2013 João Paulo Rechi Vita
5 Copyright 2011-2013 BMW Car IT GmbH.
7 PulseAudio is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 PulseAudio is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
27 #include <arpa/inet.h>
30 #include <pulse/rtclock.h>
31 #include <pulse/timeval.h>
32 #include <pulse/utf8.h>
34 #include <pulsecore/core-error.h>
35 #include <pulsecore/core-rtclock.h>
36 #include <pulsecore/core-util.h>
37 #include <pulsecore/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.h>
40 #include <pulsecore/poll.h>
41 #include <pulsecore/rtpoll.h>
42 #include <pulsecore/shared.h>
43 #include <pulsecore/socket-util.h>
44 #include <pulsecore/thread.h>
45 #include <pulsecore/thread-mq.h>
46 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/sink.h>
50 #include <pulsecore/namereg.h>
53 #include "a2dp-codecs.h"
54 #include "bluez5-util.h"
57 #include "module-bluez5-device-symdef.h"
59 #ifdef BLUETOOTH_APTX_SUPPORT
63 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(false);
67 PA_MODULE_USAGE("path=<device object path>"
68 "autodetect_mtu=<boolean>");
70 #define MAX_PLAYBACK_CATCH_UP_USEC (100 * PA_USEC_PER_MSEC)
71 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
72 #define FIXED_LATENCY_PLAYBACK_SCO (125 * PA_USEC_PER_MSEC)
73 #define FIXED_LATENCY_RECORD_A2DP (25 * PA_USEC_PER_MSEC)
74 #define FIXED_LATENCY_RECORD_SCO (25 * PA_USEC_PER_MSEC)
76 #define BITPOOL_DEC_LIMIT 32
77 #define BITPOOL_DEC_STEP 5
78 #define HSP_MAX_GAIN 15
80 static const char* const valid_modargs[] = {
91 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
92 BLUETOOTH_MESSAGE_STREAM_FD_HUP,
97 PA_SOURCE_MESSAGE_SETUP_STREAM = PA_SOURCE_MESSAGE_MAX,
101 PA_SINK_MESSAGE_SETUP_STREAM = PA_SINK_MESSAGE_MAX,
104 typedef struct bluetooth_msg {
108 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
109 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
111 typedef struct sbc_info {
112 sbc_t sbc; /* Codec data */
113 bool sbc_initialized; /* Keep track if the encoder is initialized */
114 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
115 uint16_t seq_num; /* Cumulative packet sequence */
118 #ifdef BLUETOOTH_APTX_SUPPORT
119 bool aptx_initialized; /* Keep track if the encoder is initialized */
120 void *aptx; /* aptx Codec data */
122 void* buffer; /* Codec transfer buffer */
123 size_t buffer_size; /* Size of the buffer */
130 pa_hook_slot *device_connection_changed_slot;
131 pa_hook_slot *transport_state_changed_slot;
133 pa_hook_slot *sco_state_changed_slot;
134 #ifdef TIZEN_BT_AVC_TARGET
135 pa_hook_slot *avc_mode_changed_slot;
138 pa_hook_slot *transport_speaker_gain_changed_slot;
139 pa_hook_slot *transport_microphone_gain_changed_slot;
141 pa_bluetooth_discovery *discovery;
142 pa_bluetooth_device *device;
143 pa_bluetooth_transport *transport;
144 bool transport_acquired;
145 bool stream_setup_done;
148 bool transport_suspended_by_remote;
153 pa_bluetooth_profile_t profile;
154 char *output_port_name;
155 char *input_port_name;
158 pa_thread_mq thread_mq;
160 pa_rtpoll_item *rtpoll_item;
164 int stream_write_type;
165 size_t read_link_mtu;
166 size_t write_link_mtu;
167 size_t read_block_size;
168 size_t write_block_size;
170 uint64_t write_index;
171 pa_usec_t started_at;
172 pa_smoother *read_smoother;
173 pa_memchunk write_memchunk;
174 pa_sample_spec sample_spec;
175 struct sbc_info sbc_info;
182 typedef enum pa_bluetooth_form_factor {
183 PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
184 PA_BLUETOOTH_FORM_FACTOR_HEADSET,
185 PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
186 PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
187 PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
188 PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
189 PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
190 PA_BLUETOOTH_FORM_FACTOR_CAR,
191 PA_BLUETOOTH_FORM_FACTOR_HIFI,
192 PA_BLUETOOTH_FORM_FACTOR_PHONE,
193 } pa_bluetooth_form_factor_t;
195 /* Run from main thread */
196 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
197 unsigned major, minor;
198 pa_bluetooth_form_factor_t r;
200 static const pa_bluetooth_form_factor_t table[] = {
201 [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
202 [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
203 [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
204 [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
205 [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
206 [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
207 [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
208 [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
212 * See Bluetooth Assigned Numbers:
213 * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
215 major = (class_of_device >> 8) & 0x1F;
216 minor = (class_of_device >> 2) & 0x3F;
220 return PA_BLUETOOTH_FORM_FACTOR_PHONE;
224 pa_log_debug("Unknown Bluetooth major device class %u", major);
225 return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
228 r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
231 pa_log_debug("Unknown Bluetooth minor device class %u", minor);
236 /* Run from main thread */
237 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
239 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
241 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
243 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
245 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
247 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
249 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
251 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
253 case PA_BLUETOOTH_FORM_FACTOR_CAR:
255 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
257 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
261 pa_assert_not_reached();
264 #ifdef BLUETOOTH_APTX_SUPPORT
265 void* (*aptx_new)(short endian);
266 int (*aptx_encode)(void* _state, void* _pcmL, void* _pcmR, void* _buffer);
268 const char *aptx_new_name = "NewAptxEnc";
269 const char *aptx_encode_name = "aptxbtenc_encodestereo";
271 static bool pa_load_aptx_sym(void *handle )
276 aptx_new = (void* (*)(short endian))dlsym(handle, aptx_new_name);
279 pa_log_debug("Load Symbol(%s)", aptx_new_name);
281 pa_log_debug("Fail to Load Symbol(%s)", aptx_new_name);
285 aptx_encode = (int (*)(void* _state, void* _pcmL, void* _pcmR,
287 dlsym(handle, "aptxbtenc_encodestereo");
290 pa_log_debug("Load Symbol(%s)", aptx_encode_name);
292 pa_log_debug("Fail to Load Symbol(%s)", aptx_encode_name);
300 /* Run from main thread */
301 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
302 pa_device_port *port;
304 if (direction == PA_DIRECTION_OUTPUT) {
305 pa_sink_new_data *sink_new_data = new_data;
307 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
308 pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
309 pa_device_port_ref(port);
311 pa_source_new_data *source_new_data = new_data;
313 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
314 pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
315 pa_device_port_ref(port);
319 /* Run from IO thread */
320 static int sco_process_render(struct userdata *u) {
322 pa_memchunk memchunk;
325 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
326 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
329 pa_sink_render_full(u->sink, u->write_block_size, &memchunk);
331 pa_assert(memchunk.length == u->write_block_size);
336 /* Now write that data to the socket. The socket is of type
337 * SEQPACKET, and we generated the data of the MTU size, so this
338 * should just work. */
340 p = (const uint8_t *) pa_memblock_acquire_chunk(&memchunk);
341 l = pa_write(u->stream_fd, p, memchunk.length, &u->stream_write_type);
342 pa_memblock_release(memchunk.memblock);
350 /* Retry right away if we got interrupted */
352 else if (errno == EAGAIN)
353 /* Hmm, apparently the socket was not writable, give up for now */
356 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
360 pa_assert((size_t) l <= memchunk.length);
362 if ((size_t) l != memchunk.length) {
363 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
364 (unsigned long long) l,
365 (unsigned long long) memchunk.length);
369 u->write_index += (uint64_t) memchunk.length;
370 pa_memblock_unref(memchunk.memblock);
375 /* Run from IO thread */
376 static int sco_process_push(struct userdata *u) {
378 pa_memchunk memchunk;
381 bool found_tstamp = false;
382 pa_usec_t tstamp = 0;
385 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
386 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
387 pa_assert(u->source);
388 pa_assert(u->read_smoother);
390 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
391 memchunk.index = memchunk.length = 0;
405 m.msg_controllen = sizeof(aux);
407 p = pa_memblock_acquire(memchunk.memblock);
409 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
410 l = recvmsg(u->stream_fd, &m, 0);
411 pa_memblock_release(memchunk.memblock);
416 if (l < 0 && errno == EINTR)
417 /* Retry right away if we got interrupted */
420 pa_memblock_unref(memchunk.memblock);
422 if (l < 0 && errno == EAGAIN)
423 /* Hmm, apparently the socket was not readable, give up for now. */
426 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
430 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
432 /* In some rare occasions, we might receive packets of a very strange
433 * size. This could potentially be possible if the SCO packet was
434 * received partially over-the-air, or more probably due to hardware
435 * issues in our Bluetooth adapter. In these cases, in order to avoid
436 * an assertion failure due to unaligned data, just discard the whole
438 if (!pa_frame_aligned(l, &u->sample_spec)) {
439 pa_log_warn("SCO packet received of unaligned size: %zu", l);
440 pa_memblock_unref(memchunk.memblock);
444 memchunk.length = (size_t) l;
445 u->read_index += (uint64_t) l;
447 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
448 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
449 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
450 pa_rtclock_from_wallclock(tv);
451 tstamp = pa_timeval_load(tv);
457 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
458 tstamp = pa_rtclock_now();
461 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
462 pa_smoother_resume(u->read_smoother, tstamp, true);
464 pa_source_post(u->source, &memchunk);
465 pa_memblock_unref(memchunk.memblock);
470 /* Run from IO thread */
471 static void a2dp_prepare_buffer(struct userdata *u) {
472 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
476 if (u->sbc_info.buffer_size >= min_buffer_size)
479 u->sbc_info.buffer_size = 2 * min_buffer_size;
480 pa_xfree(u->sbc_info.buffer);
481 u->sbc_info.buffer = pa_xmalloc(u->sbc_info.buffer_size);
484 /* Run from IO thread */
485 static int a2dp_process_render(struct userdata *u) {
486 struct sbc_info *sbc_info;
487 struct rtp_header *header;
488 struct rtp_payload *payload;
492 size_t to_write, to_encode;
493 unsigned frame_count;
497 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
500 /* First, render some data */
501 if (!u->write_memchunk.memblock)
502 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
504 pa_assert(u->write_memchunk.length == u->write_block_size);
506 a2dp_prepare_buffer(u);
508 sbc_info = &u->sbc_info;
509 header = sbc_info->buffer;
510 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
514 /* Try to create a packet of the full MTU */
516 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
517 to_encode = u->write_memchunk.length;
519 d = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
520 to_write = sbc_info->buffer_size - sizeof(*header) - sizeof(*payload);
522 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
526 encoded = sbc_encode(&sbc_info->sbc,
531 if (PA_UNLIKELY(encoded <= 0)) {
532 pa_log_error("SBC encoding error (%li)", (long) encoded);
533 pa_memblock_release(u->write_memchunk.memblock);
537 pa_assert_fp((size_t) encoded <= to_encode);
538 pa_assert_fp((size_t) encoded == sbc_info->codesize);
540 pa_assert_fp((size_t) written <= to_write);
541 pa_assert_fp((size_t) written == sbc_info->frame_length);
543 p = (const uint8_t*) p + encoded;
544 to_encode -= encoded;
546 d = (uint8_t*) d + written;
552 pa_memblock_release(u->write_memchunk.memblock);
554 pa_assert(to_encode == 0);
557 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
560 /* write it to the fifo */
561 memset(sbc_info->buffer, 0, sizeof(*header) + sizeof(*payload));
564 header->sequence_number = htons(sbc_info->seq_num++);
565 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
566 header->ssrc = htonl(1);
567 payload->frame_count = frame_count;
569 nbytes = (uint8_t*) d - (uint8_t*) sbc_info->buffer;
574 l = pa_write(u->stream_fd, sbc_info->buffer, nbytes, &u->stream_write_type);
581 /* Retry right away if we got interrupted */
584 else if (errno == EAGAIN)
585 /* Hmm, apparently the socket was not writable, give up for now */
588 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
593 pa_assert((size_t) l <= nbytes);
595 if ((size_t) l != nbytes) {
596 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
597 (unsigned long long) l,
598 (unsigned long long) nbytes);
603 u->write_index += (uint64_t) u->write_memchunk.length;
604 pa_memblock_unref(u->write_memchunk.memblock);
605 pa_memchunk_reset(&u->write_memchunk);
615 #ifdef BLUETOOTH_APTX_SUPPORT
616 /* Run from IO thread */
617 static int a2dp_aptx_process_render(struct userdata *u) {
618 struct sbc_info *a2dp;
622 size_t to_write, to_encode;
627 const short *mybuffer;
630 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
633 /* First, render some data */
634 if (!u->write_memchunk.memblock)
635 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
637 pa_assert(u->write_memchunk.length == u->write_block_size);
639 a2dp_prepare_buffer(u);
643 /* Try to create a packet of the full MTU */
644 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
645 to_encode = u->write_memchunk.length;
647 d = (uint8_t*) a2dp->buffer ;
648 to_write = a2dp->buffer_size;
650 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
654 mybuffer = (uint8_t *)p;
656 for (i = 0; i < 4; i += 1) {
657 pcmL[i] = mybuffer[2*i];
658 pcmR[i] = mybuffer[2*i+1];
660 /*(8 audio samples)16 bytes of audo data encoded to 4 bytes*/
661 aptx_encode(a2dp->aptx, pcmL, pcmR, (short*)d);
666 pa_assert_fp((size_t) encoded <= to_encode);
667 pa_assert_fp((size_t) written <= to_write);
669 p = (const uint8_t*) p + encoded;
670 to_encode -= encoded;
672 d = (uint8_t*) d + written;
677 pa_memblock_release(u->write_memchunk.memblock);
679 pa_assert(to_encode == 0);
682 pa_log_debug("Using APTX encoder implementation");
685 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
690 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
697 /* Retry right away if we got interrupted */
700 else if (errno == EAGAIN)
701 /* Hmm, apparently the socket was not writable, give up for now */
704 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
709 pa_assert((size_t) l <= nbytes);
711 if ((size_t) l != nbytes) {
712 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
713 (unsigned long long) l,
714 (unsigned long long) nbytes);
719 u->write_index += (uint64_t) u->write_memchunk.length;
720 pa_memblock_unref(u->write_memchunk.memblock);
721 pa_memchunk_reset(&u->write_memchunk);
733 /* Run from IO thread */
734 static int a2dp_process_null_render(struct userdata *u) {
736 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
739 /* First, render some data */
740 if (!u->write_memchunk.memblock)
741 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
743 pa_assert(u->write_memchunk.length == u->write_block_size);
745 u->write_index += (uint64_t) u->write_memchunk.length;
746 pa_memblock_unref(u->write_memchunk.memblock);
747 pa_memchunk_reset(&u->write_memchunk);
753 /* Run from IO thread */
754 static int a2dp_process_push(struct userdata *u) {
756 pa_memchunk memchunk;
759 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
760 pa_assert(u->source);
761 pa_assert(u->read_smoother);
763 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
764 memchunk.index = memchunk.length = 0;
767 bool found_tstamp = false;
769 struct sbc_info *sbc_info;
770 struct rtp_header *header;
771 struct rtp_payload *payload;
775 size_t to_write, to_decode;
776 size_t total_written = 0;
778 a2dp_prepare_buffer(u);
780 sbc_info = &u->sbc_info;
781 header = sbc_info->buffer;
782 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
784 l = pa_read(u->stream_fd, sbc_info->buffer, sbc_info->buffer_size, &u->stream_write_type);
788 if (l < 0 && errno == EINTR)
789 /* Retry right away if we got interrupted */
792 else if (l < 0 && errno == EAGAIN)
793 /* Hmm, apparently the socket was not readable, give up for now. */
796 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
801 pa_assert((size_t) l <= sbc_info->buffer_size);
803 /* TODO: get timestamp from rtp */
805 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
806 tstamp = pa_rtclock_now();
809 p = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
810 to_decode = l - sizeof(*header) - sizeof(*payload);
812 d = pa_memblock_acquire(memchunk.memblock);
813 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
815 while (PA_LIKELY(to_decode > 0)) {
819 decoded = sbc_decode(&sbc_info->sbc,
824 if (PA_UNLIKELY(decoded <= 0)) {
825 pa_log_error("SBC decoding error (%li)", (long) decoded);
826 pa_memblock_release(memchunk.memblock);
827 pa_memblock_unref(memchunk.memblock);
831 total_written += written;
833 /* Reset frame length, it can be changed due to bitpool change */
834 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
836 pa_assert_fp((size_t) decoded <= to_decode);
837 pa_assert_fp((size_t) decoded == sbc_info->frame_length);
839 pa_assert_fp((size_t) written == sbc_info->codesize);
841 p = (const uint8_t*) p + decoded;
842 to_decode -= decoded;
844 d = (uint8_t*) d + written;
848 u->read_index += (uint64_t) total_written;
849 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
850 pa_smoother_resume(u->read_smoother, tstamp, true);
852 memchunk.length -= to_write;
854 pa_memblock_release(memchunk.memblock);
856 pa_source_post(u->source, &memchunk);
862 pa_memblock_unref(memchunk.memblock);
867 /* Run from I/O thread */
868 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
869 struct sbc_info *sbc_info;
873 sbc_info = &u->sbc_info;
875 if (sbc_info->sbc.bitpool == bitpool)
878 if (bitpool > sbc_info->max_bitpool)
879 bitpool = sbc_info->max_bitpool;
880 else if (bitpool < sbc_info->min_bitpool)
881 bitpool = sbc_info->min_bitpool;
883 sbc_info->sbc.bitpool = bitpool;
885 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
886 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
888 pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
891 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
892 / sbc_info->frame_length * sbc_info->codesize;
894 u->write_block_size =
895 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
896 / sbc_info->frame_length * sbc_info->codesize;
898 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
899 pa_sink_set_fixed_latency_within_thread(u->sink,
900 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
903 /* Run from I/O thread */
904 static void a2dp_reduce_bitpool(struct userdata *u) {
905 struct sbc_info *sbc_info;
910 sbc_info = &u->sbc_info;
912 /* Check if bitpool is already at its limit */
913 if (sbc_info->sbc.bitpool <= BITPOOL_DEC_LIMIT)
916 bitpool = sbc_info->sbc.bitpool - BITPOOL_DEC_STEP;
918 if (bitpool < BITPOOL_DEC_LIMIT)
919 bitpool = BITPOOL_DEC_LIMIT;
921 a2dp_set_bitpool(u, bitpool);
924 static void teardown_stream(struct userdata *u) {
925 if (u->rtpoll_item) {
926 pa_rtpoll_item_free(u->rtpoll_item);
927 u->rtpoll_item = NULL;
930 if (u->stream_fd >= 0) {
931 pa_close(u->stream_fd);
935 if (u->read_smoother) {
936 pa_smoother_free(u->read_smoother);
937 u->read_smoother = NULL;
940 if (u->write_memchunk.memblock) {
941 pa_memblock_unref(u->write_memchunk.memblock);
942 pa_memchunk_reset(&u->write_memchunk);
945 pa_log_debug("Audio stream torn down");
946 u->stream_setup_done = false;
949 static int transport_acquire(struct userdata *u, bool optional) {
950 pa_assert(u->transport);
952 if (u->transport_acquired)
955 pa_log_debug("Acquiring transport %s", u->transport->path);
957 u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
958 if (u->stream_fd < 0)
961 u->transport_acquired = true;
964 u->transport_suspended_by_remote = false;
966 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
971 static void transport_release(struct userdata *u) {
972 pa_assert(u->transport);
974 /* Ignore if already released */
975 if (!u->transport_acquired)
978 pa_log_debug("Releasing transport %s", u->transport->path);
980 u->transport->release(u->transport);
982 u->transport_acquired = false;
985 /* The below code would be less effect for most of case */
986 if (u->transport_suspended_by_remote)
987 pa_log_info("Released by remote suspend request");
992 /* Set transport state to idle if this was not already done by the remote end closing
993 * the file descriptor. Only do this when called from the I/O thread */
994 if (pa_thread_mq_get() != NULL && u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
995 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
998 /* Run from I/O thread */
999 static void transport_config_mtu(struct userdata *u) {
1000 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1001 u->read_block_size = u->read_link_mtu;
1002 u->write_block_size = u->write_link_mtu;
1004 if (!pa_frame_aligned(u->read_block_size, &u->source->sample_spec)) {
1006 pa_log_debug("Got invalid read MTU: %zu, rounding down", u->read_block_size);
1008 pa_log_debug("Got invalid read MTU: %lu, rounding down", u->read_block_size);
1010 u->read_block_size = pa_frame_align(u->read_block_size, &u->source->sample_spec);
1013 if (!pa_frame_aligned(u->write_block_size, &u->sink->sample_spec)) {
1015 pa_log_debug("Got invalid write MTU: %zu, rounding down", u->write_block_size);
1017 pa_log_debug("Got invalid write MTU: %lu, rounding down", u->write_block_size);
1019 u->write_block_size = pa_frame_align(u->write_block_size, &u->sink->sample_spec);
1023 } else if(u->sbc_info.sbc_initialized) {
1027 u->read_block_size =
1028 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1029 / u->sbc_info.frame_length * u->sbc_info.codesize;
1031 u->write_block_size =
1032 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
1033 / u->sbc_info.frame_length * u->sbc_info.codesize;
1037 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
1038 pa_sink_set_fixed_latency_within_thread(u->sink,
1039 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
1040 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
1041 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
1045 pa_source_set_fixed_latency_within_thread(u->source,
1046 (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
1047 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
1048 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
1051 /* Run from I/O thread */
1052 static void setup_stream(struct userdata *u) {
1053 struct pollfd *pollfd;
1056 /* return if stream is already set up */
1057 if (u->stream_setup_done)
1060 pa_log_info("Transport %s resuming", u->transport->path);
1062 transport_config_mtu(u);
1064 pa_make_fd_nonblock(u->stream_fd);
1065 pa_make_socket_low_delay(u->stream_fd);
1068 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
1069 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
1071 pa_log_debug("Stream properly set up, we're ready to roll!");
1073 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1074 a2dp_set_bitpool(u, u->sbc_info.max_bitpool);
1076 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
1077 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
1078 pollfd->fd = u->stream_fd;
1079 pollfd->events = pollfd->revents = 0;
1081 u->read_index = u->write_index = 0;
1083 u->stream_setup_done = true;
1086 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
1089 /* Called from I/O thread, returns true if the transport was acquired or
1090 * a connection was requested successfully. */
1091 static bool setup_transport_and_stream(struct userdata *u) {
1092 int transport_error;
1094 transport_error = transport_acquire(u, false);
1095 if (transport_error < 0) {
1096 if (transport_error != -EAGAIN)
1103 /* Run from IO thread */
1104 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1105 struct userdata *u = PA_SOURCE(o)->userdata;
1106 bool failed = false;
1109 pa_assert(u->source == PA_SOURCE(o));
1110 pa_assert(u->transport);
1114 case PA_SOURCE_MESSAGE_SET_STATE:
1116 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1118 case PA_SOURCE_SUSPENDED:
1119 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
1120 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1123 /* Stop the device if the sink is suspended as well */
1124 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
1125 transport_release(u);
1127 if (u->read_smoother)
1128 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1132 case PA_SOURCE_IDLE:
1133 case PA_SOURCE_RUNNING:
1134 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1137 /* Resume the device if the sink was suspended as well */
1138 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state))
1139 failed = !setup_transport_and_stream(u);
1141 /* We don't resume the smoother here. Instead we
1142 * wait until the first packet arrives */
1146 case PA_SOURCE_UNLINKED:
1147 case PA_SOURCE_INIT:
1148 case PA_SOURCE_INVALID_STATE:
1154 case PA_SOURCE_MESSAGE_GET_LATENCY: {
1157 if (u->read_smoother) {
1158 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1159 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1161 *((int64_t*) data) = u->source->thread_info.fixed_latency + wi - ri;
1163 *((int64_t*) data) = 0;
1168 case PA_SOURCE_MESSAGE_SETUP_STREAM:
1174 r = pa_source_process_msg(o, code, data, offset, chunk);
1176 return (r < 0 || !failed) ? r : -1;
1179 /* Run from main thread */
1180 static void source_set_volume_cb(pa_source *s) {
1191 pa_assert(u->source == s);
1193 if (u->transport->set_microphone_gain == NULL)
1196 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1198 if (gain > HSP_MAX_GAIN)
1199 gain = HSP_MAX_GAIN;
1201 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1203 /* increment volume by one to correct rounding errors */
1204 if (volume < PA_VOLUME_NORM)
1207 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1209 /* Set soft volume when in headset role */
1210 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1211 pa_cvolume_set(&s->soft_volume, u->sample_spec.channels, volume);
1213 /* If we are in the AG role, we send a command to the head set to change
1214 * the microphone gain. In the HS role, source and sink are swapped, so
1215 * in this case we notify the AG that the speaker gain has changed */
1216 u->transport->set_microphone_gain(u->transport, gain);
1219 /* Run from main thread */
1220 static int add_source(struct userdata *u) {
1221 pa_source_new_data data;
1223 pa_assert(u->transport);
1225 pa_source_new_data_init(&data);
1226 data.module = u->module;
1227 data.card = u->card;
1228 data.driver = __FILE__;
1229 data.name = pa_sprintf_malloc("bluez_source.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1230 data.namereg_fail = false;
1231 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1232 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1233 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1234 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1236 connect_ports(u, &data, PA_DIRECTION_INPUT);
1238 if (!u->transport_acquired)
1239 switch (u->profile) {
1240 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1241 case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1242 data.suspend_cause = PA_SUSPEND_USER;
1244 case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1245 /* u->stream_fd contains the error returned by the last transport_acquire()
1246 * EAGAIN means we are waiting for a NewConnection signal */
1247 if (u->stream_fd == -EAGAIN)
1248 data.suspend_cause = PA_SUSPEND_USER;
1250 pa_assert_not_reached();
1252 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1253 case PA_BLUETOOTH_PROFILE_OFF:
1254 pa_assert_not_reached();
1258 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1259 pa_source_new_data_done(&data);
1261 pa_log_error("Failed to create source");
1265 u->source->userdata = u;
1266 u->source->parent.process_msg = source_process_msg;
1268 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1269 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1270 u->source->n_volume_steps = 16;
1275 /* Run from IO thread */
1276 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1277 struct userdata *u = PA_SINK(o)->userdata;
1278 bool failed = false;
1281 pa_assert(u->sink == PA_SINK(o));
1282 pa_assert(u->transport);
1286 case PA_SINK_MESSAGE_SET_STATE:
1288 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
1290 case PA_SINK_SUSPENDED:
1291 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1292 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
1295 /* Stop the device if the source is suspended as well */
1296 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1297 /* We deliberately ignore whether stopping
1298 * actually worked. Since the stream_fd is
1299 * closed it doesn't really matter */
1300 transport_release(u);
1305 case PA_SINK_RUNNING:
1306 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1309 /* Wait until PA_BLUETOOTH_TRANSPORT_IDLE */
1310 if ((u->transport != NULL) && (u->transport->state ==
1311 PA_BLUETOOTH_TRANSPORT_STATE_IDLE))
1312 pa_log_info("This is good time for(%d)",
1313 (pa_sink_state_t) PA_PTR_TO_UINT(data));
1315 pa_log_info("Wait for PA_BLUETOOTH_TRANSPORT_STATE_IDLE");
1317 /* Resume the device if the source was suspended as well */
1318 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1319 failed = !setup_transport_and_stream(u);
1323 case PA_SINK_UNLINKED:
1325 case PA_SINK_INVALID_STATE:
1331 case PA_SINK_MESSAGE_GET_LATENCY: {
1334 if (u->read_smoother) {
1335 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1336 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
1338 ri = pa_rtclock_now() - u->started_at;
1339 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1342 *((int64_t*) data) = u->sink->thread_info.fixed_latency + wi - ri;
1347 case PA_SINK_MESSAGE_SETUP_STREAM:
1352 r = pa_sink_process_msg(o, code, data, offset, chunk);
1354 return (r < 0 || !failed) ? r : -1;
1357 /* Run from main thread */
1358 static void sink_set_volume_cb(pa_sink *s) {
1369 pa_assert(u->sink == s);
1371 if (u->transport->set_speaker_gain == NULL)
1374 gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1376 if (gain > HSP_MAX_GAIN)
1377 gain = HSP_MAX_GAIN;
1379 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1381 /* increment volume by one to correct rounding errors */
1382 if (volume < PA_VOLUME_NORM)
1385 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1387 /* Set soft volume when in headset role */
1388 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1389 pa_cvolume_set(&s->soft_volume, u->sample_spec.channels, volume);
1391 /* If we are in the AG role, we send a command to the head set to change
1392 * the speaker gain. In the HS role, source and sink are swapped, so
1393 * in this case we notify the AG that the microphone gain has changed */
1394 u->transport->set_speaker_gain(u->transport, gain);
1397 /* Run from main thread */
1398 static int add_sink(struct userdata *u) {
1399 pa_sink_new_data data;
1401 pa_assert(u->transport);
1403 pa_sink_new_data_init(&data);
1404 data.module = u->module;
1405 data.card = u->card;
1406 data.driver = __FILE__;
1407 data.name = pa_sprintf_malloc("bluez_sink.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1408 data.namereg_fail = false;
1409 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1410 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1411 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1412 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1414 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1416 if (!u->transport_acquired)
1417 switch (u->profile) {
1418 case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1419 data.suspend_cause = PA_SUSPEND_USER;
1421 case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1422 /* u->stream_fd contains the error returned by the last transport_acquire()
1423 * EAGAIN means we are waiting for a NewConnection signal */
1424 if (u->stream_fd == -EAGAIN)
1425 data.suspend_cause = PA_SUSPEND_USER;
1427 pa_assert_not_reached();
1429 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1430 /* Profile switch should have failed */
1431 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1432 case PA_BLUETOOTH_PROFILE_OFF:
1433 pa_assert_not_reached();
1437 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1438 pa_sink_new_data_done(&data);
1440 pa_log_error("Failed to create sink");
1444 #ifdef TIZEN_BT_AVC_TARGET
1446 unsigned int avc_mode = PA_BLUETOOTH_AVC_OFF;
1448 if (pa_bluetooth_transport_get_avc_mode(u->transport, &avc_mode) != 0)
1449 pa_log_info("Fail to get the initial AVC mode");
1451 u->transport->avc_mode = avc_mode;
1453 pa_sink_set_avc_mode(u->sink, u->transport->avc_mode);
1457 u->sink->userdata = u;
1458 u->sink->parent.process_msg = sink_process_msg;
1460 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1461 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1462 u->sink->n_volume_steps = 16;
1467 #ifdef BLUETOOTH_APTX_SUPPORT
1468 /* should be implemeted */
1469 static void bt_transport_config_a2dp_for_aptx(struct userdata *u) {
1470 const pa_bluetooth_transport *t;
1471 struct sbc_info *a2dp = &u->sbc_info;
1476 u->sample_spec.format = PA_SAMPLE_S16LE;
1478 if (!a2dp->aptx_initialized) {
1479 #if __BYTE_ORDER==__LITTLE_ENDIAN
1480 a2dp->aptx = aptx_new(1);
1481 #elif __BYTE_ORDER==__BIG_ENDIAN
1482 a2dp->aptx = aptx_new(0);
1484 #error "Unknown byte order"
1486 a2dp->aptx_initialized = true;
1489 pa_log_debug("aptx Encoder is intialized !!");
1491 u->write_block_size =(size_t)(u->write_link_mtu/(size_t)16) *16*4 ;
1492 pa_log_info("APTX parameters block_size(%d),link_mtu(%d)",u->write_block_size,u->write_link_mtu);
1497 /* Run from main thread */
1498 static void transport_config(struct userdata *u) {
1499 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1500 u->sample_spec.format = PA_SAMPLE_S16LE;
1501 u->sample_spec.channels = 1;
1502 u->sample_spec.rate = 8000;
1504 sbc_info_t *sbc_info = &u->sbc_info;
1506 #ifdef BLUETOOTH_APTX_SUPPORT
1507 const pa_bluetooth_transport *t;
1508 a2dp_aptx_t *aptx_config;
1511 pa_assert(u->transport);
1513 #ifdef BLUETOOTH_APTX_SUPPORT
1515 if (t->codec == A2DP_CODEC_VENDOR) {
1516 aptx_config = (a2dp_aptx_t *) t->config;
1517 if (aptx_config->vendor_id[0] == APTX_VENDOR_ID0 &&
1518 aptx_config->vendor_id[1] == APTX_VENDOR_ID1 &&
1519 aptx_config->vendor_id[2] == APTX_VENDOR_ID2 &&
1520 aptx_config->vendor_id[3] == APTX_VENDOR_ID3 &&
1521 aptx_config->codec_id[0] == APTX_CODEC_ID0 &&
1522 aptx_config->codec_id[1] == APTX_CODEC_ID1 ){
1523 pa_log("A2DP_CODEC_NON_A2DP and this is APTX Codec");
1525 bt_transport_config_a2dp_for_aptx(u);
1528 pa_log("A2DP_CODEC_NON_A2DP but this is not APTX Codec");
1534 u->sample_spec.format = PA_SAMPLE_S16LE;
1535 config = (a2dp_sbc_t *) u->transport->config;
1537 if (sbc_info->sbc_initialized)
1538 sbc_reinit(&sbc_info->sbc, 0);
1540 sbc_init(&sbc_info->sbc, 0);
1541 sbc_info->sbc_initialized = true;
1543 switch (config->frequency) {
1544 case SBC_SAMPLING_FREQ_16000:
1545 sbc_info->sbc.frequency = SBC_FREQ_16000;
1546 u->sample_spec.rate = 16000U;
1548 case SBC_SAMPLING_FREQ_32000:
1549 sbc_info->sbc.frequency = SBC_FREQ_32000;
1550 u->sample_spec.rate = 32000U;
1552 case SBC_SAMPLING_FREQ_44100:
1553 sbc_info->sbc.frequency = SBC_FREQ_44100;
1554 u->sample_spec.rate = 44100U;
1556 case SBC_SAMPLING_FREQ_48000:
1557 sbc_info->sbc.frequency = SBC_FREQ_48000;
1558 u->sample_spec.rate = 48000U;
1561 pa_assert_not_reached();
1564 switch (config->channel_mode) {
1565 case SBC_CHANNEL_MODE_MONO:
1566 sbc_info->sbc.mode = SBC_MODE_MONO;
1567 u->sample_spec.channels = 1;
1569 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1570 sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1571 u->sample_spec.channels = 2;
1573 case SBC_CHANNEL_MODE_STEREO:
1574 sbc_info->sbc.mode = SBC_MODE_STEREO;
1575 u->sample_spec.channels = 2;
1577 case SBC_CHANNEL_MODE_JOINT_STEREO:
1578 sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
1579 u->sample_spec.channels = 2;
1582 pa_assert_not_reached();
1585 switch (config->allocation_method) {
1586 case SBC_ALLOCATION_SNR:
1587 sbc_info->sbc.allocation = SBC_AM_SNR;
1589 case SBC_ALLOCATION_LOUDNESS:
1590 sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
1593 pa_assert_not_reached();
1596 switch (config->subbands) {
1597 case SBC_SUBBANDS_4:
1598 sbc_info->sbc.subbands = SBC_SB_4;
1600 case SBC_SUBBANDS_8:
1601 sbc_info->sbc.subbands = SBC_SB_8;
1604 pa_assert_not_reached();
1607 switch (config->block_length) {
1608 case SBC_BLOCK_LENGTH_4:
1609 sbc_info->sbc.blocks = SBC_BLK_4;
1611 case SBC_BLOCK_LENGTH_8:
1612 sbc_info->sbc.blocks = SBC_BLK_8;
1614 case SBC_BLOCK_LENGTH_12:
1615 sbc_info->sbc.blocks = SBC_BLK_12;
1617 case SBC_BLOCK_LENGTH_16:
1618 sbc_info->sbc.blocks = SBC_BLK_16;
1621 pa_assert_not_reached();
1624 sbc_info->min_bitpool = config->min_bitpool;
1625 sbc_info->max_bitpool = config->max_bitpool;
1627 /* Set minimum bitpool for source to get the maximum possible block_size */
1628 sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
1629 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
1630 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
1632 pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
1633 sbc_info->sbc.allocation, sbc_info->sbc.subbands ? 8 : 4, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
1637 /* Run from main thread */
1638 static int setup_transport(struct userdata *u) {
1639 pa_bluetooth_transport *t;
1642 pa_assert(!u->transport);
1643 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1645 /* check if profile has a transport */
1646 t = u->device->transports[u->profile];
1647 if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1648 pa_log_warn("Profile %s has no transport", pa_bluetooth_profile_to_string(u->profile));
1654 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1655 transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1657 int transport_error;
1659 transport_error = transport_acquire(u, false);
1660 if (transport_error < 0 && transport_error != -EAGAIN)
1661 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1664 transport_config(u);
1669 /* Run from main thread */
1670 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1671 static const pa_direction_t profile_direction[] = {
1672 [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1673 [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1674 [PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1675 [PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1676 [PA_BLUETOOTH_PROFILE_OFF] = 0
1679 return profile_direction[p];
1682 /* Run from main thread */
1683 static int init_profile(struct userdata *u) {
1686 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1688 if (setup_transport(u) < 0)
1691 pa_assert(u->transport);
1693 if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
1694 if (add_sink(u) < 0)
1697 if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
1698 if (add_source(u) < 0)
1704 /* I/O thread function */
1705 static void thread_func(void *userdata) {
1706 struct userdata *u = userdata;
1707 unsigned do_write = 0;
1708 unsigned pending_read_bytes = 0;
1709 bool writable = false;
1712 pa_assert(u->transport);
1714 pa_log_debug("IO Thread starting up");
1716 if (u->core->realtime_scheduling)
1717 pa_make_realtime(u->core->realtime_priority);
1719 pa_thread_mq_install(&u->thread_mq);
1721 /* Setup the stream only if the transport was already acquired */
1722 if (u->transport_acquired)
1726 struct pollfd *pollfd;
1728 bool disable_timer = true;
1730 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1732 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1733 pa_log_info("FD error: %s%s%s%s",
1734 pollfd->revents & POLLERR ? "POLLERR " :"",
1735 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1736 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1737 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1739 if (pollfd->revents & POLLHUP) {
1743 pending_read_bytes = 0;
1745 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
1750 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1752 /* We should send two blocks to the device before we expect
1755 if (u->write_index == 0 && u->read_index <= 0)
1758 if (pollfd && (pollfd->revents & POLLIN)) {
1761 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1762 n_read = a2dp_process_push(u);
1764 n_read = sco_process_push(u);
1770 /* We just read something, so we are supposed to write something, too */
1771 pending_read_bytes += n_read;
1772 do_write += pending_read_bytes / u->write_block_size;
1773 pending_read_bytes = pending_read_bytes % u->write_block_size;
1778 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1780 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1781 pa_sink_process_rewind(u->sink, 0);
1784 if (pollfd->revents & POLLOUT)
1787 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1788 pa_usec_t time_passed;
1789 pa_usec_t audio_sent;
1791 /* Hmm, there is no input stream we could synchronize
1792 * to. So let's do things by time */
1794 time_passed = pa_rtclock_now() - u->started_at;
1795 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1797 if (audio_sent <= time_passed) {
1798 pa_usec_t audio_to_send = time_passed - audio_sent;
1800 /* Never try to catch up for more than 100ms */
1801 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1802 pa_usec_t skip_usec;
1803 uint64_t skip_bytes;
1805 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1806 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1808 if (skip_bytes > 0) {
1811 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1812 (unsigned long long) skip_usec,
1813 (unsigned long long) skip_bytes);
1815 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1816 pa_memblock_unref(tmp.memblock);
1817 u->write_index += skip_bytes;
1819 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1820 a2dp_reduce_bitpool(u);
1825 pending_read_bytes = 0;
1829 if (writable && do_write > 0) {
1832 if (u->write_index <= 0)
1833 u->started_at = pa_rtclock_now();
1835 if ((u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) &&
1836 !u->transport_suspended_by_remote) {
1837 if(u->sbc_info.sbc_initialized) {
1838 if ((n_written = a2dp_process_render(u)) < 0)
1841 #ifdef BLUETOOTH_APTX_SUPPORT
1842 if ((n_written = a2dp_aptx_process_render(u)) < 0)
1848 } else if ((u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) &&
1849 u->transport_suspended_by_remote) {
1850 if ((n_written = a2dp_process_null_render(u)) < 0)
1853 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
1854 if ((n_written = a2dp_process_render(u)) < 0)
1858 if ((n_written = sco_process_render(u)) < 0)
1863 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1865 do_write -= n_written;
1869 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1870 pa_usec_t sleep_for;
1871 pa_usec_t time_passed, next_write_at;
1874 /* Hmm, there is no input stream we could synchronize
1875 * to. So let's estimate when we need to wake up the latest */
1876 time_passed = pa_rtclock_now() - u->started_at;
1877 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1878 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1879 /* 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); */
1881 /* drop stream every 500 ms */
1882 sleep_for = PA_USEC_PER_MSEC * 500;
1884 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1885 disable_timer = false;
1891 pa_rtpoll_set_timer_disabled(u->rtpoll);
1893 /* Hmm, nothing to do. Let's sleep */
1895 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1896 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1898 if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1899 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1903 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1904 transport_release(u);
1910 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1911 pa_log_debug("IO thread failed");
1912 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1913 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1916 pa_log_debug("IO thread shutting down");
1919 /* Run from main thread */
1920 static int start_thread(struct userdata *u) {
1922 pa_assert(!u->thread);
1923 pa_assert(!u->rtpoll);
1924 pa_assert(!u->rtpoll_item);
1926 u->rtpoll = pa_rtpoll_new();
1928 if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1929 pa_log("pa_thread_mq_init() failed.");
1933 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1934 pa_log_error("Failed to create IO thread");
1939 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1940 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1942 /* If we are in the headset role, the sink should not become default
1943 * unless there is no other sound device available. */
1944 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1945 u->sink->priority = 1500;
1947 pa_sink_put(u->sink);
1949 if (u->sink->set_volume)
1950 u->sink->set_volume(u->sink);
1954 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1955 pa_source_set_rtpoll(u->source, u->rtpoll);
1957 /* If we are in the headset role or the device is an a2dp source,
1958 * the source should not become default unless there is no other
1959 * sound device available. */
1960 if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY || u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1961 u->source->priority = 1500;
1963 pa_source_put(u->source);
1965 if (u->source->set_volume)
1966 u->source->set_volume(u->source);
1972 /* Run from main thread */
1973 static void stop_thread(struct userdata *u) {
1977 pa_sink_unlink(u->sink);
1980 pa_source_unlink(u->source);
1983 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1984 pa_thread_free(u->thread);
1988 if (u->rtpoll_item) {
1989 pa_rtpoll_item_free(u->rtpoll_item);
1990 u->rtpoll_item = NULL;
1994 pa_rtpoll_free(u->rtpoll);
1996 pa_thread_mq_done(&u->thread_mq);
2000 transport_release(u);
2001 u->transport = NULL;
2005 pa_sink_unref(u->sink);
2010 pa_source_unref(u->source);
2014 if (u->read_smoother) {
2015 pa_smoother_free(u->read_smoother);
2016 u->read_smoother = NULL;
2020 /* Run from main thread */
2021 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
2022 pa_available_t result = PA_AVAILABLE_NO;
2026 pa_assert(u->device);
2028 for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
2029 pa_bluetooth_transport *transport;
2031 if (!(get_profile_direction(i) & direction))
2034 if (!(transport = u->device->transports[i]))
2037 switch(transport->state) {
2038 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
2041 case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
2042 if (result == PA_AVAILABLE_NO)
2043 result = PA_AVAILABLE_UNKNOWN;
2047 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
2048 return PA_AVAILABLE_YES;
2055 /* Run from main thread */
2056 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
2058 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
2059 return PA_AVAILABLE_NO;
2060 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
2061 return PA_AVAILABLE_YES;
2063 return PA_AVAILABLE_UNKNOWN;
2067 /* Run from main thread */
2068 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
2069 pa_device_port *port;
2070 pa_device_port_new_data port_data;
2071 const char *name_prefix, *input_description, *output_description;
2075 pa_assert(u->device);
2077 name_prefix = "unknown";
2078 input_description = _("Bluetooth Input");
2079 output_description = _("Bluetooth Output");
2081 switch (form_factor_from_class(u->device->class_of_device)) {
2082 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
2083 name_prefix = "headset";
2084 input_description = output_description = _("Headset");
2087 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
2088 name_prefix = "handsfree";
2089 input_description = output_description = _("Handsfree");
2092 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
2093 name_prefix = "microphone";
2094 input_description = _("Microphone");
2095 output_description = _("Bluetooth Output");
2098 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
2099 name_prefix = "speaker";
2100 input_description = _("Bluetooth Input");
2101 output_description = _("Speaker");
2104 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
2105 name_prefix = "headphone";
2106 input_description = _("Bluetooth Input");
2107 output_description = _("Headphone");
2110 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
2111 name_prefix = "portable";
2112 input_description = output_description = _("Portable");
2115 case PA_BLUETOOTH_FORM_FACTOR_CAR:
2116 name_prefix = "car";
2117 input_description = output_description = _("Car");
2120 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
2121 name_prefix = "hifi";
2122 input_description = output_description = _("HiFi");
2125 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
2126 name_prefix = "phone";
2127 input_description = output_description = _("Phone");
2130 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
2131 name_prefix = "unknown";
2132 input_description = _("Bluetooth Input");
2133 output_description = _("Bluetooth Output");
2137 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
2138 pa_device_port_new_data_init(&port_data);
2139 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
2140 pa_device_port_new_data_set_description(&port_data, output_description);
2141 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
2142 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
2143 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2144 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2145 pa_device_port_new_data_done(&port_data);
2147 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
2148 pa_device_port_new_data_init(&port_data);
2149 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
2150 pa_device_port_new_data_set_description(&port_data, input_description);
2151 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
2152 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
2153 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2154 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2155 pa_device_port_new_data_done(&port_data);
2158 /* Run from main thread */
2159 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluetooth_profile_t profile, pa_hashmap *ports) {
2160 pa_device_port *input_port, *output_port;
2162 pa_card_profile *cp = NULL;
2163 pa_bluetooth_profile_t *p;
2165 pa_assert(u->input_port_name);
2166 pa_assert(u->output_port_name);
2167 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2168 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2170 name = pa_bluetooth_profile_to_string(profile);
2173 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
2174 cp = pa_card_profile_new(name, _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
2178 cp->max_sink_channels = 2;
2179 cp->max_source_channels = 0;
2180 pa_hashmap_put(output_port->profiles, cp->name, cp);
2182 p = PA_CARD_PROFILE_DATA(cp);
2185 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
2186 cp = pa_card_profile_new(name, _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
2190 cp->max_sink_channels = 0;
2191 cp->max_source_channels = 2;
2192 pa_hashmap_put(input_port->profiles, cp->name, cp);
2194 p = PA_CARD_PROFILE_DATA(cp);
2196 case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
2197 cp = pa_card_profile_new(name, _("Headset Head Unit (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
2201 cp->max_sink_channels = 1;
2202 cp->max_source_channels = 1;
2203 pa_hashmap_put(input_port->profiles, cp->name, cp);
2204 pa_hashmap_put(output_port->profiles, cp->name, cp);
2206 p = PA_CARD_PROFILE_DATA(cp);
2209 case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
2210 cp = pa_card_profile_new(name, _("Headset Audio Gateway (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
2214 cp->max_sink_channels = 1;
2215 cp->max_source_channels = 1;
2216 pa_hashmap_put(input_port->profiles, cp->name, cp);
2217 pa_hashmap_put(output_port->profiles, cp->name, cp);
2219 p = PA_CARD_PROFILE_DATA(cp);
2221 case PA_BLUETOOTH_PROFILE_OFF:
2222 pa_assert_not_reached();
2227 if (u->device->transports[*p])
2228 cp->available = transport_state_to_availability(u->device->transports[*p]->state);
2230 cp->available = PA_AVAILABLE_NO;
2235 /* Run from main thread */
2236 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
2238 pa_bluetooth_profile_t *p;
2241 pa_assert(new_profile);
2242 pa_assert_se(u = c->userdata);
2244 p = PA_CARD_PROFILE_DATA(new_profile);
2246 if (*p != PA_BLUETOOTH_PROFILE_OFF) {
2247 const pa_bluetooth_device *d = u->device;
2249 if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2250 pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
2259 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2260 if (init_profile(u) < 0)
2263 if (u->sink || u->source)
2264 if (start_thread(u) < 0)
2272 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2277 static int uuid_to_profile(const char *uuid, pa_bluetooth_profile_t *_r) {
2278 if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK))
2279 *_r = PA_BLUETOOTH_PROFILE_A2DP_SINK;
2280 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE))
2281 *_r = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
2282 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_HS) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF))
2283 *_r = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
2284 else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG))
2285 *_r = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
2287 return -PA_ERR_INVALID;
2292 /* Run from main thread */
2293 static int add_card(struct userdata *u) {
2294 const pa_bluetooth_device *d;
2295 pa_card_new_data data;
2297 pa_bluetooth_form_factor_t ff;
2298 pa_card_profile *cp;
2299 pa_bluetooth_profile_t *p;
2304 pa_assert(u->device);
2308 pa_card_new_data_init(&data);
2309 data.driver = __FILE__;
2310 data.module = u->module;
2312 alias = pa_utf8_filter(d->alias);
2313 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2316 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2317 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2318 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2319 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2321 if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2322 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2324 pa_proplist_sets(data.proplist, "bluez.path", d->path);
2325 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2326 pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2327 data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2328 data.namereg_fail = false;
2330 create_card_ports(u, data.ports);
2332 PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2333 pa_bluetooth_profile_t profile;
2335 if (uuid_to_profile(uuid, &profile) < 0)
2338 if (pa_hashmap_get(data.profiles, pa_bluetooth_profile_to_string(profile)))
2341 cp = create_card_profile(u, profile, data.ports);
2342 pa_hashmap_put(data.profiles, cp->name, cp);
2345 pa_assert(!pa_hashmap_isempty(data.profiles));
2347 cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2348 cp->available = PA_AVAILABLE_YES;
2349 p = PA_CARD_PROFILE_DATA(cp);
2350 *p = PA_BLUETOOTH_PROFILE_OFF;
2351 pa_hashmap_put(data.profiles, cp->name, cp);
2354 /* Default profile was assigned in the previous tizen version. Because pa_card_new_data_set_profile function
2355 * was removed pulseaudio 11.1 version. So we can't use these codes. If some problems occurs in later.
2356 * We should use this code. */
2358 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2359 pa_log_debug("default_profile: %s", default_profile);
2361 if (pa_hashmap_get(data.profiles, default_profile))
2362 pa_card_new_data_set_profile(&data, default_profile);
2364 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2369 u->card = pa_card_new(u->core, &data);
2370 pa_card_new_data_done(&data);
2372 pa_log("Failed to allocate card.");
2376 u->card->userdata = u;
2377 u->card->set_profile = set_profile_cb;
2378 pa_card_choose_initial_profile(u->card);
2379 pa_card_put(u->card);
2381 p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2388 /* Run from main thread */
2389 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2390 bool acquire = false;
2391 bool release = false;
2392 pa_card_profile *cp;
2393 pa_device_port *port;
2394 pa_available_t oldavail;
2398 pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
2400 oldavail = cp->available;
2401 pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2403 /* Update port availability */
2404 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2405 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2406 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2407 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2409 /* Acquire or release transport as needed */
2410 acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2411 release = (oldavail != PA_AVAILABLE_NO && t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2413 if (acquire && transport_acquire(u, true) >= 0) {
2415 pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2417 /* When the ofono backend resumes source or sink when in the audio gateway role, the
2418 * state of source or sink may already be RUNNING before the transport is acquired via
2419 * hf_audio_agent_new_connection(), so the pa_source_suspend() call will not lead to a
2420 * state change message. In this case we explicitely need to signal the I/O thread to
2421 * set up the stream. */
2422 if (PA_SOURCE_IS_OPENED(u->source->state))
2423 pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), PA_SOURCE_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2425 /* We remove the IDLE suspend cause, because otherwise
2426 * module-loopback doesn't uncork its streams. FIXME: Messing with
2427 * the IDLE suspend cause here is wrong, the correct way to handle
2428 * this would probably be to uncork the loopback streams not only
2429 * when the other end is unsuspended, but also when the other end's
2430 * suspend cause changes to IDLE only (currently there's no
2431 * notification mechanism for suspend cause changes, though). */
2432 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2436 pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2439 u->transport_suspended_by_remote = false;
2441 /* Same comment as above */
2442 if (PA_SINK_IS_OPENED(u->sink->state))
2443 pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), PA_SINK_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2445 /* FIXME: See the previous comment. */
2446 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2450 if (release && u->transport_acquired) {
2451 /* FIXME: this release is racy, since the audio stream might have
2452 * been set up again in the meantime (but not processed yet by PA).
2453 * BlueZ should probably release the transport automatically, and in
2454 * that case we would just mark the transport as released */
2456 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2458 pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2459 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2463 pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2465 /* if we change PA state as Suspend, PA client application
2466 * such as music app would face lock-up */
2467 u->transport_suspended_by_remote = true;
2469 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2475 /* Run from main thread */
2476 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2480 if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
2483 pa_log_debug("Unloading module for device %s", d->path);
2484 pa_module_unload(u->module, true);
2490 static void dbus_sco_open_handler(struct userdata *u, struct pa_bluetooth_transport *t)
2497 pa_log_info("Suspending sink %s to handle the SCO connection", u->sink->name);
2499 if (pa_sink_check_suspend(u->sink, NULL, NULL) > 0) {
2500 sink_null = (pa_sink *)pa_namereg_get(u->core, "null", 0);
2503 PA_IDXSET_FOREACH(si, u->core->sink_inputs, idx) {
2504 pa_sink_input_move_to(si, sink_null, false);
2509 pa_sink_suspend(u->sink, true, PA_SUSPEND_INTERNAL);
2513 /* Run from main thread */
2514 static pa_hook_result_t sco_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2518 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2521 if (t->device == u->device)
2522 dbus_sco_open_handler(u, t);
2527 #ifdef TIZEN_BT_AVC_TARGET
2528 static pa_hook_result_t avc_mode_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2532 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2535 if (t->device == u->device)
2536 pa_sink_set_avc_mode(u->sink, t->avc_mode);
2544 /* Run from main thread */
2545 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2549 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2550 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2552 if (t->device == u->device)
2553 handle_transport_state_change(u, t);
2558 static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2566 if (t != u->transport)
2569 gain = t->speaker_gain;
2570 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2572 /* increment volume by one to correct rounding errors */
2573 if (volume < PA_VOLUME_NORM)
2576 pa_cvolume_set(&v, u->sample_spec.channels, volume);
2577 if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
2578 pa_sink_volume_changed(u->sink, &v);
2580 pa_sink_set_volume(u->sink, &v, true, true);
2585 static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2593 if (t != u->transport)
2596 gain = t->microphone_gain;
2597 volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2599 /* increment volume by one to correct rounding errors */
2600 if (volume < PA_VOLUME_NORM)
2603 pa_cvolume_set(&v, u->sample_spec.channels, volume);
2605 if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
2606 pa_source_volume_changed(u->source, &v);
2608 pa_source_set_volume(u->source, &v, true, true);
2613 /* Run from main thread context */
2614 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2615 struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
2616 struct userdata *u = m->card->userdata;
2619 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2620 if (m->card->module->unload_requested)
2623 pa_log_debug("Switching the profile to off due to IO thread failure.");
2624 pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
2626 case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
2627 if (u->transport->state > PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2628 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
2635 int pa__init(pa_module* m) {
2639 bool autodetect_mtu;
2640 #ifdef BLUETOOTH_APTX_SUPPORT
2646 m->userdata = u = pa_xnew0(struct userdata, 1);
2650 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2651 pa_log_error("Failed to parse module arguments");
2652 goto fail_free_modargs;
2656 u->sample_spec = m->core->default_sample_spec;
2660 if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2661 pa_log_error("Failed to get device path from module arguments");
2662 goto fail_free_modargs;
2665 if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2666 pa_bluetooth_discovery_ref(u->discovery);
2668 pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2669 goto fail_free_modargs;
2672 if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2673 pa_log_error("%s is unknown", path);
2674 goto fail_free_modargs;
2677 autodetect_mtu = false;
2678 if (pa_modargs_get_value_boolean(ma, "autodetect_mtu", &autodetect_mtu) < 0) {
2679 pa_log("Invalid boolean value for autodetect_mtu parameter");
2680 goto fail_free_modargs;
2683 u->device->autodetect_mtu = autodetect_mtu;
2685 #ifndef __TIZEN_BT__
2686 pa_modargs_free(ma);
2689 u->device_connection_changed_slot =
2690 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2691 PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2693 u->transport_state_changed_slot =
2694 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2695 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2697 u->transport_speaker_gain_changed_slot =
2698 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2700 u->transport_microphone_gain_changed_slot =
2701 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2704 u->sco_state_changed_slot =
2705 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_SCO_STATE_CHANGED),
2706 PA_HOOK_NORMAL, (pa_hook_cb_t) sco_state_changed_cb, u);
2708 #ifdef TIZEN_BT_AVC_TARGET
2709 u->avc_mode_changed_slot =
2710 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_AVC_MODE_CHANGED),
2711 PA_HOOK_NORMAL, (pa_hook_cb_t) avc_mode_changed_cb, u);
2715 if (add_card(u) < 0)
2718 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2721 u->msg->parent.process_msg = device_process_msg;
2722 u->msg->card = u->card;
2723 u->stream_setup_done = false;
2725 #ifdef BLUETOOTH_APTX_SUPPORT
2726 handle = pa_aptx_get_handle();
2729 pa_log_debug("Aptx Library loaded\n");
2730 pa_load_aptx_sym(handle);
2735 pa_modargs_free(ma);
2739 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2740 if (init_profile(u) < 0)
2743 if (u->sink || u->source)
2744 if (start_thread(u) < 0)
2752 pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2759 pa_modargs_free(ma);
2768 void pa__done(pa_module *m) {
2773 if (!(u = m->userdata))
2778 if (u->device_connection_changed_slot)
2779 pa_hook_slot_free(u->device_connection_changed_slot);
2781 if (u->transport_state_changed_slot)
2782 pa_hook_slot_free(u->transport_state_changed_slot);
2784 if (u->transport_speaker_gain_changed_slot)
2785 pa_hook_slot_free(u->transport_speaker_gain_changed_slot);
2788 if (u->sco_state_changed_slot)
2789 pa_hook_slot_free(u->sco_state_changed_slot);
2790 if (u->avc_mode_changed_slot)
2791 pa_hook_slot_free(u->avc_mode_changed_slot);
2794 if (u->transport_microphone_gain_changed_slot)
2795 pa_hook_slot_free(u->transport_microphone_gain_changed_slot);
2797 if (u->sbc_info.buffer)
2798 pa_xfree(u->sbc_info.buffer);
2800 if (u->sbc_info.sbc_initialized)
2801 sbc_finish(&u->sbc_info.sbc);
2807 pa_card_free(u->card);
2810 pa_bluetooth_discovery_unref(u->discovery);
2812 pa_xfree(u->output_port_name);
2813 pa_xfree(u->input_port_name);
2818 int pa__get_n_used(pa_module *m) {
2822 pa_assert_se(u = m->userdata);
2824 return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);