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
29 #include <linux/sockios.h>
30 #include <arpa/inet.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.h>
37 #include <pulsecore/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.h>
40 #include <pulsecore/core-rtclock.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/core-error.h>
43 #include <pulsecore/shared.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/poll.h>
48 #include <pulsecore/rtpoll.h>
49 #include <pulsecore/time-smoother.h>
50 #include <pulsecore/namereg.h>
51 #include <pulsecore/dbus-shared.h>
55 #include "module-bluetooth-device-symdef.h"
56 #include "a2dp-codecs.h"
58 #include "bluetooth-util.h"
60 #define BITPOOL_DEC_LIMIT 32
61 #define BITPOOL_DEC_STEP 5
62 #define HSP_MAX_GAIN 15
64 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
65 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
66 PA_MODULE_VERSION(PACKAGE_VERSION
);
67 PA_MODULE_LOAD_ONCE(FALSE
);
69 "name=<name for the card/sink/source, to be prefixed> "
70 "card_name=<name for the card> "
71 "card_properties=<properties for the card> "
72 "sink_name=<name for the sink> "
73 "sink_properties=<properties for the sink> "
74 "source_name=<name for the source> "
75 "source_properties=<properties for the source> "
76 "address=<address of the device> "
77 "profile=<a2dp|hsp|hfgw> "
79 "channels=<number of channels> "
80 "path=<device object path> "
81 "auto_connect=<automatically connect?> "
82 "sco_sink=<SCO over PCM sink name> "
83 "sco_source=<SCO over PCM source name>");
85 /* TODO: not close fd when entering suspend mode in a2dp */
87 static const char* const valid_modargs
[] = {
107 sbc_t sbc
; /* Codec data */
108 pa_bool_t sbc_initialized
; /* Keep track if the encoder is initialized */
109 size_t codesize
, frame_length
; /* SBC Codesize, frame_length. We simply cache those values here */
111 void* buffer
; /* Codec transfer buffer */
112 size_t buffer_size
; /* Size of the buffer */
114 uint16_t seq_num
; /* Cumulative packet sequence */
121 void (*sco_sink_set_volume
)(pa_sink
*s
);
122 pa_source
*sco_source
;
123 void (*sco_source_set_volume
)(pa_source
*s
);
124 pa_hook_slot
*sink_state_changed_slot
;
125 pa_hook_slot
*source_state_changed_slot
;
126 pa_hook_slot
*nrec_changed_slot
;
129 struct bluetooth_msg
{
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
*transport_removed_slot
;
149 pa_hook_slot
*device_removed_slot
;
150 pa_hook_slot
*discovery_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 pa_bt_audio_state_t
get_profile_audio_state(const struct userdata
*u
, const pa_bluetooth_device
*d
) {
372 return d
->headset_state
;
374 return d
->audio_sink_state
;
375 case PROFILE_A2DP_SOURCE
:
376 return d
->audio_source_state
;
378 return d
->hfgw_state
;
383 pa_assert_not_reached();
386 static int bt_transport_acquire(struct userdata
*u
, pa_bool_t start
) {
387 const char *accesstype
= "rw";
389 pa_assert(u
->transport
);
391 if (bt_transport_is_acquired(u
)) {
397 pa_log_debug("Acquiring transport %s", u
->transport
->path
);
400 /* FIXME: we are trying to acquire the transport only if the stream is
401 playing, without actually initiating the stream request from our side
402 (which is typically undesireable specially for hfgw use-cases.
403 However this approach is racy, since the stream could have been
404 suspended in the meantime, so we can't really guarantee that the
405 stream will not be requested until BlueZ's API supports this
407 if (get_profile_audio_state(u
, u
->device
) < PA_BT_AUDIO_STATE_PLAYING
) {
408 pa_log_info("Failed optional acquire of transport %s", u
->transport
->path
);
413 u
->stream_fd
= pa_bluetooth_transport_acquire(u
->transport
, accesstype
, &u
->read_link_mtu
, &u
->write_link_mtu
);
414 if (u
->stream_fd
< 0) {
416 pa_log("Failed to acquire transport %s", u
->transport
->path
);
418 pa_log_info("Failed optional acquire of transport %s", u
->transport
->path
);
423 u
->accesstype
= pa_xstrdup(accesstype
);
424 pa_log_info("Transport %s acquired: fd %d", u
->transport
->path
, u
->stream_fd
);
430 /* If thread is still about to start, the stream will be set up in the beginning of thread_func() */
431 if (u
->thread
== NULL
)
439 /* Run from IO thread */
440 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
441 struct userdata
*u
= PA_SINK(o
)->userdata
;
442 pa_bool_t failed
= FALSE
;
445 pa_assert(u
->sink
== PA_SINK(o
));
446 pa_assert(u
->transport
);
450 case PA_SINK_MESSAGE_SET_STATE
:
452 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
454 case PA_SINK_SUSPENDED
:
455 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
456 if (!PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
))
459 /* Stop the device if the source is suspended as well */
460 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
)
461 /* We deliberately ignore whether stopping
462 * actually worked. Since the stream_fd is
463 * closed it doesn't really matter */
464 bt_transport_release(u
);
469 case PA_SINK_RUNNING
:
470 if (u
->sink
->thread_info
.state
!= PA_SINK_SUSPENDED
)
473 /* Resume the device if the source was suspended as well */
474 if (!u
->source
|| !PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
)) {
475 if (bt_transport_acquire(u
, TRUE
) < 0)
480 case PA_SINK_UNLINKED
:
482 case PA_SINK_INVALID_STATE
:
487 case PA_SINK_MESSAGE_GET_LATENCY
: {
489 if (u
->read_smoother
) {
492 ri
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
493 wi
= pa_bytes_to_usec(u
->write_index
+ u
->write_block_size
, &u
->sample_spec
);
495 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
499 ri
= pa_rtclock_now() - u
->started_at
;
500 wi
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
502 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
505 *((pa_usec_t
*) data
) += u
->sink
->thread_info
.fixed_latency
;
510 r
= pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
512 return (r
< 0 || !failed
) ? r
: -1;
515 /* Run from IO thread */
516 static int source_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
517 struct userdata
*u
= PA_SOURCE(o
)->userdata
;
518 pa_bool_t failed
= FALSE
;
521 pa_assert(u
->source
== PA_SOURCE(o
));
522 pa_assert(u
->transport
);
526 case PA_SOURCE_MESSAGE_SET_STATE
:
528 switch ((pa_source_state_t
) PA_PTR_TO_UINT(data
)) {
530 case PA_SOURCE_SUSPENDED
:
531 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
532 if (!PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
))
535 /* Stop the device if the sink is suspended as well */
536 if (!u
->sink
|| u
->sink
->state
== PA_SINK_SUSPENDED
)
537 bt_transport_release(u
);
539 if (u
->read_smoother
)
540 pa_smoother_pause(u
->read_smoother
, pa_rtclock_now());
544 case PA_SOURCE_RUNNING
:
545 if (u
->source
->thread_info
.state
!= PA_SOURCE_SUSPENDED
)
548 /* Resume the device if the sink was suspended as well */
549 if (!u
->sink
|| !PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
)) {
550 if (bt_transport_acquire(u
, TRUE
) < 0)
553 /* We don't resume the smoother here. Instead we
554 * wait until the first packet arrives */
557 case PA_SOURCE_UNLINKED
:
559 case PA_SOURCE_INVALID_STATE
:
564 case PA_SOURCE_MESSAGE_GET_LATENCY
: {
567 if (u
->read_smoother
) {
568 wi
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
569 ri
= pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
);
571 *((pa_usec_t
*) data
) = (wi
> ri
? wi
- ri
: 0) + u
->source
->thread_info
.fixed_latency
;
573 *((pa_usec_t
*) data
) = 0;
580 r
= pa_source_process_msg(o
, code
, data
, offset
, chunk
);
582 return (r
< 0 || !failed
) ? r
: -1;
585 /* Called from main thread context */
586 static int device_process_msg(pa_msgobject
*obj
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
587 struct bluetooth_msg
*u
= BLUETOOTH_MSG(obj
);
590 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED
: {
591 if (u
->card
->module
->unload_requested
)
594 pa_log_debug("Switching the profile to off due to IO thread failure.");
596 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
603 /* Run from IO thread */
604 static int hsp_process_render(struct userdata
*u
) {
608 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
611 /* First, render some data */
612 if (!u
->write_memchunk
.memblock
)
613 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
615 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
621 /* Now write that data to the socket. The socket is of type
622 * SEQPACKET, and we generated the data of the MTU size, so this
623 * should just work. */
625 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
626 l
= pa_write(u
->stream_fd
, p
, u
->write_memchunk
.length
, &u
->stream_write_type
);
627 pa_memblock_release(u
->write_memchunk
.memblock
);
634 /* Retry right away if we got interrupted */
637 else if (errno
== EAGAIN
)
638 /* Hmm, apparently the socket was not writable, give up for now */
641 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno
));
646 pa_assert((size_t) l
<= u
->write_memchunk
.length
);
648 if ((size_t) l
!= u
->write_memchunk
.length
) {
649 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
650 (unsigned long long) l
,
651 (unsigned long long) u
->write_memchunk
.length
);
656 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
657 pa_memblock_unref(u
->write_memchunk
.memblock
);
658 pa_memchunk_reset(&u
->write_memchunk
);
667 /* Run from IO thread */
668 static int hsp_process_push(struct userdata
*u
) {
670 pa_memchunk memchunk
;
673 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
674 pa_assert(u
->source
);
675 pa_assert(u
->read_smoother
);
677 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
678 memchunk
.index
= memchunk
.length
= 0;
687 pa_bool_t found_tstamp
= FALSE
;
690 memset(&m
, 0, sizeof(m
));
691 memset(&aux
, 0, sizeof(aux
));
692 memset(&iov
, 0, sizeof(iov
));
697 m
.msg_controllen
= sizeof(aux
);
699 p
= pa_memblock_acquire(memchunk
.memblock
);
701 iov
.iov_len
= pa_memblock_get_length(memchunk
.memblock
);
702 l
= recvmsg(u
->stream_fd
, &m
, 0);
703 pa_memblock_release(memchunk
.memblock
);
707 if (l
< 0 && errno
== EINTR
)
708 /* Retry right away if we got interrupted */
711 else if (l
< 0 && errno
== EAGAIN
)
712 /* Hmm, apparently the socket was not readable, give up for now. */
715 pa_log_error("Failed to read data from SCO socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
720 pa_assert((size_t) l
<= pa_memblock_get_length(memchunk
.memblock
));
722 memchunk
.length
= (size_t) l
;
723 u
->read_index
+= (uint64_t) l
;
725 for (cm
= CMSG_FIRSTHDR(&m
); cm
; cm
= CMSG_NXTHDR(&m
, cm
))
726 if (cm
->cmsg_level
== SOL_SOCKET
&& cm
->cmsg_type
== SO_TIMESTAMP
) {
727 struct timeval
*tv
= (struct timeval
*) CMSG_DATA(cm
);
728 pa_rtclock_from_wallclock(tv
);
729 tstamp
= pa_timeval_load(tv
);
735 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
736 tstamp
= pa_rtclock_now();
739 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
740 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
742 pa_source_post(u
->source
, &memchunk
);
748 pa_memblock_unref(memchunk
.memblock
);
753 /* Run from IO thread */
754 static void a2dp_prepare_buffer(struct userdata
*u
) {
755 size_t min_buffer_size
= PA_MAX(u
->read_link_mtu
, u
->write_link_mtu
);
759 if (u
->a2dp
.buffer_size
>= min_buffer_size
)
762 u
->a2dp
.buffer_size
= 2 * min_buffer_size
;
763 pa_xfree(u
->a2dp
.buffer
);
764 u
->a2dp
.buffer
= pa_xmalloc(u
->a2dp
.buffer_size
);
767 /* Run from IO thread */
768 static int a2dp_process_render(struct userdata
*u
) {
769 struct a2dp_info
*a2dp
;
770 struct rtp_header
*header
;
771 struct rtp_payload
*payload
;
775 size_t to_write
, to_encode
;
776 unsigned frame_count
;
780 pa_assert(u
->profile
== PROFILE_A2DP
);
783 /* First, render some data */
784 if (!u
->write_memchunk
.memblock
)
785 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
787 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
789 a2dp_prepare_buffer(u
);
792 header
= a2dp
->buffer
;
793 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
797 /* Try to create a packet of the full MTU */
799 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
800 to_encode
= u
->write_memchunk
.length
;
802 d
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
803 to_write
= a2dp
->buffer_size
- sizeof(*header
) - sizeof(*payload
);
805 while (PA_LIKELY(to_encode
> 0 && to_write
> 0)) {
809 encoded
= sbc_encode(&a2dp
->sbc
,
814 if (PA_UNLIKELY(encoded
<= 0)) {
815 pa_log_error("SBC encoding error (%li)", (long) encoded
);
816 pa_memblock_release(u
->write_memchunk
.memblock
);
820 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
821 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
823 pa_assert_fp((size_t) encoded
<= to_encode
);
824 pa_assert_fp((size_t) encoded
== a2dp
->codesize
);
826 pa_assert_fp((size_t) written
<= to_write
);
827 pa_assert_fp((size_t) written
== a2dp
->frame_length
);
829 p
= (const uint8_t*) p
+ encoded
;
830 to_encode
-= encoded
;
832 d
= (uint8_t*) d
+ written
;
838 pa_memblock_release(u
->write_memchunk
.memblock
);
840 pa_assert(to_encode
== 0);
843 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp
->sbc
)));
846 /* write it to the fifo */
847 memset(a2dp
->buffer
, 0, sizeof(*header
) + sizeof(*payload
));
850 header
->sequence_number
= htons(a2dp
->seq_num
++);
851 header
->timestamp
= htonl(u
->write_index
/ pa_frame_size(&u
->sample_spec
));
852 header
->ssrc
= htonl(1);
853 payload
->frame_count
= frame_count
;
855 nbytes
= (uint8_t*) d
- (uint8_t*) a2dp
->buffer
;
860 l
= pa_write(u
->stream_fd
, a2dp
->buffer
, nbytes
, &u
->stream_write_type
);
867 /* Retry right away if we got interrupted */
870 else if (errno
== EAGAIN
)
871 /* Hmm, apparently the socket was not writable, give up for now */
874 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno
));
879 pa_assert((size_t) l
<= nbytes
);
881 if ((size_t) l
!= nbytes
) {
882 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
883 (unsigned long long) l
,
884 (unsigned long long) nbytes
);
889 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
890 pa_memblock_unref(u
->write_memchunk
.memblock
);
891 pa_memchunk_reset(&u
->write_memchunk
);
901 static int a2dp_process_push(struct userdata
*u
) {
903 pa_memchunk memchunk
;
906 pa_assert(u
->profile
== PROFILE_A2DP_SOURCE
);
907 pa_assert(u
->source
);
908 pa_assert(u
->read_smoother
);
910 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
911 memchunk
.index
= memchunk
.length
= 0;
914 pa_bool_t found_tstamp
= FALSE
;
916 struct a2dp_info
*a2dp
;
917 struct rtp_header
*header
;
918 struct rtp_payload
*payload
;
922 size_t to_write
, to_decode
;
924 a2dp_prepare_buffer(u
);
927 header
= a2dp
->buffer
;
928 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
930 l
= pa_read(u
->stream_fd
, a2dp
->buffer
, a2dp
->buffer_size
, &u
->stream_write_type
);
934 if (l
< 0 && errno
== EINTR
)
935 /* Retry right away if we got interrupted */
938 else if (l
< 0 && errno
== EAGAIN
)
939 /* Hmm, apparently the socket was not readable, give up for now. */
942 pa_log_error("Failed to read data from socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
947 pa_assert((size_t) l
<= a2dp
->buffer_size
);
949 u
->read_index
+= (uint64_t) l
;
951 /* TODO: get timestamp from rtp */
953 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
954 tstamp
= pa_rtclock_now();
957 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
958 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
960 p
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
961 to_decode
= l
- sizeof(*header
) - sizeof(*payload
);
963 d
= pa_memblock_acquire(memchunk
.memblock
);
964 to_write
= memchunk
.length
= pa_memblock_get_length(memchunk
.memblock
);
966 while (PA_LIKELY(to_decode
> 0)) {
970 decoded
= sbc_decode(&a2dp
->sbc
,
975 if (PA_UNLIKELY(decoded
<= 0)) {
976 pa_log_error("SBC decoding error (%li)", (long) decoded
);
977 pa_memblock_release(memchunk
.memblock
);
978 pa_memblock_unref(memchunk
.memblock
);
982 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
983 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
985 /* Reset frame length, it can be changed due to bitpool change */
986 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
988 pa_assert_fp((size_t) decoded
<= to_decode
);
989 pa_assert_fp((size_t) decoded
== a2dp
->frame_length
);
991 pa_assert_fp((size_t) written
== a2dp
->codesize
);
993 p
= (const uint8_t*) p
+ decoded
;
994 to_decode
-= decoded
;
996 d
= (uint8_t*) d
+ written
;
1000 memchunk
.length
-= to_write
;
1002 pa_memblock_release(memchunk
.memblock
);
1004 pa_source_post(u
->source
, &memchunk
);
1010 pa_memblock_unref(memchunk
.memblock
);
1015 static void a2dp_reduce_bitpool(struct userdata
*u
)
1017 struct a2dp_info
*a2dp
;
1024 /* Check if bitpool is already at its limit */
1025 if (a2dp
->sbc
.bitpool
<= BITPOOL_DEC_LIMIT
)
1028 bitpool
= a2dp
->sbc
.bitpool
- BITPOOL_DEC_STEP
;
1030 if (bitpool
< BITPOOL_DEC_LIMIT
)
1031 bitpool
= BITPOOL_DEC_LIMIT
;
1033 a2dp_set_bitpool(u
, bitpool
);
1036 static void thread_func(void *userdata
) {
1037 struct userdata
*u
= userdata
;
1038 unsigned do_write
= 0;
1039 unsigned pending_read_bytes
= 0;
1040 pa_bool_t writable
= FALSE
;
1043 pa_assert(u
->transport
);
1045 pa_log_debug("IO Thread starting up");
1047 if (u
->core
->realtime_scheduling
)
1048 pa_make_realtime(u
->core
->realtime_priority
);
1050 pa_thread_mq_install(&u
->thread_mq
);
1052 /* Setup the stream only if the transport was already acquired */
1053 if (bt_transport_is_acquired(u
))
1057 struct pollfd
*pollfd
;
1059 pa_bool_t disable_timer
= TRUE
;
1061 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1063 if (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) {
1065 /* We should send two blocks to the device before we expect
1068 if (u
->write_index
== 0 && u
->read_index
<= 0)
1071 if (pollfd
&& (pollfd
->revents
& POLLIN
)) {
1074 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
)
1075 n_read
= hsp_process_push(u
);
1077 n_read
= a2dp_process_push(u
);
1082 /* We just read something, so we are supposed to write something, too */
1083 pending_read_bytes
+= n_read
;
1084 do_write
+= pending_read_bytes
/ u
->write_block_size
;
1085 pending_read_bytes
= pending_read_bytes
% u
->write_block_size
;
1089 if (u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
)) {
1091 if (PA_UNLIKELY(u
->sink
->thread_info
.rewind_requested
))
1092 pa_sink_process_rewind(u
->sink
, 0);
1095 if (pollfd
->revents
& POLLOUT
)
1098 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1099 pa_usec_t time_passed
;
1100 pa_usec_t audio_sent
;
1102 /* Hmm, there is no input stream we could synchronize
1103 * to. So let's do things by time */
1105 time_passed
= pa_rtclock_now() - u
->started_at
;
1106 audio_sent
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1108 if (audio_sent
<= time_passed
) {
1109 pa_usec_t audio_to_send
= time_passed
- audio_sent
;
1111 /* Never try to catch up for more than 100ms */
1112 if (u
->write_index
> 0 && audio_to_send
> MAX_PLAYBACK_CATCH_UP_USEC
) {
1113 pa_usec_t skip_usec
;
1114 uint64_t skip_bytes
;
1116 skip_usec
= audio_to_send
- MAX_PLAYBACK_CATCH_UP_USEC
;
1117 skip_bytes
= pa_usec_to_bytes(skip_usec
, &u
->sample_spec
);
1119 if (skip_bytes
> 0) {
1122 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1123 (unsigned long long) skip_usec
,
1124 (unsigned long long) skip_bytes
);
1126 pa_sink_render_full(u
->sink
, skip_bytes
, &tmp
);
1127 pa_memblock_unref(tmp
.memblock
);
1128 u
->write_index
+= skip_bytes
;
1130 if (u
->profile
== PROFILE_A2DP
)
1131 a2dp_reduce_bitpool(u
);
1136 pending_read_bytes
= 0;
1140 if (writable
&& do_write
> 0) {
1143 if (u
->write_index
<= 0)
1144 u
->started_at
= pa_rtclock_now();
1146 if (u
->profile
== PROFILE_A2DP
) {
1147 if ((n_written
= a2dp_process_render(u
)) < 0)
1150 if ((n_written
= hsp_process_render(u
)) < 0)
1155 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1157 do_write
-= n_written
;
1161 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0) {
1162 pa_usec_t sleep_for
;
1163 pa_usec_t time_passed
, next_write_at
;
1166 /* Hmm, there is no input stream we could synchronize
1167 * to. So let's estimate when we need to wake up the latest */
1168 time_passed
= pa_rtclock_now() - u
->started_at
;
1169 next_write_at
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1170 sleep_for
= time_passed
< next_write_at
? next_write_at
- time_passed
: 0;
1171 /* 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); */
1173 /* drop stream every 500 ms */
1174 sleep_for
= PA_USEC_PER_MSEC
* 500;
1176 pa_rtpoll_set_timer_relative(u
->rtpoll
, sleep_for
);
1177 disable_timer
= FALSE
;
1183 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
1185 /* Hmm, nothing to do. Let's sleep */
1187 pollfd
->events
= (short) (((u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
) && !writable
) ? POLLOUT
: 0) |
1188 (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
) ? POLLIN
: 0));
1190 if ((ret
= pa_rtpoll_run(u
->rtpoll
, TRUE
)) < 0) {
1191 pa_log_debug("pa_rtpoll_run failed with: %d", ret
);
1195 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1196 bt_transport_release(u
);
1200 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1202 if (pollfd
&& (pollfd
->revents
& ~(POLLOUT
|POLLIN
))) {
1203 pa_log_info("FD error: %s%s%s%s",
1204 pollfd
->revents
& POLLERR
? "POLLERR " :"",
1205 pollfd
->revents
& POLLHUP
? "POLLHUP " :"",
1206 pollfd
->revents
& POLLPRI
? "POLLPRI " :"",
1207 pollfd
->revents
& POLLNVAL
? "POLLNVAL " :"");
1214 /* In case of HUP, just tear down the streams */
1215 if (!pollfd
|| (pollfd
->revents
& POLLHUP
) == 0)
1219 pending_read_bytes
= 0;
1226 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1227 pa_log_debug("IO thread failed");
1228 pa_asyncmsgq_post(pa_thread_mq_get()->outq
, PA_MSGOBJECT(u
->msg
), BLUETOOTH_MESSAGE_IO_THREAD_FAILED
, NULL
, 0, NULL
, NULL
);
1229 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1232 pa_log_debug("IO thread shutting down");
1235 static pa_bt_audio_state_t
parse_state_property_change(DBusMessage
*m
) {
1236 DBusMessageIter iter
;
1237 DBusMessageIter variant
;
1240 pa_bt_audio_state_t state
;
1242 if (!dbus_message_iter_init(m
, &iter
)) {
1243 pa_log("Failed to parse PropertyChanged");
1244 return PA_BT_AUDIO_STATE_INVALID
;
1247 if (dbus_message_iter_get_arg_type(&iter
) != DBUS_TYPE_STRING
) {
1248 pa_log("Property name not a string");
1249 return PA_BT_AUDIO_STATE_INVALID
;
1252 dbus_message_iter_get_basic(&iter
, &key
);
1254 if (!pa_streq(key
, "State"))
1255 return PA_BT_AUDIO_STATE_INVALID
;
1257 if (!dbus_message_iter_next(&iter
)) {
1258 pa_log("Property value missing");
1259 return PA_BT_AUDIO_STATE_INVALID
;
1262 dbus_message_iter_recurse(&iter
, &variant
);
1264 if (dbus_message_iter_get_arg_type(&variant
) != DBUS_TYPE_STRING
) {
1265 pa_log("Property value not a string");
1266 return PA_BT_AUDIO_STATE_INVALID
;
1269 dbus_message_iter_get_basic(&variant
, &value
);
1271 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m
), value
);
1273 state
= pa_bt_audio_state_from_string(value
);
1275 if (state
== PA_BT_AUDIO_STATE_INVALID
)
1276 pa_log("Unexpected value for property 'State': '%s'", value
);
1281 static pa_port_available_t
audio_state_to_availability(pa_bt_audio_state_t state
) {
1282 if (state
< PA_BT_AUDIO_STATE_CONNECTED
)
1283 return PA_PORT_AVAILABLE_NO
;
1284 else if (state
>= PA_BT_AUDIO_STATE_PLAYING
)
1285 return PA_PORT_AVAILABLE_YES
;
1287 return PA_PORT_AVAILABLE_UNKNOWN
;
1290 static pa_port_available_t
audio_state_to_availability_merged(pa_bt_audio_state_t state1
, pa_bt_audio_state_t state2
) {
1291 if (state1
< PA_BT_AUDIO_STATE_CONNECTED
&& state2
< PA_BT_AUDIO_STATE_CONNECTED
)
1292 return PA_PORT_AVAILABLE_NO
;
1293 else if (state1
>= PA_BT_AUDIO_STATE_PLAYING
|| state2
>= PA_BT_AUDIO_STATE_PLAYING
)
1294 return PA_PORT_AVAILABLE_YES
;
1296 return PA_PORT_AVAILABLE_UNKNOWN
;
1299 /* Run from main thread */
1300 static DBusHandlerResult
filter_cb(DBusConnection
*bus
, DBusMessage
*m
, void *userdata
) {
1303 bool acquire
= FALSE
;
1304 bool release
= FALSE
;
1308 pa_assert_se(u
= userdata
);
1310 dbus_error_init(&err
);
1312 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1313 dbus_message_get_interface(m
),
1314 dbus_message_get_path(m
),
1315 dbus_message_get_member(m
));
1317 if (!dbus_message_has_path(m
, u
->path
) && (!u
->transport
|| !dbus_message_has_path(m
, u
->transport
->path
)))
1320 if (dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged") ||
1321 dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1326 if (!dbus_message_get_args(m
, &err
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
) || gain
> HSP_MAX_GAIN
) {
1327 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err
.message
);
1331 if (u
->profile
== PROFILE_HSP
) {
1332 if (u
->sink
&& dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged")) {
1333 pa_volume_t volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1335 /* increment volume by one to correct rounding errors */
1336 if (volume
< PA_VOLUME_NORM
)
1339 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1340 pa_sink_volume_changed(u
->sink
, &v
);
1342 } else if (u
->source
&& dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1343 pa_volume_t volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1345 /* increment volume by one to correct rounding errors */
1346 if (volume
< PA_VOLUME_NORM
)
1349 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1350 pa_source_volume_changed(u
->source
, &v
);
1353 } else if (dbus_message_is_signal(m
, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1354 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1356 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "hfgw")) {
1357 pa_device_port
*port
;
1358 pa_port_available_t available
= audio_state_to_availability(state
);
1360 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1361 pa_device_port_set_available(port
, available
);
1363 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1364 pa_device_port_set_available(port
, available
);
1366 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1367 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1369 } else if (dbus_message_is_signal(m
, "org.bluez.Headset", "PropertyChanged")) {
1370 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1372 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "hsp")) {
1373 pa_device_port
*port
;
1374 pa_port_available_t available
;
1376 if (pa_hashmap_get(u
->card
->profiles
, "a2dp") == NULL
)
1377 available
= audio_state_to_availability(state
);
1379 available
= audio_state_to_availability_merged(state
, u
->device
->audio_sink_state
);
1381 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1382 pa_device_port_set_available(port
, available
);
1384 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1385 pa_device_port_set_available(port
, available
);
1387 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1388 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1390 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSource", "PropertyChanged")) {
1391 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1393 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "a2dp_source")) {
1394 pa_device_port
*port
;
1395 pa_port_available_t available
= audio_state_to_availability(state
);
1397 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1398 pa_device_port_set_available(port
, available
);
1400 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1401 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1403 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSink", "PropertyChanged")) {
1404 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1406 if (state
!= PA_BT_AUDIO_STATE_INVALID
&& pa_hashmap_get(u
->card
->profiles
, "a2dp")) {
1407 pa_device_port
*port
;
1408 pa_port_available_t available
;
1410 if (pa_hashmap_get(u
->card
->profiles
, "hsp") == NULL
)
1411 available
= audio_state_to_availability(state
);
1413 available
= audio_state_to_availability_merged(state
, u
->device
->headset_state
);
1415 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1416 pa_device_port_set_available(port
, available
);
1418 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1419 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1424 if (bt_transport_acquire(u
, FALSE
) >= 0) {
1426 pa_source_suspend(u
->source
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1429 pa_sink_suspend(u
->sink
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1432 if (release
&& bt_transport_is_acquired(u
)) {
1433 /* FIXME: this release is racy, since the audio stream might have
1434 been set up again in the meantime (but not processed yet by PA).
1435 BlueZ should probably release the transport automatically, and
1436 in that case we would just mark the transport as released */
1438 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1440 pa_source_suspend(u
->source
, TRUE
, PA_SUSPEND_USER
);
1443 pa_sink_suspend(u
->sink
, TRUE
, PA_SUSPEND_USER
);
1447 dbus_error_free(&err
);
1449 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1452 /* Run from main thread */
1453 static void sink_set_volume_cb(pa_sink
*s
) {
1463 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1464 u
= pa_shared_get(s
->core
, k
);
1468 pa_assert(u
->sink
== s
);
1469 pa_assert(u
->profile
== PROFILE_HSP
);
1471 gain
= (pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
) / PA_VOLUME_NORM
;
1473 if (gain
> HSP_MAX_GAIN
)
1474 gain
= HSP_MAX_GAIN
;
1476 volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1478 /* increment volume by one to correct rounding errors */
1479 if (volume
< PA_VOLUME_NORM
)
1482 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1484 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetSpeakerGain"));
1485 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1486 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1487 dbus_message_unref(m
);
1490 /* Run from main thread */
1491 static void source_set_volume_cb(pa_source
*s
) {
1501 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1502 u
= pa_shared_get(s
->core
, k
);
1506 pa_assert(u
->source
== s
);
1507 pa_assert(u
->profile
== PROFILE_HSP
);
1509 gain
= (pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
) / PA_VOLUME_NORM
;
1511 if (gain
> HSP_MAX_GAIN
)
1512 gain
= HSP_MAX_GAIN
;
1514 volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1516 /* increment volume by one to correct rounding errors */
1517 if (volume
< PA_VOLUME_NORM
)
1520 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1522 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetMicrophoneGain"));
1523 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1524 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1525 dbus_message_unref(m
);
1528 /* Run from main thread */
1529 static char *get_name(const char *type
, pa_modargs
*ma
, const char *device_id
, pa_bool_t
*namereg_fail
) {
1535 pa_assert(device_id
);
1536 pa_assert(namereg_fail
);
1538 t
= pa_sprintf_malloc("%s_name", type
);
1539 n
= pa_modargs_get_value(ma
, t
, NULL
);
1543 *namereg_fail
= TRUE
;
1544 return pa_xstrdup(n
);
1547 if ((n
= pa_modargs_get_value(ma
, "name", NULL
)))
1548 *namereg_fail
= TRUE
;
1551 *namereg_fail
= FALSE
;
1554 return pa_sprintf_malloc("bluez_%s.%s", type
, n
);
1557 static int sco_over_pcm_state_update(struct userdata
*u
, pa_bool_t changed
) {
1559 pa_assert(USE_SCO_OVER_PCM(u
));
1561 if (PA_SINK_IS_OPENED(pa_sink_get_state(u
->hsp
.sco_sink
)) ||
1562 PA_SOURCE_IS_OPENED(pa_source_get_state(u
->hsp
.sco_source
))) {
1564 if (u
->stream_fd
>= 0)
1567 pa_log_debug("Resuming SCO over PCM");
1568 if (init_profile(u
) < 0) {
1569 pa_log("Can't resume SCO over PCM");
1573 return bt_transport_acquire(u
, TRUE
);
1577 if (u
->stream_fd
< 0)
1580 pa_log_debug("Closing SCO over PCM");
1582 bt_transport_release(u
);
1588 static pa_hook_result_t
sink_state_changed_cb(pa_core
*c
, pa_sink
*s
, struct userdata
*u
) {
1590 pa_sink_assert_ref(s
);
1593 if (s
!= u
->hsp
.sco_sink
)
1596 sco_over_pcm_state_update(u
, TRUE
);
1601 static pa_hook_result_t
source_state_changed_cb(pa_core
*c
, pa_source
*s
, struct userdata
*u
) {
1603 pa_source_assert_ref(s
);
1606 if (s
!= u
->hsp
.sco_source
)
1609 sco_over_pcm_state_update(u
, TRUE
);
1614 static pa_hook_result_t
nrec_changed_cb(pa_bluetooth_transport
*t
, void *call_data
, struct userdata
*u
) {
1620 p
= pa_proplist_new();
1621 pa_proplist_sets(p
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1622 pa_source_update_proplist(u
->source
, PA_UPDATE_REPLACE
, p
);
1623 pa_proplist_free(p
);
1628 static void connect_ports(struct userdata
*u
, void *sink_or_source_new_data
, pa_direction_t direction
) {
1630 pa_sink_new_data
*sink_new_data
;
1631 pa_source_new_data
*source_new_data
;
1633 pa_device_port
*port
;
1635 if (direction
== PA_DIRECTION_OUTPUT
)
1636 data
.sink_new_data
= sink_or_source_new_data
;
1638 data
.source_new_data
= sink_or_source_new_data
;
1640 switch (u
->profile
) {
1642 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1643 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1644 pa_device_port_ref(port
);
1647 case PROFILE_A2DP_SOURCE
:
1648 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1649 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1650 pa_device_port_ref(port
);
1654 if (direction
== PA_DIRECTION_OUTPUT
) {
1655 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "bluetooth-output"));
1656 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1658 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1659 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1661 pa_device_port_ref(port
);
1665 if (direction
== PA_DIRECTION_OUTPUT
) {
1666 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1667 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1669 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1670 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1672 pa_device_port_ref(port
);
1676 pa_assert_not_reached();
1680 static const char *profile_to_string(enum profile profile
) {
1684 case PROFILE_A2DP_SOURCE
:
1685 return "a2dp_source";
1691 pa_assert_not_reached();
1695 static int sink_set_port_cb(pa_sink
*s
, pa_device_port
*p
) {
1699 static int source_set_port_cb(pa_source
*s
, pa_device_port
*p
) {
1703 /* Run from main thread */
1704 static int add_sink(struct userdata
*u
) {
1707 pa_assert(u
->transport
);
1709 if (USE_SCO_OVER_PCM(u
)) {
1712 u
->sink
= u
->hsp
.sco_sink
;
1713 p
= pa_proplist_new();
1714 pa_proplist_sets(p
, "bluetooth.protocol", profile_to_string(u
->profile
));
1715 pa_proplist_update(u
->sink
->proplist
, PA_UPDATE_MERGE
, p
);
1716 pa_proplist_free(p
);
1718 if (!u
->hsp
.sink_state_changed_slot
)
1719 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
);
1722 pa_sink_new_data data
;
1725 pa_sink_new_data_init(&data
);
1726 data
.driver
= __FILE__
;
1727 data
.module
= u
->module
;
1728 pa_sink_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1729 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1730 if (u
->profile
== PROFILE_HSP
)
1731 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1732 data
.card
= u
->card
;
1733 data
.name
= get_name("sink", u
->modargs
, u
->address
, &b
);
1734 data
.namereg_fail
= b
;
1736 if (pa_modargs_get_proplist(u
->modargs
, "sink_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1737 pa_log("Invalid properties");
1738 pa_sink_new_data_done(&data
);
1741 connect_ports(u
, &data
, PA_DIRECTION_OUTPUT
);
1743 if (!bt_transport_is_acquired(u
))
1744 switch (u
->profile
) {
1747 pa_assert_not_reached(); /* Profile switch should have failed */
1750 data
.suspend_cause
= PA_SUSPEND_USER
;
1752 case PROFILE_A2DP_SOURCE
:
1754 pa_assert_not_reached();
1757 u
->sink
= pa_sink_new(u
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
);
1758 pa_sink_new_data_done(&data
);
1761 pa_log_error("Failed to create sink");
1765 u
->sink
->userdata
= u
;
1766 u
->sink
->parent
.process_msg
= sink_process_msg
;
1767 u
->sink
->set_port
= sink_set_port_cb
;
1770 if (u
->profile
== PROFILE_HSP
) {
1771 pa_sink_set_set_volume_callback(u
->sink
, sink_set_volume_cb
);
1772 u
->sink
->n_volume_steps
= 16;
1774 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
1775 pa_shared_set(u
->core
, k
, u
);
1782 /* Run from main thread */
1783 static int add_source(struct userdata
*u
) {
1786 pa_assert(u
->transport
);
1788 if (USE_SCO_OVER_PCM(u
)) {
1789 u
->source
= u
->hsp
.sco_source
;
1790 pa_proplist_sets(u
->source
->proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1792 if (!u
->hsp
.source_state_changed_slot
)
1793 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
);
1796 pa_source_new_data data
;
1799 pa_source_new_data_init(&data
);
1800 data
.driver
= __FILE__
;
1801 data
.module
= u
->module
;
1802 pa_source_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1803 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1804 if (u
->profile
== PROFILE_HSP
)
1805 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1807 data
.card
= u
->card
;
1808 data
.name
= get_name("source", u
->modargs
, u
->address
, &b
);
1809 data
.namereg_fail
= b
;
1811 if (pa_modargs_get_proplist(u
->modargs
, "source_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1812 pa_log("Invalid properties");
1813 pa_source_new_data_done(&data
);
1817 connect_ports(u
, &data
, PA_DIRECTION_INPUT
);
1819 if (!bt_transport_is_acquired(u
))
1820 switch (u
->profile
) {
1822 pa_assert_not_reached(); /* Profile switch should have failed */
1824 case PROFILE_A2DP_SOURCE
:
1826 data
.suspend_cause
= PA_SUSPEND_USER
;
1830 pa_assert_not_reached();
1833 u
->source
= pa_source_new(u
->core
, &data
, PA_SOURCE_HARDWARE
|PA_SOURCE_LATENCY
);
1834 pa_source_new_data_done(&data
);
1837 pa_log_error("Failed to create source");
1841 u
->source
->userdata
= u
;
1842 u
->source
->parent
.process_msg
= source_process_msg
;
1843 u
->source
->set_port
= source_set_port_cb
;
1846 if ((u
->profile
== PROFILE_HSP
) || (u
->profile
== PROFILE_HFGW
)) {
1847 pa_bluetooth_transport
*t
= u
->transport
;
1848 pa_proplist_sets(u
->source
->proplist
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1850 if (!u
->hsp
.nrec_changed_slot
)
1851 u
->hsp
.nrec_changed_slot
= pa_hook_connect(&t
->hooks
[PA_BLUETOOTH_TRANSPORT_HOOK_NREC_CHANGED
], PA_HOOK_NORMAL
, (pa_hook_cb_t
) nrec_changed_cb
, u
);
1854 if (u
->profile
== PROFILE_HSP
) {
1855 pa_source_set_set_volume_callback(u
->source
, source_set_volume_cb
);
1856 u
->source
->n_volume_steps
= 16;
1858 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
1859 pa_shared_set(u
->core
, k
, u
);
1866 static void bt_transport_config_a2dp(struct userdata
*u
) {
1867 const pa_bluetooth_transport
*t
;
1868 struct a2dp_info
*a2dp
= &u
->a2dp
;
1874 config
= (a2dp_sbc_t
*) t
->config
;
1876 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1878 if (a2dp
->sbc_initialized
)
1879 sbc_reinit(&a2dp
->sbc
, 0);
1881 sbc_init(&a2dp
->sbc
, 0);
1882 a2dp
->sbc_initialized
= TRUE
;
1884 switch (config
->frequency
) {
1885 case SBC_SAMPLING_FREQ_16000
:
1886 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
1887 u
->sample_spec
.rate
= 16000U;
1889 case SBC_SAMPLING_FREQ_32000
:
1890 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
1891 u
->sample_spec
.rate
= 32000U;
1893 case SBC_SAMPLING_FREQ_44100
:
1894 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
1895 u
->sample_spec
.rate
= 44100U;
1897 case SBC_SAMPLING_FREQ_48000
:
1898 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
1899 u
->sample_spec
.rate
= 48000U;
1902 pa_assert_not_reached();
1905 switch (config
->channel_mode
) {
1906 case SBC_CHANNEL_MODE_MONO
:
1907 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
1908 u
->sample_spec
.channels
= 1;
1910 case SBC_CHANNEL_MODE_DUAL_CHANNEL
:
1911 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
1912 u
->sample_spec
.channels
= 2;
1914 case SBC_CHANNEL_MODE_STEREO
:
1915 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
1916 u
->sample_spec
.channels
= 2;
1918 case SBC_CHANNEL_MODE_JOINT_STEREO
:
1919 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
1920 u
->sample_spec
.channels
= 2;
1923 pa_assert_not_reached();
1926 switch (config
->allocation_method
) {
1927 case SBC_ALLOCATION_SNR
:
1928 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
1930 case SBC_ALLOCATION_LOUDNESS
:
1931 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
1934 pa_assert_not_reached();
1937 switch (config
->subbands
) {
1938 case SBC_SUBBANDS_4
:
1939 a2dp
->sbc
.subbands
= SBC_SB_4
;
1941 case SBC_SUBBANDS_8
:
1942 a2dp
->sbc
.subbands
= SBC_SB_8
;
1945 pa_assert_not_reached();
1948 switch (config
->block_length
) {
1949 case SBC_BLOCK_LENGTH_4
:
1950 a2dp
->sbc
.blocks
= SBC_BLK_4
;
1952 case SBC_BLOCK_LENGTH_8
:
1953 a2dp
->sbc
.blocks
= SBC_BLK_8
;
1955 case SBC_BLOCK_LENGTH_12
:
1956 a2dp
->sbc
.blocks
= SBC_BLK_12
;
1958 case SBC_BLOCK_LENGTH_16
:
1959 a2dp
->sbc
.blocks
= SBC_BLK_16
;
1962 pa_assert_not_reached();
1965 a2dp
->min_bitpool
= config
->min_bitpool
;
1966 a2dp
->max_bitpool
= config
->max_bitpool
;
1968 /* Set minimum bitpool for source to get the maximum possible block_size */
1969 a2dp
->sbc
.bitpool
= u
->profile
== PROFILE_A2DP
? a2dp
->max_bitpool
: a2dp
->min_bitpool
;
1970 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
1971 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
1973 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1974 a2dp
->sbc
.allocation
, a2dp
->sbc
.subbands
, a2dp
->sbc
.blocks
, a2dp
->sbc
.bitpool
);
1977 static void bt_transport_config(struct userdata
*u
) {
1978 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
1979 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1980 u
->sample_spec
.channels
= 1;
1981 u
->sample_spec
.rate
= 8000;
1983 bt_transport_config_a2dp(u
);
1986 /* Run from main thread */
1987 static pa_hook_result_t
transport_removed_cb(pa_bluetooth_transport
*t
, void *call_data
, struct userdata
*u
) {
1991 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
1996 /* Run from main thread */
1997 static int setup_transport(struct userdata
*u
) {
1998 pa_bluetooth_transport
*t
;
2001 pa_assert(!u
->transport
);
2003 /* check if profile has a transport */
2004 t
= pa_bluetooth_device_get_transport(u
->device
, u
->profile
);
2006 pa_log_warn("Profile has no transport");
2012 u
->transport_removed_slot
= pa_hook_connect(&t
->hooks
[PA_BLUETOOTH_TRANSPORT_HOOK_REMOVED
], PA_HOOK_NORMAL
,
2013 (pa_hook_cb_t
) transport_removed_cb
, u
);
2015 if (u
->profile
== PROFILE_A2DP_SOURCE
|| u
->profile
== PROFILE_HFGW
)
2016 bt_transport_acquire(u
, FALSE
); /* In case of error, the sink/sources will be created suspended */
2017 else if (bt_transport_acquire(u
, TRUE
) < 0)
2018 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
2020 bt_transport_config(u
);
2025 /* Run from main thread */
2026 static int init_profile(struct userdata
*u
) {
2029 pa_assert(u
->profile
!= PROFILE_OFF
);
2031 if (setup_transport(u
) < 0)
2034 pa_assert(u
->transport
);
2036 if (u
->profile
== PROFILE_A2DP
||
2037 u
->profile
== PROFILE_HSP
||
2038 u
->profile
== PROFILE_HFGW
)
2039 if (add_sink(u
) < 0)
2042 if (u
->profile
== PROFILE_HSP
||
2043 u
->profile
== PROFILE_A2DP_SOURCE
||
2044 u
->profile
== PROFILE_HFGW
)
2045 if (add_source(u
) < 0)
2051 /* Run from main thread */
2052 static void stop_thread(struct userdata
*u
) {
2057 if (u
->sink
&& !USE_SCO_OVER_PCM(u
))
2058 pa_sink_unlink(u
->sink
);
2060 if (u
->source
&& !USE_SCO_OVER_PCM(u
))
2061 pa_source_unlink(u
->source
);
2064 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
2065 pa_thread_free(u
->thread
);
2069 if (u
->rtpoll_item
) {
2070 pa_rtpoll_item_free(u
->rtpoll_item
);
2071 u
->rtpoll_item
= NULL
;
2074 if (u
->hsp
.sink_state_changed_slot
) {
2075 pa_hook_slot_free(u
->hsp
.sink_state_changed_slot
);
2076 u
->hsp
.sink_state_changed_slot
= NULL
;
2079 if (u
->hsp
.source_state_changed_slot
) {
2080 pa_hook_slot_free(u
->hsp
.source_state_changed_slot
);
2081 u
->hsp
.source_state_changed_slot
= NULL
;
2084 if (u
->hsp
.nrec_changed_slot
) {
2085 pa_hook_slot_free(u
->hsp
.nrec_changed_slot
);
2086 u
->hsp
.nrec_changed_slot
= NULL
;
2089 if (u
->transport_removed_slot
) {
2090 pa_hook_slot_free(u
->transport_removed_slot
);
2091 u
->transport_removed_slot
= NULL
;
2095 bt_transport_release(u
);
2096 u
->transport
= NULL
;
2100 if (u
->profile
== PROFILE_HSP
) {
2101 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2102 pa_shared_remove(u
->core
, k
);
2106 pa_sink_unref(u
->sink
);
2111 if (u
->profile
== PROFILE_HSP
) {
2112 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2113 pa_shared_remove(u
->core
, k
);
2117 pa_source_unref(u
->source
);
2122 pa_thread_mq_done(&u
->thread_mq
);
2124 pa_rtpoll_free(u
->rtpoll
);
2128 if (u
->read_smoother
) {
2129 pa_smoother_free(u
->read_smoother
);
2130 u
->read_smoother
= NULL
;
2134 /* Run from main thread */
2135 static int start_thread(struct userdata
*u
) {
2137 pa_assert(!u
->thread
);
2138 pa_assert(!u
->rtpoll
);
2139 pa_assert(!u
->rtpoll_item
);
2141 u
->rtpoll
= pa_rtpoll_new();
2142 pa_thread_mq_init(&u
->thread_mq
, u
->core
->mainloop
, u
->rtpoll
);
2144 if (USE_SCO_OVER_PCM(u
)) {
2145 if (sco_over_pcm_state_update(u
, FALSE
) < 0) {
2149 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2150 pa_shared_remove(u
->core
, k
);
2155 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2156 pa_shared_remove(u
->core
, k
);
2163 pa_sink_ref(u
->sink
);
2164 pa_source_ref(u
->source
);
2165 /* FIXME: monitor stream_fd error */
2169 if (!(u
->thread
= pa_thread_new("bluetooth", thread_func
, u
))) {
2170 pa_log_error("Failed to create IO thread");
2175 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
2176 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
2177 pa_sink_put(u
->sink
);
2179 if (u
->sink
->set_volume
)
2180 u
->sink
->set_volume(u
->sink
);
2184 pa_source_set_asyncmsgq(u
->source
, u
->thread_mq
.inq
);
2185 pa_source_set_rtpoll(u
->source
, u
->rtpoll
);
2186 pa_source_put(u
->source
);
2188 if (u
->source
->set_volume
)
2189 u
->source
->set_volume(u
->source
);
2195 static void save_sco_volume_callbacks(struct userdata
*u
) {
2197 pa_assert(USE_SCO_OVER_PCM(u
));
2199 u
->hsp
.sco_sink_set_volume
= u
->hsp
.sco_sink
->set_volume
;
2200 u
->hsp
.sco_source_set_volume
= u
->hsp
.sco_source
->set_volume
;
2203 static void restore_sco_volume_callbacks(struct userdata
*u
) {
2205 pa_assert(USE_SCO_OVER_PCM(u
));
2207 pa_sink_set_set_volume_callback(u
->hsp
.sco_sink
, u
->hsp
.sco_sink_set_volume
);
2208 pa_source_set_set_volume_callback(u
->hsp
.sco_source
, u
->hsp
.sco_source_set_volume
);
2211 /* Run from main thread */
2212 static int card_set_profile(pa_card
*c
, pa_card_profile
*new_profile
) {
2217 pa_assert(new_profile
);
2218 pa_assert_se(u
= c
->userdata
);
2220 d
= PA_CARD_PROFILE_DATA(new_profile
);
2222 if (*d
!= PROFILE_OFF
) {
2223 const pa_bluetooth_device
*device
= u
->device
;
2225 if (device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) {
2226 pa_log_warn("HSP is not connected, refused to switch profile");
2228 } else if (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) {
2229 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2231 } else if (device
->audio_source_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP_SOURCE
) {
2232 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2234 } else if (device
->hfgw_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
) {
2235 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2242 if (USE_SCO_OVER_PCM(u
))
2243 restore_sco_volume_callbacks(u
);
2246 u
->sample_spec
= u
->requested_sample_spec
;
2248 if (USE_SCO_OVER_PCM(u
))
2249 save_sco_volume_callbacks(u
);
2251 if (u
->profile
!= PROFILE_OFF
)
2252 if (init_profile(u
) < 0)
2255 if (u
->sink
|| u
->source
)
2256 if (start_thread(u
) < 0)
2264 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
2269 static void create_ports_for_profile(struct userdata
*u
, pa_hashmap
*ports
, pa_card_profile
*profile
) {
2270 pa_bluetooth_device
*device
= u
->device
;
2271 pa_device_port
*port
;
2274 d
= PA_CARD_PROFILE_DATA(profile
);
2278 if ((port
= pa_hashmap_get(ports
, "bluetooth-output")) != NULL
) {
2279 port
->priority
= PA_MAX(port
->priority
, profile
->priority
* 100);
2280 port
->available
= audio_state_to_availability_merged(device
->headset_state
, device
->audio_sink_state
);
2281 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2283 pa_assert_se(port
= pa_device_port_new(u
->core
, "bluetooth-output", _("Bluetooth Output"), 0));
2284 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2285 port
->is_output
= 1;
2287 port
->priority
= profile
->priority
* 100;
2288 port
->available
= audio_state_to_availability(device
->audio_sink_state
);
2289 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2294 case PROFILE_A2DP_SOURCE
:
2295 pa_assert_se(port
= pa_device_port_new(u
->core
, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2296 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2297 port
->is_output
= 0;
2299 port
->priority
= profile
->priority
* 100;
2300 port
->available
= audio_state_to_availability(device
->audio_source_state
);
2301 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2305 if ((port
= pa_hashmap_get(ports
, "bluetooth-output")) != NULL
) {
2306 port
->priority
= PA_MAX(port
->priority
, profile
->priority
* 100);
2307 port
->available
= audio_state_to_availability_merged(device
->headset_state
, device
->audio_sink_state
);
2308 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2310 pa_assert_se(port
= pa_device_port_new(u
->core
, "bluetooth-output", _("Bluetooth Output"), 0));
2311 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2312 port
->is_output
= 1;
2314 port
->priority
= profile
->priority
* 100;
2315 port
->available
= audio_state_to_availability(device
->headset_state
);
2316 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2319 pa_assert_se(port
= pa_device_port_new(u
->core
, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2320 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2321 port
->is_output
= 0;
2323 port
->priority
= profile
->priority
* 100;
2324 port
->available
= audio_state_to_availability(device
->headset_state
);
2325 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2329 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2330 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2331 port
->is_output
= 1;
2333 port
->priority
= profile
->priority
* 100;
2334 port
->available
= audio_state_to_availability(device
->hfgw_state
);
2335 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2337 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2338 pa_assert_se(pa_hashmap_put(ports
, port
->name
, port
) >= 0);
2339 port
->is_output
= 0;
2341 port
->priority
= profile
->priority
* 100;
2342 port
->available
= audio_state_to_availability(device
->hfgw_state
);
2343 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2347 pa_assert_not_reached();
2352 /* Run from main thread */
2353 static pa_card_profile
*create_card_profile(struct userdata
*u
, const char *uuid
) {
2354 pa_card_profile
*p
= NULL
;
2357 if (pa_streq(uuid
, A2DP_SINK_UUID
)) {
2358 p
= pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile
));
2362 p
->max_sink_channels
= 2;
2363 p
->max_source_channels
= 0;
2365 d
= PA_CARD_PROFILE_DATA(p
);
2367 } else if (pa_streq(uuid
, A2DP_SOURCE_UUID
)) {
2368 p
= pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile
));
2372 p
->max_sink_channels
= 0;
2373 p
->max_source_channels
= 2;
2375 d
= PA_CARD_PROFILE_DATA(p
);
2376 *d
= PROFILE_A2DP_SOURCE
;
2377 } else if (pa_streq(uuid
, HSP_HS_UUID
) || pa_streq(uuid
, HFP_HS_UUID
)) {
2378 p
= pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile
));
2382 p
->max_sink_channels
= 1;
2383 p
->max_source_channels
= 1;
2385 d
= PA_CARD_PROFILE_DATA(p
);
2387 } else if (pa_streq(uuid
, HFP_AG_UUID
)) {
2388 p
= pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile
));
2392 p
->max_sink_channels
= 1;
2393 p
->max_source_channels
= 1;
2395 d
= PA_CARD_PROFILE_DATA(p
);
2402 /* Run from main thread */
2403 static int add_card(struct userdata
*u
) {
2404 pa_card_new_data data
;
2410 const char *default_profile
;
2411 const pa_bluetooth_device
*device
= u
->device
;
2412 const pa_bluetooth_uuid
*uuid
;
2417 pa_card_new_data_init(&data
);
2418 data
.driver
= __FILE__
;
2419 data
.module
= u
->module
;
2421 n
= pa_bluetooth_cleanup_name(device
->name
);
2422 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_DESCRIPTION
, n
);
2424 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, device
->address
);
2425 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_API
, "bluez");
2426 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_CLASS
, "sound");
2427 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_BUS
, "bluetooth");
2428 if ((ff
= pa_bluetooth_get_form_factor(device
->class)))
2429 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_FORM_FACTOR
, ff
);
2430 pa_proplist_sets(data
.proplist
, "bluez.path", device
->path
);
2431 pa_proplist_setf(data
.proplist
, "bluez.class", "0x%06x", (unsigned) device
->class);
2432 pa_proplist_sets(data
.proplist
, "bluez.name", device
->name
);
2433 data
.name
= get_name("card", u
->modargs
, device
->address
, &b
);
2434 data
.namereg_fail
= b
;
2436 if (pa_modargs_get_proplist(u
->modargs
, "card_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
2437 pa_log("Invalid properties");
2438 pa_card_new_data_done(&data
);
2442 PA_LLIST_FOREACH(uuid
, device
->uuids
) {
2443 p
= create_card_profile(u
, uuid
->uuid
);
2448 if (pa_hashmap_get(data
.profiles
, p
->name
)) {
2449 pa_card_profile_free(p
);
2453 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2454 create_ports_for_profile(u
, data
.ports
, p
);
2457 pa_assert(!pa_hashmap_isempty(data
.profiles
));
2459 p
= pa_card_profile_new("off", _("Off"), sizeof(enum profile
));
2460 d
= PA_CARD_PROFILE_DATA(p
);
2462 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2464 if ((default_profile
= pa_modargs_get_value(u
->modargs
, "profile", NULL
))) {
2465 if (pa_hashmap_get(data
.profiles
, default_profile
))
2466 pa_card_new_data_set_profile(&data
, default_profile
);
2468 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile
);
2471 u
->card
= pa_card_new(u
->core
, &data
);
2472 pa_card_new_data_done(&data
);
2475 pa_log("Failed to allocate card.");
2479 u
->card
->userdata
= u
;
2480 u
->card
->set_profile
= card_set_profile
;
2482 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2484 if ((device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) ||
2485 (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) ||
2486 (device
->audio_source_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP_SOURCE
) ||
2487 (device
->hfgw_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
)) {
2488 pa_log_warn("Default profile not connected, selecting off profile");
2489 u
->card
->active_profile
= pa_hashmap_get(u
->card
->profiles
, "off");
2490 u
->card
->save_profile
= FALSE
;
2493 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2496 if (USE_SCO_OVER_PCM(u
))
2497 save_sco_volume_callbacks(u
);
2502 /* Run from main thread */
2503 static pa_bluetooth_device
* find_device(struct userdata
*u
, const char *address
, const char *path
) {
2504 pa_bluetooth_device
*d
= NULL
;
2508 if (!address
&& !path
) {
2509 pa_log_error("Failed to get device address/path from module arguments.");
2514 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, path
))) {
2515 pa_log_error("%s is not a valid BlueZ audio device.", path
);
2519 if (address
&& !(pa_streq(d
->address
, address
))) {
2520 pa_log_error("Passed path %s address %s != %s don't match.", path
, d
->address
, address
);
2525 if (!(d
= pa_bluetooth_discovery_get_by_address(u
->discovery
, address
))) {
2526 pa_log_error("%s is not known.", address
);
2532 u
->address
= pa_xstrdup(d
->address
);
2533 u
->path
= pa_xstrdup(d
->path
);
2539 /* Run from main thread */
2540 static pa_hook_result_t
uuid_added_cb(pa_bluetooth_device
*d
, const char *uuid
, struct userdata
*u
) {
2542 pa_hashmap
*new_ports
;
2548 p
= create_card_profile(u
, uuid
);
2553 if (pa_hashmap_get(u
->card
->profiles
, p
->name
)) {
2554 pa_card_profile_free(p
);
2558 pa_card_add_profile(u
->card
, p
);
2560 new_ports
= pa_hashmap_new(pa_idxset_string_hash_func
, pa_idxset_string_compare_func
);
2562 create_ports_for_profile(u
, new_ports
, p
);
2564 pa_card_add_ports(u
->card
, new_ports
);
2566 pa_device_port_hashmap_free(new_ports
);
2571 /* Run from main thread */
2572 static int setup_dbus(struct userdata
*u
) {
2575 dbus_error_init(&err
);
2577 u
->connection
= pa_dbus_bus_get(u
->core
, DBUS_BUS_SYSTEM
, &err
);
2579 if (dbus_error_is_set(&err
) || !u
->connection
) {
2580 pa_log("Failed to get D-Bus connection: %s", err
.message
);
2581 dbus_error_free(&err
);
2588 /* Run from main thread */
2589 static pa_hook_result_t
device_removed_cb(pa_bluetooth_device
*d
, void *call_data
, struct userdata
*u
) {
2593 pa_log_debug("Device %s removed: unloading module", d
->path
);
2594 pa_module_unload(u
->core
, u
->module
, TRUE
);
2599 /* Run from main thread */
2600 static pa_hook_result_t
discovery_hook_cb(pa_bluetooth_discovery
*y
, const pa_bluetooth_device
*d
, struct userdata
*u
) {
2607 if (pa_bluetooth_device_any_audio_connected(d
))
2610 pa_log_debug("Unloading module, because device %s doesn't have any audio profiles connected anymore.", d
->path
);
2611 pa_module_unload(u
->core
, u
->module
, true);
2616 int pa__init(pa_module
* m
) {
2620 const char *address
, *path
;
2622 char *mike
, *speaker
;
2623 pa_bluetooth_device
*device
;
2627 dbus_error_init(&err
);
2629 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
2630 pa_log_error("Failed to parse module arguments");
2634 m
->userdata
= u
= pa_xnew0(struct userdata
, 1);
2638 u
->sample_spec
= m
->core
->default_sample_spec
;
2641 if (pa_modargs_get_value(ma
, "sco_sink", NULL
) &&
2642 !(u
->hsp
.sco_sink
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_sink", NULL
), PA_NAMEREG_SINK
))) {
2643 pa_log("SCO sink not found");
2647 if (pa_modargs_get_value(ma
, "sco_source", NULL
) &&
2648 !(u
->hsp
.sco_source
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_source", NULL
), PA_NAMEREG_SOURCE
))) {
2649 pa_log("SCO source not found");
2653 if (pa_modargs_get_value_u32(ma
, "rate", &u
->sample_spec
.rate
) < 0 ||
2654 u
->sample_spec
.rate
<= 0 || u
->sample_spec
.rate
> PA_RATE_MAX
) {
2655 pa_log_error("Failed to get rate from module arguments");
2659 u
->auto_connect
= TRUE
;
2660 if (pa_modargs_get_value_boolean(ma
, "auto_connect", &u
->auto_connect
)) {
2661 pa_log("Failed to parse auto_connect= argument");
2665 channels
= u
->sample_spec
.channels
;
2666 if (pa_modargs_get_value_u32(ma
, "channels", &channels
) < 0 ||
2667 channels
<= 0 || channels
> PA_CHANNELS_MAX
) {
2668 pa_log_error("Failed to get channels from module arguments");
2671 u
->sample_spec
.channels
= (uint8_t) channels
;
2672 u
->requested_sample_spec
= u
->sample_spec
;
2674 address
= pa_modargs_get_value(ma
, "address", NULL
);
2675 path
= pa_modargs_get_value(ma
, "path", NULL
);
2677 if (setup_dbus(u
) < 0)
2680 if (!(u
->discovery
= pa_bluetooth_discovery_get(m
->core
)))
2683 if (!(device
= find_device(u
, address
, path
)))
2686 u
->device_removed_slot
= pa_hook_connect(&device
->hooks
[PA_BLUETOOTH_DEVICE_HOOK_REMOVED
], PA_HOOK_NORMAL
,
2687 (pa_hook_cb_t
) device_removed_cb
, u
);
2689 u
->discovery_slot
= pa_hook_connect(pa_bluetooth_discovery_hook(u
->discovery
), PA_HOOK_NORMAL
,
2690 (pa_hook_cb_t
) discovery_hook_cb
, u
);
2694 u
->uuid_added_slot
= pa_hook_connect(&device
->hooks
[PA_BLUETOOTH_DEVICE_HOOK_UUID_ADDED
], PA_HOOK_NORMAL
,
2695 (pa_hook_cb_t
) uuid_added_cb
, u
);
2697 /* Add the card structure. This will also initialize the default profile */
2698 if (add_card(u
) < 0)
2701 if (!(u
->msg
= pa_msgobject_new(bluetooth_msg
)))
2704 u
->msg
->parent
.process_msg
= device_process_msg
;
2705 u
->msg
->card
= u
->card
;
2707 if (!dbus_connection_add_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
, NULL
)) {
2708 pa_log_error("Failed to add filter function");
2711 u
->filter_added
= TRUE
;
2713 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2714 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2716 if (pa_dbus_add_matches(
2717 pa_dbus_connection_get(u
->connection
), &err
,
2720 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2721 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2722 "type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged'",
2723 "type='signal',sender='org.bluez',interface='org.bluez.AudioSource',member='PropertyChanged'",
2724 "type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged'",
2730 pa_log("Failed to add D-Bus matches: %s", err
.message
);
2737 if (u
->profile
!= PROFILE_OFF
)
2738 if (init_profile(u
) < 0)
2741 if (u
->sink
|| u
->source
)
2742 if (start_thread(u
) < 0)
2750 pa_assert_se(pa_card_set_profile(u
->card
, "off", false) >= 0);
2758 dbus_error_free(&err
);
2763 int pa__get_n_used(pa_module
*m
) {
2767 pa_assert_se(u
= m
->userdata
);
2770 (u
->sink
? pa_sink_linked_by(u
->sink
) : 0) +
2771 (u
->source
? pa_source_linked_by(u
->source
) : 0);
2774 void pa__done(pa_module
*m
) {
2779 if (!(u
= m
->userdata
))
2784 if (u
->discovery_slot
)
2785 pa_hook_slot_free(u
->discovery_slot
);
2787 if (u
->device_removed_slot
)
2788 pa_hook_slot_free(u
->device_removed_slot
);
2790 if (USE_SCO_OVER_PCM(u
))
2791 restore_sco_volume_callbacks(u
);
2793 if (u
->connection
) {
2796 char *speaker
, *mike
;
2797 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2798 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2800 pa_dbus_remove_matches(pa_dbus_connection_get(u
->connection
), speaker
, mike
,
2801 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2802 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2809 if (u
->filter_added
)
2810 dbus_connection_remove_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
);
2812 pa_dbus_connection_unref(u
->connection
);
2815 if (u
->uuid_added_slot
)
2816 pa_hook_slot_free(u
->uuid_added_slot
);
2822 pa_card_free(u
->card
);
2824 if (u
->read_smoother
)
2825 pa_smoother_free(u
->read_smoother
);
2828 pa_xfree(u
->a2dp
.buffer
);
2830 sbc_finish(&u
->a2dp
.sbc
);
2833 pa_modargs_free(u
->modargs
);
2835 pa_xfree(u
->address
);
2839 pa_bluetooth_discovery_unref(u
->discovery
);