2 This file is part of PulseAudio.
4 Copyright 2008-2009 Joao Paulo Rechi Vita
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
28 #include <linux/sockios.h>
29 #include <arpa/inet.h>
31 #include <pulse/i18n.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/modargs.h>
39 #include <pulsecore/core-rtclock.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/socket-util.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/poll.h>
46 #include <pulsecore/rtpoll.h>
47 #include <pulsecore/time-smoother.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
50 #include <pulsecore/llist.h>
52 #include "module-bluetooth-device-symdef.h"
56 #include "bluetooth-util.h"
58 #define MAX_BITPOOL 64
59 #define MIN_BITPOOL 2U
61 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION
);
64 PA_MODULE_LOAD_ONCE(FALSE
);
66 "name=<name for the card/sink/source, to be prefixed> "
67 "card_name=<name for the card> "
68 "card_properties=<properties for the card> "
69 "sink_name=<name for the sink> "
70 "sink_properties=<properties for the sink> "
71 "source_name=<name for the source> "
72 "source_properties=<properties for the source> "
73 "address=<address of the device> "
74 "profile=<a2dp|hsp|hfgw> "
76 "channels=<number of channels> "
77 "path=<device object path> "
78 "auto_connect=<automatically connect?>");
82 "sco_sink=<SCO over PCM sink name> "
83 "sco_source=<SCO over PCM source name>"
87 /* TODO: not close fd when entering suspend mode in a2dp */
89 static const char* const valid_modargs
[] = {
111 sbc_capabilities_t sbc_capabilities
;
112 sbc_t sbc
; /* Codec data */
113 pa_bool_t sbc_initialized
; /* Keep track if the encoder is initialized */
114 size_t codesize
, frame_length
; /* SBC Codesize, frame_length. We simply cache those values here */
116 void* buffer
; /* Codec transfer buffer */
117 size_t buffer_size
; /* Size of the buffer */
119 uint16_t seq_num
; /* Cumulative packet sequence */
123 pcm_capabilities_t pcm_capabilities
;
126 pa_source
*sco_source
;
128 pa_hook_slot
*sink_state_changed_slot
;
129 pa_hook_slot
*source_state_changed_slot
;
141 pa_bluetooth_discovery
*discovery
;
142 pa_bool_t auto_connect
;
144 pa_dbus_connection
*connection
;
150 pa_thread_mq thread_mq
;
152 pa_rtpoll_item
*rtpoll_item
;
155 uint64_t read_index
, write_index
;
156 pa_usec_t started_at
;
157 pa_smoother
*read_smoother
;
159 pa_memchunk write_memchunk
;
161 pa_sample_spec sample_spec
, requested_sample_spec
;
169 struct a2dp_info a2dp
;
172 enum profile profile
;
176 int stream_write_type
;
177 int service_write_type
, service_read_type
;
179 pa_bool_t filter_added
;
182 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
183 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
184 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
185 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
187 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
190 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
193 static int init_bt(struct userdata
*u
);
194 static int init_profile(struct userdata
*u
);
196 static int service_send(struct userdata
*u
, const bt_audio_msg_header_t
*msg
) {
201 pa_assert(msg
->length
> 0);
203 if (u
->service_fd
< 0) {
204 pa_log_warn("Service not connected");
208 pa_log_debug("Sending %s -> %s",
209 pa_strnull(bt_audio_strtype(msg
->type
)),
210 pa_strnull(bt_audio_strname(msg
->name
)));
212 if ((r
= pa_loop_write(u
->service_fd
, msg
, msg
->length
, &u
->service_write_type
)) == (ssize_t
) msg
->length
)
216 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno
));
218 pa_log_error("Short write()");
223 static int service_recv(struct userdata
*u
, bt_audio_msg_header_t
*msg
, size_t room
) {
227 pa_assert(u
->service_fd
>= 0);
229 pa_assert(room
>= sizeof(*msg
));
231 pa_log_debug("Trying to receive message from audio service...");
233 /* First, read the header */
234 if ((r
= pa_loop_read(u
->service_fd
, msg
, sizeof(*msg
), &u
->service_read_type
)) != sizeof(*msg
))
237 if (msg
->length
< sizeof(*msg
)) {
238 pa_log_error("Invalid message size.");
242 if (msg
->length
> room
) {
243 pa_log_error("Not enough room.");
247 /* Secondly, read the payload */
248 if (msg
->length
> sizeof(*msg
)) {
250 size_t remains
= msg
->length
- sizeof(*msg
);
252 if ((r
= pa_loop_read(u
->service_fd
,
253 (uint8_t*) msg
+ sizeof(*msg
),
255 &u
->service_read_type
)) != (ssize_t
) remains
)
259 pa_log_debug("Received %s <- %s",
260 pa_strnull(bt_audio_strtype(msg
->type
)),
261 pa_strnull(bt_audio_strname(msg
->name
)));
268 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno
));
270 pa_log_error("Short read()");
275 static ssize_t
service_expect(struct userdata
*u
, bt_audio_msg_header_t
*rsp
, size_t room
, uint8_t expected_name
, size_t expected_size
) {
279 pa_assert(u
->service_fd
>= 0);
282 if ((r
= service_recv(u
, rsp
, room
)) < 0)
285 if ((rsp
->type
!= BT_INDICATION
&& rsp
->type
!= BT_RESPONSE
) ||
286 rsp
->name
!= expected_name
||
287 (expected_size
> 0 && rsp
->length
!= expected_size
)) {
289 if (rsp
->type
== BT_ERROR
&& rsp
->length
== sizeof(bt_audio_error_t
))
290 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t
*) rsp
)->posix_errno
));
292 pa_log_error("Bogus message %s received while %s was expected",
293 pa_strnull(bt_audio_strname(rsp
->name
)),
294 pa_strnull(bt_audio_strname(expected_name
)));
301 /* Run from main thread */
302 static int parse_caps(struct userdata
*u
, uint8_t seid
, const struct bt_get_capabilities_rsp
*rsp
) {
304 const codec_capabilities_t
*codec
;
309 bytes_left
= rsp
->h
.length
- sizeof(*rsp
);
311 if (bytes_left
< sizeof(codec_capabilities_t
)) {
312 pa_log_error("Packet too small to store codec information.");
316 codec
= (codec_capabilities_t
*) rsp
->data
; /** ALIGNMENT? **/
318 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left
, (unsigned long) sizeof(*codec
));
320 if (((u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
) && codec
->transport
!= BT_CAPABILITIES_TRANSPORT_A2DP
) ||
321 ((u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) && codec
->transport
!= BT_CAPABILITIES_TRANSPORT_SCO
)) {
322 pa_log_error("Got capabilities for wrong codec.");
326 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
328 if (bytes_left
<= 0 || codec
->length
!= sizeof(u
->hsp
.pcm_capabilities
))
331 pa_assert(codec
->type
== BT_HFP_CODEC_PCM
);
333 if (codec
->configured
&& seid
== 0)
336 memcpy(&u
->hsp
.pcm_capabilities
, codec
, sizeof(u
->hsp
.pcm_capabilities
));
338 } else if (u
->profile
== PROFILE_A2DP
) {
340 while (bytes_left
> 0) {
341 if ((codec
->type
== BT_A2DP_SBC_SINK
) && !codec
->lock
)
344 bytes_left
-= codec
->length
;
345 codec
= (const codec_capabilities_t
*) ((const uint8_t*) codec
+ codec
->length
);
348 if (bytes_left
<= 0 || codec
->length
!= sizeof(u
->a2dp
.sbc_capabilities
))
351 pa_assert(codec
->type
== BT_A2DP_SBC_SINK
);
353 if (codec
->configured
&& seid
== 0)
356 memcpy(&u
->a2dp
.sbc_capabilities
, codec
, sizeof(u
->a2dp
.sbc_capabilities
));
358 } else if (u
->profile
== PROFILE_A2DP_SOURCE
) {
360 while (bytes_left
> 0) {
361 if ((codec
->type
== BT_A2DP_SBC_SOURCE
) && !codec
->lock
)
364 bytes_left
-= codec
->length
;
365 codec
= (const codec_capabilities_t
*) ((const uint8_t*) codec
+ codec
->length
);
368 if (bytes_left
<= 0 || codec
->length
!= sizeof(u
->a2dp
.sbc_capabilities
))
371 pa_assert(codec
->type
== BT_A2DP_SBC_SOURCE
);
373 if (codec
->configured
&& seid
== 0)
376 memcpy(&u
->a2dp
.sbc_capabilities
, codec
, sizeof(u
->a2dp
.sbc_capabilities
));
382 /* Run from main thread */
383 static int get_caps(struct userdata
*u
, uint8_t seid
) {
385 struct bt_get_capabilities_req getcaps_req
;
386 struct bt_get_capabilities_rsp getcaps_rsp
;
387 bt_audio_error_t error
;
388 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
394 memset(&msg
, 0, sizeof(msg
));
395 msg
.getcaps_req
.h
.type
= BT_REQUEST
;
396 msg
.getcaps_req
.h
.name
= BT_GET_CAPABILITIES
;
397 msg
.getcaps_req
.h
.length
= sizeof(msg
.getcaps_req
);
398 msg
.getcaps_req
.seid
= seid
;
400 pa_strlcpy(msg
.getcaps_req
.object
, u
->path
, sizeof(msg
.getcaps_req
.object
));
401 if (u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
)
402 msg
.getcaps_req
.transport
= BT_CAPABILITIES_TRANSPORT_A2DP
;
404 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
405 msg
.getcaps_req
.transport
= BT_CAPABILITIES_TRANSPORT_SCO
;
407 msg
.getcaps_req
.flags
= u
->auto_connect
? BT_FLAG_AUTOCONNECT
: 0;
409 if (service_send(u
, &msg
.getcaps_req
.h
) < 0)
412 if (service_expect(u
, &msg
.getcaps_rsp
.h
, sizeof(msg
), BT_GET_CAPABILITIES
, 0) < 0)
415 ret
= parse_caps(u
, seid
, &msg
.getcaps_rsp
);
419 return get_caps(u
, ret
);
422 /* Run from main thread */
423 static uint8_t a2dp_default_bitpool(uint8_t freq
, uint8_t mode
) {
426 case BT_SBC_SAMPLING_FREQ_16000
:
427 case BT_SBC_SAMPLING_FREQ_32000
:
430 case BT_SBC_SAMPLING_FREQ_44100
:
433 case BT_A2DP_CHANNEL_MODE_MONO
:
434 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
437 case BT_A2DP_CHANNEL_MODE_STEREO
:
438 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
442 pa_log_warn("Invalid channel mode %u", mode
);
446 case BT_SBC_SAMPLING_FREQ_48000
:
449 case BT_A2DP_CHANNEL_MODE_MONO
:
450 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
453 case BT_A2DP_CHANNEL_MODE_STEREO
:
454 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
458 pa_log_warn("Invalid channel mode %u", mode
);
463 pa_log_warn("Invalid sampling freq %u", freq
);
468 /* Run from main thread */
469 static int setup_a2dp(struct userdata
*u
) {
470 sbc_capabilities_t
*cap
;
473 static const struct {
477 { 16000U, BT_SBC_SAMPLING_FREQ_16000
},
478 { 32000U, BT_SBC_SAMPLING_FREQ_32000
},
479 { 44100U, BT_SBC_SAMPLING_FREQ_44100
},
480 { 48000U, BT_SBC_SAMPLING_FREQ_48000
}
484 pa_assert(u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
);
486 cap
= &u
->a2dp
.sbc_capabilities
;
488 /* Find the lowest freq that is at least as high as the requested
490 for (i
= 0; (unsigned) i
< PA_ELEMENTSOF(freq_table
); i
++)
491 if (freq_table
[i
].rate
>= u
->sample_spec
.rate
&& (cap
->frequency
& freq_table
[i
].cap
)) {
492 u
->sample_spec
.rate
= freq_table
[i
].rate
;
493 cap
->frequency
= freq_table
[i
].cap
;
497 if ((unsigned) i
== PA_ELEMENTSOF(freq_table
)) {
498 for (--i
; i
>= 0; i
--) {
499 if (cap
->frequency
& freq_table
[i
].cap
) {
500 u
->sample_spec
.rate
= freq_table
[i
].rate
;
501 cap
->frequency
= freq_table
[i
].cap
;
507 pa_log("Not suitable sample rate");
512 pa_assert((unsigned) i
< PA_ELEMENTSOF(freq_table
));
514 if (cap
->capability
.configured
)
517 if (u
->sample_spec
.channels
<= 1) {
518 if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_MONO
) {
519 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_MONO
;
520 u
->sample_spec
.channels
= 1;
522 u
->sample_spec
.channels
= 2;
525 if (u
->sample_spec
.channels
>= 2) {
526 u
->sample_spec
.channels
= 2;
528 if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_JOINT_STEREO
)
529 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_JOINT_STEREO
;
530 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_STEREO
)
531 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_STEREO
;
532 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
)
533 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
;
534 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_MONO
) {
535 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_MONO
;
536 u
->sample_spec
.channels
= 1;
538 pa_log("No supported channel modes");
543 if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_16
)
544 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_16
;
545 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_12
)
546 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_12
;
547 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_8
)
548 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_8
;
549 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_4
)
550 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_4
;
552 pa_log_error("No supported block lengths");
556 if (cap
->subbands
& BT_A2DP_SUBBANDS_8
)
557 cap
->subbands
= BT_A2DP_SUBBANDS_8
;
558 else if (cap
->subbands
& BT_A2DP_SUBBANDS_4
)
559 cap
->subbands
= BT_A2DP_SUBBANDS_4
;
561 pa_log_error("No supported subbands");
565 if (cap
->allocation_method
& BT_A2DP_ALLOCATION_LOUDNESS
)
566 cap
->allocation_method
= BT_A2DP_ALLOCATION_LOUDNESS
;
567 else if (cap
->allocation_method
& BT_A2DP_ALLOCATION_SNR
)
568 cap
->allocation_method
= BT_A2DP_ALLOCATION_SNR
;
570 cap
->min_bitpool
= (uint8_t) PA_MAX(MIN_BITPOOL
, cap
->min_bitpool
);
571 cap
->max_bitpool
= (uint8_t) PA_MIN(a2dp_default_bitpool(cap
->frequency
, cap
->channel_mode
), cap
->max_bitpool
);
576 /* Run from main thread */
577 static void setup_sbc(struct a2dp_info
*a2dp
) {
578 sbc_capabilities_t
*active_capabilities
;
582 active_capabilities
= &a2dp
->sbc_capabilities
;
584 if (a2dp
->sbc_initialized
)
585 sbc_reinit(&a2dp
->sbc
, 0);
587 sbc_init(&a2dp
->sbc
, 0);
588 a2dp
->sbc_initialized
= TRUE
;
590 switch (active_capabilities
->frequency
) {
591 case BT_SBC_SAMPLING_FREQ_16000
:
592 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
594 case BT_SBC_SAMPLING_FREQ_32000
:
595 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
597 case BT_SBC_SAMPLING_FREQ_44100
:
598 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
600 case BT_SBC_SAMPLING_FREQ_48000
:
601 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
604 pa_assert_not_reached();
607 switch (active_capabilities
->channel_mode
) {
608 case BT_A2DP_CHANNEL_MODE_MONO
:
609 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
611 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
612 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
614 case BT_A2DP_CHANNEL_MODE_STEREO
:
615 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
617 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
618 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
621 pa_assert_not_reached();
624 switch (active_capabilities
->allocation_method
) {
625 case BT_A2DP_ALLOCATION_SNR
:
626 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
628 case BT_A2DP_ALLOCATION_LOUDNESS
:
629 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
632 pa_assert_not_reached();
635 switch (active_capabilities
->subbands
) {
636 case BT_A2DP_SUBBANDS_4
:
637 a2dp
->sbc
.subbands
= SBC_SB_4
;
639 case BT_A2DP_SUBBANDS_8
:
640 a2dp
->sbc
.subbands
= SBC_SB_8
;
643 pa_assert_not_reached();
646 switch (active_capabilities
->block_length
) {
647 case BT_A2DP_BLOCK_LENGTH_4
:
648 a2dp
->sbc
.blocks
= SBC_BLK_4
;
650 case BT_A2DP_BLOCK_LENGTH_8
:
651 a2dp
->sbc
.blocks
= SBC_BLK_8
;
653 case BT_A2DP_BLOCK_LENGTH_12
:
654 a2dp
->sbc
.blocks
= SBC_BLK_12
;
656 case BT_A2DP_BLOCK_LENGTH_16
:
657 a2dp
->sbc
.blocks
= SBC_BLK_16
;
660 pa_assert_not_reached();
663 a2dp
->sbc
.bitpool
= active_capabilities
->max_bitpool
;
664 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
665 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
668 /* Run from main thread */
669 static int set_conf(struct userdata
*u
) {
671 struct bt_open_req open_req
;
672 struct bt_open_rsp open_rsp
;
673 struct bt_set_configuration_req setconf_req
;
674 struct bt_set_configuration_rsp setconf_rsp
;
675 bt_audio_error_t error
;
676 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
679 memset(&msg
, 0, sizeof(msg
));
680 msg
.open_req
.h
.type
= BT_REQUEST
;
681 msg
.open_req
.h
.name
= BT_OPEN
;
682 msg
.open_req
.h
.length
= sizeof(msg
.open_req
);
684 pa_strlcpy(msg
.open_req
.object
, u
->path
, sizeof(msg
.open_req
.object
));
685 msg
.open_req
.seid
= (u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
) ? u
->a2dp
.sbc_capabilities
.capability
.seid
: BT_A2DP_SEID_RANGE
+ 1;
686 msg
.open_req
.lock
= (u
->profile
== PROFILE_A2DP
) ? BT_WRITE_LOCK
: BT_READ_LOCK
| BT_WRITE_LOCK
;
688 if (service_send(u
, &msg
.open_req
.h
) < 0)
691 if (service_expect(u
, &msg
.open_rsp
.h
, sizeof(msg
), BT_OPEN
, sizeof(msg
.open_rsp
)) < 0)
694 if (u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
) {
695 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
697 if (setup_a2dp(u
) < 0)
700 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
702 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
703 u
->sample_spec
.channels
= 1;
704 u
->sample_spec
.rate
= 8000;
707 memset(&msg
, 0, sizeof(msg
));
708 msg
.setconf_req
.h
.type
= BT_REQUEST
;
709 msg
.setconf_req
.h
.name
= BT_SET_CONFIGURATION
;
710 msg
.setconf_req
.h
.length
= sizeof(msg
.setconf_req
);
712 if (u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
) {
713 memcpy(&msg
.setconf_req
.codec
, &u
->a2dp
.sbc_capabilities
, sizeof(u
->a2dp
.sbc_capabilities
));
715 msg
.setconf_req
.codec
.transport
= BT_CAPABILITIES_TRANSPORT_SCO
;
716 msg
.setconf_req
.codec
.seid
= BT_A2DP_SEID_RANGE
+ 1;
717 msg
.setconf_req
.codec
.length
= sizeof(pcm_capabilities_t
);
719 msg
.setconf_req
.h
.length
+= msg
.setconf_req
.codec
.length
- sizeof(msg
.setconf_req
.codec
);
721 if (service_send(u
, &msg
.setconf_req
.h
) < 0)
724 if (service_expect(u
, &msg
.setconf_rsp
.h
, sizeof(msg
), BT_SET_CONFIGURATION
, sizeof(msg
.setconf_rsp
)) < 0)
727 u
->link_mtu
= msg
.setconf_rsp
.link_mtu
;
729 /* setup SBC encoder now we agree on parameters */
730 if (u
->profile
== PROFILE_A2DP
|| u
->profile
== PROFILE_A2DP_SOURCE
) {
734 ((u
->link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
735 / u
->a2dp
.frame_length
738 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
739 u
->a2dp
.sbc
.allocation
, u
->a2dp
.sbc
.subbands
, u
->a2dp
.sbc
.blocks
, u
->a2dp
.sbc
.bitpool
);
741 u
->block_size
= u
->link_mtu
;
746 /* from IO thread, except in SCO over PCM */
748 static int setup_stream(struct userdata
*u
) {
749 struct pollfd
*pollfd
;
752 pa_make_fd_nonblock(u
->stream_fd
);
753 pa_make_socket_low_delay(u
->stream_fd
);
756 if (setsockopt(u
->stream_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
)) < 0)
757 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno
));
759 pa_log_debug("Stream properly set up, we're ready to roll!");
761 u
->rtpoll_item
= pa_rtpoll_item_new(u
->rtpoll
, PA_RTPOLL_NEVER
, 1);
762 pollfd
= pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
);
763 pollfd
->fd
= u
->stream_fd
;
764 pollfd
->events
= pollfd
->revents
= 0;
766 u
->read_index
= u
->write_index
= 0;
770 u
->read_smoother
= pa_smoother_new(
782 static int start_stream_fd(struct userdata
*u
) {
784 bt_audio_msg_header_t rsp
;
785 struct bt_start_stream_req start_req
;
786 struct bt_start_stream_rsp start_rsp
;
787 struct bt_new_stream_ind streamfd_ind
;
788 bt_audio_error_t error
;
789 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
793 pa_assert(u
->rtpoll
);
794 pa_assert(!u
->rtpoll_item
);
795 pa_assert(u
->stream_fd
< 0);
797 memset(msg
.buf
, 0, BT_SUGGESTED_BUFFER_SIZE
);
798 msg
.start_req
.h
.type
= BT_REQUEST
;
799 msg
.start_req
.h
.name
= BT_START_STREAM
;
800 msg
.start_req
.h
.length
= sizeof(msg
.start_req
);
802 if (service_send(u
, &msg
.start_req
.h
) < 0)
805 if (service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_START_STREAM
, sizeof(msg
.start_rsp
)) < 0)
808 if (service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_NEW_STREAM
, sizeof(msg
.streamfd_ind
)) < 0)
811 if ((u
->stream_fd
= bt_audio_service_get_data_fd(u
->service_fd
)) < 0) {
812 pa_log("Failed to get stream fd from audio service.");
816 return setup_stream(u
);
820 static int stop_stream_fd(struct userdata
*u
) {
822 bt_audio_msg_header_t rsp
;
823 struct bt_stop_stream_req start_req
;
824 struct bt_stop_stream_rsp start_rsp
;
825 bt_audio_error_t error
;
826 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
831 pa_assert(u
->rtpoll
);
833 if (u
->rtpoll_item
) {
834 pa_rtpoll_item_free(u
->rtpoll_item
);
835 u
->rtpoll_item
= NULL
;
838 if (u
->stream_fd
>= 0) {
839 memset(msg
.buf
, 0, BT_SUGGESTED_BUFFER_SIZE
);
840 msg
.start_req
.h
.type
= BT_REQUEST
;
841 msg
.start_req
.h
.name
= BT_STOP_STREAM
;
842 msg
.start_req
.h
.length
= sizeof(msg
.start_req
);
844 if (service_send(u
, &msg
.start_req
.h
) < 0 ||
845 service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_STOP_STREAM
, sizeof(msg
.start_rsp
)) < 0)
848 pa_close(u
->stream_fd
);
852 if (u
->read_smoother
) {
853 pa_smoother_free(u
->read_smoother
);
854 u
->read_smoother
= NULL
;
860 static void bt_transport_release(struct userdata
*u
)
862 const char *accesstype
= "rw";
863 const pa_bluetooth_transport
*t
;
865 /* Ignore if already released */
869 pa_log_debug("Releasing transport %s", u
->transport
);
871 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
873 pa_bluetooth_transport_release(t
, accesstype
);
875 pa_xfree(u
->accesstype
);
876 u
->accesstype
= NULL
;
878 if (u
->rtpoll_item
) {
879 pa_rtpoll_item_free(u
->rtpoll_item
);
880 u
->rtpoll_item
= NULL
;
883 if (u
->stream_fd
>= 0) {
884 pa_close(u
->stream_fd
);
888 if (u
->read_smoother
) {
889 pa_smoother_free(u
->read_smoother
);
890 u
->read_smoother
= NULL
;
894 static int bt_transport_acquire(struct userdata
*u
, pa_bool_t start
)
896 const char *accesstype
= "rw";
897 const pa_bluetooth_transport
*t
;
905 pa_log_debug("Acquiring transport %s", u
->transport
);
907 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
909 pa_log("Transport %s no longer available", u
->transport
);
910 pa_xfree(u
->transport
);
915 u
->stream_fd
= pa_bluetooth_transport_acquire(t
, accesstype
);
916 if (u
->stream_fd
< 0)
919 u
->accesstype
= pa_xstrdup(accesstype
);
920 pa_log_info("Transport %s acquired: fd %d", u
->transport
, u
->stream_fd
);
926 pa_log_info("Transport %s resuming", u
->transport
);
927 return setup_stream(u
);
930 /* Run from IO thread */
931 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
932 struct userdata
*u
= PA_SINK(o
)->userdata
;
933 pa_bool_t failed
= FALSE
;
936 pa_assert(u
->sink
== PA_SINK(o
));
940 case PA_SINK_MESSAGE_SET_STATE
:
942 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
944 case PA_SINK_SUSPENDED
:
945 pa_assert(PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
));
947 /* Stop the device if the source is suspended as well */
948 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
) {
949 /* We deliberately ignore whether stopping
950 * actually worked. Since the stream_fd is
951 * closed it doesn't really matter */
953 bt_transport_release(u
);
961 case PA_SINK_RUNNING
:
962 if (u
->sink
->thread_info
.state
!= PA_SINK_SUSPENDED
)
965 /* Resume the device if the source was suspended as well */
966 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
) {
968 if (bt_transport_acquire(u
, TRUE
) < 0)
970 } else if (start_stream_fd(u
) < 0)
975 case PA_SINK_UNLINKED
:
977 case PA_SINK_INVALID_STATE
:
982 case PA_SINK_MESSAGE_GET_LATENCY
: {
984 if (u
->read_smoother
) {
987 ri
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
988 wi
= pa_bytes_to_usec(u
->write_index
+ u
->block_size
, &u
->sample_spec
);
990 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
994 ri
= pa_rtclock_now() - u
->started_at
;
995 wi
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
997 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
1000 *((pa_usec_t
*) data
) += u
->sink
->thread_info
.fixed_latency
;
1005 r
= pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
1007 return (r
< 0 || !failed
) ? r
: -1;
1010 /* Run from IO thread */
1011 static int source_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
1012 struct userdata
*u
= PA_SOURCE(o
)->userdata
;
1013 pa_bool_t failed
= FALSE
;
1016 pa_assert(u
->source
== PA_SOURCE(o
));
1020 case PA_SOURCE_MESSAGE_SET_STATE
:
1022 switch ((pa_source_state_t
) PA_PTR_TO_UINT(data
)) {
1024 case PA_SOURCE_SUSPENDED
:
1025 pa_assert(PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
));
1027 /* Stop the device if the sink is suspended as well */
1028 if (!u
->sink
|| u
->sink
->state
== PA_SINK_SUSPENDED
) {
1030 bt_transport_release(u
);
1035 if (u
->read_smoother
)
1036 pa_smoother_pause(u
->read_smoother
, pa_rtclock_now());
1039 case PA_SOURCE_IDLE
:
1040 case PA_SOURCE_RUNNING
:
1041 if (u
->source
->thread_info
.state
!= PA_SOURCE_SUSPENDED
)
1044 /* Resume the device if the sink was suspended as well */
1045 if (!u
->sink
|| u
->sink
->thread_info
.state
== PA_SINK_SUSPENDED
) {
1047 if (bt_transport_acquire(u
, TRUE
) < 0)
1049 } else if (start_stream_fd(u
) < 0)
1052 /* We don't resume the smoother here. Instead we
1053 * wait until the first packet arrives */
1056 case PA_SOURCE_UNLINKED
:
1057 case PA_SOURCE_INIT
:
1058 case PA_SOURCE_INVALID_STATE
:
1063 case PA_SOURCE_MESSAGE_GET_LATENCY
: {
1066 if (u
->read_smoother
) {
1067 wi
= pa_smoother_get(u
->read_smoother
, pa_rtclock_now());
1068 ri
= pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
);
1070 *((pa_usec_t
*) data
) = (wi
> ri
? wi
- ri
: 0) + u
->source
->thread_info
.fixed_latency
;
1072 *((pa_usec_t
*) data
) = 0;
1079 r
= pa_source_process_msg(o
, code
, data
, offset
, chunk
);
1081 return (r
< 0 || !failed
) ? r
: -1;
1084 /* Run from IO thread */
1085 static int hsp_process_render(struct userdata
*u
) {
1089 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
1092 /* First, render some data */
1093 if (!u
->write_memchunk
.memblock
)
1094 pa_sink_render_full(u
->sink
, u
->block_size
, &u
->write_memchunk
);
1096 pa_assert(u
->write_memchunk
.length
== u
->block_size
);
1102 /* Now write that data to the socket. The socket is of type
1103 * SEQPACKET, and we generated the data of the MTU size, so this
1104 * should just work. */
1106 p
= (const uint8_t*) pa_memblock_acquire(u
->write_memchunk
.memblock
) + u
->write_memchunk
.index
;
1107 l
= pa_write(u
->stream_fd
, p
, u
->write_memchunk
.length
, &u
->stream_write_type
);
1108 pa_memblock_release(u
->write_memchunk
.memblock
);
1115 /* Retry right away if we got interrupted */
1118 else if (errno
== EAGAIN
)
1119 /* Hmm, apparently the socket was not writable, give up for now */
1122 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno
));
1127 pa_assert((size_t) l
<= u
->write_memchunk
.length
);
1129 if ((size_t) l
!= u
->write_memchunk
.length
) {
1130 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1131 (unsigned long long) l
,
1132 (unsigned long long) u
->write_memchunk
.length
);
1137 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
1138 pa_memblock_unref(u
->write_memchunk
.memblock
);
1139 pa_memchunk_reset(&u
->write_memchunk
);
1148 /* Run from IO thread */
1149 static int hsp_process_push(struct userdata
*u
) {
1151 pa_memchunk memchunk
;
1154 pa_assert(u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
);
1155 pa_assert(u
->source
);
1156 pa_assert(u
->read_smoother
);
1158 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->block_size
);
1159 memchunk
.index
= memchunk
.length
= 0;
1168 pa_bool_t found_tstamp
= FALSE
;
1171 memset(&m
, 0, sizeof(m
));
1172 memset(&aux
, 0, sizeof(aux
));
1173 memset(&iov
, 0, sizeof(iov
));
1177 m
.msg_control
= aux
;
1178 m
.msg_controllen
= sizeof(aux
);
1180 p
= pa_memblock_acquire(memchunk
.memblock
);
1182 iov
.iov_len
= pa_memblock_get_length(memchunk
.memblock
);
1183 l
= recvmsg(u
->stream_fd
, &m
, 0);
1184 pa_memblock_release(memchunk
.memblock
);
1188 if (l
< 0 && errno
== EINTR
)
1189 /* Retry right away if we got interrupted */
1192 else if (l
< 0 && errno
== EAGAIN
)
1193 /* Hmm, apparently the socket was not readable, give up for now. */
1196 pa_log_error("Failed to read data from SCO socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
1201 pa_assert((size_t) l
<= pa_memblock_get_length(memchunk
.memblock
));
1203 memchunk
.length
= (size_t) l
;
1204 u
->read_index
+= (uint64_t) l
;
1206 for (cm
= CMSG_FIRSTHDR(&m
); cm
; cm
= CMSG_NXTHDR(&m
, cm
))
1207 if (cm
->cmsg_level
== SOL_SOCKET
&& cm
->cmsg_type
== SO_TIMESTAMP
) {
1208 struct timeval
*tv
= (struct timeval
*) CMSG_DATA(cm
);
1209 pa_rtclock_from_wallclock(tv
);
1210 tstamp
= pa_timeval_load(tv
);
1211 found_tstamp
= TRUE
;
1215 if (!found_tstamp
) {
1216 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1217 tstamp
= pa_rtclock_now();
1220 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
1221 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
1223 pa_source_post(u
->source
, &memchunk
);
1229 pa_memblock_unref(memchunk
.memblock
);
1234 /* Run from IO thread */
1235 static void a2dp_prepare_buffer(struct userdata
*u
) {
1238 if (u
->a2dp
.buffer_size
>= u
->link_mtu
)
1241 u
->a2dp
.buffer_size
= 2 * u
->link_mtu
;
1242 pa_xfree(u
->a2dp
.buffer
);
1243 u
->a2dp
.buffer
= pa_xmalloc(u
->a2dp
.buffer_size
);
1246 /* Run from IO thread */
1247 static int a2dp_process_render(struct userdata
*u
) {
1248 struct a2dp_info
*a2dp
;
1249 struct rtp_header
*header
;
1250 struct rtp_payload
*payload
;
1254 size_t to_write
, to_encode
;
1255 unsigned frame_count
;
1259 pa_assert(u
->profile
== PROFILE_A2DP
);
1262 /* First, render some data */
1263 if (!u
->write_memchunk
.memblock
)
1264 pa_sink_render_full(u
->sink
, u
->block_size
, &u
->write_memchunk
);
1266 pa_assert(u
->write_memchunk
.length
== u
->block_size
);
1268 a2dp_prepare_buffer(u
);
1271 header
= a2dp
->buffer
;
1272 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
1276 /* Try to create a packet of the full MTU */
1278 p
= (const uint8_t*) pa_memblock_acquire(u
->write_memchunk
.memblock
) + u
->write_memchunk
.index
;
1279 to_encode
= u
->write_memchunk
.length
;
1281 d
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
1282 to_write
= a2dp
->buffer_size
- sizeof(*header
) - sizeof(*payload
);
1284 while (PA_LIKELY(to_encode
> 0 && to_write
> 0)) {
1288 encoded
= sbc_encode(&a2dp
->sbc
,
1293 if (PA_UNLIKELY(encoded
<= 0)) {
1294 pa_log_error("SBC encoding error (%li)", (long) encoded
);
1295 pa_memblock_release(u
->write_memchunk
.memblock
);
1299 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1300 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1302 pa_assert_fp((size_t) encoded
<= to_encode
);
1303 pa_assert_fp((size_t) encoded
== a2dp
->codesize
);
1305 pa_assert_fp((size_t) written
<= to_write
);
1306 pa_assert_fp((size_t) written
== a2dp
->frame_length
);
1308 p
= (const uint8_t*) p
+ encoded
;
1309 to_encode
-= encoded
;
1311 d
= (uint8_t*) d
+ written
;
1312 to_write
-= written
;
1317 pa_memblock_release(u
->write_memchunk
.memblock
);
1319 pa_assert(to_encode
== 0);
1322 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp
->sbc
)));
1325 /* write it to the fifo */
1326 memset(a2dp
->buffer
, 0, sizeof(*header
) + sizeof(*payload
));
1329 header
->sequence_number
= htons(a2dp
->seq_num
++);
1330 header
->timestamp
= htonl(u
->write_index
/ pa_frame_size(&u
->sample_spec
));
1331 header
->ssrc
= htonl(1);
1332 payload
->frame_count
= frame_count
;
1334 nbytes
= (uint8_t*) d
- (uint8_t*) a2dp
->buffer
;
1339 l
= pa_write(u
->stream_fd
, a2dp
->buffer
, nbytes
, &u
->stream_write_type
);
1346 /* Retry right away if we got interrupted */
1349 else if (errno
== EAGAIN
)
1350 /* Hmm, apparently the socket was not writable, give up for now */
1353 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno
));
1358 pa_assert((size_t) l
<= nbytes
);
1360 if ((size_t) l
!= nbytes
) {
1361 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1362 (unsigned long long) l
,
1363 (unsigned long long) nbytes
);
1368 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
1369 pa_memblock_unref(u
->write_memchunk
.memblock
);
1370 pa_memchunk_reset(&u
->write_memchunk
);
1380 static int a2dp_process_push(struct userdata
*u
) {
1382 pa_memchunk memchunk
;
1385 pa_assert(u
->profile
== PROFILE_A2DP_SOURCE
);
1386 pa_assert(u
->source
);
1387 pa_assert(u
->read_smoother
);
1389 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->block_size
);
1390 memchunk
.index
= memchunk
.length
= 0;
1393 pa_bool_t found_tstamp
= FALSE
;
1395 struct a2dp_info
*a2dp
;
1396 struct rtp_header
*header
;
1397 struct rtp_payload
*payload
;
1401 size_t to_write
, to_decode
;
1402 unsigned frame_count
;
1404 a2dp_prepare_buffer(u
);
1407 header
= a2dp
->buffer
;
1408 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
1410 l
= pa_read(u
->stream_fd
, a2dp
->buffer
, a2dp
->buffer_size
, &u
->stream_write_type
);
1414 if (l
< 0 && errno
== EINTR
)
1415 /* Retry right away if we got interrupted */
1418 else if (l
< 0 && errno
== EAGAIN
)
1419 /* Hmm, apparently the socket was not readable, give up for now. */
1422 pa_log_error("Failed to read data from socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
1427 pa_assert((size_t) l
<= a2dp
->buffer_size
);
1429 u
->read_index
+= (uint64_t) l
;
1431 /* TODO: get timestamp from rtp */
1432 if (!found_tstamp
) {
1433 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1434 tstamp
= pa_rtclock_now();
1437 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
1438 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
1440 p
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
1441 to_decode
= l
- sizeof(*header
) - sizeof(*payload
);
1443 d
= pa_memblock_acquire(memchunk
.memblock
);
1444 to_write
= memchunk
.length
= pa_memblock_get_length(memchunk
.memblock
);
1446 while (PA_LIKELY(to_decode
> 0 && to_write
> 0)) {
1450 decoded
= sbc_decode(&a2dp
->sbc
,
1455 if (PA_UNLIKELY(decoded
<= 0)) {
1456 pa_log_error("SBC decoding error (%li)", (long) decoded
);
1457 pa_memblock_release(memchunk
.memblock
);
1458 pa_memblock_unref(memchunk
.memblock
);
1462 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1463 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1465 pa_assert_fp((size_t) decoded
<= to_decode
);
1466 pa_assert_fp((size_t) decoded
== a2dp
->frame_length
);
1468 pa_assert_fp((size_t) written
<= to_write
);
1469 pa_assert_fp((size_t) written
== a2dp
->codesize
);
1471 p
= (const uint8_t*) p
+ decoded
;
1472 to_decode
-= decoded
;
1474 d
= (uint8_t*) d
+ written
;
1475 to_write
-= written
;
1480 pa_memblock_release(memchunk
.memblock
);
1482 pa_source_post(u
->source
, &memchunk
);
1488 pa_memblock_unref(memchunk
.memblock
);
1493 static void thread_func(void *userdata
) {
1494 struct userdata
*u
= userdata
;
1495 unsigned do_write
= 0;
1496 pa_bool_t writable
= FALSE
;
1500 pa_log_debug("IO Thread starting up");
1502 if (u
->core
->realtime_scheduling
)
1503 pa_make_realtime(u
->core
->realtime_priority
);
1505 pa_thread_mq_install(&u
->thread_mq
);
1508 if (bt_transport_acquire(u
, TRUE
) < 0)
1510 } else if (start_stream_fd(u
) < 0)
1514 struct pollfd
*pollfd
;
1516 pa_bool_t disable_timer
= TRUE
;
1518 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1520 if (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) {
1522 /* We should send two blocks to the device before we expect
1525 if (u
->write_index
== 0 && u
->read_index
<= 0)
1528 if (pollfd
&& (pollfd
->revents
& POLLIN
)) {
1531 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
)
1532 n_read
= hsp_process_push(u
);
1534 n_read
= a2dp_process_push(u
);
1539 /* We just read something, so we are supposed to write something, too */
1544 if (u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
)) {
1546 if (u
->sink
->thread_info
.rewind_requested
)
1547 pa_sink_process_rewind(u
->sink
, 0);
1550 if (pollfd
->revents
& POLLOUT
)
1553 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1554 pa_usec_t time_passed
;
1555 pa_usec_t audio_sent
;
1557 /* Hmm, there is no input stream we could synchronize
1558 * to. So let's do things by time */
1560 time_passed
= pa_rtclock_now() - u
->started_at
;
1561 audio_sent
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1563 if (audio_sent
<= time_passed
) {
1564 pa_usec_t audio_to_send
= time_passed
- audio_sent
;
1566 /* Never try to catch up for more than 100ms */
1567 if (u
->write_index
> 0 && audio_to_send
> MAX_PLAYBACK_CATCH_UP_USEC
) {
1568 pa_usec_t skip_usec
;
1569 uint64_t skip_bytes
;
1571 skip_usec
= audio_to_send
- MAX_PLAYBACK_CATCH_UP_USEC
;
1572 skip_bytes
= pa_usec_to_bytes(skip_usec
, &u
->sample_spec
);
1574 if (skip_bytes
> 0) {
1577 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1578 (unsigned long long) skip_usec
,
1579 (unsigned long long) skip_bytes
);
1581 pa_sink_render_full(u
->sink
, skip_bytes
, &tmp
);
1582 pa_memblock_unref(tmp
.memblock
);
1583 u
->write_index
+= skip_bytes
;
1591 if (writable
&& do_write
> 0) {
1594 if (u
->write_index
<= 0)
1595 u
->started_at
= pa_rtclock_now();
1597 if (u
->profile
== PROFILE_A2DP
) {
1598 if ((n_written
= a2dp_process_render(u
)) < 0)
1601 if ((n_written
= hsp_process_render(u
)) < 0)
1606 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1608 do_write
-= n_written
;
1612 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1613 pa_usec_t time_passed
, next_write_at
, sleep_for
;
1615 /* Hmm, there is no input stream we could synchronize
1616 * to. So let's estimate when we need to wake up the latest */
1618 time_passed
= pa_rtclock_now() - u
->started_at
;
1619 next_write_at
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1620 sleep_for
= time_passed
< next_write_at
? next_write_at
- time_passed
: 0;
1622 /* 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); */
1624 pa_rtpoll_set_timer_relative(u
->rtpoll
, sleep_for
);
1625 disable_timer
= FALSE
;
1631 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
1633 /* Hmm, nothing to do. Let's sleep */
1635 pollfd
->events
= (short) (((u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
) && !writable
) ? POLLOUT
: 0) |
1636 (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
) ? POLLIN
: 0));
1638 if ((ret
= pa_rtpoll_run(u
->rtpoll
, TRUE
)) < 0)
1644 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1646 if (pollfd
&& (pollfd
->revents
& ~(POLLOUT
|POLLIN
))) {
1647 pa_log_info("FD error: %s%s%s%s",
1648 pollfd
->revents
& POLLERR
? "POLLERR " :"",
1649 pollfd
->revents
& POLLHUP
? "POLLHUP " :"",
1650 pollfd
->revents
& POLLPRI
? "POLLPRI " :"",
1651 pollfd
->revents
& POLLNVAL
? "POLLNVAL " :"");
1657 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1658 pa_log_debug("IO thread failed");
1659 pa_asyncmsgq_post(u
->thread_mq
.outq
, PA_MSGOBJECT(u
->core
), PA_CORE_MESSAGE_UNLOAD_MODULE
, u
->module
, 0, NULL
, NULL
);
1660 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1663 pa_log_debug("IO thread shutting down");
1666 /* Run from main thread */
1667 static DBusHandlerResult
filter_cb(DBusConnection
*bus
, DBusMessage
*m
, void *userdata
) {
1673 pa_assert_se(u
= userdata
);
1675 dbus_error_init(&err
);
1677 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1678 dbus_message_get_interface(m
),
1679 dbus_message_get_path(m
),
1680 dbus_message_get_member(m
));
1682 if (!dbus_message_has_path(m
, u
->path
))
1685 if (dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged") ||
1686 dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1691 if (!dbus_message_get_args(m
, &err
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
) || gain
> 15) {
1692 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err
.message
);
1696 if (u
->profile
== PROFILE_HSP
) {
1697 if (u
->sink
&& dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged")) {
1699 pa_cvolume_set(&v
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1700 pa_sink_volume_changed(u
->sink
, &v
);
1702 } else if (u
->source
&& dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1704 pa_cvolume_set(&v
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1705 pa_source_volume_changed(u
->source
, &v
);
1711 dbus_error_free(&err
);
1713 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1716 /* Run from main thread */
1717 static void sink_set_volume_cb(pa_sink
*s
) {
1718 struct userdata
*u
= s
->userdata
;
1724 if (u
->profile
!= PROFILE_HSP
)
1727 gain
= (pa_cvolume_max(&s
->real_volume
) * 15) / PA_VOLUME_NORM
;
1732 pa_cvolume_set(&s
->real_volume
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1734 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetSpeakerGain"));
1735 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1736 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1737 dbus_message_unref(m
);
1740 /* Run from main thread */
1741 static void source_set_volume_cb(pa_source
*s
) {
1742 struct userdata
*u
= s
->userdata
;
1748 if (u
->profile
!= PROFILE_HSP
)
1751 gain
= (pa_cvolume_max(&s
->volume
) * 15) / PA_VOLUME_NORM
;
1756 pa_cvolume_set(&s
->volume
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1758 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetMicrophoneGain"));
1759 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1760 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1761 dbus_message_unref(m
);
1764 /* Run from main thread */
1765 static char *get_name(const char *type
, pa_modargs
*ma
, const char *device_id
, pa_bool_t
*namereg_fail
) {
1771 pa_assert(device_id
);
1772 pa_assert(namereg_fail
);
1774 t
= pa_sprintf_malloc("%s_name", type
);
1775 n
= pa_modargs_get_value(ma
, t
, NULL
);
1779 *namereg_fail
= TRUE
;
1780 return pa_xstrdup(n
);
1783 if ((n
= pa_modargs_get_value(ma
, "name", NULL
)))
1784 *namereg_fail
= TRUE
;
1787 *namereg_fail
= FALSE
;
1790 return pa_sprintf_malloc("bluez_%s.%s", type
, n
);
1795 static void sco_over_pcm_state_update(struct userdata
*u
) {
1797 pa_assert(USE_SCO_OVER_PCM(u
));
1799 if (PA_SINK_IS_OPENED(pa_sink_get_state(u
->hsp
.sco_sink
)) ||
1800 PA_SOURCE_IS_OPENED(pa_source_get_state(u
->hsp
.sco_source
))) {
1802 if (u
->service_fd
>= 0)
1807 pa_log_debug("Resuming SCO over PCM");
1808 if (init_profile(u
) < 0)
1809 pa_log("Can't resume SCO over PCM");
1812 bt_transport_acquire(u
, TRUE
);
1817 if (u
->service_fd
< 0)
1821 bt_transport_release(u
);
1825 pa_log_debug("Closing SCO over PCM");
1826 pa_close(u
->service_fd
);
1831 static pa_hook_result_t
sink_state_changed_cb(pa_core
*c
, pa_sink
*s
, struct userdata
*u
) {
1833 pa_sink_assert_ref(s
);
1836 if (s
!= u
->hsp
.sco_sink
)
1839 sco_over_pcm_state_update(u
);
1844 static pa_hook_result_t
source_state_changed_cb(pa_core
*c
, pa_source
*s
, struct userdata
*u
) {
1846 pa_source_assert_ref(s
);
1849 if (s
!= u
->hsp
.sco_source
)
1852 sco_over_pcm_state_update(u
);
1859 /* Run from main thread */
1860 static int add_sink(struct userdata
*u
) {
1863 if (USE_SCO_OVER_PCM(u
)) {
1866 u
->sink
= u
->hsp
.sco_sink
;
1867 p
= pa_proplist_new();
1868 pa_proplist_sets(p
, "bluetooth.protocol", "sco");
1869 pa_proplist_update(u
->sink
->proplist
, PA_UPDATE_MERGE
, p
);
1870 pa_proplist_free(p
);
1872 if (!u
->hsp
.sink_state_changed_slot
)
1873 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
);
1879 pa_sink_new_data data
;
1882 pa_sink_new_data_init(&data
);
1883 data
.driver
= __FILE__
;
1884 data
.module
= u
->module
;
1885 pa_sink_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1886 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", u
->profile
== PROFILE_A2DP
? "a2dp" : "sco");
1887 if (u
->profile
== PROFILE_HSP
)
1888 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1889 data
.card
= u
->card
;
1890 data
.name
= get_name("sink", u
->modargs
, u
->address
, &b
);
1891 data
.namereg_fail
= b
;
1893 if (pa_modargs_get_proplist(u
->modargs
, "sink_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1894 pa_log("Invalid properties");
1895 pa_sink_new_data_done(&data
);
1899 u
->sink
= pa_sink_new(u
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
| (u
->profile
== PROFILE_HSP
? PA_SINK_HW_VOLUME_CTRL
: 0));
1900 pa_sink_new_data_done(&data
);
1903 pa_log_error("Failed to create sink");
1907 u
->sink
->userdata
= u
;
1908 u
->sink
->parent
.process_msg
= sink_process_msg
;
1910 pa_sink_set_max_request(u
->sink
, u
->block_size
);
1911 pa_sink_set_fixed_latency(u
->sink
,
1912 (u
->profile
== PROFILE_A2DP
? FIXED_LATENCY_PLAYBACK_A2DP
: FIXED_LATENCY_PLAYBACK_HSP
) +
1913 pa_bytes_to_usec(u
->block_size
, &u
->sample_spec
));
1916 if (u
->profile
== PROFILE_HSP
) {
1917 u
->sink
->set_volume
= sink_set_volume_cb
;
1918 u
->sink
->n_volume_steps
= 16;
1924 /* Run from main thread */
1925 static int add_source(struct userdata
*u
) {
1928 if (USE_SCO_OVER_PCM(u
)) {
1929 u
->source
= u
->hsp
.sco_source
;
1930 pa_proplist_sets(u
->source
->proplist
, "bluetooth.protocol", "hsp");
1932 if (!u
->hsp
.source_state_changed_slot
)
1933 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
);
1939 pa_source_new_data data
;
1942 pa_source_new_data_init(&data
);
1943 data
.driver
= __FILE__
;
1944 data
.module
= u
->module
;
1945 pa_source_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1946 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", u
->profile
== PROFILE_A2DP_SOURCE
? "a2dp_source" : "hsp");
1947 if ((u
->profile
== PROFILE_HSP
) || (u
->profile
== PROFILE_HFGW
))
1948 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_INTENDED_ROLES
, "phone");
1949 data
.card
= u
->card
;
1950 data
.name
= get_name("source", u
->modargs
, u
->address
, &b
);
1951 data
.namereg_fail
= b
;
1953 if (pa_modargs_get_proplist(u
->modargs
, "source_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
1954 pa_log("Invalid properties");
1955 pa_source_new_data_done(&data
);
1959 u
->source
= pa_source_new(u
->core
, &data
, PA_SOURCE_HARDWARE
|PA_SOURCE_LATENCY
| (u
->profile
== PROFILE_HSP
? PA_SOURCE_HW_VOLUME_CTRL
: 0));
1960 pa_source_new_data_done(&data
);
1963 pa_log_error("Failed to create source");
1967 u
->source
->userdata
= u
;
1968 u
->source
->parent
.process_msg
= source_process_msg
;
1970 pa_source_set_fixed_latency(u
->source
,
1971 (u
->profile
== PROFILE_A2DP_SOURCE
? FIXED_LATENCY_RECORD_A2DP
: FIXED_LATENCY_RECORD_HSP
) +
1972 pa_bytes_to_usec(u
->block_size
, &u
->sample_spec
));
1975 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
)
1976 pa_proplist_sets(u
->source
->proplist
, "bluetooth.nrec", (u
->hsp
.pcm_capabilities
.flags
& BT_PCM_FLAG_NREC
) ? "1" : "0");
1978 if (u
->profile
== PROFILE_HSP
) {
1979 u
->source
->set_volume
= source_set_volume_cb
;
1980 u
->source
->n_volume_steps
= 16;
1986 /* Run from main thread */
1987 static void shutdown_bt(struct userdata
*u
) {
1990 if (u
->stream_fd
>= 0) {
1991 pa_close(u
->stream_fd
);
1994 u
->stream_write_type
= 0;
1997 if (u
->service_fd
>= 0) {
1998 pa_close(u
->service_fd
);
2000 u
->service_write_type
= 0;
2001 u
->service_read_type
= 0;
2004 if (u
->write_memchunk
.memblock
) {
2005 pa_memblock_unref(u
->write_memchunk
.memblock
);
2006 pa_memchunk_reset(&u
->write_memchunk
);
2010 static int bt_transport_config_a2dp(struct userdata
*u
)
2012 const pa_bluetooth_transport
*t
;
2013 struct a2dp_info
*a2dp
= &u
->a2dp
;
2014 sbc_capabilities_raw_t
*config
;
2016 t
= pa_bluetooth_discovery_get_transport(u
->discovery
, u
->transport
);
2019 config
= (sbc_capabilities_raw_t
*) t
->config
;
2021 if (a2dp
->sbc_initialized
)
2022 sbc_reinit(&a2dp
->sbc
, 0);
2024 sbc_init(&a2dp
->sbc
, 0);
2025 a2dp
->sbc_initialized
= TRUE
;
2027 switch (config
->frequency
) {
2028 case BT_SBC_SAMPLING_FREQ_16000
:
2029 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
2031 case BT_SBC_SAMPLING_FREQ_32000
:
2032 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
2034 case BT_SBC_SAMPLING_FREQ_44100
:
2035 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
2037 case BT_SBC_SAMPLING_FREQ_48000
:
2038 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
2041 pa_assert_not_reached();
2044 switch (config
->channel_mode
) {
2045 case BT_A2DP_CHANNEL_MODE_MONO
:
2046 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
2048 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
2049 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
2051 case BT_A2DP_CHANNEL_MODE_STEREO
:
2052 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
2054 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
2055 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
2058 pa_assert_not_reached();
2061 switch (config
->allocation_method
) {
2062 case BT_A2DP_ALLOCATION_SNR
:
2063 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
2065 case BT_A2DP_ALLOCATION_LOUDNESS
:
2066 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
2069 pa_assert_not_reached();
2072 switch (config
->subbands
) {
2073 case BT_A2DP_SUBBANDS_4
:
2074 a2dp
->sbc
.subbands
= SBC_SB_4
;
2076 case BT_A2DP_SUBBANDS_8
:
2077 a2dp
->sbc
.subbands
= SBC_SB_8
;
2080 pa_assert_not_reached();
2083 switch (config
->block_length
) {
2084 case BT_A2DP_BLOCK_LENGTH_4
:
2085 a2dp
->sbc
.blocks
= SBC_BLK_4
;
2087 case BT_A2DP_BLOCK_LENGTH_8
:
2088 a2dp
->sbc
.blocks
= SBC_BLK_8
;
2090 case BT_A2DP_BLOCK_LENGTH_12
:
2091 a2dp
->sbc
.blocks
= SBC_BLK_12
;
2093 case BT_A2DP_BLOCK_LENGTH_16
:
2094 a2dp
->sbc
.blocks
= SBC_BLK_16
;
2097 pa_assert_not_reached();
2100 a2dp
->sbc
.bitpool
= config
->max_bitpool
;
2101 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
2102 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
2105 ((u
->link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
2106 / a2dp
->frame_length
2109 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2110 a2dp
->sbc
.allocation
, a2dp
->sbc
.subbands
, a2dp
->sbc
.blocks
, a2dp
->sbc
.bitpool
);
2115 static int bt_transport_config(struct userdata
*u
)
2117 if (u
->profile
== PROFILE_HSP
|| u
->profile
== PROFILE_HFGW
) {
2118 u
->block_size
= u
->link_mtu
;
2122 return bt_transport_config_a2dp(u
);
2125 static int parse_transport_property(struct userdata
*u
, DBusMessageIter
*i
)
2128 DBusMessageIter variant_i
;
2133 if (dbus_message_iter_get_arg_type(i
) != DBUS_TYPE_STRING
) {
2134 pa_log("Property name not a string.");
2138 dbus_message_iter_get_basic(i
, &key
);
2140 if (!dbus_message_iter_next(i
)) {
2141 pa_log("Property value missing");
2145 if (dbus_message_iter_get_arg_type(i
) != DBUS_TYPE_VARIANT
) {
2146 pa_log("Property value not a variant.");
2150 dbus_message_iter_recurse(i
, &variant_i
);
2152 switch (dbus_message_iter_get_arg_type(&variant_i
)) {
2154 case DBUS_TYPE_UINT16
: {
2157 dbus_message_iter_get_basic(&variant_i
, &value
);
2159 if (pa_streq(key
, "OMTU"))
2160 u
->link_mtu
= value
;
2170 /* Run from main thread */
2171 static int bt_transport_open(struct userdata
*u
)
2174 DBusMessageIter arg_i
, element_i
;
2177 if (bt_transport_acquire(u
, FALSE
) < 0)
2180 dbus_error_init(&err
);
2182 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->transport
, "org.bluez.MediaTransport", "GetProperties"));
2183 r
= dbus_connection_send_with_reply_and_block(pa_dbus_connection_get(u
->connection
), m
, -1, &err
);
2185 if (dbus_error_is_set(&err
) || !r
) {
2186 pa_log("Failed to get transport properties: %s", err
.message
);
2190 if (!dbus_message_iter_init(r
, &arg_i
)) {
2191 pa_log("GetProperties reply has no arguments.");
2195 if (dbus_message_iter_get_arg_type(&arg_i
) != DBUS_TYPE_ARRAY
) {
2196 pa_log("GetProperties argument is not an array.");
2200 dbus_message_iter_recurse(&arg_i
, &element_i
);
2201 while (dbus_message_iter_get_arg_type(&element_i
) != DBUS_TYPE_INVALID
) {
2203 if (dbus_message_iter_get_arg_type(&element_i
) == DBUS_TYPE_DICT_ENTRY
) {
2204 DBusMessageIter dict_i
;
2206 dbus_message_iter_recurse(&element_i
, &dict_i
);
2208 parse_transport_property(u
, &dict_i
);
2211 if (!dbus_message_iter_next(&element_i
))
2215 return bt_transport_config(u
);
2218 dbus_message_unref(r
);
2222 /* Run from main thread */
2223 static int init_bt(struct userdata
*u
) {
2228 u
->stream_write_type
= 0;
2229 u
->service_write_type
= 0;
2230 u
->service_read_type
= 0;
2232 if ((u
->service_fd
= bt_audio_service_open()) < 0) {
2233 pa_log_warn("Bluetooth audio service not available");
2237 pa_log_debug("Connected to the bluetooth audio service");
2242 /* Run from main thread */
2243 static int setup_bt(struct userdata
*u
) {
2244 const pa_bluetooth_device
*d
;
2245 const pa_bluetooth_transport
*t
;
2249 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
))) {
2250 pa_log_error("Failed to get device object.");
2254 /* release transport if exist */
2256 bt_transport_release(u
);
2257 pa_xfree(u
->transport
);
2258 u
->transport
= NULL
;
2261 /* check if profile has a transport */
2262 t
= pa_bluetooth_device_get_transport(d
, u
->profile
);
2264 u
->transport
= pa_xstrdup(t
->path
);
2265 return bt_transport_open(u
);
2268 if (get_caps(u
, 0) < 0)
2271 pa_log_debug("Got device capabilities");
2273 if (set_conf(u
) < 0)
2276 pa_log_debug("Connection to the device configured");
2279 if (USE_SCO_OVER_PCM(u
)) {
2280 pa_log_debug("Configured to use SCO over PCM");
2285 pa_log_debug("Got the stream socket");
2290 /* Run from main thread */
2291 static int init_profile(struct userdata
*u
) {
2294 pa_assert(u
->profile
!= PROFILE_OFF
);
2296 if (setup_bt(u
) < 0)
2299 if (u
->profile
== PROFILE_A2DP
||
2300 u
->profile
== PROFILE_HSP
||
2301 u
->profile
== PROFILE_HFGW
)
2302 if (add_sink(u
) < 0)
2305 if (u
->profile
== PROFILE_HSP
||
2306 u
->profile
== PROFILE_A2DP_SOURCE
||
2307 u
->profile
== PROFILE_HFGW
)
2308 if (add_source(u
) < 0)
2314 /* Run from main thread */
2315 static void stop_thread(struct userdata
*u
) {
2319 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
2320 pa_thread_free(u
->thread
);
2324 if (u
->rtpoll_item
) {
2325 pa_rtpoll_item_free(u
->rtpoll_item
);
2326 u
->rtpoll_item
= NULL
;
2329 if (u
->hsp
.sink_state_changed_slot
) {
2330 pa_hook_slot_free(u
->hsp
.sink_state_changed_slot
);
2331 u
->hsp
.sink_state_changed_slot
= NULL
;
2334 if (u
->hsp
.source_state_changed_slot
) {
2335 pa_hook_slot_free(u
->hsp
.source_state_changed_slot
);
2336 u
->hsp
.source_state_changed_slot
= NULL
;
2340 pa_sink_unref(u
->sink
);
2345 pa_source_unref(u
->source
);
2350 pa_thread_mq_done(&u
->thread_mq
);
2352 pa_rtpoll_free(u
->rtpoll
);
2356 if (u
->read_smoother
) {
2357 pa_smoother_free(u
->read_smoother
);
2358 u
->read_smoother
= NULL
;
2362 /* Run from main thread */
2363 static int start_thread(struct userdata
*u
) {
2365 pa_assert(!u
->thread
);
2366 pa_assert(!u
->rtpoll
);
2367 pa_assert(!u
->rtpoll_item
);
2369 u
->rtpoll
= pa_rtpoll_new();
2370 pa_thread_mq_init(&u
->thread_mq
, u
->core
->mainloop
, u
->rtpoll
);
2373 if (USE_SCO_OVER_PCM(u
)) {
2375 if (bt_transport_acquire(u
, TRUE
) < 0)
2377 } else if (start_stream_fd(u
) < 0)
2380 pa_sink_ref(u
->sink
);
2381 pa_source_ref(u
->source
);
2382 /* FIXME: monitor stream_fd error */
2387 if (!(u
->thread
= pa_thread_new("bluetooth", thread_func
, u
))) {
2388 pa_log_error("Failed to create IO thread");
2394 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
2395 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
2396 pa_sink_put(u
->sink
);
2398 if (u
->sink
->set_volume
)
2399 u
->sink
->set_volume(u
->sink
);
2403 pa_source_set_asyncmsgq(u
->source
, u
->thread_mq
.inq
);
2404 pa_source_set_rtpoll(u
->source
, u
->rtpoll
);
2405 pa_source_put(u
->source
);
2407 if (u
->source
->set_volume
)
2408 u
->source
->set_volume(u
->source
);
2414 /* Run from main thread */
2415 static int card_set_profile(pa_card
*c
, pa_card_profile
*new_profile
) {
2418 pa_queue
*inputs
= NULL
, *outputs
= NULL
;
2419 const pa_bluetooth_device
*device
;
2422 pa_assert(new_profile
);
2423 pa_assert_se(u
= c
->userdata
);
2425 d
= PA_CARD_PROFILE_DATA(new_profile
);
2427 if (!(device
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
))) {
2428 pa_log_error("Failed to get device object.");
2432 /* The state signal is sent by bluez, so it is racy to check
2433 strictly for CONNECTED, we should also accept STREAMING state
2434 as being good enough. However, if the profile is used
2435 concurrently (which is unlikely), ipc will fail later on, and
2436 module will be unloaded. */
2437 if (device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) {
2438 pa_log_warn("HSP is not connected, refused to switch profile");
2441 else if (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) {
2442 pa_log_warn("A2DP is not connected, refused to switch profile");
2445 else if (device
->hfgw_state
<= PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
) {
2446 pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2451 inputs
= pa_sink_move_all_start(u
->sink
, NULL
);
2453 if (!USE_SCO_OVER_PCM(u
))
2455 pa_sink_unlink(u
->sink
);
2459 outputs
= pa_source_move_all_start(u
->source
, NULL
);
2461 if (!USE_SCO_OVER_PCM(u
))
2463 pa_source_unlink(u
->source
);
2470 u
->sample_spec
= u
->requested_sample_spec
;
2474 if (u
->profile
!= PROFILE_OFF
)
2477 if (u
->sink
|| u
->source
)
2482 pa_sink_move_all_finish(u
->sink
, inputs
, FALSE
);
2484 pa_sink_move_all_fail(inputs
);
2489 pa_source_move_all_finish(u
->source
, outputs
, FALSE
);
2491 pa_source_move_all_fail(outputs
);
2497 /* Run from main thread */
2498 static int add_card(struct userdata
*u
, const pa_bluetooth_device
*device
) {
2499 pa_card_new_data data
;
2505 const char *default_profile
;
2510 pa_card_new_data_init(&data
);
2511 data
.driver
= __FILE__
;
2512 data
.module
= u
->module
;
2514 n
= pa_bluetooth_cleanup_name(device
->name
);
2515 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_DESCRIPTION
, n
);
2517 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, device
->address
);
2518 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_API
, "bluez");
2519 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_CLASS
, "sound");
2520 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_BUS
, "bluetooth");
2521 if ((ff
= pa_bluetooth_get_form_factor(device
->class)))
2522 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_FORM_FACTOR
, ff
);
2523 pa_proplist_sets(data
.proplist
, "bluez.path", device
->path
);
2524 pa_proplist_setf(data
.proplist
, "bluez.class", "0x%06x", (unsigned) device
->class);
2525 pa_proplist_sets(data
.proplist
, "bluez.name", device
->name
);
2526 data
.name
= get_name("card", u
->modargs
, device
->address
, &b
);
2527 data
.namereg_fail
= b
;
2529 if (pa_modargs_get_proplist(u
->modargs
, "card_properties", data
.proplist
, PA_UPDATE_REPLACE
) < 0) {
2530 pa_log("Invalid properties");
2531 pa_card_new_data_done(&data
);
2535 data
.profiles
= pa_hashmap_new(pa_idxset_string_hash_func
, pa_idxset_string_compare_func
);
2537 /* we base hsp/a2dp availability on UUIDs.
2538 Ideally, it would be based on "Connected" state, but
2539 we can't afford to wait for this information when
2540 we are loaded with profile="hsp", for instance */
2541 if (pa_bluetooth_uuid_has(device
->uuids
, A2DP_SINK_UUID
)) {
2542 p
= pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile
));
2546 p
->max_sink_channels
= 2;
2547 p
->max_source_channels
= 0;
2549 d
= PA_CARD_PROFILE_DATA(p
);
2552 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2555 if (pa_bluetooth_uuid_has(device
->uuids
, A2DP_SOURCE_UUID
)) {
2556 p
= pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile
));
2560 p
->max_sink_channels
= 0;
2561 p
->max_source_channels
= 2;
2563 d
= PA_CARD_PROFILE_DATA(p
);
2564 *d
= PROFILE_A2DP_SOURCE
;
2566 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2569 if (pa_bluetooth_uuid_has(device
->uuids
, HSP_HS_UUID
) ||
2570 pa_bluetooth_uuid_has(device
->uuids
, HFP_HS_UUID
)) {
2571 p
= pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile
));
2575 p
->max_sink_channels
= 1;
2576 p
->max_source_channels
= 1;
2578 d
= PA_CARD_PROFILE_DATA(p
);
2581 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2584 if (pa_bluetooth_uuid_has(device
->uuids
, HFP_AG_UUID
)) {
2585 p
= pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile
));
2589 p
->max_sink_channels
= 1;
2590 p
->max_source_channels
= 1;
2592 d
= PA_CARD_PROFILE_DATA(p
);
2595 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2598 pa_assert(!pa_hashmap_isempty(data
.profiles
));
2600 p
= pa_card_profile_new("off", _("Off"), sizeof(enum profile
));
2601 d
= PA_CARD_PROFILE_DATA(p
);
2603 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2605 if ((default_profile
= pa_modargs_get_value(u
->modargs
, "profile", NULL
))) {
2606 if (pa_hashmap_get(data
.profiles
, default_profile
))
2607 pa_card_new_data_set_profile(&data
, default_profile
);
2609 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile
);
2612 u
->card
= pa_card_new(u
->core
, &data
);
2613 pa_card_new_data_done(&data
);
2616 pa_log("Failed to allocate card.");
2620 u
->card
->userdata
= u
;
2621 u
->card
->set_profile
= card_set_profile
;
2623 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2625 if ((device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) ||
2626 (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) ||
2627 (device
->hfgw_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HFGW
)) {
2628 pa_log_warn("Default profile not connected, selecting off profile");
2629 u
->card
->active_profile
= pa_hashmap_get(u
->card
->profiles
, "off");
2630 u
->card
->save_profile
= FALSE
;
2633 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2639 /* Run from main thread */
2640 static const pa_bluetooth_device
* find_device(struct userdata
*u
, const char *address
, const char *path
) {
2641 const pa_bluetooth_device
*d
= NULL
;
2645 if (!address
&& !path
) {
2646 pa_log_error("Failed to get device address/path from module arguments.");
2651 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, path
))) {
2652 pa_log_error("%s is not a valid BlueZ audio device.", path
);
2656 if (address
&& !(pa_streq(d
->address
, address
))) {
2657 pa_log_error("Passed path %s address %s != %s don't match.", path
, d
->address
, address
);
2662 if (!(d
= pa_bluetooth_discovery_get_by_address(u
->discovery
, address
))) {
2663 pa_log_error("%s is not known.", address
);
2669 u
->address
= pa_xstrdup(d
->address
);
2670 u
->path
= pa_xstrdup(d
->path
);
2676 /* Run from main thread */
2677 static int setup_dbus(struct userdata
*u
) {
2680 dbus_error_init(&err
);
2682 u
->connection
= pa_dbus_bus_get(u
->core
, DBUS_BUS_SYSTEM
, &err
);
2684 if (dbus_error_is_set(&err
) || !u
->connection
) {
2685 pa_log("Failed to get D-Bus connection: %s", err
.message
);
2686 dbus_error_free(&err
);
2693 int pa__init(pa_module
* m
) {
2697 const char *address
, *path
;
2699 char *mike
, *speaker
;
2700 const pa_bluetooth_device
*device
;
2704 dbus_error_init(&err
);
2706 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
2707 pa_log_error("Failed to parse module arguments");
2711 m
->userdata
= u
= pa_xnew0(struct userdata
, 1);
2716 u
->sample_spec
= m
->core
->default_sample_spec
;
2720 if (pa_modargs_get_value(ma
, "sco_sink", NULL
) &&
2721 !(u
->hsp
.sco_sink
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_sink", NULL
), PA_NAMEREG_SINK
))) {
2722 pa_log("SCO sink not found");
2726 if (pa_modargs_get_value(ma
, "sco_source", NULL
) &&
2727 !(u
->hsp
.sco_source
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_source", NULL
), PA_NAMEREG_SOURCE
))) {
2728 pa_log("SCO source not found");
2733 if (pa_modargs_get_value_u32(ma
, "rate", &u
->sample_spec
.rate
) < 0 ||
2734 u
->sample_spec
.rate
<= 0 || u
->sample_spec
.rate
> PA_RATE_MAX
) {
2735 pa_log_error("Failed to get rate from module arguments");
2739 u
->auto_connect
= TRUE
;
2740 if (pa_modargs_get_value_boolean(ma
, "auto_connect", &u
->auto_connect
)) {
2741 pa_log("Failed to parse auto_connect= argument");
2745 channels
= u
->sample_spec
.channels
;
2746 if (pa_modargs_get_value_u32(ma
, "channels", &channels
) < 0 ||
2747 channels
<= 0 || channels
> PA_CHANNELS_MAX
) {
2748 pa_log_error("Failed to get channels from module arguments");
2751 u
->sample_spec
.channels
= (uint8_t) channels
;
2752 u
->requested_sample_spec
= u
->sample_spec
;
2754 address
= pa_modargs_get_value(ma
, "address", NULL
);
2755 path
= pa_modargs_get_value(ma
, "path", NULL
);
2757 if (setup_dbus(u
) < 0)
2760 if (!(u
->discovery
= pa_bluetooth_discovery_get(m
->core
)))
2763 if (!(device
= find_device(u
, address
, path
)))
2766 /* Add the card structure. This will also initialize the default profile */
2767 if (add_card(u
, device
) < 0)
2770 if (!dbus_connection_add_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
, NULL
)) {
2771 pa_log_error("Failed to add filter function");
2774 u
->filter_added
= TRUE
;
2776 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2777 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2779 if (pa_dbus_add_matches(
2780 pa_dbus_connection_get(u
->connection
), &err
,
2788 pa_log("Failed to add D-Bus matches: %s", err
.message
);
2795 /* Connect to the BT service */
2798 if (u
->profile
!= PROFILE_OFF
)
2799 if (init_profile(u
) < 0)
2802 if (u
->sink
|| u
->source
)
2803 if (start_thread(u
) < 0)
2812 dbus_error_free(&err
);
2817 int pa__get_n_used(pa_module
*m
) {
2821 pa_assert_se(u
= m
->userdata
);
2824 (u
->sink
? pa_sink_linked_by(u
->sink
) : 0) +
2825 (u
->source
? pa_source_linked_by(u
->source
) : 0);
2828 void pa__done(pa_module
*m
) {
2832 if (!(u
= m
->userdata
))
2837 && !USE_SCO_OVER_PCM(u
)
2840 pa_sink_unlink(u
->sink
);
2844 && !USE_SCO_OVER_PCM(u
)
2847 pa_source_unlink(u
->source
);
2851 if (u
->connection
) {
2854 char *speaker
, *mike
;
2855 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2856 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2858 pa_dbus_remove_matches(pa_dbus_connection_get(u
->connection
),
2867 if (u
->filter_added
)
2868 dbus_connection_remove_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
);
2870 pa_dbus_connection_unref(u
->connection
);
2874 pa_card_free(u
->card
);
2876 if (u
->read_smoother
)
2877 pa_smoother_free(u
->read_smoother
);
2882 pa_xfree(u
->a2dp
.buffer
);
2884 sbc_finish(&u
->a2dp
.sbc
);
2887 pa_modargs_free(u
->modargs
);
2889 pa_xfree(u
->address
);
2893 bt_transport_release(u
);
2894 pa_xfree(u
->transport
);
2898 pa_bluetooth_discovery_unref(u
->discovery
);