2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
5 Copyright 2011-2012 BMW Car IT GmbH.
7 PulseAudio is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 PulseAudio is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with PulseAudio; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
33 #include <pulse/rtclock.h>
34 #include <pulse/sample.h>
35 #include <pulse/timeval.h>
36 #include <pulse/xmalloc.h>
38 #include <pulsecore/i18n.h>
39 #include <pulsecore/module.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-rtclock.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/core-error.h>
44 #include <pulsecore/shared.h>
45 #include <pulsecore/socket-util.h>
46 #include <pulsecore/thread.h>
47 #include <pulsecore/thread-mq.h>
48 #include <pulsecore/poll.h>
49 #include <pulsecore/rtpoll.h>
50 #include <pulsecore/time-smoother.h>
51 #include <pulsecore/namereg.h>
52 #include <pulsecore/dbus-shared.h>
56 #include "module-bluetooth-device-symdef.h"
57 #include "a2dp-codecs.h"
59 #include "bluetooth-util.h"
61 #define BITPOOL_DEC_LIMIT 32
62 #define BITPOOL_DEC_STEP 5
63 #define HSP_MAX_GAIN 15
65 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
66 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
67 PA_MODULE_VERSION(PACKAGE_VERSION
);
68 PA_MODULE_LOAD_ONCE(FALSE
);
70 "name=<name for the card/sink/source, to be prefixed> "
71 "card_name=<name for the card> "
72 "card_properties=<properties for the card> "
73 "sink_name=<name for the sink> "
74 "sink_properties=<properties for the sink> "
75 "source_name=<name for the source> "
76 "source_properties=<properties for the source> "
77 "address=<address of the device> "
78 "profile=<a2dp|hsp|hfgw> "
80 "channels=<number of channels> "
81 "path=<device object path> "
82 "auto_connect=<automatically connect?> "
83 "sco_sink=<SCO over PCM sink name> "
84 "sco_source=<SCO over PCM source name>");
86 /* TODO: not close fd when entering suspend mode in a2dp */
88 static const char* const valid_modargs
[] = {
108 sbc_t sbc
; /* Codec data */
109 pa_bool_t sbc_initialized
; /* Keep track if the encoder is initialized */
110 size_t codesize
, frame_length
; /* SBC Codesize, frame_length. We simply cache those values here */
112 void* buffer
; /* Codec transfer buffer */
113 size_t buffer_size
; /* Size of the buffer */
115 uint16_t seq_num
; /* Cumulative packet sequence */
122 void (*sco_sink_set_volume
)(pa_sink
*s
);
123 pa_source
*sco_source
;
124 void (*sco_source_set_volume
)(pa_source
*s
);
125 pa_hook_slot
*sink_state_changed_slot
;
126 pa_hook_slot
*source_state_changed_slot
;
129 struct bluetooth_msg
{
134 typedef struct bluetooth_msg bluetooth_msg
;
135 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg
, pa_msgobject
);
136 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
142 pa_bluetooth_device
*device
;
143 pa_hook_slot
*uuid_added_slot
;
146 pa_bluetooth_transport
*transport
;
148 pa_hook_slot
*discovery_slot
;
149 pa_hook_slot
*transport_state_changed_slot
;
150 pa_hook_slot
*transport_nrec_changed_slot
;
152 pa_bluetooth_discovery
*discovery
;
153 pa_bool_t auto_connect
;
155 pa_dbus_connection
*connection
;
161 pa_thread_mq thread_mq
;
163 pa_rtpoll_item
*rtpoll_item
;
167 uint64_t read_index
, write_index
;
168 pa_usec_t started_at
;
169 pa_smoother
*read_smoother
;
171 pa_memchunk write_memchunk
;
173 pa_sample_spec sample_spec
, requested_sample_spec
;
177 size_t read_link_mtu
;
178 size_t read_block_size
;
180 size_t write_link_mtu
;
181 size_t write_block_size
;
183 struct a2dp_info a2dp
;
186 enum profile profile
;
190 int stream_write_type
;
192 pa_bool_t filter_added
;
196 BLUETOOTH_MESSAGE_IO_THREAD_FAILED
,
197 BLUETOOTH_MESSAGE_MAX
200 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
201 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
202 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
203 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
205 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
207 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
209 static int init_profile(struct userdata
*u
);
212 static void a2dp_set_bitpool(struct userdata
*u
, uint8_t bitpool
)
214 struct a2dp_info
*a2dp
;
220 if (a2dp
->sbc
.bitpool
== bitpool
)
223 if (bitpool
> a2dp
->max_bitpool
)
224 bitpool
= a2dp
->max_bitpool
;
225 else if (bitpool
< a2dp
->min_bitpool
)
226 bitpool
= a2dp
->min_bitpool
;
228 a2dp
->sbc
.bitpool
= bitpool
;
230 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
231 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
233 pa_log_debug("Bitpool has changed to %u", a2dp
->sbc
.bitpool
);
236 (u
->read_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
237 / a2dp
->frame_length
* a2dp
->codesize
;
239 u
->write_block_size
=
240 (u
->write_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
241 / a2dp
->frame_length
* a2dp
->codesize
;
243 pa_sink_set_max_request_within_thread(u
->sink
, u
->write_block_size
);
244 pa_sink_set_fixed_latency_within_thread(u
->sink
,
245 FIXED_LATENCY_PLAYBACK_A2DP
+ pa_bytes_to_usec(u
->write_block_size
, &u
->sample_spec
));
248 /* from IO thread, except in SCO over PCM */
249 static void bt_transport_config_mtu(struct userdata
*u
) {
250 /* Calculate block sizes */
251 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
252 u
->read_block_size
= u
->read_link_mtu
;
253 u
->write_block_size
= u
->write_link_mtu
;
256 (u
->read_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
257 / u
->a2dp
.frame_length
* u
->a2dp
.codesize
;
259 u
->write_block_size
=
260 (u
->write_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
261 / u
->a2dp
.frame_length
* u
->a2dp
.codesize
;
264 if (USE_SCO_OVER_PCM(u
))
268 pa_sink_set_max_request_within_thread(u
->sink
, u
->write_block_size
);
269 pa_sink_set_fixed_latency_within_thread(u
->sink
,
270 (u
->profile
== PROFILE_A2DP
?
271 FIXED_LATENCY_PLAYBACK_A2DP
: FIXED_LATENCY_PLAYBACK_HSP
) +
272 pa_bytes_to_usec(u
->write_block_size
, &u
->sample_spec
));
276 pa_source_set_fixed_latency_within_thread(u
->source
,
277 (u
->profile
== PROFILE_A2DP_SOURCE
?
278 FIXED_LATENCY_RECORD_A2DP
: FIXED_LATENCY_RECORD_HSP
) +
279 pa_bytes_to_usec(u
->read_block_size
, &u
->sample_spec
));
282 /* from IO thread, except in SCO over PCM */
284 static void setup_stream(struct userdata
*u
) {
285 struct pollfd
*pollfd
;
288 pa_log_info("Transport %s resuming", u
->transport
->path
);
290 bt_transport_config_mtu(u
);
292 pa_make_fd_nonblock(u
->stream_fd
);
293 pa_make_socket_low_delay(u
->stream_fd
);
296 if (setsockopt(u
->stream_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
)) < 0)
297 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno
));
299 pa_log_debug("Stream properly set up, we're ready to roll!");
301 if (u
->profile
== PROFILE_A2DP
)
302 a2dp_set_bitpool(u
, u
->a2dp
.max_bitpool
);
304 u
->rtpoll_item
= pa_rtpoll_item_new(u
->rtpoll
, PA_RTPOLL_NEVER
, 1);
305 pollfd
= pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
);
306 pollfd
->fd
= u
->stream_fd
;
307 pollfd
->events
= pollfd
->revents
= 0;
309 u
->read_index
= u
->write_index
= 0;
313 u
->read_smoother
= pa_smoother_new(
323 static bool bt_transport_is_acquired(struct userdata
*u
) {
324 if (u
->accesstype
== NULL
) {
325 pa_assert(u
->stream_fd
< 0);
328 /* During IO thread HUP stream_fd can be -1 */
333 static void teardown_stream(struct userdata
*u
) {
334 if (u
->rtpoll_item
) {
335 pa_rtpoll_item_free(u
->rtpoll_item
);
336 u
->rtpoll_item
= NULL
;
339 if (u
->stream_fd
>= 0) {
340 pa_close(u
->stream_fd
);
344 if (u
->read_smoother
) {
345 pa_smoother_free(u
->read_smoother
);
346 u
->read_smoother
= NULL
;
349 pa_log_debug("Audio stream torn down");
352 static void bt_transport_release(struct userdata
*u
) {
353 pa_assert(u
->transport
);
355 /* Ignore if already released */
356 if (!bt_transport_is_acquired(u
))
359 pa_log_debug("Releasing transport %s", u
->transport
->path
);
361 pa_bluetooth_transport_release(u
->transport
, u
->accesstype
);
363 pa_xfree(u
->accesstype
);
364 u
->accesstype
= NULL
;
369 static int bt_transport_acquire(struct userdata
*u
, pa_bool_t start
) {
370 const char *accesstype
= "rw";
372 pa_assert(u
->transport
);
374 if (bt_transport_is_acquired(u
)) {
380 pa_log_debug("Acquiring transport %s", u
->transport
->path
);
383 /* FIXME: we are trying to acquire the transport only if the stream is
384 playing, without actually initiating the stream request from our side
385 (which is typically undesireable specially for hfgw use-cases.
386 However this approach is racy, since the stream could have been
387 suspended in the meantime, so we can't really guarantee that the
388 stream will not be requested until BlueZ's API supports this
390 if (u
->device
->profile_state
[u
->profile
] < PA_BT_AUDIO_STATE_PLAYING
) {
391 pa_log_info("Failed optional acquire of transport %s", u
->transport
->path
);
396 u
->stream_fd
= pa_bluetooth_transport_acquire(u
->transport
, accesstype
, &u
->read_link_mtu
, &u
->write_link_mtu
);
397 if (u
->stream_fd
< 0) {
399 pa_log("Failed to acquire transport %s", u
->transport
->path
);
401 pa_log_info("Failed optional acquire of transport %s", u
->transport
->path
);
406 u
->accesstype
= pa_xstrdup(accesstype
);
407 pa_log_info("Transport %s acquired: fd %d", u
->transport
->path
, u
->stream_fd
);
413 /* If thread is still about to start, the stream will be set up in the beginning of thread_func() */
414 if (u
->thread
== NULL
)
422 /* Run from IO thread */
423 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
424 struct userdata
*u
= PA_SINK(o
)->userdata
;
425 pa_bool_t failed
= FALSE
;
428 pa_assert(u
->sink
== PA_SINK(o
));
429 pa_assert(u
->transport
);
433 case PA_SINK_MESSAGE_SET_STATE
:
435 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
437 case PA_SINK_SUSPENDED
:
438 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
439 if (!PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
))
442 /* Stop the device if the source is suspended as well */
443 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
)
444 /* We deliberately ignore whether stopping
445 * actually worked. Since the stream_fd is
446 * closed it doesn't really matter */
447 bt_transport_release(u
);
452 case PA_SINK_RUNNING
:
453 if (u
->sink
->thread_info
.state
!= PA_SINK_SUSPENDED
)
456 /* Resume the device if the source was suspended as well */
457 if (!u
->source
|| !PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
)) {
458 if (bt_transport_acquire(u
, TRUE
) < 0)
463 case PA_SINK_UNLINKED
:
465 case PA_SINK_INVALID_STATE
:
470 case PA_SINK_MESSAGE_GET_LATENCY
: {
472 if (u
->read_smoother
) {
475 ri
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
476 wi
= pa_bytes_to_usec(u
->write_index
+ u
->write_block_size
, &u
->sample_spec
);
478 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
482 ri
= pa_rtclock_now() - u
->started_at
;
483 wi
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
485 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
488 *((pa_usec_t
*) data
) += u
->sink
->thread_info
.fixed_latency
;
493 r
= pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
495 return (r
< 0 || !failed
) ? r
: -1;
498 /* Run from IO thread */
499 static int source_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
500 struct userdata
*u
= PA_SOURCE(o
)->userdata
;
501 pa_bool_t failed
= FALSE
;
504 pa_assert(u
->source
== PA_SOURCE(o
));
505 pa_assert(u
->transport
);
509 case PA_SOURCE_MESSAGE_SET_STATE
:
511 switch ((pa_source_state_t
) PA_PTR_TO_UINT(data
)) {
513 case PA_SOURCE_SUSPENDED
:
514 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
515 if (!PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
))
518 /* Stop the device if the sink is suspended as well */
519 if (!u
->sink
|| u
->sink
->state
== PA_SINK_SUSPENDED
)
520 bt_transport_release(u
);
522 if (u
->read_smoother
)
523 pa_smoother_pause(u
->read_smoother
, pa_rtclock_now());
527 case PA_SOURCE_RUNNING
:
528 if (u
->source
->thread_info
.state
!= PA_SOURCE_SUSPENDED
)
531 /* Resume the device if the sink was suspended as well */
532 if (!u
->sink
|| !PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
)) {
533 if (bt_transport_acquire(u
, TRUE
) < 0)
536 /* We don't resume the smoother here. Instead we
537 * wait until the first packet arrives */
540 case PA_SOURCE_UNLINKED
:
542 case PA_SOURCE_INVALID_STATE
:
547 case PA_SOURCE_MESSAGE_GET_LATENCY
: {
550 if (u
->read_smoother
) {
551 wi
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
552 ri
= pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
);
554 *((pa_usec_t
*) data
) = (wi
> ri
? wi
- ri
: 0) + u
->source
->thread_info
.fixed_latency
;
556 *((pa_usec_t
*) data
) = 0;
563 r
= pa_source_process_msg(o
, code
, data
, offset
, chunk
);
565 return (r
< 0 || !failed
) ? r
: -1;
568 /* Called from main thread context */
569 static int device_process_msg(pa_msgobject
*obj
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
570 struct bluetooth_msg
*u
= BLUETOOTH_MSG(obj
);
573 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED
: {
574 if (u
->card
->module
->unload_requested
)
577 pa_log_debug("Switching the profile to off due to IO thread failure.");
579 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
586 /* Run from IO thread */
587 static int hsp_process_render(struct userdata
*u
) {
591 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
594 /* First, render some data */
595 if (!u
->write_memchunk
.memblock
)
596 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
598 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
604 /* Now write that data to the socket. The socket is of type
605 * SEQPACKET, and we generated the data of the MTU size, so this
606 * should just work. */
608 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
609 l
= pa_write(u
->stream_fd
, p
, u
->write_memchunk
.length
, &u
->stream_write_type
);
610 pa_memblock_release(u
->write_memchunk
.memblock
);
617 /* Retry right away if we got interrupted */
620 else if (errno
== EAGAIN
)
621 /* Hmm, apparently the socket was not writable, give up for now */
624 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno
));
629 pa_assert((size_t) l
<= u
->write_memchunk
.length
);
631 if ((size_t) l
!= u
->write_memchunk
.length
) {
632 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
633 (unsigned long long) l
,
634 (unsigned long long) u
->write_memchunk
.length
);
639 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
640 pa_memblock_unref(u
->write_memchunk
.memblock
);
641 pa_memchunk_reset(&u
->write_memchunk
);
650 /* Run from IO thread */
651 static int hsp_process_push(struct userdata
*u
) {
653 pa_memchunk memchunk
;
656 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
657 pa_assert(u
->source
);
658 pa_assert(u
->read_smoother
);
660 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
661 memchunk
.index
= memchunk
.length
= 0;
670 pa_bool_t found_tstamp
= FALSE
;
673 memset(&m
, 0, sizeof(m
));
674 memset(&aux
, 0, sizeof(aux
));
675 memset(&iov
, 0, sizeof(iov
));
680 m
.msg_controllen
= sizeof(aux
);
682 p
= pa_memblock_acquire(memchunk
.memblock
);
684 iov
.iov_len
= pa_memblock_get_length(memchunk
.memblock
);
685 l
= recvmsg(u
->stream_fd
, &m
, 0);
686 pa_memblock_release(memchunk
.memblock
);
690 if (l
< 0 && errno
== EINTR
)
691 /* Retry right away if we got interrupted */
694 else if (l
< 0 && errno
== EAGAIN
)
695 /* Hmm, apparently the socket was not readable, give up for now. */
698 pa_log_error("Failed to read data from SCO socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
703 pa_assert((size_t) l
<= pa_memblock_get_length(memchunk
.memblock
));
705 memchunk
.length
= (size_t) l
;
706 u
->read_index
+= (uint64_t) l
;
708 for (cm
= CMSG_FIRSTHDR(&m
); cm
; cm
= CMSG_NXTHDR(&m
, cm
))
709 if (cm
->cmsg_level
== SOL_SOCKET
&& cm
->cmsg_type
== SO_TIMESTAMP
) {
710 struct timeval
*tv
= (struct timeval
*) CMSG_DATA(cm
);
711 pa_rtclock_from_wallclock(tv
);
712 tstamp
= pa_timeval_load(tv
);
718 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
719 tstamp
= pa_rtclock_now();
722 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
723 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
725 pa_source_post(u
->source
, &memchunk
);
731 pa_memblock_unref(memchunk
.memblock
);
736 /* Run from IO thread */
737 static void a2dp_prepare_buffer(struct userdata
*u
) {
738 size_t min_buffer_size
= PA_MAX(u
->read_link_mtu
, u
->write_link_mtu
);
742 if (u
->a2dp
.buffer_size
>= min_buffer_size
)
745 u
->a2dp
.buffer_size
= 2 * min_buffer_size
;
746 pa_xfree(u
->a2dp
.buffer
);
747 u
->a2dp
.buffer
= pa_xmalloc(u
->a2dp
.buffer_size
);
750 /* Run from IO thread */
751 static int a2dp_process_render(struct userdata
*u
) {
752 struct a2dp_info
*a2dp
;
753 struct rtp_header
*header
;
754 struct rtp_payload
*payload
;
758 size_t to_write
, to_encode
;
759 unsigned frame_count
;
763 pa_assert(u
->profile
== PROFILE_A2DP
);
766 /* First, render some data */
767 if (!u
->write_memchunk
.memblock
)
768 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
770 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
772 a2dp_prepare_buffer(u
);
775 header
= a2dp
->buffer
;
776 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
780 /* Try to create a packet of the full MTU */
782 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
783 to_encode
= u
->write_memchunk
.length
;
785 d
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
786 to_write
= a2dp
->buffer_size
- sizeof(*header
) - sizeof(*payload
);
788 while (PA_LIKELY(to_encode
> 0 && to_write
> 0)) {
792 encoded
= sbc_encode(&a2dp
->sbc
,
797 if (PA_UNLIKELY(encoded
<= 0)) {
798 pa_log_error("SBC encoding error (%li)", (long) encoded
);
799 pa_memblock_release(u
->write_memchunk
.memblock
);
803 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
804 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
806 pa_assert_fp((size_t) encoded
<= to_encode
);
807 pa_assert_fp((size_t) encoded
== a2dp
->codesize
);
809 pa_assert_fp((size_t) written
<= to_write
);
810 pa_assert_fp((size_t) written
== a2dp
->frame_length
);
812 p
= (const uint8_t*) p
+ encoded
;
813 to_encode
-= encoded
;
815 d
= (uint8_t*) d
+ written
;
821 pa_memblock_release(u
->write_memchunk
.memblock
);
823 pa_assert(to_encode
== 0);
826 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp
->sbc
)));
829 /* write it to the fifo */
830 memset(a2dp
->buffer
, 0, sizeof(*header
) + sizeof(*payload
));
833 header
->sequence_number
= htons(a2dp
->seq_num
++);
834 header
->timestamp
= htonl(u
->write_index
/ pa_frame_size(&u
->sample_spec
));
835 header
->ssrc
= htonl(1);
836 payload
->frame_count
= frame_count
;
838 nbytes
= (uint8_t*) d
- (uint8_t*) a2dp
->buffer
;
843 l
= pa_write(u
->stream_fd
, a2dp
->buffer
, nbytes
, &u
->stream_write_type
);
850 /* Retry right away if we got interrupted */
853 else if (errno
== EAGAIN
)
854 /* Hmm, apparently the socket was not writable, give up for now */
857 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno
));
862 pa_assert((size_t) l
<= nbytes
);
864 if ((size_t) l
!= nbytes
) {
865 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
866 (unsigned long long) l
,
867 (unsigned long long) nbytes
);
872 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
873 pa_memblock_unref(u
->write_memchunk
.memblock
);
874 pa_memchunk_reset(&u
->write_memchunk
);
884 static int a2dp_process_push(struct userdata
*u
) {
886 pa_memchunk memchunk
;
889 pa_assert(u
->profile
== PROFILE_A2DP_SOURCE
);
890 pa_assert(u
->source
);
891 pa_assert(u
->read_smoother
);
893 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
894 memchunk
.index
= memchunk
.length
= 0;
897 pa_bool_t found_tstamp
= FALSE
;
899 struct a2dp_info
*a2dp
;
900 struct rtp_header
*header
;
901 struct rtp_payload
*payload
;
905 size_t to_write
, to_decode
;
907 a2dp_prepare_buffer(u
);
910 header
= a2dp
->buffer
;
911 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
913 l
= pa_read(u
->stream_fd
, a2dp
->buffer
, a2dp
->buffer_size
, &u
->stream_write_type
);
917 if (l
< 0 && errno
== EINTR
)
918 /* Retry right away if we got interrupted */
921 else if (l
< 0 && errno
== EAGAIN
)
922 /* Hmm, apparently the socket was not readable, give up for now. */
925 pa_log_error("Failed to read data from socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
930 pa_assert((size_t) l
<= a2dp
->buffer_size
);
932 u
->read_index
+= (uint64_t) l
;
934 /* TODO: get timestamp from rtp */
936 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
937 tstamp
= pa_rtclock_now();
940 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
941 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
943 p
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
944 to_decode
= l
- sizeof(*header
) - sizeof(*payload
);
946 d
= pa_memblock_acquire(memchunk
.memblock
);
947 to_write
= memchunk
.length
= pa_memblock_get_length(memchunk
.memblock
);
949 while (PA_LIKELY(to_decode
> 0)) {
953 decoded
= sbc_decode(&a2dp
->sbc
,
958 if (PA_UNLIKELY(decoded
<= 0)) {
959 pa_log_error("SBC decoding error (%li)", (long) decoded
);
960 pa_memblock_release(memchunk
.memblock
);
961 pa_memblock_unref(memchunk
.memblock
);
965 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
966 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
968 /* Reset frame length, it can be changed due to bitpool change */
969 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
971 pa_assert_fp((size_t) decoded
<= to_decode
);
972 pa_assert_fp((size_t) decoded
== a2dp
->frame_length
);
974 pa_assert_fp((size_t) written
== a2dp
->codesize
);
976 p
= (const uint8_t*) p
+ decoded
;
977 to_decode
-= decoded
;
979 d
= (uint8_t*) d
+ written
;
983 memchunk
.length
-= to_write
;
985 pa_memblock_release(memchunk
.memblock
);
987 pa_source_post(u
->source
, &memchunk
);
993 pa_memblock_unref(memchunk
.memblock
);
998 static void a2dp_reduce_bitpool(struct userdata
*u
)
1000 struct a2dp_info
*a2dp
;
1007 /* Check if bitpool is already at its limit */
1008 if (a2dp
->sbc
.bitpool
<= BITPOOL_DEC_LIMIT
)
1011 bitpool
= a2dp
->sbc
.bitpool
- BITPOOL_DEC_STEP
;
1013 if (bitpool
< BITPOOL_DEC_LIMIT
)
1014 bitpool
= BITPOOL_DEC_LIMIT
;
1016 a2dp_set_bitpool(u
, bitpool
);
1019 static void thread_func(void *userdata
) {
1020 struct userdata
*u
= userdata
;
1021 unsigned do_write
= 0;
1022 unsigned pending_read_bytes
= 0;
1023 pa_bool_t writable
= FALSE
;
1026 pa_assert(u
->transport
);
1028 pa_log_debug("IO Thread starting up");
1030 if (u
->core
->realtime_scheduling
)
1031 pa_make_realtime(u
->core
->realtime_priority
);
1033 pa_thread_mq_install(&u
->thread_mq
);
1035 /* Setup the stream only if the transport was already acquired */
1036 if (bt_transport_is_acquired(u
))
1040 struct pollfd
*pollfd
;
1042 pa_bool_t disable_timer
= TRUE
;
1044 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1046 if (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) {
1048 /* We should send two blocks to the device before we expect
1051 if (u
->write_index
== 0 && u
->read_index
<= 0)
1054 if (pollfd
&& (pollfd
->revents
& POLLIN
)) {
1057 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
)
1058 n_read
= hsp_process_push(u
);
1060 n_read
= a2dp_process_push(u
);
1065 /* We just read something, so we are supposed to write something, too */
1066 pending_read_bytes
+= n_read
;
1067 do_write
+= pending_read_bytes
/ u
->write_block_size
;
1068 pending_read_bytes
= pending_read_bytes
% u
->write_block_size
;
1072 if (u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
)) {
1074 if (PA_UNLIKELY(u
->sink
->thread_info
.rewind_requested
))
1075 pa_sink_process_rewind(u
->sink
, 0);
1078 if (pollfd
->revents
& POLLOUT
)
1081 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1082 pa_usec_t time_passed
;
1083 pa_usec_t audio_sent
;
1085 /* Hmm, there is no input stream we could synchronize
1086 * to. So let's do things by time */
1088 time_passed
= pa_rtclock_now() - u
->started_at
;
1089 audio_sent
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1091 if (audio_sent
<= time_passed
) {
1092 pa_usec_t audio_to_send
= time_passed
- audio_sent
;
1094 /* Never try to catch up for more than 100ms */
1095 if (u
->write_index
> 0 && audio_to_send
> MAX_PLAYBACK_CATCH_UP_USEC
) {
1096 pa_usec_t skip_usec
;
1097 uint64_t skip_bytes
;
1099 skip_usec
= audio_to_send
- MAX_PLAYBACK_CATCH_UP_USEC
;
1100 skip_bytes
= pa_usec_to_bytes(skip_usec
, &u
->sample_spec
);
1102 if (skip_bytes
> 0) {
1105 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1106 (unsigned long long) skip_usec
,
1107 (unsigned long long) skip_bytes
);
1109 pa_sink_render_full(u
->sink
, skip_bytes
, &tmp
);
1110 pa_memblock_unref(tmp
.memblock
);
1111 u
->write_index
+= skip_bytes
;
1113 if (u
->profile
== PROFILE_A2DP
)
1114 a2dp_reduce_bitpool(u
);
1119 pending_read_bytes
= 0;
1123 if (writable
&& do_write
> 0) {
1126 if (u
->write_index
<= 0)
1127 u
->started_at
= pa_rtclock_now();
1129 if (u
->profile
== PROFILE_A2DP
) {
1130 if ((n_written
= a2dp_process_render(u
)) < 0)
1133 if ((n_written
= hsp_process_render(u
)) < 0)
1138 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1140 do_write
-= n_written
;
1144 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0) {
1145 pa_usec_t sleep_for
;
1146 pa_usec_t time_passed
, next_write_at
;
1149 /* Hmm, there is no input stream we could synchronize
1150 * to. So let's estimate when we need to wake up the latest */
1151 time_passed
= pa_rtclock_now() - u
->started_at
;
1152 next_write_at
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1153 sleep_for
= time_passed
< next_write_at
? next_write_at
- time_passed
: 0;
1154 /* 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); */
1156 /* drop stream every 500 ms */
1157 sleep_for
= PA_USEC_PER_MSEC
* 500;
1159 pa_rtpoll_set_timer_relative(u
->rtpoll
, sleep_for
);
1160 disable_timer
= FALSE
;
1166 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
1168 /* Hmm, nothing to do. Let's sleep */
1170 pollfd
->events
= (short) (((u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
) && !writable
) ? POLLOUT
: 0) |
1171 (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
) ? POLLIN
: 0));
1173 if ((ret
= pa_rtpoll_run(u
->rtpoll
, TRUE
)) < 0) {
1174 pa_log_debug("pa_rtpoll_run failed with: %d", ret
);
1178 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1179 bt_transport_release(u
);
1183 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1185 if (pollfd
&& (pollfd
->revents
& ~(POLLOUT
|POLLIN
))) {
1186 pa_log_info("FD error: %s%s%s%s",
1187 pollfd
->revents
& POLLERR
? "POLLERR " :"",
1188 pollfd
->revents
& POLLHUP
? "POLLHUP " :"",
1189 pollfd
->revents
& POLLPRI
? "POLLPRI " :"",
1190 pollfd
->revents
& POLLNVAL
? "POLLNVAL " :"");
1197 /* In case of HUP, just tear down the streams */
1198 if (!pollfd
|| (pollfd
->revents
& POLLHUP
) == 0)
1202 pending_read_bytes
= 0;
1209 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1210 pa_log_debug("IO thread failed");
1211 pa_asyncmsgq_post(pa_thread_mq_get()->outq
, PA_MSGOBJECT(u
->msg
), BLUETOOTH_MESSAGE_IO_THREAD_FAILED
, NULL
, 0, NULL
, NULL
);
1212 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1215 pa_log_debug("IO thread shutting down");
1218 static pa_bt_audio_state_t
parse_state_property_change(DBusMessage
*m
) {
1219 DBusMessageIter iter
;
1220 DBusMessageIter variant
;
1223 pa_bt_audio_state_t state
;
1225 if (!dbus_message_iter_init(m
, &iter
)) {
1226 pa_log("Failed to parse PropertyChanged");
1227 return PA_BT_AUDIO_STATE_INVALID
;
1230 if (dbus_message_iter_get_arg_type(&iter
) != DBUS_TYPE_STRING
) {
1231 pa_log("Property name not a string");
1232 return PA_BT_AUDIO_STATE_INVALID
;
1235 dbus_message_iter_get_basic(&iter
, &key
);
1237 if (!pa_streq(key
, "State"))
1238 return PA_BT_AUDIO_STATE_INVALID
;
1240 if (!dbus_message_iter_next(&iter
)) {
1241 pa_log("Property value missing");
1242 return PA_BT_AUDIO_STATE_INVALID
;
1245 dbus_message_iter_recurse(&iter
, &variant
);
1247 if (dbus_message_iter_get_arg_type(&variant
) != DBUS_TYPE_STRING
) {
1248 pa_log("Property value not a string");
1249 return PA_BT_AUDIO_STATE_INVALID
;
1252 dbus_message_iter_get_basic(&variant
, &value
);
1254 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m
), value
);
1256 state
= pa_bt_audio_state_from_string(value
);
1258 if (state
== PA_BT_AUDIO_STATE_INVALID
)
1259 pa_log("Unexpected value for property 'State': '%s'", value
);
1264 static pa_port_available_t
audio_state_to_availability(pa_bt_audio_state_t state
) {
1265 if (state
< PA_BT_AUDIO_STATE_CONNECTED
)
1266 return PA_PORT_AVAILABLE_NO
;
1267 else if (state
>= PA_BT_AUDIO_STATE_PLAYING
)
1268 return PA_PORT_AVAILABLE_YES
;
1270 return PA_PORT_AVAILABLE_UNKNOWN
;
1273 static pa_port_available_t
audio_state_to_availability_merged(pa_bt_audio_state_t state1
, pa_bt_audio_state_t state2
) {
1274 if (state1
< PA_BT_AUDIO_STATE_CONNECTED
&& state2
< PA_BT_AUDIO_STATE_CONNECTED
)
1275 return PA_PORT_AVAILABLE_NO
;
1276 else if (state1
>= PA_BT_AUDIO_STATE_PLAYING
|| state2
>= PA_BT_AUDIO_STATE_PLAYING
)
1277 return PA_PORT_AVAILABLE_YES
;
1279 return PA_PORT_AVAILABLE_UNKNOWN
;
1282 /* Run from main thread */
1283 static DBusHandlerResult
filter_cb(DBusConnection
*bus
, DBusMessage
*m
, void *userdata
) {
1286 bool acquire
= FALSE
;
1287 bool release
= FALSE
;
1291 pa_assert_se(u
= userdata
);
1293 dbus_error_init(&err
);
1295 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1296 dbus_message_get_interface(m
),
1297 dbus_message_get_path(m
),
1298 dbus_message_get_member(m
));
1300 if (!dbus_message_has_path(m
, u
->path
) && (!u
->transport
|| !dbus_message_has_path(m
, u
->transport
->path
)))
1303 if (dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged") ||
1304 dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1309 if (!dbus_message_get_args(m
, &err
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
) || gain
> HSP_MAX_GAIN
) {
1310 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err
.message
);
1314 if (u
->profile
== PROFILE_HSP
) {
1315 if (u
->sink
&& dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged")) {
1316 pa_volume_t volume
= (pa_volume_t
) round((double) gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1318 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1319 pa_sink_volume_changed(u
->sink
, &v
);
1321 } else if (u
->source
&& dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1322 pa_volume_t volume
= (pa_volume_t
) round((double) gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1324 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1325 pa_source_volume_changed(u
->source
, &v
);
1328 } else if (dbus_message_is_signal(m
, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1329 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1331 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "hfgw")) {
1332 pa_device_port
*port
;
1333 pa_port_available_t available
= audio_state_to_availability(state
);
1335 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1336 pa_device_port_set_available(port
, available
);
1338 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1339 pa_device_port_set_available(port
, available
);
1341 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1342 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1344 } else if (dbus_message_is_signal(m
, "org.bluez.Headset", "PropertyChanged")) {
1345 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1347 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "hsp")) {
1348 pa_device_port
*port
;
1349 pa_port_available_t available
;
1351 if (pa_hashmap_get(u
->card
->profiles
, "a2dp") == NULL
)
1352 available
= audio_state_to_availability(state
);
1354 available
= audio_state_to_availability_merged(state
, u
->device
->profile_state
[PROFILE_A2DP
]);
1356 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1357 pa_device_port_set_available(port
, available
);
1359 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1360 pa_device_port_set_available(port
, available
);
1362 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1363 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1365 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSource", "PropertyChanged")) {
1366 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1368 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "a2dp_source")) {
1369 pa_device_port
*port
;
1370 pa_port_available_t available
= audio_state_to_availability(state
);
1372 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1373 pa_device_port_set_available(port
, available
);
1375 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1376 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1378 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSink", "PropertyChanged")) {
1379 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1381 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "a2dp")) {
1382 pa_device_port
*port
;
1383 pa_port_available_t available
;
1385 if (pa_hashmap_get(u
->card
->profiles
, "hsp") == NULL
)
1386 available
= audio_state_to_availability(state
);
1388 available
= audio_state_to_availability_merged(state
, u
->device
->profile_state
[PROFILE_HSP
]);
1390 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1391 pa_device_port_set_available(port
, available
);
1393 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1394 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1399 if (bt_transport_acquire(u
, FALSE
) >= 0) {
1401 pa_log_debug("Resuming source %s, because the bluetooth audio state changed to 'playing'.", u
->source
->name
);
1402 pa_source_suspend(u
->source
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1406 pa_log_debug("Resuming sink %s, because the bluetooth audio state changed to 'playing'.", u
->sink
->name
);
1407 pa_sink_suspend(u
->sink
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1411 if (release
&& bt_transport_is_acquired(u
)) {
1412 /* FIXME: this release is racy, since the audio stream might have
1413 been set up again in the meantime (but not processed yet by PA).
1414 BlueZ should probably release the transport automatically, and
1415 in that case we would just mark the transport as released */
1417 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1419 pa_log_debug("Suspending source %s, because the remote end closed the stream.", u
->source
->name
);
1420 pa_source_suspend(u
->source
, TRUE
, PA_SUSPEND_USER
);
1424 pa_log_debug("Suspending sink %s, because the remote end closed the stream.", u
->sink
->name
);
1425 pa_sink_suspend(u
->sink
, TRUE
, PA_SUSPEND_USER
);
1430 dbus_error_free(&err
);
1432 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1435 /* Run from main thread */
1436 static void sink_set_volume_cb(pa_sink
*s
) {
1446 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1447 u
= pa_shared_get(s
->core
, k
);
1451 pa_assert(u
->sink
== s
);
1452 pa_assert(u
->profile
== PROFILE_HSP
);
1454 gain
= (dbus_uint16_t
) round((double) pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
/ PA_VOLUME_NORM
);
1455 volume
= (pa_volume_t
) round((double) gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1457 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1459 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetSpeakerGain"));
1460 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1461 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1462 dbus_message_unref(m
);
1465 /* Run from main thread */
1466 static void source_set_volume_cb(pa_source
*s
) {
1476 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1477 u
= pa_shared_get(s
->core
, k
);
1481 pa_assert(u
->source
== s
);
1482 pa_assert(u
->profile
== PROFILE_HSP
);
1484 gain
= (dbus_uint16_t
) round((double) pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
/ PA_VOLUME_NORM
);
1485 volume
= (pa_volume_t
) round((double) gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1487 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1489 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetMicrophoneGain"));
1490 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1491 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1492 dbus_message_unref(m
);
1495 /* Run from main thread */
1496 static char *get_name(const char *type
, pa_modargs
*ma
, const char *device_id
, pa_bool_t
*namereg_fail
) {
1502 pa_assert(device_id
);
1503 pa_assert(namereg_fail
);
1505 t
= pa_sprintf_malloc("%s_name", type
);
1506 n
= pa_modargs_get_value(ma
, t
, NULL
);
1510 *namereg_fail
= TRUE
;
1511 return pa_xstrdup(n
);
1514 if ((n
= pa_modargs_get_value(ma
, "name", NULL
)))
1515 *namereg_fail
= TRUE
;
1518 *namereg_fail
= FALSE
;
1521 return pa_sprintf_malloc("bluez_%s.%s", type
, n
);
1524 static int sco_over_pcm_state_update(struct userdata
*u
, pa_bool_t changed
) {
1526 pa_assert(USE_SCO_OVER_PCM(u
));
1528 if (PA_SINK_IS_OPENED(pa_sink_get_state(u
->hsp
.sco_sink
)) ||
1529 PA_SOURCE_IS_OPENED(pa_source_get_state(u
->hsp
.sco_source
))) {
1531 if (u
->stream_fd
>= 0)
1534 pa_log_debug("Resuming SCO over PCM");
1535 if (init_profile(u
) < 0) {
1536 pa_log("Can't resume SCO over PCM");
1540 return bt_transport_acquire(u
, TRUE
);
1544 if (u
->stream_fd
< 0)
1547 pa_log_debug("Closing SCO over PCM");
1549 bt_transport_release(u
);
1555 static pa_hook_result_t
sink_state_changed_cb(pa_core
*c
, pa_sink
*s
, struct userdata
*u
) {
1557 pa_sink_assert_ref(s
);
1560 if (s
!= u
->hsp
.sco_sink
)
1563 sco_over_pcm_state_update(u
, TRUE
);
1568 static pa_hook_result_t
source_state_changed_cb(pa_core
*c
, pa_source
*s
, struct userdata
*u
) {
1570 pa_source_assert_ref(s
);
1573 if (s
!= u
->hsp
.sco_source
)
1576 sco_over_pcm_state_update(u
, TRUE
);
1581 static pa_hook_result_t
transport_nrec_changed_cb(pa_bluetooth_discovery
*y
, pa_bluetooth_transport
*t
, struct userdata
*u
) {
1587 if (t
!= u
->transport
)
1590 p
= pa_proplist_new();
1591 pa_proplist_sets(p
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1592 pa_source_update_proplist(u
->source
, PA_UPDATE_REPLACE
, p
);
1593 pa_proplist_free(p
);
1598 static void connect_ports(struct userdata
*u
, void *sink_or_source_new_data
, pa_direction_t direction
) {
1600 pa_sink_new_data
*sink_new_data
;
1601 pa_source_new_data
*source_new_data
;
1603 pa_device_port
*port
;
1605 if (direction
== PA_DIRECTION_OUTPUT
)
1606 data
.sink_new_data
= sink_or_source_new_data
;
1608 data
.source_new_data
= sink_or_source_new_data
;
1610 switch (u
->profile
) {
1612 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1613 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1614 pa_device_port_ref(port
);
1617 case PROFILE_A2DP_SOURCE
:
1618 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1619 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1620 pa_device_port_ref(port
);
1624 if (direction
== PA_DIRECTION_OUTPUT
) {
1625 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1626 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1628 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1629 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1631 pa_device_port_ref(port
);
1635 if (direction
== PA_DIRECTION_OUTPUT
) {
1636 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1637 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1639 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1640 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1642 pa_device_port_ref(port
);
1646 pa_assert_not_reached();
1650 static const char *profile_to_string(enum profile profile
) {
1654 case PROFILE_A2DP_SOURCE
:
1655 return "a2dp_source";
1661 pa_assert_not_reached();
1665 static int sink_set_port_cb(pa_sink
*s
, pa_device_port
*p
) {
1669 static int source_set_port_cb(pa_source
*s
, pa_device_port
*p
) {
1673 /* Run from main thread */
1674 static int add_sink(struct userdata
*u
) {
1677 pa_assert(u
->transport
);
1679 if (USE_SCO_OVER_PCM(u
)) {
1682 u
->sink
= u
->hsp
.sco_sink
;
1683 p
= pa_proplist_new();
1684 pa_proplist_sets(p
, "bluetooth.protocol", profile_to_string(u
->profile
));
1685 pa_proplist_update(u
->sink
->proplist
, PA_UPDATE_MERGE
, p
);
1686 pa_proplist_free(p
);
1688 if (!u
->hsp
.sink_state_changed_slot
)
1689 u
->hsp
.sink_state_changed_slot
= pa_hook_connect(&u
->core
->hooks
[PA_CORE_HOOK_SINK_STATE_CHANGED
], PA_HOOK_NORMAL
, (pa_hook_cb_t
) sink_state_changed_cb
, u
);
1692 pa_sink_new_data data
;
1695 pa_sink_new_data_init(&data
);
1696 data
.driver
= __FILE__
;
1697 data
.module
= u
->module
;
1698 pa_sink_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1699 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1700 if (u
->profile
== PROFILE_HSP
)
1701 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1702 data
.card
= u
->card
;
1703 data
.name
= get_name("sink", u
->modargs
, u
->address
, &b
);
1704 data
.namereg_fail
= b
;
1706 if (pa_modargs_get_proplist(u
->modargs
, "sink_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1707 pa_log("Invalid properties");
1708 pa_sink_new_data_done(&data
);
1711 connect_ports(u
, &data
, PA_DIRECTION_OUTPUT
);
1713 if (!bt_transport_is_acquired(u
))
1714 switch (u
->profile
) {
1717 pa_assert_not_reached(); /* Profile switch should have failed */
1720 data
.suspend_cause
= PA_SUSPEND_USER
;
1722 case PROFILE_A2DP_SOURCE
:
1724 pa_assert_not_reached();
1727 u
->sink
= pa_sink_new(u
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
);
1728 pa_sink_new_data_done(&data
);
1731 pa_log_error("Failed to create sink");
1735 u
->sink
->userdata
= u
;
1736 u
->sink
->parent
.process_msg
= sink_process_msg
;
1737 u
->sink
->set_port
= sink_set_port_cb
;
1740 if (u
->profile
== PROFILE_HSP
) {
1741 pa_sink_set_set_volume_callback(u
->sink
, sink_set_volume_cb
);
1742 u
->sink
->n_volume_steps
= 16;
1744 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
1745 pa_shared_set(u
->core
, k
, u
);
1752 /* Run from main thread */
1753 static int add_source(struct userdata
*u
) {
1756 pa_assert(u
->transport
);
1758 if (USE_SCO_OVER_PCM(u
)) {
1759 u
->source
= u
->hsp
.sco_source
;
1760 pa_proplist_sets(u
->source
->proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1762 if (!u
->hsp
.source_state_changed_slot
)
1763 u
->hsp
.source_state_changed_slot
= pa_hook_connect(&u
->core
->hooks
[PA_CORE_HOOK_SOURCE_STATE_CHANGED
], PA_HOOK_NORMAL
, (pa_hook_cb_t
) source_state_changed_cb
, u
);
1766 pa_source_new_data data
;
1769 pa_source_new_data_init(&data
);
1770 data
.driver
= __FILE__
;
1771 data
.module
= u
->module
;
1772 pa_source_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1773 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1774 if (u
->profile
== PROFILE_HSP
)
1775 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1777 data
.card
= u
->card
;
1778 data
.name
= get_name("source", u
->modargs
, u
->address
, &b
);
1779 data
.namereg_fail
= b
;
1781 if (pa_modargs_get_proplist(u
->modargs
, "source_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1782 pa_log("Invalid properties");
1783 pa_source_new_data_done(&data
);
1787 connect_ports(u
, &data
, PA_DIRECTION_INPUT
);
1789 if (!bt_transport_is_acquired(u
))
1790 switch (u
->profile
) {
1792 pa_assert_not_reached(); /* Profile switch should have failed */
1794 case PROFILE_A2DP_SOURCE
:
1796 data
.suspend_cause
= PA_SUSPEND_USER
;
1800 pa_assert_not_reached();
1803 u
->source
= pa_source_new(u
->core
, &data
, PA_SOURCE_HARDWARE
|PA_SOURCE_LATENCY
);
1804 pa_source_new_data_done(&data
);
1807 pa_log_error("Failed to create source");
1811 u
->source
->userdata
= u
;
1812 u
->source
->parent
.process_msg
= source_process_msg
;
1813 u
->source
->set_port
= source_set_port_cb
;
1816 if ((u
->profile
== PROFILE_HSP
) || (u
->profile
== PROFILE_HFGW
)) {
1817 pa_bluetooth_transport
*t
= u
->transport
;
1818 pa_proplist_sets(u
->source
->proplist
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1821 if (u
->profile
== PROFILE_HSP
) {
1822 pa_source_set_set_volume_callback(u
->source
, source_set_volume_cb
);
1823 u
->source
->n_volume_steps
= 16;
1825 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
1826 pa_shared_set(u
->core
, k
, u
);
1833 static void bt_transport_config_a2dp(struct userdata
*u
) {
1834 const pa_bluetooth_transport
*t
;
1835 struct a2dp_info
*a2dp
= &u
->a2dp
;
1841 config
= (a2dp_sbc_t
*) t
->config
;
1843 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1845 if (a2dp
->sbc_initialized
)
1846 sbc_reinit(&a2dp
->sbc
, 0);
1848 sbc_init(&a2dp
->sbc
, 0);
1849 a2dp
->sbc_initialized
= TRUE
;
1851 switch (config
->frequency
) {
1852 case SBC_SAMPLING_FREQ_16000
:
1853 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
1854 u
->sample_spec
.rate
= 16000U;
1856 case SBC_SAMPLING_FREQ_32000
:
1857 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
1858 u
->sample_spec
.rate
= 32000U;
1860 case SBC_SAMPLING_FREQ_44100
:
1861 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
1862 u
->sample_spec
.rate
= 44100U;
1864 case SBC_SAMPLING_FREQ_48000
:
1865 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
1866 u
->sample_spec
.rate
= 48000U;
1869 pa_assert_not_reached();
1872 switch (config
->channel_mode
) {
1873 case SBC_CHANNEL_MODE_MONO
:
1874 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
1875 u
->sample_spec
.channels
= 1;
1877 case SBC_CHANNEL_MODE_DUAL_CHANNEL
:
1878 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
1879 u
->sample_spec
.channels
= 2;
1881 case SBC_CHANNEL_MODE_STEREO
:
1882 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
1883 u
->sample_spec
.channels
= 2;
1885 case SBC_CHANNEL_MODE_JOINT_STEREO
:
1886 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
1887 u
->sample_spec
.channels
= 2;
1890 pa_assert_not_reached();
1893 switch (config
->allocation_method
) {
1894 case SBC_ALLOCATION_SNR
:
1895 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
1897 case SBC_ALLOCATION_LOUDNESS
:
1898 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
1901 pa_assert_not_reached();
1904 switch (config
->subbands
) {
1905 case SBC_SUBBANDS_4
:
1906 a2dp
->sbc
.subbands
= SBC_SB_4
;
1908 case SBC_SUBBANDS_8
:
1909 a2dp
->sbc
.subbands
= SBC_SB_8
;
1912 pa_assert_not_reached();
1915 switch (config
->block_length
) {
1916 case SBC_BLOCK_LENGTH_4
:
1917 a2dp
->sbc
.blocks
= SBC_BLK_4
;
1919 case SBC_BLOCK_LENGTH_8
:
1920 a2dp
->sbc
.blocks
= SBC_BLK_8
;
1922 case SBC_BLOCK_LENGTH_12
:
1923 a2dp
->sbc
.blocks
= SBC_BLK_12
;
1925 case SBC_BLOCK_LENGTH_16
:
1926 a2dp
->sbc
.blocks
= SBC_BLK_16
;
1929 pa_assert_not_reached();
1932 a2dp
->min_bitpool
= config
->min_bitpool
;
1933 a2dp
->max_bitpool
= config
->max_bitpool
;
1935 /* Set minimum bitpool for source to get the maximum possible block_size */
1936 a2dp
->sbc
.bitpool
= u
->profile
== PROFILE_A2DP
? a2dp
->max_bitpool
: a2dp
->min_bitpool
;
1937 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
1938 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
1940 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1941 a2dp
->sbc
.allocation
, a2dp
->sbc
.subbands
, a2dp
->sbc
.blocks
, a2dp
->sbc
.bitpool
);
1944 static void bt_transport_config(struct userdata
*u
) {
1945 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
1946 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1947 u
->sample_spec
.channels
= 1;
1948 u
->sample_spec
.rate
= 8000;
1950 bt_transport_config_a2dp(u
);
1953 /* Run from main thread */
1954 static pa_hook_result_t
transport_state_changed_cb(pa_bluetooth_discovery
*y
, pa_bluetooth_transport
*t
, struct userdata
*u
) {
1958 if (t
== u
->transport
&& t
->state
== PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED
)
1959 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
1964 /* Run from main thread */
1965 static int setup_transport(struct userdata
*u
) {
1966 pa_bluetooth_transport
*t
;
1969 pa_assert(!u
->transport
);
1970 pa_assert(u
->profile
!= PROFILE_OFF
);
1972 /* check if profile has a transport */
1973 t
= u
->device
->transports
[u
->profile
];
1975 pa_log_warn("Profile has no transport");
1981 if (u
->profile
== PROFILE_A2DP_SOURCE
|| u
->profile
== PROFILE_HFGW
)
1982 bt_transport_acquire(u
, FALSE
); /* In case of error, the sink/sources will be created suspended */
1983 else if (bt_transport_acquire(u
, TRUE
) < 0)
1984 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1986 bt_transport_config(u
);
1991 /* Run from main thread */
1992 static int init_profile(struct userdata
*u
) {
1995 pa_assert(u
->profile
!= PROFILE_OFF
);
1997 if (setup_transport(u
) < 0)
2000 pa_assert(u
->transport
);
2002 if (u
->profile
== PROFILE_A2DP
||
2003 u
->profile
== PROFILE_HSP
||
2004 u
->profile
== PROFILE_HFGW
)
2005 if (add_sink(u
) < 0)
2008 if (u
->profile
== PROFILE_HSP
||
2009 u
->profile
== PROFILE_A2DP_SOURCE
||
2010 u
->profile
== PROFILE_HFGW
)
2011 if (add_source(u
) < 0)
2017 /* Run from main thread */
2018 static void stop_thread(struct userdata
*u
) {
2023 if (u
->sink
&& !USE_SCO_OVER_PCM(u
))
2024 pa_sink_unlink(u
->sink
);
2026 if (u
->source
&& !USE_SCO_OVER_PCM(u
))
2027 pa_source_unlink(u
->source
);
2030 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
2031 pa_thread_free(u
->thread
);
2035 if (u
->rtpoll_item
) {
2036 pa_rtpoll_item_free(u
->rtpoll_item
);
2037 u
->rtpoll_item
= NULL
;
2040 if (u
->hsp
.sink_state_changed_slot
) {
2041 pa_hook_slot_free(u
->hsp
.sink_state_changed_slot
);
2042 u
->hsp
.sink_state_changed_slot
= NULL
;
2045 if (u
->hsp
.source_state_changed_slot
) {
2046 pa_hook_slot_free(u
->hsp
.source_state_changed_slot
);
2047 u
->hsp
.source_state_changed_slot
= NULL
;
2051 bt_transport_release(u
);
2052 u
->transport
= NULL
;
2056 if (u
->profile
== PROFILE_HSP
) {
2057 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2058 pa_shared_remove(u
->core
, k
);
2062 pa_sink_unref(u
->sink
);
2067 if (u
->profile
== PROFILE_HSP
) {
2068 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2069 pa_shared_remove(u
->core
, k
);
2073 pa_source_unref(u
->source
);
2078 pa_thread_mq_done(&u
->thread_mq
);
2080 pa_rtpoll_free(u
->rtpoll
);
2084 if (u
->read_smoother
) {
2085 pa_smoother_free(u
->read_smoother
);
2086 u
->read_smoother
= NULL
;
2090 /* Run from main thread */
2091 static int start_thread(struct userdata
*u
) {
2093 pa_assert(!u
->thread
);
2094 pa_assert(!u
->rtpoll
);
2095 pa_assert(!u
->rtpoll_item
);
2097 u
->rtpoll
= pa_rtpoll_new();
2098 pa_thread_mq_init(&u
->thread_mq
, u
->core
->mainloop
, u
->rtpoll
);
2100 if (USE_SCO_OVER_PCM(u
)) {
2101 if (sco_over_pcm_state_update(u
, FALSE
) < 0) {
2105 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2106 pa_shared_remove(u
->core
, k
);
2111 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2112 pa_shared_remove(u
->core
, k
);
2119 pa_sink_ref(u
->sink
);
2120 pa_source_ref(u
->source
);
2121 /* FIXME: monitor stream_fd error */
2125 if (!(u
->thread
= pa_thread_new("bluetooth", thread_func
, u
))) {
2126 pa_log_error("Failed to create IO thread");
2131 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
2132 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
2133 pa_sink_put(u
->sink
);
2135 if (u
->sink
->set_volume
)
2136 u
->sink
->set_volume(u
->sink
);
2140 pa_source_set_asyncmsgq(u
->source
, u
->thread_mq
.inq
);
2141 pa_source_set_rtpoll(u
->source
, u
->rtpoll
);
2142 pa_source_put(u
->source
);
2144 if (u
->source
->set_volume
)
2145 u
->source
->set_volume(u
->source
);
2151 static void save_sco_volume_callbacks(struct userdata
*u
) {
2153 pa_assert(USE_SCO_OVER_PCM(u
));
2155 u
->hsp
.sco_sink_set_volume
= u
->hsp
.sco_sink
->set_volume
;
2156 u
->hsp
.sco_source_set_volume
= u
->hsp
.sco_source
->set_volume
;
2159 static void restore_sco_volume_callbacks(struct userdata
*u
) {
2161 pa_assert(USE_SCO_OVER_PCM(u
));
2163 pa_sink_set_set_volume_callback(u
->hsp
.sco_sink
, u
->hsp
.sco_sink_set_volume
);
2164 pa_source_set_set_volume_callback(u
->hsp
.sco_source
, u
->hsp
.sco_source_set_volume
);
2167 /* Run from main thread */
2168 static int card_set_profile(pa_card
*c
, pa_card_profile
*new_profile
) {
2173 pa_assert(new_profile
);
2174 pa_assert_se(u
= c
->userdata
);
2176 d
= PA_CARD_PROFILE_DATA(new_profile
);
2178 if (*d
!= PROFILE_OFF
) {
2179 const pa_bluetooth_device
*device
= u
->device
;
2181 if (device
->profile_state
[*d
] < PA_BT_AUDIO_STATE_CONNECTED
) {
2182 pa_log_warn("Profile not connected, refused to switch profile to %s", new_profile
->name
);
2189 if (USE_SCO_OVER_PCM(u
))
2190 restore_sco_volume_callbacks(u
);
2193 u
->sample_spec
= u
->requested_sample_spec
;
2195 if (USE_SCO_OVER_PCM(u
))
2196 save_sco_volume_callbacks(u
);
2198 if (u
->profile
!= PROFILE_OFF
)
2199 if (init_profile(u
) < 0)
2202 if (u
->sink
|| u
->source
)
2203 if (start_thread(u
) < 0)
2211 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
2216 static void create_ports_for_profile(struct userdata
*u
, pa_hashmap
*ports
, pa_card_profile
*profile
) {
2217 pa_bluetooth_device
*device
= u
->device
;
2218 pa_device_port
*port
;
2221 d
= PA_CARD_PROFILE_DATA(profile
);
2225 if ((port
= pa_hashmap_get(ports
, "bluetooth-output")) != NULL
) {
2226 port
->priority
= PA_MAX(port
->priority
, profile
->priority
* 100);
2227 port
->available
= audio_state_to_availability_merged(device
->profile_state
[PROFILE_HSP
],
2228 device
->profile_state
[PROFILE_A2DP
]);
2229 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2231 pa_assert_se(port
= pa_device_port_new(u
->core
, "bluetooth-output", _("Bluetooth Output"), 0));
2232 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2233 port
->is_output
= 1;
2235 port
->priority
= profile
->priority
* 100;
2236 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2237 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2242 case PROFILE_A2DP_SOURCE
:
2243 pa_assert_se(port
= pa_device_port_new(u
->core
, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2244 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2245 port
->is_output
= 0;
2247 port
->priority
= profile
->priority
* 100;
2248 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2249 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2253 if ((port
= pa_hashmap_get(ports
, "bluetooth-output")) != NULL
) {
2254 port
->priority
= PA_MAX(port
->priority
, profile
->priority
* 100);
2255 port
->available
= audio_state_to_availability_merged(device
->profile_state
[PROFILE_HSP
],
2256 device
->profile_state
[PROFILE_A2DP
]);
2257 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2259 pa_assert_se(port
= pa_device_port_new(u
->core
, "bluetooth-output", _("Bluetooth Output"), 0));
2260 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2261 port
->is_output
= 1;
2263 port
->priority
= profile
->priority
* 100;
2264 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2265 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2268 pa_assert_se(port
= pa_device_port_new(u
->core
, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2269 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2270 port
->is_output
= 0;
2272 port
->priority
= profile
->priority
* 100;
2273 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2274 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2278 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2279 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2280 port
->is_output
= 1;
2282 port
->priority
= profile
->priority
* 100;
2283 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2284 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2286 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2287 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2288 port
->is_output
= 0;
2290 port
->priority
= profile
->priority
* 100;
2291 port
->available
= audio_state_to_availability(device
->profile_state
[*d
]);
2292 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2296 pa_assert_not_reached();
2301 /* Run from main thread */
2302 static pa_card_profile
*create_card_profile(struct userdata
*u
, const char *uuid
) {
2303 pa_card_profile
*p
= NULL
;
2306 if (pa_streq(uuid
, A2DP_SINK_UUID
)) {
2307 p
= pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile
));
2311 p
->max_sink_channels
= 2;
2312 p
->max_source_channels
= 0;
2314 d
= PA_CARD_PROFILE_DATA(p
);
2316 } else if (pa_streq(uuid
, A2DP_SOURCE_UUID
)) {
2317 p
= pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile
));
2321 p
->max_sink_channels
= 0;
2322 p
->max_source_channels
= 2;
2324 d
= PA_CARD_PROFILE_DATA(p
);
2325 *d
= PROFILE_A2DP_SOURCE
;
2326 } else if (pa_streq(uuid
, HSP_HS_UUID
) || pa_streq(uuid
, HFP_HS_UUID
)) {
2327 p
= pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile
));
2331 p
->max_sink_channels
= 1;
2332 p
->max_source_channels
= 1;
2334 d
= PA_CARD_PROFILE_DATA(p
);
2336 } else if (pa_streq(uuid
, HFP_AG_UUID
)) {
2337 p
= pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile
));
2341 p
->max_sink_channels
= 1;
2342 p
->max_source_channels
= 1;
2344 d
= PA_CARD_PROFILE_DATA(p
);
2351 /* Run from main thread */
2352 static int add_card(struct userdata
*u
) {
2353 pa_card_new_data data
;
2359 const char *default_profile
;
2360 const pa_bluetooth_device
*device
= u
->device
;
2361 const pa_bluetooth_uuid
*uuid
;
2366 pa_card_new_data_init(&data
);
2367 data
.driver
= __FILE__
;
2368 data
.module
= u
->module
;
2370 n
= pa_bluetooth_cleanup_name(device
->name
);
2371 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_DESCRIPTION
, n
);
2373 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, device
->address
);
2374 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_API
, "bluez");
2375 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_CLASS
, "sound");
2376 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_BUS
, "bluetooth");
2377 if ((ff
= pa_bluetooth_get_form_factor(device
->class)))
2378 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_FORM_FACTOR
, ff
);
2379 pa_proplist_sets(data
.proplist
, "bluez.path", device
->path
);
2380 pa_proplist_setf(data
.proplist
, "bluez.class", "0x%06x", (unsigned) device
->class);
2381 pa_proplist_sets(data
.proplist
, "bluez.name", device
->name
);
2382 data
.name
= get_name("card", u
->modargs
, device
->address
, &b
);
2383 data
.namereg_fail
= b
;
2385 if (pa_modargs_get_proplist(u
->modargs
, "card_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
2386 pa_log("Invalid properties");
2387 pa_card_new_data_done(&data
);
2391 PA_LLIST_FOREACH(uuid
, device
->uuids
) {
2392 p
= create_card_profile(u
, uuid
->uuid
);
2397 if (pa_hashmap_get(data
.profiles
, p
->name
)) {
2398 pa_card_profile_free(p
);
2402 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2403 create_ports_for_profile(u
, data
.ports
, p
);
2406 pa_assert(!pa_hashmap_isempty(data
.profiles
));
2408 p
= pa_card_profile_new("off", _("Off"), sizeof(enum profile
));
2409 d
= PA_CARD_PROFILE_DATA(p
);
2411 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2413 if ((default_profile
= pa_modargs_get_value(u
->modargs
, "profile", NULL
))) {
2414 if (pa_hashmap_get(data
.profiles
, default_profile
))
2415 pa_card_new_data_set_profile(&data
, default_profile
);
2417 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile
);
2420 u
->card
= pa_card_new(u
->core
, &data
);
2421 pa_card_new_data_done(&data
);
2424 pa_log("Failed to allocate card.");
2428 u
->card
->userdata
= u
;
2429 u
->card
->set_profile
= card_set_profile
;
2431 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2433 if (*d
!= PROFILE_OFF
&& (device
->profile_state
[*d
] < PA_BT_AUDIO_STATE_CONNECTED
)) {
2434 pa_log_warn("Default profile not connected, selecting off profile");
2435 u
->card
->active_profile
= pa_hashmap_get(u
->card
->profiles
, "off");
2436 u
->card
->save_profile
= FALSE
;
2439 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2442 if (USE_SCO_OVER_PCM(u
))
2443 save_sco_volume_callbacks(u
);
2448 /* Run from main thread */
2449 static pa_bluetooth_device
* find_device(struct userdata
*u
, const char *address
, const char *path
) {
2450 pa_bluetooth_device
*d
= NULL
;
2454 if (!address
&& !path
) {
2455 pa_log_error("Failed to get device address/path from module arguments.");
2460 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, path
))) {
2461 pa_log_error("%s is not a valid BlueZ audio device.", path
);
2465 if (address
&& !(pa_streq(d
->address
, address
))) {
2466 pa_log_error("Passed path %s address %s != %s don't match.", path
, d
->address
, address
);
2471 if (!(d
= pa_bluetooth_discovery_get_by_address(u
->discovery
, address
))) {
2472 pa_log_error("%s is not known.", address
);
2478 u
->address
= pa_xstrdup(d
->address
);
2479 u
->path
= pa_xstrdup(d
->path
);
2485 /* Run from main thread */
2486 static pa_hook_result_t
uuid_added_cb(pa_bluetooth_discovery
*y
, const struct pa_bluetooth_hook_uuid_data
*data
,
2487 struct userdata
*u
) {
2489 pa_hashmap
*new_ports
;
2492 pa_assert(data
->device
);
2493 pa_assert(data
->uuid
);
2496 if (data
->device
!= u
->device
)
2499 p
= create_card_profile(u
, data
->uuid
);
2504 if (pa_hashmap_get(u
->card
->profiles
, p
->name
)) {
2505 pa_card_profile_free(p
);
2509 pa_card_add_profile(u
->card
, p
);
2511 new_ports
= pa_hashmap_new(pa_idxset_string_hash_func
, pa_idxset_string_compare_func
);
2513 create_ports_for_profile(u
, new_ports
, p
);
2515 pa_card_add_ports(u
->card
, new_ports
);
2517 pa_device_port_hashmap_free(new_ports
);
2522 /* Run from main thread */
2523 static int setup_dbus(struct userdata
*u
) {
2526 dbus_error_init(&err
);
2528 u
->connection
= pa_dbus_bus_get(u
->core
, DBUS_BUS_SYSTEM
, &err
);
2530 if (dbus_error_is_set(&err
) || !u
->connection
) {
2531 pa_log("Failed to get D-Bus connection: %s", err
.message
);
2532 dbus_error_free(&err
);
2539 /* Run from main thread */
2540 static pa_hook_result_t
discovery_hook_cb(pa_bluetooth_discovery
*y
, const pa_bluetooth_device
*d
, struct userdata
*u
) {
2548 pa_log_debug("Device %s removed: unloading module", d
->path
);
2549 else if (!pa_bluetooth_device_any_audio_connected(d
))
2550 pa_log_debug("Unloading module, because device %s doesn't have any audio profiles connected anymore.", d
->path
);
2554 pa_module_unload(u
->core
, u
->module
, true);
2559 int pa__init(pa_module
* m
) {
2563 const char *address
, *path
;
2565 char *mike
, *speaker
;
2566 pa_bluetooth_device
*device
;
2570 dbus_error_init(&err
);
2572 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
2573 pa_log_error("Failed to parse module arguments");
2577 m
->userdata
= u
= pa_xnew0(struct userdata
, 1);
2581 u
->sample_spec
= m
->core
->default_sample_spec
;
2584 if (pa_modargs_get_value(ma
, "sco_sink", NULL
) &&
2585 !(u
->hsp
.sco_sink
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_sink", NULL
), PA_NAMEREG_SINK
))) {
2586 pa_log("SCO sink not found");
2590 if (pa_modargs_get_value(ma
, "sco_source", NULL
) &&
2591 !(u
->hsp
.sco_source
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_source", NULL
), PA_NAMEREG_SOURCE
))) {
2592 pa_log("SCO source not found");
2596 if (pa_modargs_get_value_u32(ma
, "rate", &u
->sample_spec
.rate
) < 0 ||
2597 u
->sample_spec
.rate
<= 0 || u
->sample_spec
.rate
> PA_RATE_MAX
) {
2598 pa_log_error("Failed to get rate from module arguments");
2602 u
->auto_connect
= TRUE
;
2603 if (pa_modargs_get_value_boolean(ma
, "auto_connect", &u
->auto_connect
)) {
2604 pa_log("Failed to parse auto_connect= argument");
2608 channels
= u
->sample_spec
.channels
;
2609 if (pa_modargs_get_value_u32(ma
, "channels", &channels
) < 0 ||
2610 channels
<= 0 || channels
> PA_CHANNELS_MAX
) {
2611 pa_log_error("Failed to get channels from module arguments");
2614 u
->sample_spec
.channels
= (uint8_t) channels
;
2615 u
->requested_sample_spec
= u
->sample_spec
;
2617 address
= pa_modargs_get_value(ma
, "address", NULL
);
2618 path
= pa_modargs_get_value(ma
, "path", NULL
);
2620 if (setup_dbus(u
) < 0)
2623 if (!(u
->discovery
= pa_bluetooth_discovery_get(m
->core
)))
2626 if (!(device
= find_device(u
, address
, path
)))
2632 pa_hook_connect(pa_bluetooth_discovery_hook(u
->discovery
, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED
),
2633 PA_HOOK_NORMAL
, (pa_hook_cb_t
) discovery_hook_cb
, u
);
2635 u
->uuid_added_slot
=
2636 pa_hook_connect(pa_bluetooth_discovery_hook(u
->discovery
, PA_BLUETOOTH_HOOK_DEVICE_UUID_ADDED
),
2637 PA_HOOK_NORMAL
, (pa_hook_cb_t
) uuid_added_cb
, u
);
2639 u
->transport_state_changed_slot
=
2640 pa_hook_connect(pa_bluetooth_discovery_hook(u
->discovery
, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED
),
2641 PA_HOOK_NORMAL
, (pa_hook_cb_t
) transport_state_changed_cb
, u
);
2643 u
->transport_nrec_changed_slot
=
2644 pa_hook_connect(pa_bluetooth_discovery_hook(u
->discovery
, PA_BLUETOOTH_HOOK_TRANSPORT_NREC_CHANGED
),
2645 PA_HOOK_NORMAL
, (pa_hook_cb_t
) transport_nrec_changed_cb
, u
);
2647 /* Add the card structure. This will also initialize the default profile */
2648 if (add_card(u
) < 0)
2651 if (!(u
->msg
= pa_msgobject_new(bluetooth_msg
)))
2654 u
->msg
->parent
.process_msg
= device_process_msg
;
2655 u
->msg
->card
= u
->card
;
2657 if (!dbus_connection_add_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
, NULL
)) {
2658 pa_log_error("Failed to add filter function");
2661 u
->filter_added
= TRUE
;
2663 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2664 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2666 if (pa_dbus_add_matches(
2667 pa_dbus_connection_get(u
->connection
), &err
,
2670 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2671 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2672 "type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged'",
2673 "type='signal',sender='org.bluez',interface='org.bluez.AudioSource',member='PropertyChanged'",
2674 "type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged'",
2680 pa_log("Failed to add D-Bus matches: %s", err
.message
);
2687 if (u
->profile
!= PROFILE_OFF
)
2688 if (init_profile(u
) < 0)
2691 if (u
->sink
|| u
->source
)
2692 if (start_thread(u
) < 0)
2700 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
2708 dbus_error_free(&err
);
2713 int pa__get_n_used(pa_module
*m
) {
2717 pa_assert_se(u
= m
->userdata
);
2720 (u
->sink
? pa_sink_linked_by(u
->sink
) : 0) +
2721 (u
->source
? pa_source_linked_by(u
->source
) : 0);
2724 void pa__done(pa_module
*m
) {
2729 if (!(u
= m
->userdata
))
2734 if (u
->discovery_slot
)
2735 pa_hook_slot_free(u
->discovery_slot
);
2737 if (u
->transport_state_changed_slot
)
2738 pa_hook_slot_free(u
->transport_state_changed_slot
);
2740 if (u
->transport_nrec_changed_slot
)
2741 pa_hook_slot_free(u
->transport_nrec_changed_slot
);
2743 if (USE_SCO_OVER_PCM(u
))
2744 restore_sco_volume_callbacks(u
);
2746 if (u
->connection
) {
2749 char *speaker
, *mike
;
2750 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2751 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2753 pa_dbus_remove_matches(pa_dbus_connection_get(u
->connection
), speaker
, mike
,
2754 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2755 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2762 if (u
->filter_added
)
2763 dbus_connection_remove_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
);
2765 pa_dbus_connection_unref(u
->connection
);
2768 if (u
->uuid_added_slot
)
2769 pa_hook_slot_free(u
->uuid_added_slot
);
2775 pa_card_free(u
->card
);
2777 if (u
->read_smoother
)
2778 pa_smoother_free(u
->read_smoother
);
2781 pa_xfree(u
->a2dp
.buffer
);
2783 sbc_finish(&u
->a2dp
.sbc
);
2786 pa_modargs_free(u
->modargs
);
2788 pa_xfree(u
->address
);
2792 pa_bluetooth_discovery_unref(u
->discovery
);