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"
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_capabilities_t sbc_capabilities
;
109 sbc_t sbc
; /* Codec data */
110 pa_bool_t sbc_initialized
; /* Keep track if the encoder is initialized */
111 size_t codesize
, frame_length
; /* SBC Codesize, frame_length. We simply cache those values here */
113 void* buffer
; /* Codec transfer buffer */
114 size_t buffer_size
; /* Size of the buffer */
116 uint16_t seq_num
; /* Cumulative packet sequence */
122 pcm_capabilities_t pcm_capabilities
;
124 void (*sco_sink_set_volume
)(pa_sink
*s
);
125 pa_source
*sco_source
;
126 void (*sco_source_set_volume
)(pa_source
*s
);
127 pa_hook_slot
*sink_state_changed_slot
;
128 pa_hook_slot
*source_state_changed_slot
;
129 pa_hook_slot
*nrec_changed_slot
;
132 struct bluetooth_msg
{
137 typedef struct bluetooth_msg bluetooth_msg
;
138 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg
, pa_msgobject
);
139 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
150 pa_bluetooth_discovery
*discovery
;
151 pa_bool_t auto_connect
;
153 pa_dbus_connection
*connection
;
159 pa_thread_mq thread_mq
;
161 pa_rtpoll_item
*rtpoll_item
;
165 uint64_t read_index
, write_index
;
166 pa_usec_t started_at
;
167 pa_smoother
*read_smoother
;
169 pa_memchunk write_memchunk
;
171 pa_sample_spec sample_spec
, requested_sample_spec
;
175 size_t read_link_mtu
;
176 size_t read_block_size
;
178 size_t write_link_mtu
;
179 size_t write_block_size
;
181 struct a2dp_info a2dp
;
184 enum profile profile
;
188 int stream_write_type
;
190 pa_bool_t filter_added
;
194 BLUETOOTH_MESSAGE_IO_THREAD_FAILED
,
195 BLUETOOTH_MESSAGE_MAX
198 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
199 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
200 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
201 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
203 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
205 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
207 static int init_profile(struct userdata
*u
);
210 static void a2dp_set_bitpool(struct userdata
*u
, uint8_t bitpool
)
212 struct a2dp_info
*a2dp
;
218 if (a2dp
->sbc
.bitpool
== bitpool
)
221 if (bitpool
> a2dp
->max_bitpool
)
222 bitpool
= a2dp
->max_bitpool
;
223 else if (bitpool
< a2dp
->min_bitpool
)
224 bitpool
= a2dp
->min_bitpool
;
226 a2dp
->sbc
.bitpool
= bitpool
;
228 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
229 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
231 pa_log_debug("Bitpool has changed to %u", a2dp
->sbc
.bitpool
);
234 (u
->read_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
235 / a2dp
->frame_length
* a2dp
->codesize
;
237 u
->write_block_size
=
238 (u
->write_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
239 / a2dp
->frame_length
* a2dp
->codesize
;
241 pa_sink_set_max_request_within_thread(u
->sink
, u
->write_block_size
);
242 pa_sink_set_fixed_latency_within_thread(u
->sink
,
243 FIXED_LATENCY_PLAYBACK_A2DP
+ pa_bytes_to_usec(u
->write_block_size
, &u
->sample_spec
));
246 /* from IO thread, except in SCO over PCM */
247 static void bt_transport_config_mtu(struct userdata
*u
) {
248 /* Calculate block sizes */
249 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
250 u
->read_block_size
= u
->read_link_mtu
;
251 u
->write_block_size
= u
->write_link_mtu
;
254 (u
->read_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
255 / u
->a2dp
.frame_length
* u
->a2dp
.codesize
;
257 u
->write_block_size
=
258 (u
->write_link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
259 / u
->a2dp
.frame_length
* u
->a2dp
.codesize
;
262 if (USE_SCO_OVER_PCM(u
))
266 pa_sink_set_max_request_within_thread(u
->sink
, u
->write_block_size
);
267 pa_sink_set_fixed_latency_within_thread(u
->sink
,
268 (u
->profile
== PROFILE_A2DP
?
269 FIXED_LATENCY_PLAYBACK_A2DP
: FIXED_LATENCY_PLAYBACK_HSP
) +
270 pa_bytes_to_usec(u
->write_block_size
, &u
->sample_spec
));
274 pa_source_set_fixed_latency_within_thread(u
->source
,
275 (u
->profile
== PROFILE_A2DP_SOURCE
?
276 FIXED_LATENCY_RECORD_A2DP
: FIXED_LATENCY_RECORD_HSP
) +
277 pa_bytes_to_usec(u
->read_block_size
, &u
->sample_spec
));
280 /* from IO thread, except in SCO over PCM */
282 static void setup_stream(struct userdata
*u
) {
283 struct pollfd
*pollfd
;
286 bt_transport_config_mtu(u
);
288 pa_make_fd_nonblock(u
->stream_fd
);
289 pa_make_socket_low_delay(u
->stream_fd
);
292 if (setsockopt(u
->stream_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
)) < 0)
293 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno
));
295 pa_log_debug("Stream properly set up, we're ready to roll!");
297 if (u
->profile
== PROFILE_A2DP
)
298 a2dp_set_bitpool(u
, u
->a2dp
.max_bitpool
);
300 u
->rtpoll_item
= pa_rtpoll_item_new(u
->rtpoll
, PA_RTPOLL_NEVER
, 1);
301 pollfd
= pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
);
302 pollfd
->fd
= u
->stream_fd
;
303 pollfd
->events
= pollfd
->revents
= 0;
305 u
->read_index
= u
->write_index
= 0;
309 u
->read_smoother
= pa_smoother_new(
319 static bool bt_transport_is_acquired(struct userdata
*u
) {
320 if (u
->accesstype
== NULL
) {
321 pa_assert(u
->stream_fd
< 0);
324 /* During IO thread HUP stream_fd can be -1 */
329 static void teardown_stream(struct userdata
*u
) {
330 if (u
->rtpoll_item
) {
331 pa_rtpoll_item_free(u
->rtpoll_item
);
332 u
->rtpoll_item
= NULL
;
335 if (u
->stream_fd
>= 0) {
336 pa_close(u
->stream_fd
);
340 if (u
->read_smoother
) {
341 pa_smoother_free(u
->read_smoother
);
342 u
->read_smoother
= NULL
;
345 pa_log_debug("Audio stream torn down");
348 static void bt_transport_release(struct userdata
*u
) {
349 const char *accesstype
= "rw";
350 const pa_bluetooth_transport
*t
;
352 /* Ignore if already released */
353 if (!bt_transport_is_acquired(u
))
356 pa_log_debug("Releasing transport %s", u
->transport
);
358 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
360 pa_bluetooth_transport_release(t
, accesstype
);
362 pa_xfree(u
->accesstype
);
363 u
->accesstype
= NULL
;
368 static pa_bt_audio_state_t
get_profile_audio_state(const struct userdata
*u
, const pa_bluetooth_device
*d
) {
371 return d
->headset_state
;
373 return d
->audio_sink_state
;
374 case PROFILE_A2DP_SOURCE
:
375 return d
->audio_source_state
;
377 return d
->hfgw_state
;
382 pa_assert_not_reached();
385 static int bt_transport_acquire(struct userdata
*u
, pa_bool_t start
) {
386 const char *accesstype
= "rw";
387 const pa_bluetooth_device
*d
;
388 const pa_bluetooth_transport
*t
;
390 if (u
->transport
== NULL
) {
391 pa_log("Transport no longer available.");
395 if (bt_transport_is_acquired(u
)) {
401 pa_log_debug("Acquiring transport %s", u
->transport
);
403 d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
);
405 pa_log_error("Failed to get device object.");
409 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
411 pa_log("Transport %s no longer available", u
->transport
);
412 pa_xfree(u
->transport
);
418 /* FIXME: we are trying to acquire the transport only if the stream is
419 playing, without actually initiating the stream request from our side
420 (which is typically undesireable specially for hfgw use-cases.
421 However this approach is racy, since the stream could have been
422 suspended in the meantime, so we can't really guarantee that the
423 stream will not be requested until BlueZ's API supports this
425 if (get_profile_audio_state(u
, d
) < PA_BT_AUDIO_STATE_PLAYING
) {
426 pa_log_info("Failed optional acquire of transport %s", u
->transport
);
431 u
->stream_fd
= pa_bluetooth_transport_acquire(t
, accesstype
, &u
->read_link_mtu
, &u
->write_link_mtu
);
432 if (u
->stream_fd
< 0) {
434 pa_log("Failed to acquire transport %s", u
->transport
);
436 pa_log_info("Failed optional acquire of transport %s", u
->transport
);
441 u
->accesstype
= pa_xstrdup(accesstype
);
442 pa_log_info("Transport %s acquired: fd %d", u
->transport
, u
->stream_fd
);
448 pa_log_info("Transport %s resuming", u
->transport
);
454 /* Run from IO thread */
455 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
456 struct userdata
*u
= PA_SINK(o
)->userdata
;
457 pa_bool_t failed
= FALSE
;
460 pa_assert(u
->sink
== PA_SINK(o
));
461 pa_assert(u
->transport
);
465 case PA_SINK_MESSAGE_SET_STATE
:
467 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
469 case PA_SINK_SUSPENDED
:
470 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
471 if (!PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
))
474 /* Stop the device if the source is suspended as well */
475 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
)
476 /* We deliberately ignore whether stopping
477 * actually worked. Since the stream_fd is
478 * closed it doesn't really matter */
479 bt_transport_release(u
);
484 case PA_SINK_RUNNING
:
485 if (u
->sink
->thread_info
.state
!= PA_SINK_SUSPENDED
)
488 /* Resume the device if the source was suspended as well */
489 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
) {
490 if (bt_transport_acquire(u
, TRUE
) < 0)
495 case PA_SINK_UNLINKED
:
497 case PA_SINK_INVALID_STATE
:
502 case PA_SINK_MESSAGE_GET_LATENCY
: {
504 if (u
->read_smoother
) {
507 ri
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
508 wi
= pa_bytes_to_usec(u
->write_index
+ u
->write_block_size
, &u
->sample_spec
);
510 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
514 ri
= pa_rtclock_now() - u
->started_at
;
515 wi
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
517 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
520 *((pa_usec_t
*) data
) += u
->sink
->thread_info
.fixed_latency
;
525 r
= pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
527 return (r
< 0 || !failed
) ? r
: -1;
530 /* Run from IO thread */
531 static int source_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
532 struct userdata
*u
= PA_SOURCE(o
)->userdata
;
533 pa_bool_t failed
= FALSE
;
536 pa_assert(u
->source
== PA_SOURCE(o
));
537 pa_assert(u
->transport
);
541 case PA_SOURCE_MESSAGE_SET_STATE
:
543 switch ((pa_source_state_t
) PA_PTR_TO_UINT(data
)) {
545 case PA_SOURCE_SUSPENDED
:
546 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
547 if (!PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
))
550 /* Stop the device if the sink is suspended as well */
551 if (!u
->sink
|| u
->sink
->state
== PA_SINK_SUSPENDED
)
552 bt_transport_release(u
);
554 if (u
->read_smoother
)
555 pa_smoother_pause(u
->read_smoother
, pa_rtclock_now());
559 case PA_SOURCE_RUNNING
:
560 if (u
->source
->thread_info
.state
!= PA_SOURCE_SUSPENDED
)
563 /* Resume the device if the sink was suspended as well */
564 if (!u
->sink
|| u
->sink
->thread_info
.state
== PA_SINK_SUSPENDED
) {
565 if (bt_transport_acquire(u
, TRUE
) < 0)
568 /* We don't resume the smoother here. Instead we
569 * wait until the first packet arrives */
572 case PA_SOURCE_UNLINKED
:
574 case PA_SOURCE_INVALID_STATE
:
579 case PA_SOURCE_MESSAGE_GET_LATENCY
: {
582 if (u
->read_smoother
) {
583 wi
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
584 ri
= pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
);
586 *((pa_usec_t
*) data
) = (wi
> ri
? wi
- ri
: 0) + u
->source
->thread_info
.fixed_latency
;
588 *((pa_usec_t
*) data
) = 0;
595 r
= pa_source_process_msg(o
, code
, data
, offset
, chunk
);
597 return (r
< 0 || !failed
) ? r
: -1;
600 /* Called from main thread context */
601 static int device_process_msg(pa_msgobject
*obj
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
602 struct bluetooth_msg
*u
= BLUETOOTH_MSG(obj
);
605 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED
: {
606 if (u
->card
->module
->unload_requested
)
609 pa_log_debug("Switching the profile to off due to IO thread failure.");
611 if (pa_card_set_profile(u
->card
, "off", FALSE
) < 0)
612 pa_log_debug("Failed to switch profile to off");
619 /* Run from IO thread */
620 static int hsp_process_render(struct userdata
*u
) {
624 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
627 /* First, render some data */
628 if (!u
->write_memchunk
.memblock
)
629 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
631 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
637 /* Now write that data to the socket. The socket is of type
638 * SEQPACKET, and we generated the data of the MTU size, so this
639 * should just work. */
641 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
642 l
= pa_write(u
->stream_fd
, p
, u
->write_memchunk
.length
, &u
->stream_write_type
);
643 pa_memblock_release(u
->write_memchunk
.memblock
);
650 /* Retry right away if we got interrupted */
653 else if (errno
== EAGAIN
)
654 /* Hmm, apparently the socket was not writable, give up for now */
657 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno
));
662 pa_assert((size_t) l
<= u
->write_memchunk
.length
);
664 if ((size_t) l
!= u
->write_memchunk
.length
) {
665 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
666 (unsigned long long) l
,
667 (unsigned long long) u
->write_memchunk
.length
);
672 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
673 pa_memblock_unref(u
->write_memchunk
.memblock
);
674 pa_memchunk_reset(&u
->write_memchunk
);
683 /* Run from IO thread */
684 static int hsp_process_push(struct userdata
*u
) {
686 pa_memchunk memchunk
;
689 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
690 pa_assert(u
->source
);
691 pa_assert(u
->read_smoother
);
693 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
694 memchunk
.index
= memchunk
.length
= 0;
703 pa_bool_t found_tstamp
= FALSE
;
706 memset(&m
, 0, sizeof(m
));
707 memset(&aux
, 0, sizeof(aux
));
708 memset(&iov
, 0, sizeof(iov
));
713 m
.msg_controllen
= sizeof(aux
);
715 p
= pa_memblock_acquire(memchunk
.memblock
);
717 iov
.iov_len
= pa_memblock_get_length(memchunk
.memblock
);
718 l
= recvmsg(u
->stream_fd
, &m
, 0);
719 pa_memblock_release(memchunk
.memblock
);
723 if (l
< 0 && errno
== EINTR
)
724 /* Retry right away if we got interrupted */
727 else if (l
< 0 && errno
== EAGAIN
)
728 /* Hmm, apparently the socket was not readable, give up for now. */
731 pa_log_error("Failed to read data from SCO socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
736 pa_assert((size_t) l
<= pa_memblock_get_length(memchunk
.memblock
));
738 memchunk
.length
= (size_t) l
;
739 u
->read_index
+= (uint64_t) l
;
741 for (cm
= CMSG_FIRSTHDR(&m
); cm
; cm
= CMSG_NXTHDR(&m
, cm
))
742 if (cm
->cmsg_level
== SOL_SOCKET
&& cm
->cmsg_type
== SO_TIMESTAMP
) {
743 struct timeval
*tv
= (struct timeval
*) CMSG_DATA(cm
);
744 pa_rtclock_from_wallclock(tv
);
745 tstamp
= pa_timeval_load(tv
);
751 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
752 tstamp
= pa_rtclock_now();
755 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
756 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
758 pa_source_post(u
->source
, &memchunk
);
764 pa_memblock_unref(memchunk
.memblock
);
769 /* Run from IO thread */
770 static void a2dp_prepare_buffer(struct userdata
*u
) {
771 size_t min_buffer_size
= PA_MAX(u
->read_link_mtu
, u
->write_link_mtu
);
775 if (u
->a2dp
.buffer_size
>= min_buffer_size
)
778 u
->a2dp
.buffer_size
= 2 * min_buffer_size
;
779 pa_xfree(u
->a2dp
.buffer
);
780 u
->a2dp
.buffer
= pa_xmalloc(u
->a2dp
.buffer_size
);
783 /* Run from IO thread */
784 static int a2dp_process_render(struct userdata
*u
) {
785 struct a2dp_info
*a2dp
;
786 struct rtp_header
*header
;
787 struct rtp_payload
*payload
;
791 size_t to_write
, to_encode
;
792 unsigned frame_count
;
796 pa_assert(u
->profile
== PROFILE_A2DP
);
799 /* First, render some data */
800 if (!u
->write_memchunk
.memblock
)
801 pa_sink_render_full(u
->sink
, u
->write_block_size
, &u
->write_memchunk
);
803 pa_assert(u
->write_memchunk
.length
== u
->write_block_size
);
805 a2dp_prepare_buffer(u
);
808 header
= a2dp
->buffer
;
809 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
813 /* Try to create a packet of the full MTU */
815 p
= (const uint8_t *) pa_memblock_acquire_chunk(&u
->write_memchunk
);
816 to_encode
= u
->write_memchunk
.length
;
818 d
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
819 to_write
= a2dp
->buffer_size
- sizeof(*header
) - sizeof(*payload
);
821 while (PA_LIKELY(to_encode
> 0 && to_write
> 0)) {
825 encoded
= sbc_encode(&a2dp
->sbc
,
830 if (PA_UNLIKELY(encoded
<= 0)) {
831 pa_log_error("SBC encoding error (%li)", (long) encoded
);
832 pa_memblock_release(u
->write_memchunk
.memblock
);
836 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
837 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
839 pa_assert_fp((size_t) encoded
<= to_encode
);
840 pa_assert_fp((size_t) encoded
== a2dp
->codesize
);
842 pa_assert_fp((size_t) written
<= to_write
);
843 pa_assert_fp((size_t) written
== a2dp
->frame_length
);
845 p
= (const uint8_t*) p
+ encoded
;
846 to_encode
-= encoded
;
848 d
= (uint8_t*) d
+ written
;
854 pa_memblock_release(u
->write_memchunk
.memblock
);
856 pa_assert(to_encode
== 0);
859 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp
->sbc
)));
862 /* write it to the fifo */
863 memset(a2dp
->buffer
, 0, sizeof(*header
) + sizeof(*payload
));
866 header
->sequence_number
= htons(a2dp
->seq_num
++);
867 header
->timestamp
= htonl(u
->write_index
/ pa_frame_size(&u
->sample_spec
));
868 header
->ssrc
= htonl(1);
869 payload
->frame_count
= frame_count
;
871 nbytes
= (uint8_t*) d
- (uint8_t*) a2dp
->buffer
;
876 l
= pa_write(u
->stream_fd
, a2dp
->buffer
, nbytes
, &u
->stream_write_type
);
883 /* Retry right away if we got interrupted */
886 else if (errno
== EAGAIN
)
887 /* Hmm, apparently the socket was not writable, give up for now */
890 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno
));
895 pa_assert((size_t) l
<= nbytes
);
897 if ((size_t) l
!= nbytes
) {
898 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
899 (unsigned long long) l
,
900 (unsigned long long) nbytes
);
905 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
906 pa_memblock_unref(u
->write_memchunk
.memblock
);
907 pa_memchunk_reset(&u
->write_memchunk
);
917 static int a2dp_process_push(struct userdata
*u
) {
919 pa_memchunk memchunk
;
922 pa_assert(u
->profile
== PROFILE_A2DP_SOURCE
);
923 pa_assert(u
->source
);
924 pa_assert(u
->read_smoother
);
926 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->read_block_size
);
927 memchunk
.index
= memchunk
.length
= 0;
930 pa_bool_t found_tstamp
= FALSE
;
932 struct a2dp_info
*a2dp
;
933 struct rtp_header
*header
;
934 struct rtp_payload
*payload
;
938 size_t to_write
, to_decode
;
940 a2dp_prepare_buffer(u
);
943 header
= a2dp
->buffer
;
944 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
946 l
= pa_read(u
->stream_fd
, a2dp
->buffer
, a2dp
->buffer_size
, &u
->stream_write_type
);
950 if (l
< 0 && errno
== EINTR
)
951 /* Retry right away if we got interrupted */
954 else if (l
< 0 && errno
== EAGAIN
)
955 /* Hmm, apparently the socket was not readable, give up for now. */
958 pa_log_error("Failed to read data from socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
963 pa_assert((size_t) l
<= a2dp
->buffer_size
);
965 u
->read_index
+= (uint64_t) l
;
967 /* TODO: get timestamp from rtp */
969 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
970 tstamp
= pa_rtclock_now();
973 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
974 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
976 p
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
977 to_decode
= l
- sizeof(*header
) - sizeof(*payload
);
979 d
= pa_memblock_acquire(memchunk
.memblock
);
980 to_write
= memchunk
.length
= pa_memblock_get_length(memchunk
.memblock
);
982 while (PA_LIKELY(to_decode
> 0)) {
986 decoded
= sbc_decode(&a2dp
->sbc
,
991 if (PA_UNLIKELY(decoded
<= 0)) {
992 pa_log_error("SBC decoding error (%li)", (long) decoded
);
993 pa_memblock_release(memchunk
.memblock
);
994 pa_memblock_unref(memchunk
.memblock
);
998 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
999 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1001 /* Reset frame length, it can be changed due to bitpool change */
1002 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
1004 pa_assert_fp((size_t) decoded
<= to_decode
);
1005 pa_assert_fp((size_t) decoded
== a2dp
->frame_length
);
1007 pa_assert_fp((size_t) written
== a2dp
->codesize
);
1009 p
= (const uint8_t*) p
+ decoded
;
1010 to_decode
-= decoded
;
1012 d
= (uint8_t*) d
+ written
;
1013 to_write
-= written
;
1016 memchunk
.length
-= to_write
;
1018 pa_memblock_release(memchunk
.memblock
);
1020 pa_source_post(u
->source
, &memchunk
);
1026 pa_memblock_unref(memchunk
.memblock
);
1031 static void a2dp_reduce_bitpool(struct userdata
*u
)
1033 struct a2dp_info
*a2dp
;
1040 /* Check if bitpool is already at its limit */
1041 if (a2dp
->sbc
.bitpool
<= BITPOOL_DEC_LIMIT
)
1044 bitpool
= a2dp
->sbc
.bitpool
- BITPOOL_DEC_STEP
;
1046 if (bitpool
< BITPOOL_DEC_LIMIT
)
1047 bitpool
= BITPOOL_DEC_LIMIT
;
1049 a2dp_set_bitpool(u
, bitpool
);
1052 static void thread_func(void *userdata
) {
1053 struct userdata
*u
= userdata
;
1054 unsigned do_write
= 0;
1055 unsigned pending_read_bytes
= 0;
1056 pa_bool_t writable
= FALSE
;
1059 pa_assert(u
->transport
);
1061 pa_log_debug("IO Thread starting up");
1063 if (u
->core
->realtime_scheduling
)
1064 pa_make_realtime(u
->core
->realtime_priority
);
1066 pa_thread_mq_install(&u
->thread_mq
);
1068 /* Setup the stream only if the transport was already acquired */
1069 if (bt_transport_is_acquired(u
))
1070 bt_transport_acquire(u
, TRUE
);
1073 struct pollfd
*pollfd
;
1075 pa_bool_t disable_timer
= TRUE
;
1077 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1079 if (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) {
1081 /* We should send two blocks to the device before we expect
1084 if (u
->write_index
== 0 && u
->read_index
<= 0)
1087 if (pollfd
&& (pollfd
->revents
& POLLIN
)) {
1090 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
)
1091 n_read
= hsp_process_push(u
);
1093 n_read
= a2dp_process_push(u
);
1098 /* We just read something, so we are supposed to write something, too */
1099 pending_read_bytes
+= n_read
;
1100 do_write
+= pending_read_bytes
/ u
->write_block_size
;
1101 pending_read_bytes
= pending_read_bytes
% u
->write_block_size
;
1105 if (u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
)) {
1107 if (u
->sink
->thread_info
.rewind_requested
)
1108 pa_sink_process_rewind(u
->sink
, 0);
1111 if (pollfd
->revents
& POLLOUT
)
1114 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1115 pa_usec_t time_passed
;
1116 pa_usec_t audio_sent
;
1118 /* Hmm, there is no input stream we could synchronize
1119 * to. So let's do things by time */
1121 time_passed
= pa_rtclock_now() - u
->started_at
;
1122 audio_sent
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1124 if (audio_sent
<= time_passed
) {
1125 pa_usec_t audio_to_send
= time_passed
- audio_sent
;
1127 /* Never try to catch up for more than 100ms */
1128 if (u
->write_index
> 0 && audio_to_send
> MAX_PLAYBACK_CATCH_UP_USEC
) {
1129 pa_usec_t skip_usec
;
1130 uint64_t skip_bytes
;
1132 skip_usec
= audio_to_send
- MAX_PLAYBACK_CATCH_UP_USEC
;
1133 skip_bytes
= pa_usec_to_bytes(skip_usec
, &u
->sample_spec
);
1135 if (skip_bytes
> 0) {
1138 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1139 (unsigned long long) skip_usec
,
1140 (unsigned long long) skip_bytes
);
1142 pa_sink_render_full(u
->sink
, skip_bytes
, &tmp
);
1143 pa_memblock_unref(tmp
.memblock
);
1144 u
->write_index
+= skip_bytes
;
1146 if (u
->profile
== PROFILE_A2DP
)
1147 a2dp_reduce_bitpool(u
);
1152 pending_read_bytes
= 0;
1156 if (writable
&& do_write
> 0) {
1159 if (u
->write_index
<= 0)
1160 u
->started_at
= pa_rtclock_now();
1162 if (u
->profile
== PROFILE_A2DP
) {
1163 if ((n_written
= a2dp_process_render(u
)) < 0)
1166 if ((n_written
= hsp_process_render(u
)) < 0)
1171 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1173 do_write
-= n_written
;
1177 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0) {
1178 pa_usec_t sleep_for
;
1179 pa_usec_t time_passed
, next_write_at
;
1182 /* Hmm, there is no input stream we could synchronize
1183 * to. So let's estimate when we need to wake up the latest */
1184 time_passed
= pa_rtclock_now() - u
->started_at
;
1185 next_write_at
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1186 sleep_for
= time_passed
< next_write_at
? next_write_at
- time_passed
: 0;
1187 /* 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); */
1189 /* drop stream every 500 ms */
1190 sleep_for
= PA_USEC_PER_MSEC
* 500;
1192 pa_rtpoll_set_timer_relative(u
->rtpoll
, sleep_for
);
1193 disable_timer
= FALSE
;
1199 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
1201 /* Hmm, nothing to do. Let's sleep */
1203 pollfd
->events
= (short) (((u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
) && !writable
) ? POLLOUT
: 0) |
1204 (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
) ? POLLIN
: 0));
1206 if ((ret
= pa_rtpoll_run(u
->rtpoll
, TRUE
)) < 0) {
1207 pa_log_debug("pa_rtpoll_run failed with: %d", ret
);
1211 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1212 bt_transport_release(u
);
1216 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1218 if (pollfd
&& (pollfd
->revents
& ~(POLLOUT
|POLLIN
))) {
1219 pa_log_info("FD error: %s%s%s%s",
1220 pollfd
->revents
& POLLERR
? "POLLERR " :"",
1221 pollfd
->revents
& POLLHUP
? "POLLHUP " :"",
1222 pollfd
->revents
& POLLPRI
? "POLLPRI " :"",
1223 pollfd
->revents
& POLLNVAL
? "POLLNVAL " :"");
1230 /* In case of HUP, just tear down the streams */
1231 if (!pollfd
|| (pollfd
->revents
& POLLHUP
) == 0)
1235 pending_read_bytes
= 0;
1242 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1243 pa_log_debug("IO thread failed");
1244 pa_asyncmsgq_post(pa_thread_mq_get()->outq
, PA_MSGOBJECT(u
->msg
), BLUETOOTH_MESSAGE_IO_THREAD_FAILED
, NULL
, 0, NULL
, NULL
);
1245 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1248 pa_log_debug("IO thread shutting down");
1251 static pa_bt_audio_state_t
parse_state_property_change(DBusMessage
*m
) {
1252 DBusMessageIter iter
;
1253 DBusMessageIter variant
;
1256 pa_bt_audio_state_t state
;
1258 if (!dbus_message_iter_init(m
, &iter
)) {
1259 pa_log("Failed to parse PropertyChanged");
1260 return PA_BT_AUDIO_STATE_INVALID
;
1263 if (dbus_message_iter_get_arg_type(&iter
) != DBUS_TYPE_STRING
) {
1264 pa_log("Property name not a string");
1265 return PA_BT_AUDIO_STATE_INVALID
;
1268 dbus_message_iter_get_basic(&iter
, &key
);
1270 if (!pa_streq(key
, "State"))
1271 return PA_BT_AUDIO_STATE_INVALID
;
1273 if (!dbus_message_iter_next(&iter
)) {
1274 pa_log("Property value missing");
1275 return PA_BT_AUDIO_STATE_INVALID
;
1278 dbus_message_iter_recurse(&iter
, &variant
);
1280 if (dbus_message_iter_get_arg_type(&variant
) != DBUS_TYPE_STRING
) {
1281 pa_log("Property value not a string");
1282 return PA_BT_AUDIO_STATE_INVALID
;
1285 dbus_message_iter_get_basic(&variant
, &value
);
1287 pa_log_debug("dbus: %s property 'State' changed to value '%s'", dbus_message_get_interface(m
), value
);
1289 state
= pa_bt_audio_state_from_string(value
);
1291 if (state
== PA_BT_AUDIO_STATE_INVALID
)
1292 pa_log("Unexpected value for property 'State': '%s'", value
);
1297 static pa_port_available_t
audio_state_to_availability(pa_bt_audio_state_t state
) {
1298 if (state
< PA_BT_AUDIO_STATE_CONNECTED
)
1299 return PA_PORT_AVAILABLE_NO
;
1300 else if (state
>= PA_BT_AUDIO_STATE_PLAYING
)
1301 return PA_PORT_AVAILABLE_YES
;
1303 return PA_PORT_AVAILABLE_UNKNOWN
;
1306 /* Run from main thread */
1307 static DBusHandlerResult
filter_cb(DBusConnection
*bus
, DBusMessage
*m
, void *userdata
) {
1310 bool acquire
= FALSE
;
1311 bool release
= FALSE
;
1315 pa_assert_se(u
= userdata
);
1317 dbus_error_init(&err
);
1319 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1320 dbus_message_get_interface(m
),
1321 dbus_message_get_path(m
),
1322 dbus_message_get_member(m
));
1324 if (!dbus_message_has_path(m
, u
->path
) && !dbus_message_has_path(m
, u
->transport
))
1327 if (dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged") ||
1328 dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1333 if (!dbus_message_get_args(m
, &err
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
) || gain
> HSP_MAX_GAIN
) {
1334 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err
.message
);
1338 if (u
->profile
== PROFILE_HSP
) {
1339 if (u
->sink
&& dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged")) {
1340 pa_volume_t volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1342 /* increment volume by one to correct rounding errors */
1343 if (volume
< PA_VOLUME_NORM
)
1346 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1347 pa_sink_volume_changed(u
->sink
, &v
);
1349 } else if (u
->source
&& dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1350 pa_volume_t volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1352 /* increment volume by one to correct rounding errors */
1353 if (volume
< PA_VOLUME_NORM
)
1356 pa_cvolume_set(&v
, u
->sample_spec
.channels
, volume
);
1357 pa_source_volume_changed(u
->source
, &v
);
1360 } else if (dbus_message_is_signal(m
, "org.bluez.HandsfreeGateway", "PropertyChanged")) {
1361 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1363 if (state
!= PA_BT_AUDIO_STATE_INVALID
) {
1364 pa_device_port
*port
;
1365 pa_port_available_t available
= audio_state_to_availability(state
);
1367 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1368 pa_device_port_set_available(port
, available
);
1370 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1371 pa_device_port_set_available(port
, available
);
1373 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1374 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HFGW
);
1376 } else if (dbus_message_is_signal(m
, "org.bluez.Headset", "PropertyChanged")) {
1377 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1379 if (state
!= PA_BT_AUDIO_STATE_INVALID
) {
1380 pa_device_port
*port
;
1381 pa_port_available_t available
= audio_state_to_availability(state
);
1383 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-output"));
1384 pa_device_port_set_available(port
, available
);
1386 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1387 pa_device_port_set_available(port
, available
);
1389 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1390 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_HSP
);
1392 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSource", "PropertyChanged")) {
1393 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1395 if (state
!= PA_BT_AUDIO_STATE_INVALID
) {
1396 pa_device_port
*port
;
1397 pa_port_available_t available
= audio_state_to_availability(state
);
1399 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1400 pa_device_port_set_available(port
, available
);
1402 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1403 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP_SOURCE
);
1405 } else if (dbus_message_is_signal(m
, "org.bluez.AudioSink", "PropertyChanged")) {
1406 pa_bt_audio_state_t state
= parse_state_property_change(m
);
1408 if (state
!= PA_BT_AUDIO_STATE_INVALID
) {
1409 pa_device_port
*port
;
1410 pa_port_available_t available
= audio_state_to_availability(state
);
1412 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-output"));
1413 pa_device_port_set_available(port
, available
);
1415 acquire
= (available
== PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1416 release
= (available
!= PA_PORT_AVAILABLE_YES
&& u
->profile
== PROFILE_A2DP
);
1421 if (bt_transport_acquire(u
, FALSE
) >= 0) {
1423 pa_source_suspend(u
->source
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1426 pa_sink_suspend(u
->sink
, FALSE
, PA_SUSPEND_IDLE
|PA_SUSPEND_USER
);
1429 if (release
&& bt_transport_is_acquired(u
)) {
1430 /* FIXME: this release is racy, since the audio stream might have
1431 been set up again in the meantime (but not processed yet by PA).
1432 BlueZ should probably release the transport automatically, and
1433 in that case we would just mark the transport as released */
1435 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1437 pa_source_suspend(u
->source
, TRUE
, PA_SUSPEND_USER
);
1440 pa_sink_suspend(u
->sink
, TRUE
, PA_SUSPEND_USER
);
1444 dbus_error_free(&err
);
1446 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1449 /* Run from main thread */
1450 static void sink_set_volume_cb(pa_sink
*s
) {
1460 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1461 u
= pa_shared_get(s
->core
, k
);
1465 pa_assert(u
->sink
== s
);
1466 pa_assert(u
->profile
== PROFILE_HSP
);
1468 gain
= (pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
) / PA_VOLUME_NORM
;
1470 if (gain
> HSP_MAX_GAIN
)
1471 gain
= HSP_MAX_GAIN
;
1473 volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1475 /* increment volume by one to correct rounding errors */
1476 if (volume
< PA_VOLUME_NORM
)
1479 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1481 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetSpeakerGain"));
1482 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1483 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1484 dbus_message_unref(m
);
1487 /* Run from main thread */
1488 static void source_set_volume_cb(pa_source
*s
) {
1498 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) s
);
1499 u
= pa_shared_get(s
->core
, k
);
1503 pa_assert(u
->source
== s
);
1504 pa_assert(u
->profile
== PROFILE_HSP
);
1506 gain
= (pa_cvolume_max(&s
->real_volume
) * HSP_MAX_GAIN
) / PA_VOLUME_NORM
;
1508 if (gain
> HSP_MAX_GAIN
)
1509 gain
= HSP_MAX_GAIN
;
1511 volume
= (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ HSP_MAX_GAIN
);
1513 /* increment volume by one to correct rounding errors */
1514 if (volume
< PA_VOLUME_NORM
)
1517 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, volume
);
1519 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetMicrophoneGain"));
1520 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1521 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1522 dbus_message_unref(m
);
1525 /* Run from main thread */
1526 static char *get_name(const char *type
, pa_modargs
*ma
, const char *device_id
, pa_bool_t
*namereg_fail
) {
1532 pa_assert(device_id
);
1533 pa_assert(namereg_fail
);
1535 t
= pa_sprintf_malloc("%s_name", type
);
1536 n
= pa_modargs_get_value(ma
, t
, NULL
);
1540 *namereg_fail
= TRUE
;
1541 return pa_xstrdup(n
);
1544 if ((n
= pa_modargs_get_value(ma
, "name", NULL
)))
1545 *namereg_fail
= TRUE
;
1548 *namereg_fail
= FALSE
;
1551 return pa_sprintf_malloc("bluez_%s.%s", type
, n
);
1554 static int sco_over_pcm_state_update(struct userdata
*u
, pa_bool_t changed
) {
1556 pa_assert(USE_SCO_OVER_PCM(u
));
1558 if (PA_SINK_IS_OPENED(pa_sink_get_state(u
->hsp
.sco_sink
)) ||
1559 PA_SOURCE_IS_OPENED(pa_source_get_state(u
->hsp
.sco_source
))) {
1561 if (u
->stream_fd
>= 0)
1564 pa_log_debug("Resuming SCO over PCM");
1565 if (init_profile(u
) < 0) {
1566 pa_log("Can't resume SCO over PCM");
1570 return bt_transport_acquire(u
, TRUE
);
1574 if (u
->stream_fd
< 0)
1577 pa_log_debug("Closing SCO over PCM");
1579 bt_transport_release(u
);
1585 static pa_hook_result_t
sink_state_changed_cb(pa_core
*c
, pa_sink
*s
, struct userdata
*u
) {
1587 pa_sink_assert_ref(s
);
1590 if (s
!= u
->hsp
.sco_sink
)
1593 sco_over_pcm_state_update(u
, TRUE
);
1598 static pa_hook_result_t
source_state_changed_cb(pa_core
*c
, pa_source
*s
, struct userdata
*u
) {
1600 pa_source_assert_ref(s
);
1603 if (s
!= u
->hsp
.sco_source
)
1606 sco_over_pcm_state_update(u
, TRUE
);
1611 static pa_hook_result_t
nrec_changed_cb(pa_bluetooth_transport
*t
, void *call_data
, struct userdata
*u
) {
1617 p
= pa_proplist_new();
1618 pa_proplist_sets(p
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1619 pa_source_update_proplist(u
->source
, PA_UPDATE_REPLACE
, p
);
1620 pa_proplist_free(p
);
1625 static void connect_ports(struct userdata
*u
, void *sink_or_source_new_data
, pa_direction_t direction
) {
1627 pa_sink_new_data
*sink_new_data
;
1628 pa_source_new_data
*source_new_data
;
1630 pa_device_port
*port
;
1632 if (direction
== PA_DIRECTION_OUTPUT
)
1633 data
.sink_new_data
= sink_or_source_new_data
;
1635 data
.source_new_data
= sink_or_source_new_data
;
1637 switch (u
->profile
) {
1639 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-output"));
1640 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1641 pa_device_port_ref(port
);
1644 case PROFILE_A2DP_SOURCE
:
1645 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "a2dp-input"));
1646 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1647 pa_device_port_ref(port
);
1651 if (direction
== PA_DIRECTION_OUTPUT
) {
1652 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-output"));
1653 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1655 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hsp-input"));
1656 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1658 pa_device_port_ref(port
);
1662 if (direction
== PA_DIRECTION_OUTPUT
) {
1663 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-output"));
1664 pa_assert_se(pa_hashmap_put(data
.sink_new_data
->ports
, port
->name
, port
) >= 0);
1666 pa_assert_se(port
= pa_hashmap_get(u
->card
->ports
, "hfgw-input"));
1667 pa_assert_se(pa_hashmap_put(data
.source_new_data
->ports
, port
->name
, port
) >= 0);
1669 pa_device_port_ref(port
);
1673 pa_assert_not_reached();
1677 static const char *profile_to_string(enum profile profile
) {
1681 case PROFILE_A2DP_SOURCE
:
1682 return "a2dp_source";
1688 pa_assert_not_reached();
1692 static int sink_set_port_cb(pa_sink
*s
, pa_device_port
*p
) {
1696 static int source_set_port_cb(pa_source
*s
, pa_device_port
*p
) {
1700 /* Run from main thread */
1701 static int add_sink(struct userdata
*u
) {
1704 if (USE_SCO_OVER_PCM(u
)) {
1707 u
->sink
= u
->hsp
.sco_sink
;
1708 p
= pa_proplist_new();
1709 pa_proplist_sets(p
, "bluetooth.protocol", profile_to_string(u
->profile
));
1710 pa_proplist_update(u
->sink
->proplist
, PA_UPDATE_MERGE
, p
);
1711 pa_proplist_free(p
);
1713 if (!u
->hsp
.sink_state_changed_slot
)
1714 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
);
1717 pa_sink_new_data data
;
1720 pa_sink_new_data_init(&data
);
1721 data
.driver
= __FILE__
;
1722 data
.module
= u
->module
;
1723 pa_sink_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1724 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1725 if (u
->profile
== PROFILE_HSP
)
1726 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1727 data
.card
= u
->card
;
1728 data
.name
= get_name("sink", u
->modargs
, u
->address
, &b
);
1729 data
.namereg_fail
= b
;
1731 if (pa_modargs_get_proplist(u
->modargs
, "sink_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1732 pa_log("Invalid properties");
1733 pa_sink_new_data_done(&data
);
1736 connect_ports(u
, &data
, PA_DIRECTION_OUTPUT
);
1738 if (!bt_transport_is_acquired(u
))
1739 data
.suspend_cause
= PA_SUSPEND_USER
;
1741 u
->sink
= pa_sink_new(u
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
);
1742 pa_sink_new_data_done(&data
);
1745 pa_log_error("Failed to create sink");
1749 u
->sink
->userdata
= u
;
1750 u
->sink
->parent
.process_msg
= sink_process_msg
;
1751 u
->sink
->set_port
= sink_set_port_cb
;
1754 if (u
->profile
== PROFILE_HSP
) {
1755 pa_sink_set_set_volume_callback(u
->sink
, sink_set_volume_cb
);
1756 u
->sink
->n_volume_steps
= 16;
1758 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
1759 pa_shared_set(u
->core
, k
, u
);
1766 /* Run from main thread */
1767 static int add_source(struct userdata
*u
) {
1770 if (USE_SCO_OVER_PCM(u
)) {
1771 u
->source
= u
->hsp
.sco_source
;
1772 pa_proplist_sets(u
->source
->proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1774 if (!u
->hsp
.source_state_changed_slot
)
1775 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
);
1778 pa_source_new_data data
;
1781 pa_source_new_data_init(&data
);
1782 data
.driver
= __FILE__
;
1783 data
.module
= u
->module
;
1784 pa_source_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1785 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", profile_to_string(u
->profile
));
1786 if (u
->profile
== PROFILE_HSP
)
1787 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1789 data
.card
= u
->card
;
1790 data
.name
= get_name("source", u
->modargs
, u
->address
, &b
);
1791 data
.namereg_fail
= b
;
1793 if (pa_modargs_get_proplist(u
->modargs
, "source_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1794 pa_log("Invalid properties");
1795 pa_source_new_data_done(&data
);
1799 connect_ports(u
, &data
, PA_DIRECTION_INPUT
);
1801 if (!bt_transport_is_acquired(u
))
1802 data
.suspend_cause
= PA_SUSPEND_USER
;
1804 u
->source
= pa_source_new(u
->core
, &data
, PA_SOURCE_HARDWARE
|PA_SOURCE_LATENCY
);
1805 pa_source_new_data_done(&data
);
1808 pa_log_error("Failed to create source");
1812 u
->source
->userdata
= u
;
1813 u
->source
->parent
.process_msg
= source_process_msg
;
1814 u
->source
->set_port
= source_set_port_cb
;
1817 if ((u
->profile
== PROFILE_HSP
) || (u
->profile
== PROFILE_HFGW
)) {
1818 pa_bluetooth_transport
*t
;
1819 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
1821 pa_proplist_sets(u
->source
->proplist
, "bluetooth.nrec", t
->nrec
? "1" : "0");
1823 if (!u
->hsp
.nrec_changed_slot
)
1824 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
);
1827 if (u
->profile
== PROFILE_HSP
) {
1828 pa_source_set_set_volume_callback(u
->source
, source_set_volume_cb
);
1829 u
->source
->n_volume_steps
= 16;
1831 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
1832 pa_shared_set(u
->core
, k
, u
);
1839 static void bt_transport_config_a2dp(struct userdata
*u
) {
1840 const pa_bluetooth_transport
*t
;
1841 struct a2dp_info
*a2dp
= &u
->a2dp
;
1844 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
1847 config
= (a2dp_sbc_t
*) t
->config
;
1849 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1851 if (a2dp
->sbc_initialized
)
1852 sbc_reinit(&a2dp
->sbc
, 0);
1854 sbc_init(&a2dp
->sbc
, 0);
1855 a2dp
->sbc_initialized
= TRUE
;
1857 switch (config
->frequency
) {
1858 case BT_SBC_SAMPLING_FREQ_16000
:
1859 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
1860 u
->sample_spec
.rate
= 16000U;
1862 case BT_SBC_SAMPLING_FREQ_32000
:
1863 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
1864 u
->sample_spec
.rate
= 32000U;
1866 case BT_SBC_SAMPLING_FREQ_44100
:
1867 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
1868 u
->sample_spec
.rate
= 44100U;
1870 case BT_SBC_SAMPLING_FREQ_48000
:
1871 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
1872 u
->sample_spec
.rate
= 48000U;
1875 pa_assert_not_reached();
1878 switch (config
->channel_mode
) {
1879 case BT_A2DP_CHANNEL_MODE_MONO
:
1880 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
1881 u
->sample_spec
.channels
= 1;
1883 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
1884 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
1885 u
->sample_spec
.channels
= 2;
1887 case BT_A2DP_CHANNEL_MODE_STEREO
:
1888 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
1889 u
->sample_spec
.channels
= 2;
1891 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
1892 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
1893 u
->sample_spec
.channels
= 2;
1896 pa_assert_not_reached();
1899 switch (config
->allocation_method
) {
1900 case BT_A2DP_ALLOCATION_SNR
:
1901 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
1903 case BT_A2DP_ALLOCATION_LOUDNESS
:
1904 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
1907 pa_assert_not_reached();
1910 switch (config
->subbands
) {
1911 case BT_A2DP_SUBBANDS_4
:
1912 a2dp
->sbc
.subbands
= SBC_SB_4
;
1914 case BT_A2DP_SUBBANDS_8
:
1915 a2dp
->sbc
.subbands
= SBC_SB_8
;
1918 pa_assert_not_reached();
1921 switch (config
->block_length
) {
1922 case BT_A2DP_BLOCK_LENGTH_4
:
1923 a2dp
->sbc
.blocks
= SBC_BLK_4
;
1925 case BT_A2DP_BLOCK_LENGTH_8
:
1926 a2dp
->sbc
.blocks
= SBC_BLK_8
;
1928 case BT_A2DP_BLOCK_LENGTH_12
:
1929 a2dp
->sbc
.blocks
= SBC_BLK_12
;
1931 case BT_A2DP_BLOCK_LENGTH_16
:
1932 a2dp
->sbc
.blocks
= SBC_BLK_16
;
1935 pa_assert_not_reached();
1938 a2dp
->min_bitpool
= config
->min_bitpool
;
1939 a2dp
->max_bitpool
= config
->max_bitpool
;
1941 /* Set minimum bitpool for source to get the maximum possible block_size */
1942 a2dp
->sbc
.bitpool
= u
->profile
== PROFILE_A2DP
? a2dp
->max_bitpool
: a2dp
->min_bitpool
;
1943 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
1944 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
1946 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1947 a2dp
->sbc
.allocation
, a2dp
->sbc
.subbands
, a2dp
->sbc
.blocks
, a2dp
->sbc
.bitpool
);
1950 static void bt_transport_config(struct userdata
*u
) {
1951 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
1952 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
1953 u
->sample_spec
.channels
= 1;
1954 u
->sample_spec
.rate
= 8000;
1956 bt_transport_config_a2dp(u
);
1959 /* Run from main thread */
1960 static int setup_bt(struct userdata
*u
) {
1961 const pa_bluetooth_device
*d
;
1962 const pa_bluetooth_transport
*t
;
1966 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
))) {
1967 pa_log_error("Failed to get device object.");
1971 /* release transport if exist */
1973 bt_transport_release(u
);
1974 pa_xfree(u
->transport
);
1975 u
->transport
= NULL
;
1978 /* check if profile has a transport */
1979 t
= pa_bluetooth_device_get_transport(d
, u
->profile
);
1981 pa_log_warn("Profile has no transport");
1985 u
->transport
= pa_xstrdup(t
->path
);
1987 bt_transport_acquire(u
, FALSE
);
1989 bt_transport_config(u
);
1994 /* Run from main thread */
1995 static int init_profile(struct userdata
*u
) {
1998 pa_assert(u
->profile
!= PROFILE_OFF
);
2000 if (setup_bt(u
) < 0)
2003 if (u
->profile
== PROFILE_A2DP
||
2004 u
->profile
== PROFILE_HSP
||
2005 u
->profile
== PROFILE_HFGW
)
2006 if (add_sink(u
) < 0)
2009 if (u
->profile
== PROFILE_HSP
||
2010 u
->profile
== PROFILE_A2DP_SOURCE
||
2011 u
->profile
== PROFILE_HFGW
)
2012 if (add_source(u
) < 0)
2018 /* Run from main thread */
2019 static void stop_thread(struct userdata
*u
) {
2025 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
2026 pa_thread_free(u
->thread
);
2030 if (u
->rtpoll_item
) {
2031 pa_rtpoll_item_free(u
->rtpoll_item
);
2032 u
->rtpoll_item
= NULL
;
2035 if (u
->hsp
.sink_state_changed_slot
) {
2036 pa_hook_slot_free(u
->hsp
.sink_state_changed_slot
);
2037 u
->hsp
.sink_state_changed_slot
= NULL
;
2040 if (u
->hsp
.source_state_changed_slot
) {
2041 pa_hook_slot_free(u
->hsp
.source_state_changed_slot
);
2042 u
->hsp
.source_state_changed_slot
= NULL
;
2045 if (u
->hsp
.nrec_changed_slot
) {
2046 pa_hook_slot_free(u
->hsp
.nrec_changed_slot
);
2047 u
->hsp
.nrec_changed_slot
= NULL
;
2051 if (u
->profile
== PROFILE_HSP
) {
2052 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2053 pa_shared_remove(u
->core
, k
);
2057 pa_sink_unref(u
->sink
);
2062 if (u
->profile
== PROFILE_HSP
) {
2063 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2064 pa_shared_remove(u
->core
, k
);
2068 pa_source_unref(u
->source
);
2073 pa_thread_mq_done(&u
->thread_mq
);
2075 pa_rtpoll_free(u
->rtpoll
);
2079 if (u
->read_smoother
) {
2080 pa_smoother_free(u
->read_smoother
);
2081 u
->read_smoother
= NULL
;
2085 /* Run from main thread */
2086 static int start_thread(struct userdata
*u
) {
2088 pa_assert(!u
->thread
);
2089 pa_assert(!u
->rtpoll
);
2090 pa_assert(!u
->rtpoll_item
);
2092 u
->rtpoll
= pa_rtpoll_new();
2093 pa_thread_mq_init(&u
->thread_mq
, u
->core
->mainloop
, u
->rtpoll
);
2095 if (USE_SCO_OVER_PCM(u
)) {
2096 if (sco_over_pcm_state_update(u
, FALSE
) < 0) {
2100 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->sink
);
2101 pa_shared_remove(u
->core
, k
);
2106 k
= pa_sprintf_malloc("bluetooth-device@%p", (void*) u
->source
);
2107 pa_shared_remove(u
->core
, k
);
2114 pa_sink_ref(u
->sink
);
2115 pa_source_ref(u
->source
);
2116 /* FIXME: monitor stream_fd error */
2120 if (!(u
->thread
= pa_thread_new("bluetooth", thread_func
, u
))) {
2121 pa_log_error("Failed to create IO thread");
2127 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
2128 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
2129 pa_sink_put(u
->sink
);
2131 if (u
->sink
->set_volume
)
2132 u
->sink
->set_volume(u
->sink
);
2136 pa_source_set_asyncmsgq(u
->source
, u
->thread_mq
.inq
);
2137 pa_source_set_rtpoll(u
->source
, u
->rtpoll
);
2138 pa_source_put(u
->source
);
2140 if (u
->source
->set_volume
)
2141 u
->source
->set_volume(u
->source
);
2147 static void save_sco_volume_callbacks(struct userdata
*u
) {
2149 pa_assert(USE_SCO_OVER_PCM(u
));
2151 u
->hsp
.sco_sink_set_volume
= u
->hsp
.sco_sink
->set_volume
;
2152 u
->hsp
.sco_source_set_volume
= u
->hsp
.sco_source
->set_volume
;
2155 static void restore_sco_volume_callbacks(struct userdata
*u
) {
2157 pa_assert(USE_SCO_OVER_PCM(u
));
2159 pa_sink_set_set_volume_callback(u
->hsp
.sco_sink
, u
->hsp
.sco_sink_set_volume
);
2160 pa_source_set_set_volume_callback(u
->hsp
.sco_source
, u
->hsp
.sco_source_set_volume
);
2163 /* Run from main thread */
2164 static int card_set_profile(pa_card
*c
, pa_card_profile
*new_profile
) {
2167 pa_queue
*inputs
= NULL
, *outputs
= NULL
;
2168 const pa_bluetooth_device
*device
;
2171 pa_assert(new_profile
);
2172 pa_assert_se(u
= c
->userdata
);
2174 d
= PA_CARD_PROFILE_DATA(new_profile
);
2176 if (!(device
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
))) {
2177 pa_log_error("Failed to get device object.");
2181 /* The state signal is sent by bluez, so it is racy to check
2182 strictly for CONNECTED, we should also accept STREAMING state
2183 as being good enough. However, if the profile is used
2184 concurrently (which is unlikely), ipc will fail later on, and
2185 module will be unloaded. */
2186 if (device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) {
2187 pa_log_warn("HSP is not connected, refused to switch profile");
2189 } else if (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) {
2190 pa_log_warn("A2DP Sink is not connected, refused to switch profile");
2192 } else if (device
->audio_source_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP_SOURCE
) {
2193 pa_log_warn("A2DP Source is not connected, refused to switch profile");
2195 } else if (device
->hfgw_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
) {
2196 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2201 inputs
= pa_sink_move_all_start(u
->sink
, NULL
);
2203 if (!USE_SCO_OVER_PCM(u
))
2204 pa_sink_unlink(u
->sink
);
2208 outputs
= pa_source_move_all_start(u
->source
, NULL
);
2210 if (!USE_SCO_OVER_PCM(u
))
2211 pa_source_unlink(u
->source
);
2216 if (u
->profile
!= PROFILE_OFF
&& u
->transport
) {
2217 bt_transport_release(u
);
2218 pa_xfree(u
->transport
);
2219 u
->transport
= NULL
;
2222 if (USE_SCO_OVER_PCM(u
))
2223 restore_sco_volume_callbacks(u
);
2226 u
->sample_spec
= u
->requested_sample_spec
;
2228 if (USE_SCO_OVER_PCM(u
))
2229 save_sco_volume_callbacks(u
);
2231 if (u
->profile
!= PROFILE_OFF
)
2234 if (u
->sink
|| u
->source
)
2239 pa_sink_move_all_finish(u
->sink
, inputs
, FALSE
);
2241 pa_sink_move_all_fail(inputs
);
2246 pa_source_move_all_finish(u
->source
, outputs
, FALSE
);
2248 pa_source_move_all_fail(outputs
);
2254 static void create_ports_for_profile(struct userdata
*u
, const pa_bluetooth_device
*device
, pa_card_new_data
*card_new_data
, pa_card_profile
*profile
) {
2255 pa_device_port
*port
;
2258 d
= PA_CARD_PROFILE_DATA(profile
);
2262 pa_assert_se(port
= pa_device_port_new(u
->core
, "a2dp-output", _("Bluetooth High Quality (A2DP)"), 0));
2263 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2264 port
->is_output
= 1;
2266 port
->priority
= profile
->priority
* 100;
2267 port
->available
= audio_state_to_availability(device
->audio_sink_state
);
2268 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2271 case PROFILE_A2DP_SOURCE
:
2272 pa_assert_se(port
= pa_device_port_new(u
->core
, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2273 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2274 port
->is_output
= 0;
2276 port
->priority
= profile
->priority
* 100;
2277 port
->available
= audio_state_to_availability(device
->audio_source_state
);
2278 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2282 pa_assert_se(port
= pa_device_port_new(u
->core
, "hsp-output", _("Bluetooth Telephony (HSP/HFP)"), 0));
2283 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2284 port
->is_output
= 1;
2286 port
->priority
= profile
->priority
* 100;
2287 port
->available
= audio_state_to_availability(device
->headset_state
);
2288 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2290 pa_assert_se(port
= pa_device_port_new(u
->core
, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2291 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2292 port
->is_output
= 0;
2294 port
->priority
= profile
->priority
* 100;
2295 port
->available
= audio_state_to_availability(device
->headset_state
);
2296 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2300 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2301 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2302 port
->is_output
= 1;
2304 port
->priority
= profile
->priority
* 100;
2305 port
->available
= audio_state_to_availability(device
->hfgw_state
);
2306 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2308 pa_assert_se(port
= pa_device_port_new(u
->core
, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2309 pa_assert_se(pa_hashmap_put(card_new_data
->ports
, port
->name
, port
) >= 0);
2310 port
->is_output
= 0;
2312 port
->priority
= profile
->priority
* 100;
2313 port
->available
= audio_state_to_availability(device
->hfgw_state
);
2314 pa_hashmap_put(port
->profiles
, profile
->name
, profile
);
2318 pa_assert_not_reached();
2323 /* Run from main thread */
2324 static int add_card(struct userdata
*u
, const pa_bluetooth_device
*device
) {
2325 pa_card_new_data data
;
2331 const char *default_profile
;
2336 pa_card_new_data_init(&data
);
2337 data
.driver
= __FILE__
;
2338 data
.module
= u
->module
;
2340 n
= pa_bluetooth_cleanup_name(device
->name
);
2341 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_DESCRIPTION
, n
);
2343 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, device
->address
);
2344 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_API
, "bluez");
2345 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_CLASS
, "sound");
2346 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_BUS
, "bluetooth");
2347 if ((ff
= pa_bluetooth_get_form_factor(device
->class)))
2348 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_FORM_FACTOR
, ff
);
2349 pa_proplist_sets(data
.proplist
, "bluez.path", device
->path
);
2350 pa_proplist_setf(data
.proplist
, "bluez.class", "0x%06x", (unsigned) device
->class);
2351 pa_proplist_sets(data
.proplist
, "bluez.name", device
->name
);
2352 data
.name
= get_name("card", u
->modargs
, device
->address
, &b
);
2353 data
.namereg_fail
= b
;
2355 if (pa_modargs_get_proplist(u
->modargs
, "card_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
2356 pa_log("Invalid properties");
2357 pa_card_new_data_done(&data
);
2361 /* we base hsp/a2dp availability on UUIDs.
2362 Ideally, it would be based on "Connected" state, but
2363 we can't afford to wait for this information when
2364 we are loaded with profile="hsp", for instance */
2365 if (pa_bluetooth_uuid_has(device
->uuids
, A2DP_SINK_UUID
)) {
2366 p
= pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile
));
2370 p
->max_sink_channels
= 2;
2371 p
->max_source_channels
= 0;
2373 d
= PA_CARD_PROFILE_DATA(p
);
2375 create_ports_for_profile(u
, device
, &data
, p
);
2377 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2380 if (pa_bluetooth_uuid_has(device
->uuids
, A2DP_SOURCE_UUID
)) {
2381 p
= pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile
));
2385 p
->max_sink_channels
= 0;
2386 p
->max_source_channels
= 2;
2388 d
= PA_CARD_PROFILE_DATA(p
);
2389 *d
= PROFILE_A2DP_SOURCE
;
2390 create_ports_for_profile(u
, device
, &data
, p
);
2392 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2395 if (pa_bluetooth_uuid_has(device
->uuids
, HSP_HS_UUID
) ||
2396 pa_bluetooth_uuid_has(device
->uuids
, HFP_HS_UUID
)) {
2397 p
= pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile
));
2401 p
->max_sink_channels
= 1;
2402 p
->max_source_channels
= 1;
2404 d
= PA_CARD_PROFILE_DATA(p
);
2406 create_ports_for_profile(u
, device
, &data
, p
);
2408 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2411 if (pa_bluetooth_uuid_has(device
->uuids
, HFP_AG_UUID
)) {
2412 p
= pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile
));
2416 p
->max_sink_channels
= 1;
2417 p
->max_source_channels
= 1;
2419 d
= PA_CARD_PROFILE_DATA(p
);
2421 create_ports_for_profile(u
, device
, &data
, p
);
2423 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2426 pa_assert(!pa_hashmap_isempty(data
.profiles
));
2428 p
= pa_card_profile_new("off", _("Off"), sizeof(enum profile
));
2429 d
= PA_CARD_PROFILE_DATA(p
);
2431 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2433 if ((default_profile
= pa_modargs_get_value(u
->modargs
, "profile", NULL
))) {
2434 if (pa_hashmap_get(data
.profiles
, default_profile
))
2435 pa_card_new_data_set_profile(&data
, default_profile
);
2437 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile
);
2440 u
->card
= pa_card_new(u
->core
, &data
);
2441 pa_card_new_data_done(&data
);
2444 pa_log("Failed to allocate card.");
2448 u
->card
->userdata
= u
;
2449 u
->card
->set_profile
= card_set_profile
;
2451 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2453 if ((device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) ||
2454 (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) ||
2455 (device
->audio_source_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP_SOURCE
) ||
2456 (device
->hfgw_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
)) {
2457 pa_log_warn("Default profile not connected, selecting off profile");
2458 u
->card
->active_profile
= pa_hashmap_get(u
->card
->profiles
, "off");
2459 u
->card
->save_profile
= FALSE
;
2462 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2465 if (USE_SCO_OVER_PCM(u
))
2466 save_sco_volume_callbacks(u
);
2471 /* Run from main thread */
2472 static const pa_bluetooth_device
* find_device(struct userdata
*u
, const char *address
, const char *path
) {
2473 const pa_bluetooth_device
*d
= NULL
;
2477 if (!address
&& !path
) {
2478 pa_log_error("Failed to get device address/path from module arguments.");
2483 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, path
))) {
2484 pa_log_error("%s is not a valid BlueZ audio device.", path
);
2488 if (address
&& !(pa_streq(d
->address
, address
))) {
2489 pa_log_error("Passed path %s address %s != %s don't match.", path
, d
->address
, address
);
2494 if (!(d
= pa_bluetooth_discovery_get_by_address(u
->discovery
, address
))) {
2495 pa_log_error("%s is not known.", address
);
2501 u
->address
= pa_xstrdup(d
->address
);
2502 u
->path
= pa_xstrdup(d
->path
);
2508 /* Run from main thread */
2509 static int setup_dbus(struct userdata
*u
) {
2512 dbus_error_init(&err
);
2514 u
->connection
= pa_dbus_bus_get(u
->core
, DBUS_BUS_SYSTEM
, &err
);
2516 if (dbus_error_is_set(&err
) || !u
->connection
) {
2517 pa_log("Failed to get D-Bus connection: %s", err
.message
);
2518 dbus_error_free(&err
);
2525 int pa__init(pa_module
* m
) {
2529 const char *address
, *path
;
2531 char *mike
, *speaker
;
2532 const pa_bluetooth_device
*device
;
2536 dbus_error_init(&err
);
2538 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
2539 pa_log_error("Failed to parse module arguments");
2543 m
->userdata
= u
= pa_xnew0(struct userdata
, 1);
2547 u
->sample_spec
= m
->core
->default_sample_spec
;
2550 if (pa_modargs_get_value(ma
, "sco_sink", NULL
) &&
2551 !(u
->hsp
.sco_sink
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_sink", NULL
), PA_NAMEREG_SINK
))) {
2552 pa_log("SCO sink not found");
2556 if (pa_modargs_get_value(ma
, "sco_source", NULL
) &&
2557 !(u
->hsp
.sco_source
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_source", NULL
), PA_NAMEREG_SOURCE
))) {
2558 pa_log("SCO source not found");
2562 if (pa_modargs_get_value_u32(ma
, "rate", &u
->sample_spec
.rate
) < 0 ||
2563 u
->sample_spec
.rate
<= 0 || u
->sample_spec
.rate
> PA_RATE_MAX
) {
2564 pa_log_error("Failed to get rate from module arguments");
2568 u
->auto_connect
= TRUE
;
2569 if (pa_modargs_get_value_boolean(ma
, "auto_connect", &u
->auto_connect
)) {
2570 pa_log("Failed to parse auto_connect= argument");
2574 channels
= u
->sample_spec
.channels
;
2575 if (pa_modargs_get_value_u32(ma
, "channels", &channels
) < 0 ||
2576 channels
<= 0 || channels
> PA_CHANNELS_MAX
) {
2577 pa_log_error("Failed to get channels from module arguments");
2580 u
->sample_spec
.channels
= (uint8_t) channels
;
2581 u
->requested_sample_spec
= u
->sample_spec
;
2583 address
= pa_modargs_get_value(ma
, "address", NULL
);
2584 path
= pa_modargs_get_value(ma
, "path", NULL
);
2586 if (setup_dbus(u
) < 0)
2589 if (!(u
->discovery
= pa_bluetooth_discovery_get(m
->core
)))
2592 if (!(device
= find_device(u
, address
, path
)))
2595 /* Add the card structure. This will also initialize the default profile */
2596 if (add_card(u
, device
) < 0)
2599 if (!(u
->msg
= pa_msgobject_new(bluetooth_msg
)))
2602 u
->msg
->parent
.process_msg
= device_process_msg
;
2603 u
->msg
->card
= u
->card
;
2605 if (!dbus_connection_add_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
, NULL
)) {
2606 pa_log_error("Failed to add filter function");
2609 u
->filter_added
= TRUE
;
2611 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2612 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2614 if (pa_dbus_add_matches(
2615 pa_dbus_connection_get(u
->connection
), &err
,
2618 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2619 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2620 "type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged'",
2621 "type='signal',sender='org.bluez',interface='org.bluez.AudioSource',member='PropertyChanged'",
2622 "type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged'",
2628 pa_log("Failed to add D-Bus matches: %s", err
.message
);
2635 if (u
->profile
!= PROFILE_OFF
)
2636 if (init_profile(u
) < 0)
2639 if (u
->sink
|| u
->source
)
2640 if (start_thread(u
) < 0)
2649 dbus_error_free(&err
);
2654 int pa__get_n_used(pa_module
*m
) {
2658 pa_assert_se(u
= m
->userdata
);
2661 (u
->sink
? pa_sink_linked_by(u
->sink
) : 0) +
2662 (u
->source
? pa_source_linked_by(u
->source
) : 0);
2665 void pa__done(pa_module
*m
) {
2670 if (!(u
= m
->userdata
))
2673 if (u
->sink
&& !USE_SCO_OVER_PCM(u
))
2674 pa_sink_unlink(u
->sink
);
2676 if (u
->source
&& !USE_SCO_OVER_PCM(u
))
2677 pa_source_unlink(u
->source
);
2681 if (USE_SCO_OVER_PCM(u
))
2682 restore_sco_volume_callbacks(u
);
2684 if (u
->connection
) {
2687 char *speaker
, *mike
;
2688 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2689 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2691 pa_dbus_remove_matches(pa_dbus_connection_get(u
->connection
), speaker
, mike
,
2692 "type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'",
2693 "type='signal',sender='org.bluez',interface='org.bluez.HandsfreeGateway',member='PropertyChanged'",
2700 if (u
->filter_added
)
2701 dbus_connection_remove_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
);
2703 pa_dbus_connection_unref(u
->connection
);
2710 pa_card_free(u
->card
);
2712 if (u
->read_smoother
)
2713 pa_smoother_free(u
->read_smoother
);
2716 pa_xfree(u
->a2dp
.buffer
);
2718 sbc_finish(&u
->a2dp
.sbc
);
2721 pa_modargs_free(u
->modargs
);
2723 pa_xfree(u
->address
);
2727 bt_transport_release(u
);
2728 pa_xfree(u
->transport
);
2732 pa_bluetooth_discovery_unref(u
->discovery
);