2 This file is part of PulseAudio.
4 Copyright 2008 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
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulse/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.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/rtpoll.h>
46 #include <pulsecore/time-smoother.h>
47 #include <pulsecore/rtclock.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
51 #include "module-bluetooth-device-symdef.h"
55 #include "bluetooth-util.h"
57 #define MAX_BITPOOL 64
58 #define MIN_BITPOOL 2U
60 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
61 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
62 PA_MODULE_VERSION(PACKAGE_VERSION
);
63 PA_MODULE_LOAD_ONCE(FALSE
);
65 "name=<name for the card/sink/source, to be prefixed> "
66 "card_name=<name for the card> "
67 "sink_name=<name for the sink> "
68 "source_name=<name for the source> "
69 "address=<address of the device> "
72 "channels=<number of channels> "
73 "path=<device object path>");
77 "sco_sink=<SCO over PCM sink name> "
78 "sco_source=<SCO over PCM source name>"
82 /* TODO: not close fd when entering suspend mode in a2dp */
84 static const char* const valid_modargs
[] = {
102 sbc_capabilities_t sbc_capabilities
;
103 sbc_t sbc
; /* Codec data */
104 pa_bool_t sbc_initialized
; /* Keep track if the encoder is initialized */
105 size_t codesize
, frame_length
; /* SBC Codesize, frame_length. We simply cache those values here */
107 void* buffer
; /* Codec transfer buffer */
108 size_t buffer_size
; /* Size of the buffer */
110 uint16_t seq_num
; /* Cumulative packet sequence */
114 pcm_capabilities_t pcm_capabilities
;
117 pa_source
*sco_source
;
119 pa_hook_slot
*sink_state_changed_slot
;
120 pa_hook_slot
*source_state_changed_slot
;
135 pa_bluetooth_discovery
*discovery
;
137 pa_dbus_connection
*connection
;
143 pa_thread_mq thread_mq
;
145 pa_rtpoll_item
*rtpoll_item
;
148 uint64_t read_index
, write_index
;
149 pa_usec_t started_at
;
150 pa_smoother
*read_smoother
;
152 pa_memchunk write_memchunk
;
154 pa_sample_spec sample_spec
, requested_sample_spec
;
162 struct a2dp_info a2dp
;
165 enum profile profile
;
169 int stream_write_type
;
170 int service_write_type
, service_read_type
;
173 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
174 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
175 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
178 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
181 static int init_bt(struct userdata
*u
);
182 static int init_profile(struct userdata
*u
);
184 static int service_send(struct userdata
*u
, const bt_audio_msg_header_t
*msg
) {
188 pa_assert(u
->service_fd
>= 0);
190 pa_assert(msg
->length
> 0);
192 pa_log_debug("Sending %s -> %s",
193 pa_strnull(bt_audio_strtype(msg
->type
)),
194 pa_strnull(bt_audio_strname(msg
->name
)));
196 if ((r
= pa_loop_write(u
->service_fd
, msg
, msg
->length
, &u
->service_write_type
)) == (ssize_t
) msg
->length
)
200 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno
));
202 pa_log_error("Short write()");
207 static int service_recv(struct userdata
*u
, bt_audio_msg_header_t
*msg
, size_t room
) {
211 pa_assert(u
->service_fd
>= 0);
215 room
= BT_SUGGESTED_BUFFER_SIZE
;
217 pa_log_debug("Trying to receive message from audio service...");
219 /* First, read the header */
220 if ((r
= pa_loop_read(u
->service_fd
, msg
, sizeof(*msg
), &u
->service_read_type
)) != sizeof(*msg
))
223 if (msg
->length
< sizeof(*msg
)) {
224 pa_log_error("Invalid message size.");
228 /* Secondly, read the payload */
229 if (msg
->length
> sizeof(*msg
)) {
231 size_t remains
= msg
->length
- sizeof(*msg
);
233 if ((r
= pa_loop_read(u
->service_fd
,
234 (uint8_t*) msg
+ sizeof(*msg
),
236 &u
->service_read_type
)) != (ssize_t
) remains
)
240 pa_log_debug("Received %s <- %s",
241 pa_strnull(bt_audio_strtype(msg
->type
)),
242 pa_strnull(bt_audio_strname(msg
->name
)));
249 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno
));
251 pa_log_error("Short read()");
256 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
) {
260 pa_assert(u
->service_fd
>= 0);
263 if ((r
= service_recv(u
, rsp
, room
)) < 0)
266 if ((rsp
->type
!= BT_INDICATION
&& rsp
->type
!= BT_RESPONSE
) ||
267 rsp
->name
!= expected_name
||
268 (expected_size
> 0 && rsp
->length
!= expected_size
)) {
270 if (rsp
->type
== BT_ERROR
&& rsp
->length
== sizeof(bt_audio_error_t
))
271 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t
*) rsp
)->posix_errno
));
273 pa_log_error("Bogus message %s received while %s was expected",
274 pa_strnull(bt_audio_strname(rsp
->name
)),
275 pa_strnull(bt_audio_strname(expected_name
)));
282 /* Run from main thread */
283 static int parse_caps(struct userdata
*u
, uint8_t seid
, const struct bt_get_capabilities_rsp
*rsp
) {
285 const codec_capabilities_t
*codec
;
290 bytes_left
= rsp
->h
.length
- sizeof(*rsp
);
292 if (bytes_left
< sizeof(codec_capabilities_t
)) {
293 pa_log_error("Packet too small to store codec information.");
297 codec
= (codec_capabilities_t
*) rsp
->data
; /** ALIGNMENT? **/
299 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left
, (unsigned long) sizeof(*codec
));
301 if ((u
->profile
== PROFILE_A2DP
&& codec
->transport
!= BT_CAPABILITIES_TRANSPORT_A2DP
) ||
302 (u
->profile
== PROFILE_HSP
&& codec
->transport
!= BT_CAPABILITIES_TRANSPORT_SCO
)) {
303 pa_log_error("Got capabilities for wrong codec.");
307 if (u
->profile
== PROFILE_HSP
) {
309 if (bytes_left
<= 0 || codec
->length
!= sizeof(u
->hsp
.pcm_capabilities
))
312 pa_assert(codec
->type
== BT_HFP_CODEC_PCM
);
314 if (codec
->configured
&& seid
== 0)
317 memcpy(&u
->hsp
.pcm_capabilities
, codec
, sizeof(u
->hsp
.pcm_capabilities
));
319 } else if (u
->profile
== PROFILE_A2DP
) {
321 while (bytes_left
> 0) {
322 if ((codec
->type
== BT_A2DP_SBC_SINK
) && !codec
->lock
)
325 bytes_left
-= codec
->length
;
326 codec
= (const codec_capabilities_t
*) ((const uint8_t*) codec
+ codec
->length
);
329 if (bytes_left
<= 0 || codec
->length
!= sizeof(u
->a2dp
.sbc_capabilities
))
332 pa_assert(codec
->type
== BT_A2DP_SBC_SINK
);
334 if (codec
->configured
&& seid
== 0)
337 memcpy(&u
->a2dp
.sbc_capabilities
, codec
, sizeof(u
->a2dp
.sbc_capabilities
));
343 /* Run from main thread */
344 static int get_caps(struct userdata
*u
, uint8_t seid
) {
346 struct bt_get_capabilities_req getcaps_req
;
347 struct bt_get_capabilities_rsp getcaps_rsp
;
348 bt_audio_error_t error
;
349 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
355 memset(&msg
, 0, sizeof(msg
));
356 msg
.getcaps_req
.h
.type
= BT_REQUEST
;
357 msg
.getcaps_req
.h
.name
= BT_GET_CAPABILITIES
;
358 msg
.getcaps_req
.h
.length
= sizeof(msg
.getcaps_req
);
359 msg
.getcaps_req
.seid
= seid
;
361 pa_strlcpy(msg
.getcaps_req
.object
, u
->path
, sizeof(msg
.getcaps_req
.object
));
362 if (u
->profile
== PROFILE_A2DP
)
363 msg
.getcaps_req
.transport
= BT_CAPABILITIES_TRANSPORT_A2DP
;
365 pa_assert(u
->profile
== PROFILE_HSP
);
366 msg
.getcaps_req
.transport
= BT_CAPABILITIES_TRANSPORT_SCO
;
368 msg
.getcaps_req
.flags
= BT_FLAG_AUTOCONNECT
;
370 if (service_send(u
, &msg
.getcaps_req
.h
) < 0)
373 if (service_expect(u
, &msg
.getcaps_rsp
.h
, sizeof(msg
), BT_GET_CAPABILITIES
, 0) < 0)
376 ret
= parse_caps(u
, seid
, &msg
.getcaps_rsp
);
380 return get_caps(u
, ret
);
383 /* Run from main thread */
384 static uint8_t a2dp_default_bitpool(uint8_t freq
, uint8_t mode
) {
387 case BT_SBC_SAMPLING_FREQ_16000
:
388 case BT_SBC_SAMPLING_FREQ_32000
:
391 case BT_SBC_SAMPLING_FREQ_44100
:
394 case BT_A2DP_CHANNEL_MODE_MONO
:
395 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
398 case BT_A2DP_CHANNEL_MODE_STEREO
:
399 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
403 pa_log_warn("Invalid channel mode %u", mode
);
407 case BT_SBC_SAMPLING_FREQ_48000
:
410 case BT_A2DP_CHANNEL_MODE_MONO
:
411 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
414 case BT_A2DP_CHANNEL_MODE_STEREO
:
415 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
419 pa_log_warn("Invalid channel mode %u", mode
);
424 pa_log_warn("Invalid sampling freq %u", freq
);
429 /* Run from main thread */
430 static int setup_a2dp(struct userdata
*u
) {
431 sbc_capabilities_t
*cap
;
434 static const struct {
438 { 16000U, BT_SBC_SAMPLING_FREQ_16000
},
439 { 32000U, BT_SBC_SAMPLING_FREQ_32000
},
440 { 44100U, BT_SBC_SAMPLING_FREQ_44100
},
441 { 48000U, BT_SBC_SAMPLING_FREQ_48000
}
445 pa_assert(u
->profile
== PROFILE_A2DP
);
447 cap
= &u
->a2dp
.sbc_capabilities
;
449 /* Find the lowest freq that is at least as high as the requested
451 for (i
= 0; (unsigned) i
< PA_ELEMENTSOF(freq_table
); i
++)
452 if (freq_table
[i
].rate
>= u
->sample_spec
.rate
&& (cap
->frequency
& freq_table
[i
].cap
)) {
453 u
->sample_spec
.rate
= freq_table
[i
].rate
;
454 cap
->frequency
= freq_table
[i
].cap
;
458 if ((unsigned) i
== PA_ELEMENTSOF(freq_table
)) {
459 for (--i
; i
>= 0; i
--) {
460 if (cap
->frequency
& freq_table
[i
].cap
) {
461 u
->sample_spec
.rate
= freq_table
[i
].rate
;
462 cap
->frequency
= freq_table
[i
].cap
;
468 pa_log("Not suitable sample rate");
473 pa_assert((unsigned) i
< PA_ELEMENTSOF(freq_table
));
475 if (cap
->capability
.configured
)
478 if (u
->sample_spec
.channels
<= 1) {
479 if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_MONO
) {
480 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_MONO
;
481 u
->sample_spec
.channels
= 1;
483 u
->sample_spec
.channels
= 2;
486 if (u
->sample_spec
.channels
>= 2) {
487 u
->sample_spec
.channels
= 2;
489 if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_JOINT_STEREO
)
490 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_JOINT_STEREO
;
491 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_STEREO
)
492 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_STEREO
;
493 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
)
494 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
;
495 else if (cap
->channel_mode
& BT_A2DP_CHANNEL_MODE_MONO
) {
496 cap
->channel_mode
= BT_A2DP_CHANNEL_MODE_MONO
;
497 u
->sample_spec
.channels
= 1;
499 pa_log("No supported channel modes");
504 if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_16
)
505 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_16
;
506 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_12
)
507 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_12
;
508 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_8
)
509 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_8
;
510 else if (cap
->block_length
& BT_A2DP_BLOCK_LENGTH_4
)
511 cap
->block_length
= BT_A2DP_BLOCK_LENGTH_4
;
513 pa_log_error("No supported block lengths");
517 if (cap
->subbands
& BT_A2DP_SUBBANDS_8
)
518 cap
->subbands
= BT_A2DP_SUBBANDS_8
;
519 else if (cap
->subbands
& BT_A2DP_SUBBANDS_4
)
520 cap
->subbands
= BT_A2DP_SUBBANDS_4
;
522 pa_log_error("No supported subbands");
526 if (cap
->allocation_method
& BT_A2DP_ALLOCATION_LOUDNESS
)
527 cap
->allocation_method
= BT_A2DP_ALLOCATION_LOUDNESS
;
528 else if (cap
->allocation_method
& BT_A2DP_ALLOCATION_SNR
)
529 cap
->allocation_method
= BT_A2DP_ALLOCATION_SNR
;
531 cap
->min_bitpool
= (uint8_t) PA_MAX(MIN_BITPOOL
, cap
->min_bitpool
);
532 cap
->max_bitpool
= (uint8_t) PA_MIN(a2dp_default_bitpool(cap
->frequency
, cap
->channel_mode
), cap
->max_bitpool
);
537 /* Run from main thread */
538 static void setup_sbc(struct a2dp_info
*a2dp
) {
539 sbc_capabilities_t
*active_capabilities
;
543 active_capabilities
= &a2dp
->sbc_capabilities
;
545 if (a2dp
->sbc_initialized
)
546 sbc_reinit(&a2dp
->sbc
, 0);
548 sbc_init(&a2dp
->sbc
, 0);
549 a2dp
->sbc_initialized
= TRUE
;
551 switch (active_capabilities
->frequency
) {
552 case BT_SBC_SAMPLING_FREQ_16000
:
553 a2dp
->sbc
.frequency
= SBC_FREQ_16000
;
555 case BT_SBC_SAMPLING_FREQ_32000
:
556 a2dp
->sbc
.frequency
= SBC_FREQ_32000
;
558 case BT_SBC_SAMPLING_FREQ_44100
:
559 a2dp
->sbc
.frequency
= SBC_FREQ_44100
;
561 case BT_SBC_SAMPLING_FREQ_48000
:
562 a2dp
->sbc
.frequency
= SBC_FREQ_48000
;
565 pa_assert_not_reached();
568 switch (active_capabilities
->channel_mode
) {
569 case BT_A2DP_CHANNEL_MODE_MONO
:
570 a2dp
->sbc
.mode
= SBC_MODE_MONO
;
572 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL
:
573 a2dp
->sbc
.mode
= SBC_MODE_DUAL_CHANNEL
;
575 case BT_A2DP_CHANNEL_MODE_STEREO
:
576 a2dp
->sbc
.mode
= SBC_MODE_STEREO
;
578 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO
:
579 a2dp
->sbc
.mode
= SBC_MODE_JOINT_STEREO
;
582 pa_assert_not_reached();
585 switch (active_capabilities
->allocation_method
) {
586 case BT_A2DP_ALLOCATION_SNR
:
587 a2dp
->sbc
.allocation
= SBC_AM_SNR
;
589 case BT_A2DP_ALLOCATION_LOUDNESS
:
590 a2dp
->sbc
.allocation
= SBC_AM_LOUDNESS
;
593 pa_assert_not_reached();
596 switch (active_capabilities
->subbands
) {
597 case BT_A2DP_SUBBANDS_4
:
598 a2dp
->sbc
.subbands
= SBC_SB_4
;
600 case BT_A2DP_SUBBANDS_8
:
601 a2dp
->sbc
.subbands
= SBC_SB_8
;
604 pa_assert_not_reached();
607 switch (active_capabilities
->block_length
) {
608 case BT_A2DP_BLOCK_LENGTH_4
:
609 a2dp
->sbc
.blocks
= SBC_BLK_4
;
611 case BT_A2DP_BLOCK_LENGTH_8
:
612 a2dp
->sbc
.blocks
= SBC_BLK_8
;
614 case BT_A2DP_BLOCK_LENGTH_12
:
615 a2dp
->sbc
.blocks
= SBC_BLK_12
;
617 case BT_A2DP_BLOCK_LENGTH_16
:
618 a2dp
->sbc
.blocks
= SBC_BLK_16
;
621 pa_assert_not_reached();
624 a2dp
->sbc
.bitpool
= active_capabilities
->max_bitpool
;
625 a2dp
->codesize
= sbc_get_codesize(&a2dp
->sbc
);
626 a2dp
->frame_length
= sbc_get_frame_length(&a2dp
->sbc
);
629 /* Run from main thread */
630 static int set_conf(struct userdata
*u
) {
632 struct bt_open_req open_req
;
633 struct bt_open_rsp open_rsp
;
634 struct bt_set_configuration_req setconf_req
;
635 struct bt_set_configuration_rsp setconf_rsp
;
636 bt_audio_error_t error
;
637 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
640 memset(&msg
, 0, sizeof(msg
));
641 msg
.open_req
.h
.type
= BT_REQUEST
;
642 msg
.open_req
.h
.name
= BT_OPEN
;
643 msg
.open_req
.h
.length
= sizeof(msg
.open_req
);
645 pa_strlcpy(msg
.open_req
.object
, u
->path
, sizeof(msg
.open_req
.object
));
646 msg
.open_req
.seid
= u
->profile
== PROFILE_A2DP
? u
->a2dp
.sbc_capabilities
.capability
.seid
: BT_A2DP_SEID_RANGE
+ 1;
647 msg
.open_req
.lock
= u
->profile
== PROFILE_A2DP
? BT_WRITE_LOCK
: BT_READ_LOCK
| BT_WRITE_LOCK
;
649 if (service_send(u
, &msg
.open_req
.h
) < 0)
652 if (service_expect(u
, &msg
.open_rsp
.h
, sizeof(msg
), BT_OPEN
, sizeof(msg
.open_rsp
)) < 0)
655 if (u
->profile
== PROFILE_A2DP
) {
656 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
658 if (setup_a2dp(u
) < 0)
661 pa_assert(u
->profile
== PROFILE_HSP
);
663 u
->sample_spec
.format
= PA_SAMPLE_S16LE
;
664 u
->sample_spec
.channels
= 1;
665 u
->sample_spec
.rate
= 8000;
668 memset(&msg
, 0, sizeof(msg
));
669 msg
.setconf_req
.h
.type
= BT_REQUEST
;
670 msg
.setconf_req
.h
.name
= BT_SET_CONFIGURATION
;
671 msg
.setconf_req
.h
.length
= sizeof(msg
.setconf_req
);
673 if (u
->profile
== PROFILE_A2DP
) {
674 memcpy(&msg
.setconf_req
.codec
, &u
->a2dp
.sbc_capabilities
, sizeof(u
->a2dp
.sbc_capabilities
));
676 msg
.setconf_req
.codec
.transport
= BT_CAPABILITIES_TRANSPORT_SCO
;
677 msg
.setconf_req
.codec
.seid
= BT_A2DP_SEID_RANGE
+ 1;
678 msg
.setconf_req
.codec
.length
= sizeof(pcm_capabilities_t
);
680 msg
.setconf_req
.h
.length
+= msg
.setconf_req
.codec
.length
- sizeof(msg
.setconf_req
.codec
);
682 if (service_send(u
, &msg
.setconf_req
.h
) < 0)
685 if (service_expect(u
, &msg
.setconf_rsp
.h
, sizeof(msg
), BT_SET_CONFIGURATION
, sizeof(msg
.setconf_rsp
)) < 0)
688 u
->link_mtu
= msg
.setconf_rsp
.link_mtu
;
690 /* setup SBC encoder now we agree on parameters */
691 if (u
->profile
== PROFILE_A2DP
) {
695 ((u
->link_mtu
- sizeof(struct rtp_header
) - sizeof(struct rtp_payload
))
696 / u
->a2dp
.frame_length
699 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
700 u
->a2dp
.sbc
.allocation
, u
->a2dp
.sbc
.subbands
, u
->a2dp
.sbc
.blocks
, u
->a2dp
.sbc
.bitpool
);
702 u
->block_size
= u
->link_mtu
;
707 /* from IO thread, except in SCO over PCM */
708 static int start_stream_fd(struct userdata
*u
) {
710 bt_audio_msg_header_t rsp
;
711 struct bt_start_stream_req start_req
;
712 struct bt_start_stream_rsp start_rsp
;
713 struct bt_new_stream_ind streamfd_ind
;
714 bt_audio_error_t error
;
715 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
717 struct pollfd
*pollfd
;
721 pa_assert(u
->rtpoll
);
722 pa_assert(!u
->rtpoll_item
);
723 pa_assert(u
->stream_fd
< 0);
725 memset(msg
.buf
, 0, BT_SUGGESTED_BUFFER_SIZE
);
726 msg
.start_req
.h
.type
= BT_REQUEST
;
727 msg
.start_req
.h
.name
= BT_START_STREAM
;
728 msg
.start_req
.h
.length
= sizeof(msg
.start_req
);
730 if (service_send(u
, &msg
.start_req
.h
) < 0)
733 if (service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_START_STREAM
, sizeof(msg
.start_rsp
)) < 0)
736 if (service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_NEW_STREAM
, sizeof(msg
.streamfd_ind
)) < 0)
739 if ((u
->stream_fd
= bt_audio_service_get_data_fd(u
->service_fd
)) < 0) {
740 pa_log("Failed to get stream fd from audio service.");
744 pa_make_fd_nonblock(u
->stream_fd
);
745 pa_make_socket_low_delay(u
->stream_fd
);
748 if (setsockopt(u
->stream_fd
, SOL_SOCKET
, SO_TIMESTAMP
, &one
, sizeof(one
)) < 0)
749 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno
));
751 pa_log_debug("Stream properly set up, we're ready to roll!");
753 u
->rtpoll_item
= pa_rtpoll_item_new(u
->rtpoll
, PA_RTPOLL_NEVER
, 1);
754 pollfd
= pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
);
755 pollfd
->fd
= u
->stream_fd
;
756 pollfd
->events
= pollfd
->revents
= 0;
758 u
->read_index
= u
->write_index
= 0;
762 u
->read_smoother
= pa_smoother_new(
775 static int stop_stream_fd(struct userdata
*u
) {
777 bt_audio_msg_header_t rsp
;
778 struct bt_stop_stream_req start_req
;
779 struct bt_stop_stream_rsp start_rsp
;
780 bt_audio_error_t error
;
781 uint8_t buf
[BT_SUGGESTED_BUFFER_SIZE
];
786 pa_assert(u
->rtpoll
);
787 pa_assert(u
->rtpoll_item
);
788 pa_assert(u
->stream_fd
>= 0);
790 pa_rtpoll_item_free(u
->rtpoll_item
);
791 u
->rtpoll_item
= NULL
;
793 memset(msg
.buf
, 0, BT_SUGGESTED_BUFFER_SIZE
);
794 msg
.start_req
.h
.type
= BT_REQUEST
;
795 msg
.start_req
.h
.name
= BT_STOP_STREAM
;
796 msg
.start_req
.h
.length
= sizeof(msg
.start_req
);
798 if (service_send(u
, &msg
.start_req
.h
) < 0 ||
799 service_expect(u
, &msg
.rsp
, sizeof(msg
), BT_STOP_STREAM
, sizeof(msg
.start_rsp
)) < 0)
802 pa_close(u
->stream_fd
);
805 if (u
->read_smoother
) {
806 pa_smoother_free(u
->read_smoother
);
807 u
->read_smoother
= NULL
;
813 /* Run from IO thread */
814 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
815 struct userdata
*u
= PA_SINK(o
)->userdata
;
816 pa_bool_t failed
= FALSE
;
819 pa_assert(u
->sink
== PA_SINK(o
));
823 case PA_SINK_MESSAGE_SET_STATE
:
825 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
827 case PA_SINK_SUSPENDED
:
828 pa_assert(PA_SINK_IS_OPENED(u
->sink
->thread_info
.state
));
830 /* Stop the device if the source is suspended as well */
831 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
)
832 /* We deliberately ignore whether stopping
833 * actually worked. Since the stream_fd is
834 * closed it doesn't really matter */
840 case PA_SINK_RUNNING
:
841 if (u
->sink
->thread_info
.state
!= PA_SINK_SUSPENDED
)
844 /* Resume the device if the source was suspended as well */
845 if (!u
->source
|| u
->source
->state
== PA_SOURCE_SUSPENDED
)
846 if (start_stream_fd(u
) < 0)
850 case PA_SINK_UNLINKED
:
852 case PA_SINK_INVALID_STATE
:
857 case PA_SINK_MESSAGE_GET_LATENCY
: {
859 if (u
->read_smoother
) {
862 ri
= pa_smoother_get(u
->read_smoother
, pa_rtclock_usec());
863 wi
= pa_bytes_to_usec(u
->write_index
+ u
->block_size
, &u
->sample_spec
);
865 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
869 ri
= pa_rtclock_usec() - u
->started_at
;
870 wi
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
872 *((pa_usec_t
*) data
) = wi
> ri
? wi
- ri
: 0;
875 *((pa_usec_t
*) data
) += u
->sink
->fixed_latency
;
880 r
= pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
882 return (r
< 0 || !failed
) ? r
: -1;
885 /* Run from IO thread */
886 static int source_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
887 struct userdata
*u
= PA_SOURCE(o
)->userdata
;
888 pa_bool_t failed
= FALSE
;
891 pa_assert(u
->source
== PA_SOURCE(o
));
895 case PA_SOURCE_MESSAGE_SET_STATE
:
897 switch ((pa_source_state_t
) PA_PTR_TO_UINT(data
)) {
899 case PA_SOURCE_SUSPENDED
:
900 pa_assert(PA_SOURCE_IS_OPENED(u
->source
->thread_info
.state
));
902 /* Stop the device if the sink is suspended as well */
903 if (!u
->sink
|| u
->sink
->state
== PA_SINK_SUSPENDED
)
906 if (u
->read_smoother
)
907 pa_smoother_pause(u
->read_smoother
, pa_rtclock_usec());
911 case PA_SOURCE_RUNNING
:
912 if (u
->source
->thread_info
.state
!= PA_SOURCE_SUSPENDED
)
915 /* Resume the device if the sink was suspended as well */
916 if (!u
->sink
|| u
->sink
->thread_info
.state
== PA_SINK_SUSPENDED
)
917 if (start_stream_fd(u
) < 0)
920 /* We don't resume the smoother here. Instead we
921 * wait until the first packet arrives */
924 case PA_SOURCE_UNLINKED
:
926 case PA_SOURCE_INVALID_STATE
:
931 case PA_SOURCE_MESSAGE_GET_LATENCY
: {
934 wi
= pa_smoother_get(u
->read_smoother
, pa_rtclock_usec());
935 ri
= pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
);
937 *((pa_usec_t
*) data
) = (wi
> ri
? wi
- ri
: 0) + u
->source
->fixed_latency
;
943 r
= pa_source_process_msg(o
, code
, data
, offset
, chunk
);
945 return (r
< 0 || !failed
) ? r
: -1;
948 /* Run from IO thread */
949 static int hsp_process_render(struct userdata
*u
) {
953 pa_assert(u
->profile
== PROFILE_HSP
);
956 /* First, render some data */
957 if (!u
->write_memchunk
.memblock
)
958 pa_sink_render_full(u
->sink
, u
->block_size
, &u
->write_memchunk
);
960 pa_assert(u
->write_memchunk
.length
== u
->block_size
);
966 /* Now write that data to the socket. The socket is of type
967 * SEQPACKET, and we generated the data of the MTU size, so this
968 * should just work. */
970 p
= (const uint8_t*) pa_memblock_acquire(u
->write_memchunk
.memblock
) + u
->write_memchunk
.index
;
971 l
= pa_write(u
->stream_fd
, p
, u
->write_memchunk
.length
, &u
->stream_write_type
);
972 pa_memblock_release(u
->write_memchunk
.memblock
);
979 /* Retry right away if we got interrupted */
982 else if (errno
== EAGAIN
)
983 /* Hmm, apparently the socket was not writable, give up for now */
986 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno
));
991 pa_assert((size_t) l
<= u
->write_memchunk
.length
);
993 if ((size_t) l
!= u
->write_memchunk
.length
) {
994 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
995 (unsigned long long) l
,
996 (unsigned long long) u
->write_memchunk
.length
);
1001 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
1002 pa_memblock_unref(u
->write_memchunk
.memblock
);
1003 pa_memchunk_reset(&u
->write_memchunk
);
1012 /* Run from IO thread */
1013 static int hsp_process_push(struct userdata
*u
) {
1015 pa_memchunk memchunk
;
1018 pa_assert(u
->profile
== PROFILE_HSP
);
1019 pa_assert(u
->source
);
1020 pa_assert(u
->read_smoother
);
1022 memchunk
.memblock
= pa_memblock_new(u
->core
->mempool
, u
->block_size
);
1023 memchunk
.index
= memchunk
.length
= 0;
1032 pa_bool_t found_tstamp
= FALSE
;
1035 memset(&m
, 0, sizeof(m
));
1036 memset(&aux
, 0, sizeof(aux
));
1037 memset(&iov
, 0, sizeof(iov
));
1041 m
.msg_control
= aux
;
1042 m
.msg_controllen
= sizeof(aux
);
1044 p
= pa_memblock_acquire(memchunk
.memblock
);
1046 iov
.iov_len
= pa_memblock_get_length(memchunk
.memblock
);
1047 l
= recvmsg(u
->stream_fd
, &m
, 0);
1048 pa_memblock_release(memchunk
.memblock
);
1052 if (l
< 0 && errno
== EINTR
)
1053 /* Retry right away if we got interrupted */
1056 else if (l
< 0 && errno
== EAGAIN
)
1057 /* Hmm, apparently the socket was not readable, give up for now. */
1060 pa_log_error("Failed to read data from SCO socket: %s", l
< 0 ? pa_cstrerror(errno
) : "EOF");
1065 pa_assert((size_t) l
<= pa_memblock_get_length(memchunk
.memblock
));
1067 memchunk
.length
= (size_t) l
;
1068 u
->read_index
+= (uint64_t) l
;
1070 for (cm
= CMSG_FIRSTHDR(&m
); cm
; cm
= CMSG_NXTHDR(&m
, cm
))
1071 if (cm
->cmsg_level
== SOL_SOCKET
&& cm
->cmsg_type
== SO_TIMESTAMP
) {
1072 struct timeval
*tv
= (struct timeval
*) CMSG_DATA(cm
);
1073 pa_rtclock_from_wallclock(tv
);
1074 tstamp
= pa_timeval_load(tv
);
1075 found_tstamp
= TRUE
;
1079 if (!found_tstamp
) {
1080 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1081 tstamp
= pa_rtclock_usec();
1084 pa_smoother_put(u
->read_smoother
, tstamp
, pa_bytes_to_usec(u
->read_index
, &u
->sample_spec
));
1085 pa_smoother_resume(u
->read_smoother
, tstamp
, TRUE
);
1087 pa_source_post(u
->source
, &memchunk
);
1093 pa_memblock_unref(memchunk
.memblock
);
1098 /* Run from IO thread */
1099 static void a2dp_prepare_buffer(struct userdata
*u
) {
1102 if (u
->a2dp
.buffer_size
>= u
->link_mtu
)
1105 u
->a2dp
.buffer_size
= 2 * u
->link_mtu
;
1106 pa_xfree(u
->a2dp
.buffer
);
1107 u
->a2dp
.buffer
= pa_xmalloc(u
->a2dp
.buffer_size
);
1110 /* Run from IO thread */
1111 static int a2dp_process_render(struct userdata
*u
) {
1112 struct a2dp_info
*a2dp
;
1113 struct rtp_header
*header
;
1114 struct rtp_payload
*payload
;
1118 size_t to_write
, to_encode
;
1119 unsigned frame_count
;
1123 pa_assert(u
->profile
== PROFILE_A2DP
);
1126 /* First, render some data */
1127 if (!u
->write_memchunk
.memblock
)
1128 pa_sink_render_full(u
->sink
, u
->block_size
, &u
->write_memchunk
);
1130 pa_assert(u
->write_memchunk
.length
== u
->block_size
);
1132 a2dp_prepare_buffer(u
);
1135 header
= a2dp
->buffer
;
1136 payload
= (struct rtp_payload
*) ((uint8_t*) a2dp
->buffer
+ sizeof(*header
));
1140 /* Try to create a packet of the full MTU */
1142 p
= (const uint8_t*) pa_memblock_acquire(u
->write_memchunk
.memblock
) + u
->write_memchunk
.index
;
1143 to_encode
= u
->write_memchunk
.length
;
1145 d
= (uint8_t*) a2dp
->buffer
+ sizeof(*header
) + sizeof(*payload
);
1146 to_write
= a2dp
->buffer_size
- sizeof(*header
) - sizeof(*payload
);
1148 while (PA_LIKELY(to_encode
> 0 && to_write
> 0)) {
1152 encoded
= sbc_encode(&a2dp
->sbc
,
1157 if (PA_UNLIKELY(encoded
<= 0)) {
1158 pa_log_error("SBC encoding error (%li)", (long) encoded
);
1159 pa_memblock_release(u
->write_memchunk
.memblock
);
1163 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1164 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1166 pa_assert_fp((size_t) encoded
<= to_encode
);
1167 pa_assert_fp((size_t) encoded
== a2dp
->codesize
);
1169 pa_assert_fp((size_t) written
<= to_write
);
1170 pa_assert_fp((size_t) written
== a2dp
->frame_length
);
1172 p
= (const uint8_t*) p
+ encoded
;
1173 to_encode
-= encoded
;
1175 d
= (uint8_t*) d
+ written
;
1176 to_write
-= written
;
1181 pa_memblock_release(u
->write_memchunk
.memblock
);
1183 pa_assert(to_encode
== 0);
1186 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp
->sbc
)));
1189 /* write it to the fifo */
1190 memset(a2dp
->buffer
, 0, sizeof(*header
) + sizeof(*payload
));
1193 header
->sequence_number
= htons(a2dp
->seq_num
++);
1194 header
->timestamp
= htonl(u
->write_index
/ pa_frame_size(&u
->sample_spec
));
1195 header
->ssrc
= htonl(1);
1196 payload
->frame_count
= frame_count
;
1198 nbytes
= (uint8_t*) d
- (uint8_t*) a2dp
->buffer
;
1203 l
= pa_write(u
->stream_fd
, a2dp
->buffer
, nbytes
, &u
->stream_write_type
);
1210 /* Retry right away if we got interrupted */
1213 else if (errno
== EAGAIN
)
1214 /* Hmm, apparently the socket was not writable, give up for now */
1217 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno
));
1222 pa_assert((size_t) l
<= nbytes
);
1224 if ((size_t) l
!= nbytes
) {
1225 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1226 (unsigned long long) l
,
1227 (unsigned long long) nbytes
);
1232 u
->write_index
+= (uint64_t) u
->write_memchunk
.length
;
1233 pa_memblock_unref(u
->write_memchunk
.memblock
);
1234 pa_memchunk_reset(&u
->write_memchunk
);
1244 static void thread_func(void *userdata
) {
1245 struct userdata
*u
= userdata
;
1246 unsigned do_write
= 0;
1247 pa_bool_t writable
= FALSE
;
1251 pa_log_debug("IO Thread starting up");
1253 if (u
->core
->realtime_scheduling
)
1254 pa_make_realtime(u
->core
->realtime_priority
);
1256 if (start_stream_fd(u
) < 0)
1259 pa_thread_mq_install(&u
->thread_mq
);
1260 pa_rtpoll_install(u
->rtpoll
);
1263 struct pollfd
*pollfd
;
1265 pa_bool_t disable_timer
= TRUE
;
1267 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1269 if (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) {
1271 /* We should send two blocks to the device before we expect
1274 if (u
->write_index
== 0 && u
->read_index
<= 0)
1277 if (pollfd
&& (pollfd
->revents
& POLLIN
)) {
1280 if ((n_read
= hsp_process_push(u
)) < 0)
1283 /* We just read something, so we are supposed to write something, too */
1288 if (u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
)) {
1290 if (u
->sink
->thread_info
.rewind_requested
)
1291 pa_sink_process_rewind(u
->sink
, 0);
1294 if (pollfd
->revents
& POLLOUT
)
1297 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0 && writable
) {
1298 pa_usec_t time_passed
;
1299 uint64_t should_have_written
;
1301 /* Hmm, there is no input stream we could synchronize
1302 * to. So let's do things by time */
1304 time_passed
= pa_rtclock_usec() - u
->started_at
;
1305 should_have_written
= pa_usec_to_bytes(time_passed
, &u
->sample_spec
);
1307 do_write
= u
->write_index
<= should_have_written
;
1310 if (writable
&& do_write
> 0) {
1313 if (u
->write_index
<= 0)
1314 u
->started_at
= pa_rtclock_usec();
1316 if (u
->profile
== PROFILE_A2DP
) {
1317 if ((n_written
= a2dp_process_render(u
)) < 0)
1320 if ((n_written
= hsp_process_render(u
)) < 0)
1324 do_write
-= n_written
;
1328 if ((!u
->source
|| !PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
)) && do_write
<= 0) {
1329 pa_usec_t time_passed
, next_write_at
, sleep_for
;
1331 /* Hmm, there is no input stream we could synchronize
1332 * to. So let's estimate when we need to wake up the latest */
1334 time_passed
= pa_rtclock_usec() - u
->started_at
;
1335 next_write_at
= pa_bytes_to_usec(u
->write_index
, &u
->sample_spec
);
1336 sleep_for
= time_passed
< next_write_at
? next_write_at
- time_passed
: 0;
1338 /* 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); */
1340 pa_rtpoll_set_timer_relative(u
->rtpoll
, sleep_for
);
1341 disable_timer
= FALSE
;
1347 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
1349 /* Hmm, nothing to do. Let's sleep */
1351 pollfd
->events
= (short) (((u
->sink
&& PA_SINK_IS_LINKED(u
->sink
->thread_info
.state
) && !writable
) ? POLLOUT
: 0) |
1352 (u
->source
&& PA_SOURCE_IS_LINKED(u
->source
->thread_info
.state
) ? POLLIN
: 0));
1354 if ((ret
= pa_rtpoll_run(u
->rtpoll
, TRUE
)) < 0)
1360 pollfd
= u
->rtpoll_item
? pa_rtpoll_item_get_pollfd(u
->rtpoll_item
, NULL
) : NULL
;
1362 if (pollfd
&& (pollfd
->revents
& ~(POLLOUT
|POLLIN
))) {
1363 pa_log_info("FD error: %s%s%s%s",
1364 pollfd
->revents
& POLLERR
? "POLLERR " :"",
1365 pollfd
->revents
& POLLHUP
? "POLLHUP " :"",
1366 pollfd
->revents
& POLLPRI
? "POLLPRI " :"",
1367 pollfd
->revents
& POLLNVAL
? "POLLNVAL " :"");
1373 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1374 pa_log_debug("IO thread failed");
1375 pa_asyncmsgq_post(u
->thread_mq
.outq
, PA_MSGOBJECT(u
->core
), PA_CORE_MESSAGE_UNLOAD_MODULE
, u
->module
, 0, NULL
, NULL
);
1376 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1379 pa_log_debug("IO thread shutting down");
1382 /* Run from main thread */
1383 static DBusHandlerResult
filter_cb(DBusConnection
*bus
, DBusMessage
*m
, void *userdata
) {
1389 pa_assert_se(u
= userdata
);
1391 dbus_error_init(&err
);
1393 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1394 dbus_message_get_interface(m
),
1395 dbus_message_get_path(m
),
1396 dbus_message_get_member(m
));
1398 if (!dbus_message_has_path(m
, u
->path
))
1401 if (dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged") ||
1402 dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1407 if (!dbus_message_get_args(m
, &err
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
) || gain
> 15) {
1408 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err
.message
);
1412 if (u
->profile
== PROFILE_HSP
) {
1413 if (u
->sink
&& dbus_message_is_signal(m
, "org.bluez.Headset", "SpeakerGainChanged")) {
1415 pa_cvolume_set(&v
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1416 pa_sink_volume_changed(u
->sink
, &v
);
1418 } else if (u
->source
&& dbus_message_is_signal(m
, "org.bluez.Headset", "MicrophoneGainChanged")) {
1420 pa_cvolume_set(&v
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1421 pa_source_volume_changed(u
->source
, &v
);
1427 dbus_error_free(&err
);
1429 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1432 /* Run from main thread */
1433 static void sink_set_volume_cb(pa_sink
*s
) {
1434 struct userdata
*u
= s
->userdata
;
1440 if (u
->profile
!= PROFILE_HSP
)
1443 gain
= (pa_cvolume_max(&s
->virtual_volume
) * 15) / PA_VOLUME_NORM
;
1448 pa_cvolume_set(&s
->virtual_volume
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1450 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetSpeakerGain"));
1451 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1452 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1453 dbus_message_unref(m
);
1456 /* Run from main thread */
1457 static void source_set_volume_cb(pa_source
*s
) {
1458 struct userdata
*u
= s
->userdata
;
1464 if (u
->profile
!= PROFILE_HSP
)
1467 gain
= (pa_cvolume_max(&s
->virtual_volume
) * 15) / PA_VOLUME_NORM
;
1472 pa_cvolume_set(&s
->virtual_volume
, u
->sample_spec
.channels
, (pa_volume_t
) (gain
* PA_VOLUME_NORM
/ 15));
1474 pa_assert_se(m
= dbus_message_new_method_call("org.bluez", u
->path
, "org.bluez.Headset", "SetMicrophoneGain"));
1475 pa_assert_se(dbus_message_append_args(m
, DBUS_TYPE_UINT16
, &gain
, DBUS_TYPE_INVALID
));
1476 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u
->connection
), m
, NULL
));
1477 dbus_message_unref(m
);
1480 /* Run from main thread */
1481 static char *get_name(const char *type
, pa_modargs
*ma
, const char *device_id
, pa_bool_t
*namereg_fail
) {
1487 pa_assert(device_id
);
1488 pa_assert(namereg_fail
);
1490 t
= pa_sprintf_malloc("%s_name", type
);
1491 n
= pa_modargs_get_value(ma
, t
, NULL
);
1495 *namereg_fail
= TRUE
;
1496 return pa_xstrdup(n
);
1499 if ((n
= pa_modargs_get_value(ma
, "name", NULL
)))
1500 *namereg_fail
= TRUE
;
1503 *namereg_fail
= FALSE
;
1506 return pa_sprintf_malloc("bluez_%s.%s", type
, n
);
1511 static void sco_over_pcm_state_update(struct userdata
*u
) {
1513 pa_assert(USE_SCO_OVER_PCM(u
));
1515 if (PA_SINK_IS_OPENED(pa_sink_get_state(u
->hsp
.sco_sink
)) ||
1516 PA_SOURCE_IS_OPENED(pa_source_get_state(u
->hsp
.sco_source
))) {
1518 if (u
->service_fd
>= 0)
1521 pa_log_debug("Resuming SCO over PCM");
1522 if ((init_bt(u
) < 0) || (init_profile(u
) < 0))
1523 pa_log("Can't resume SCO over PCM");
1528 if (u
->service_fd
< 0)
1533 pa_log_debug("Closing SCO over PCM");
1534 pa_close(u
->service_fd
);
1539 static pa_hook_result_t
sink_state_changed_cb(pa_core
*c
, pa_sink
*s
, struct userdata
*u
) {
1541 pa_sink_assert_ref(s
);
1544 if (s
!= u
->hsp
.sco_sink
)
1547 sco_over_pcm_state_update(u
);
1552 static pa_hook_result_t
source_state_changed_cb(pa_core
*c
, pa_source
*s
, struct userdata
*u
) {
1554 pa_source_assert_ref(s
);
1557 if (s
!= u
->hsp
.sco_source
)
1560 sco_over_pcm_state_update(u
);
1567 /* Run from main thread */
1568 static int add_sink(struct userdata
*u
) {
1571 if (USE_SCO_OVER_PCM(u
)) {
1574 u
->sink
= u
->hsp
.sco_sink
;
1575 p
= pa_proplist_new();
1576 pa_proplist_sets(p
, "bluetooth.protocol", "sco");
1577 pa_proplist_update(u
->sink
->proplist
, PA_UPDATE_MERGE
, p
);
1578 pa_proplist_free(p
);
1580 if (!u
->hsp
.sink_state_changed_slot
)
1581 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
);
1587 pa_sink_new_data data
;
1590 pa_sink_new_data_init(&data
);
1591 data
.driver
= __FILE__
;
1592 data
.module
= u
->module
;
1593 pa_sink_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1594 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", u
->profile
== PROFILE_A2DP
? "a2dp" : "sco");
1595 data
.card
= u
->card
;
1596 data
.name
= get_name("sink", u
->modargs
, u
->address
, &b
);
1597 data
.namereg_fail
= b
;
1599 u
->sink
= pa_sink_new(u
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
| (u
->profile
== PROFILE_HSP
? PA_SINK_HW_VOLUME_CTRL
: 0));
1600 pa_sink_new_data_done(&data
);
1603 pa_log_error("Failed to create sink");
1607 u
->sink
->userdata
= u
;
1608 u
->sink
->parent
.process_msg
= sink_process_msg
;
1610 pa_sink_set_max_request(u
->sink
, u
->block_size
);
1611 pa_sink_set_fixed_latency(u
->sink
,
1612 (u
->profile
== PROFILE_A2DP
? FIXED_LATENCY_PLAYBACK_A2DP
: FIXED_LATENCY_PLAYBACK_HSP
) +
1613 pa_bytes_to_usec(u
->block_size
, &u
->sample_spec
));
1616 if (u
->profile
== PROFILE_HSP
) {
1617 u
->sink
->set_volume
= sink_set_volume_cb
;
1618 u
->sink
->n_volume_steps
= 16;
1624 /* Run from main thread */
1625 static int add_source(struct userdata
*u
) {
1628 if (USE_SCO_OVER_PCM(u
)) {
1629 u
->source
= u
->hsp
.sco_source
;
1630 pa_proplist_sets(u
->source
->proplist
, "bluetooth.protocol", "hsp");
1632 if (!u
->hsp
.source_state_changed_slot
)
1633 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
);
1639 pa_source_new_data data
;
1642 pa_source_new_data_init(&data
);
1643 data
.driver
= __FILE__
;
1644 data
.module
= u
->module
;
1645 pa_source_new_data_set_sample_spec(&data
, &u
->sample_spec
);
1646 pa_proplist_sets(data
.proplist
, "bluetooth.protocol", u
->profile
== PROFILE_A2DP
? "a2dp" : "hsp");
1647 data
.card
= u
->card
;
1648 data
.name
= get_name("source", u
->modargs
, u
->address
, &b
);
1649 data
.namereg_fail
= b
;
1651 u
->source
= pa_source_new(u
->core
, &data
, PA_SOURCE_HARDWARE
|PA_SOURCE_LATENCY
| (u
->profile
== PROFILE_HSP
? PA_SOURCE_HW_VOLUME_CTRL
: 0));
1652 pa_source_new_data_done(&data
);
1655 pa_log_error("Failed to create source");
1659 u
->source
->userdata
= u
;
1660 u
->source
->parent
.process_msg
= source_process_msg
;
1662 pa_source_set_fixed_latency(u
->source
,
1663 (/* u->profile == PROFILE_A2DP ? FIXED_LATENCY_RECORD_A2DP : */ FIXED_LATENCY_RECORD_HSP
) +
1664 pa_bytes_to_usec(u
->block_size
, &u
->sample_spec
));
1667 if (u
->profile
== PROFILE_HSP
) {
1668 pa_proplist_sets(u
->source
->proplist
, "bluetooth.nrec", (u
->hsp
.pcm_capabilities
.flags
& BT_PCM_FLAG_NREC
) ? "1" : "0");
1669 u
->source
->set_volume
= source_set_volume_cb
;
1670 u
->source
->n_volume_steps
= 16;
1676 /* Run from main thread */
1677 static void shutdown_bt(struct userdata
*u
) {
1680 if (u
->stream_fd
>= 0) {
1681 pa_close(u
->stream_fd
);
1684 u
->stream_write_type
= 0;
1687 if (u
->service_fd
>= 0) {
1688 pa_close(u
->service_fd
);
1690 u
->service_write_type
= u
->service_write_type
= 0;
1693 if (u
->write_memchunk
.memblock
) {
1694 pa_memblock_unref(u
->write_memchunk
.memblock
);
1695 pa_memchunk_reset(&u
->write_memchunk
);
1699 /* Run from main thread */
1700 static int init_bt(struct userdata
*u
) {
1705 u
->stream_write_type
= 0;
1706 u
->service_write_type
= u
->service_write_type
= 0;
1708 if ((u
->service_fd
= bt_audio_service_open()) < 0) {
1709 pa_log_error("Couldn't connect to bluetooth audio service");
1713 pa_log_debug("Connected to the bluetooth audio service");
1718 /* Run from main thread */
1719 static int setup_bt(struct userdata
*u
) {
1722 if (get_caps(u
, 0) < 0)
1725 pa_log_debug("Got device capabilities");
1727 if (set_conf(u
) < 0)
1730 pa_log_debug("Connection to the device configured");
1733 if (USE_SCO_OVER_PCM(u
)) {
1734 pa_log_debug("Configured to use SCO over PCM");
1739 pa_log_debug("Got the stream socket");
1744 /* Run from main thread */
1745 static int init_profile(struct userdata
*u
) {
1748 pa_assert(u
->profile
!= PROFILE_OFF
);
1750 if (setup_bt(u
) < 0)
1753 if (u
->profile
== PROFILE_A2DP
||
1754 u
->profile
== PROFILE_HSP
)
1755 if (add_sink(u
) < 0)
1758 if (u
->profile
== PROFILE_HSP
)
1759 if (add_source(u
) < 0)
1765 /* Run from main thread */
1766 static void stop_thread(struct userdata
*u
) {
1770 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
1771 pa_thread_free(u
->thread
);
1775 if (u
->rtpoll_item
) {
1776 pa_rtpoll_item_free(u
->rtpoll_item
);
1777 u
->rtpoll_item
= NULL
;
1780 if (u
->hsp
.sink_state_changed_slot
) {
1781 pa_hook_slot_free(u
->hsp
.sink_state_changed_slot
);
1782 u
->hsp
.sink_state_changed_slot
= NULL
;
1785 if (u
->hsp
.source_state_changed_slot
) {
1786 pa_hook_slot_free(u
->hsp
.source_state_changed_slot
);
1787 u
->hsp
.source_state_changed_slot
= NULL
;
1791 pa_sink_unref(u
->sink
);
1796 pa_source_unref(u
->source
);
1801 pa_thread_mq_done(&u
->thread_mq
);
1803 pa_rtpoll_free(u
->rtpoll
);
1807 if (u
->read_smoother
) {
1808 pa_smoother_free(u
->read_smoother
);
1809 u
->read_smoother
= NULL
;
1813 /* Run from main thread */
1814 static int start_thread(struct userdata
*u
) {
1816 pa_assert(!u
->thread
);
1817 pa_assert(!u
->rtpoll
);
1818 pa_assert(!u
->rtpoll_item
);
1820 u
->rtpoll
= pa_rtpoll_new();
1821 pa_thread_mq_init(&u
->thread_mq
, u
->core
->mainloop
, u
->rtpoll
);
1824 if (USE_SCO_OVER_PCM(u
)) {
1825 if (start_stream_fd(u
) < 0)
1828 pa_sink_ref(u
->sink
);
1829 pa_source_ref(u
->source
);
1830 /* FIXME: monitor stream_fd error */
1835 if (!(u
->thread
= pa_thread_new(thread_func
, u
))) {
1836 pa_log_error("Failed to create IO thread");
1842 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
1843 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
1844 pa_sink_put(u
->sink
);
1846 if (u
->sink
->set_volume
)
1847 u
->sink
->set_volume(u
->sink
);
1851 pa_source_set_asyncmsgq(u
->source
, u
->thread_mq
.inq
);
1852 pa_source_set_rtpoll(u
->source
, u
->rtpoll
);
1853 pa_source_put(u
->source
);
1855 if (u
->source
->set_volume
)
1856 u
->source
->set_volume(u
->source
);
1862 /* Run from main thread */
1863 static int card_set_profile(pa_card
*c
, pa_card_profile
*new_profile
) {
1866 pa_queue
*inputs
= NULL
, *outputs
= NULL
;
1867 const pa_bluetooth_device
*device
;
1870 pa_assert(new_profile
);
1871 pa_assert_se(u
= c
->userdata
);
1873 d
= PA_CARD_PROFILE_DATA(new_profile
);
1875 if (!(device
= pa_bluetooth_discovery_get_by_path(u
->discovery
, u
->path
))) {
1876 pa_log_error("Failed to get device object.");
1880 /* The state signal is sent by bluez, so it is racy to check
1881 strictly for CONNECTED, we should also accept STREAMING state
1882 as being good enough. However, if the profile is used
1883 concurrently (which is unlikely), ipc will fail later on, and
1884 module will be unloaded. */
1885 if (device
->headset_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_HSP
) {
1886 pa_log_warn("HSP is not connected, refused to switch profile");
1889 else if (device
->audio_sink_state
< PA_BT_AUDIO_STATE_CONNECTED
&& *d
== PROFILE_A2DP
) {
1890 pa_log_warn("A2DP is not connected, refused to switch profile");
1895 inputs
= pa_sink_move_all_start(u
->sink
);
1897 if (!USE_SCO_OVER_PCM(u
))
1899 pa_sink_unlink(u
->sink
);
1903 outputs
= pa_source_move_all_start(u
->source
);
1905 if (!USE_SCO_OVER_PCM(u
))
1907 pa_source_unlink(u
->source
);
1914 u
->sample_spec
= u
->requested_sample_spec
;
1918 if (u
->profile
!= PROFILE_OFF
)
1921 if (u
->sink
|| u
->source
)
1926 pa_sink_move_all_finish(u
->sink
, inputs
, FALSE
);
1928 pa_sink_move_all_fail(inputs
);
1933 pa_source_move_all_finish(u
->source
, outputs
, FALSE
);
1935 pa_source_move_all_fail(outputs
);
1941 /* Run from main thread */
1942 static int add_card(struct userdata
*u
, const char *default_profile
, const pa_bluetooth_device
*device
) {
1943 pa_card_new_data data
;
1950 pa_card_new_data_init(&data
);
1951 data
.driver
= __FILE__
;
1952 data
.module
= u
->module
;
1954 n
= pa_bluetooth_cleanup_name(device
->name
);
1955 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_DESCRIPTION
, n
);
1957 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, device
->address
);
1958 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_API
, "bluez");
1959 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_CLASS
, "sound");
1960 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_BUS
, "bluetooth");
1961 if ((ff
= pa_bluetooth_get_form_factor(device
->class)))
1962 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_FORM_FACTOR
, ff
);
1963 pa_proplist_sets(data
.proplist
, "bluez.path", device
->path
);
1964 pa_proplist_setf(data
.proplist
, "bluez.class", "0x%06x", (unsigned) device
->class);
1965 pa_proplist_sets(data
.proplist
, "bluez.name", device
->name
);
1966 data
.name
= get_name("card", u
->modargs
, device
->address
, &b
);
1967 data
.namereg_fail
= b
;
1969 data
.profiles
= pa_hashmap_new(pa_idxset_string_hash_func
, pa_idxset_string_compare_func
);
1971 /* we base hsp/a2dp availability on UUIDs.
1972 Ideally, it would be based on "Connected" state, but
1973 we can't afford to wait for this information when
1974 we are loaded with profile="hsp", for instance */
1975 if (pa_bluetooth_uuid_has(device
->uuids
, A2DP_SINK_UUID
)) {
1976 p
= pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile
));
1980 p
->max_sink_channels
= 2;
1981 p
->max_source_channels
= 0;
1983 d
= PA_CARD_PROFILE_DATA(p
);
1986 pa_hashmap_put(data
.profiles
, p
->name
, p
);
1989 if (pa_bluetooth_uuid_has(device
->uuids
, HSP_HS_UUID
) ||
1990 pa_bluetooth_uuid_has(device
->uuids
, HFP_HS_UUID
)) {
1991 p
= pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile
));
1995 p
->max_sink_channels
= 1;
1996 p
->max_source_channels
= 1;
1998 d
= PA_CARD_PROFILE_DATA(p
);
2001 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2004 pa_assert(!pa_hashmap_isempty(data
.profiles
));
2006 p
= pa_card_profile_new("off", _("Off"), sizeof(enum profile
));
2007 d
= PA_CARD_PROFILE_DATA(p
);
2009 pa_hashmap_put(data
.profiles
, p
->name
, p
);
2011 if (default_profile
) {
2012 if (pa_hashmap_get(data
.profiles
, default_profile
))
2013 pa_card_new_data_set_profile(&data
, default_profile
);
2015 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile
);
2018 u
->card
= pa_card_new(u
->core
, &data
);
2019 pa_card_new_data_done(&data
);
2022 pa_log("Failed to allocate card.");
2026 u
->card
->userdata
= u
;
2027 u
->card
->set_profile
= card_set_profile
;
2029 d
= PA_CARD_PROFILE_DATA(u
->card
->active_profile
);
2035 /* Run from main thread */
2036 static const pa_bluetooth_device
* find_device(struct userdata
*u
, const char *address
, const char *path
) {
2037 const pa_bluetooth_device
*d
= NULL
;
2041 if (!address
&& !path
) {
2042 pa_log_error("Failed to get device address/path from module arguments.");
2047 if (!(d
= pa_bluetooth_discovery_get_by_path(u
->discovery
, path
))) {
2048 pa_log_error("%s is not a valid BlueZ audio device.", path
);
2052 if (address
&& !(pa_streq(d
->address
, address
))) {
2053 pa_log_error("Passed path %s and address %s don't match.", path
, address
);
2058 if (!(d
= pa_bluetooth_discovery_get_by_address(u
->discovery
, address
))) {
2059 pa_log_error("%s is not known.", address
);
2065 u
->address
= pa_xstrdup(d
->address
);
2066 u
->path
= pa_xstrdup(d
->path
);
2072 /* Run from main thread */
2073 static int setup_dbus(struct userdata
*u
) {
2076 dbus_error_init(&err
);
2078 u
->connection
= pa_dbus_bus_get(u
->core
, DBUS_BUS_SYSTEM
, &err
);
2080 if (dbus_error_is_set(&err
) || !u
->connection
) {
2081 pa_log("Failed to get D-Bus connection: %s", err
.message
);
2082 dbus_error_free(&err
);
2089 int pa__init(pa_module
* m
) {
2093 const char *address
, *path
;
2095 char *mike
, *speaker
;
2096 const pa_bluetooth_device
*device
;
2100 dbus_error_init(&err
);
2102 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
2103 pa_log_error("Failed to parse module arguments");
2107 m
->userdata
= u
= pa_xnew0(struct userdata
, 1);
2112 u
->sample_spec
= m
->core
->default_sample_spec
;
2116 if (pa_modargs_get_value(ma
, "sco_sink", NULL
) &&
2117 !(u
->hsp
.sco_sink
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_sink", NULL
), PA_NAMEREG_SINK
))) {
2118 pa_log("SCO sink not found");
2122 if (pa_modargs_get_value(ma
, "sco_source", NULL
) &&
2123 !(u
->hsp
.sco_source
= pa_namereg_get(m
->core
, pa_modargs_get_value(ma
, "sco_source", NULL
), PA_NAMEREG_SOURCE
))) {
2124 pa_log("SCO source not found");
2129 if (pa_modargs_get_value_u32(ma
, "rate", &u
->sample_spec
.rate
) < 0 ||
2130 u
->sample_spec
.rate
<= 0 || u
->sample_spec
.rate
> PA_RATE_MAX
) {
2131 pa_log_error("Failed to get rate from module arguments");
2135 channels
= u
->sample_spec
.channels
;
2136 if (pa_modargs_get_value_u32(ma
, "channels", &channels
) < 0 ||
2137 channels
<= 0 || channels
> PA_CHANNELS_MAX
) {
2138 pa_log_error("Failed to get channels from module arguments");
2141 u
->sample_spec
.channels
= (uint8_t) channels
;
2142 u
->requested_sample_spec
= u
->sample_spec
;
2144 address
= pa_modargs_get_value(ma
, "address", NULL
);
2145 path
= pa_modargs_get_value(ma
, "path", NULL
);
2147 if (setup_dbus(u
) < 0)
2150 if (!(u
->discovery
= pa_bluetooth_discovery_get(m
->core
)))
2153 if (!(device
= find_device(u
, address
, path
)))
2156 /* Add the card structure. This will also initialize the default profile */
2157 if (add_card(u
, pa_modargs_get_value(ma
, "profile", NULL
), device
) < 0)
2160 /* Connect to the BT service and query capabilities */
2164 if (!dbus_connection_add_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
, NULL
)) {
2165 pa_log_error("Failed to add filter function");
2169 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2170 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2172 if (pa_dbus_add_matches(
2173 pa_dbus_connection_get(u
->connection
), &err
,
2181 pa_log("Failed to add D-Bus matches: %s", err
.message
);
2188 if (u
->profile
!= PROFILE_OFF
)
2189 if (init_profile(u
) < 0)
2192 if (u
->sink
|| u
->source
)
2193 if (start_thread(u
) < 0)
2202 dbus_error_free(&err
);
2207 int pa__get_n_used(pa_module
*m
) {
2211 pa_assert_se(u
= m
->userdata
);
2214 (u
->sink
? pa_sink_linked_by(u
->sink
) : 0) +
2215 (u
->source
? pa_source_linked_by(u
->source
) : 0);
2218 void pa__done(pa_module
*m
) {
2222 if (!(u
= m
->userdata
))
2227 && !USE_SCO_OVER_PCM(u
)
2230 pa_sink_unlink(u
->sink
);
2234 && !USE_SCO_OVER_PCM(u
)
2237 pa_source_unlink(u
->source
);
2241 if (u
->connection
) {
2244 char *speaker
, *mike
;
2245 speaker
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u
->path
);
2246 mike
= pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u
->path
);
2248 pa_dbus_remove_matches(pa_dbus_connection_get(u
->connection
),
2257 dbus_connection_remove_filter(pa_dbus_connection_get(u
->connection
), filter_cb
, u
);
2258 pa_dbus_connection_unref(u
->connection
);
2262 pa_card_free(u
->card
);
2264 if (u
->read_smoother
)
2265 pa_smoother_free(u
->read_smoother
);
2270 pa_xfree(u
->a2dp
.buffer
);
2272 sbc_finish(&u
->a2dp
.sbc
);
2275 pa_modargs_free(u
->modargs
);
2277 pa_xfree(u
->address
);
2281 pa_bluetooth_discovery_unref(u
->discovery
);