2
This file is part of PulseAudio.
4
Copyright 2008-2013 João Paulo Rechi Vita
5
Copyright 2011-2013 BMW Car IT GmbH.
7
PulseAudio is free software; you can redistribute it and/or modify
8
it under the terms of the GNU Lesser General Public License as
9
published by the Free Software Foundation; either version 2.1 of the
10
License, or (at your option) any later version.
12
PulseAudio is distributed in the hope that it will be useful, but
13
WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
General Public License for more details.
17
You should have received a copy of the GNU Lesser General Public
18
License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
27
#include <arpa/inet.h>
30
#include <pulse/rtclock.h>
31
#include <pulse/timeval.h>
33
#include <pulsecore/core.h>
34
#include <pulsecore/core-error.h>
35
#include <pulsecore/core-rtclock.h>
36
#include <pulsecore/core-util.h>
37
#include <pulsecore/i18n.h>
38
#include <pulsecore/module.h>
39
#include <pulsecore/modargs.h>
40
#include <pulsecore/poll.h>
41
#include <pulsecore/rtpoll.h>
42
#include <pulsecore/shared.h>
43
#include <pulsecore/socket-util.h>
44
#include <pulsecore/thread.h>
45
#include <pulsecore/thread-mq.h>
46
#include <pulsecore/time-smoother.h>
47
#include <pulsecore/namereg.h>
48
#include <pulse/mainloop-api.h>
50
#include "a2dp-codecs.h"
51
#include "bluez5-util.h"
54
#include "module-bluez5-device-symdef.h"
56
PA_MODULE_AUTHOR("João Paulo Rechi Vita");
57
PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
58
PA_MODULE_VERSION(PACKAGE_VERSION);
59
PA_MODULE_LOAD_ONCE(false);
60
PA_MODULE_USAGE("path=<device object path> "
61
"profile=<a2dp|hsp|hfgw> "
62
"sco_sink=<name of sink> "
63
"sco_source=<name of source> ");
65
#define MAX_PLAYBACK_CATCH_UP_USEC (100 * PA_USEC_PER_MSEC)
66
#define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
67
#define FIXED_LATENCY_PLAYBACK_SCO (125 * PA_USEC_PER_MSEC)
68
#define FIXED_LATENCY_RECORD_A2DP (25 * PA_USEC_PER_MSEC)
69
#define FIXED_LATENCY_RECORD_SCO (25 * PA_USEC_PER_MSEC)
71
#define BITPOOL_DEC_LIMIT 32
72
#define BITPOOL_DEC_STEP 5
73
#define HSP_MAX_GAIN 15
75
#define USE_SCO_OVER_PCM(u) (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT && (u->hsp.sco_sink && u->hsp.sco_source))
77
static const char* const valid_modargs[] = {
86
BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
87
BLUETOOTH_MESSAGE_STREAM_FD_HUP,
91
typedef struct bluetooth_msg {
95
PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
96
#define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
98
typedef struct sbc_info {
99
sbc_t sbc; /* Codec data */
100
bool sbc_initialized; /* Keep track if the encoder is initialized */
101
size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
102
uint16_t seq_num; /* Cumulative packet sequence */
106
void* buffer; /* Codec transfer buffer */
107
size_t buffer_size; /* Size of the buffer */
112
pa_source *sco_source;
121
pa_hook_slot *device_connection_changed_slot;
122
pa_hook_slot *transport_state_changed_slot;
123
pa_hook_slot *transport_speaker_gain_changed_slot;
124
pa_hook_slot *transport_microphone_gain_changed_slot;
126
pa_hook_slot *sink_state_changed_slot;
127
pa_hook_slot *source_state_changed_slot;
129
pa_hook_slot *sco_sink_proplist_changed_slot;
130
bool prevent_suspend_transport;
132
pa_bluetooth_discovery *discovery;
133
pa_bluetooth_device *device;
134
pa_bluetooth_transport *transport;
135
bool transport_acquired;
140
pa_bluetooth_profile_t profile;
141
char *output_port_name;
142
char *input_port_name;
145
pa_thread_mq thread_mq;
147
pa_rtpoll_item *rtpoll_item;
151
int stream_write_type;
152
size_t read_link_mtu;
153
size_t write_link_mtu;
154
size_t read_block_size;
155
size_t write_block_size;
157
uint64_t write_index;
158
pa_usec_t started_at;
159
pa_smoother *read_smoother;
160
pa_memchunk write_memchunk;
161
pa_sample_spec sample_spec;
162
struct sbc_info sbc_info;
165
char *default_profile;
166
bool transport_acquire_pending;
167
pa_io_event *stream_event;
169
pa_defer_event *set_default_profile_event;
172
typedef enum pa_bluetooth_form_factor {
173
PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
174
PA_BLUETOOTH_FORM_FACTOR_HEADSET,
175
PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
176
PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
177
PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
178
PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
179
PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
180
PA_BLUETOOTH_FORM_FACTOR_CAR,
181
PA_BLUETOOTH_FORM_FACTOR_HIFI,
182
PA_BLUETOOTH_FORM_FACTOR_PHONE,
183
} pa_bluetooth_form_factor_t;
185
/* Run from main thread */
186
static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
187
unsigned major, minor;
188
pa_bluetooth_form_factor_t r;
190
static const pa_bluetooth_form_factor_t table[] = {
191
[1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
192
[2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
193
[4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
194
[5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
195
[6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
196
[7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
197
[8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
198
[10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
202
* See Bluetooth Assigned Numbers:
203
* https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
205
major = (class_of_device >> 8) & 0x1F;
206
minor = (class_of_device >> 2) & 0x3F;
210
return PA_BLUETOOTH_FORM_FACTOR_PHONE;
214
pa_log_debug("Unknown Bluetooth major device class %u", major);
215
return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
218
r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
221
pa_log_debug("Unknown Bluetooth minor device class %u", minor);
226
/* Run from main thread */
227
static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
229
case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
231
case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
233
case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
235
case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
237
case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
239
case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
241
case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
243
case PA_BLUETOOTH_FORM_FACTOR_CAR:
245
case PA_BLUETOOTH_FORM_FACTOR_HIFI:
247
case PA_BLUETOOTH_FORM_FACTOR_PHONE:
251
pa_assert_not_reached();
254
/* Run from main thread */
255
static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
256
pa_device_port *port;
258
if (direction == PA_DIRECTION_OUTPUT) {
259
pa_sink_new_data *sink_new_data = new_data;
261
pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
262
pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
263
pa_device_port_ref(port);
265
pa_source_new_data *source_new_data = new_data;
267
pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
268
pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
269
pa_device_port_ref(port);
273
/* Run from IO thread */
274
static int sco_process_render(struct userdata *u) {
276
pa_memchunk memchunk;
279
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
280
u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
283
pa_sink_render_full(u->sink, u->write_block_size, &memchunk);
285
pa_assert(memchunk.length == u->write_block_size);
290
/* Now write that data to the socket. The socket is of type
291
* SEQPACKET, and we generated the data of the MTU size, so this
292
* should just work. */
294
p = (const uint8_t *) pa_memblock_acquire_chunk(&memchunk);
295
l = pa_write(u->stream_fd, p, memchunk.length, &u->stream_write_type);
296
pa_memblock_release(memchunk.memblock);
304
/* Retry right away if we got interrupted */
306
else if (errno == EAGAIN)
307
/* Hmm, apparently the socket was not writable, give up for now */
310
pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
314
pa_assert((size_t) l <= memchunk.length);
316
if ((size_t) l != memchunk.length) {
317
pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
318
(unsigned long long) l,
319
(unsigned long long) memchunk.length);
323
u->write_index += (uint64_t) memchunk.length;
324
pa_memblock_unref(memchunk.memblock);
329
/* Run from IO thread */
330
static int sco_process_push(struct userdata *u) {
332
pa_memchunk memchunk;
335
bool found_tstamp = false;
336
pa_usec_t tstamp = 0;
339
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
340
u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
341
pa_assert(u->source);
342
pa_assert(u->read_smoother);
344
memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
345
memchunk.index = memchunk.length = 0;
359
m.msg_controllen = sizeof(aux);
361
p = pa_memblock_acquire(memchunk.memblock);
363
iov.iov_len = pa_memblock_get_length(memchunk.memblock);
364
l = recvmsg(u->stream_fd, &m, 0);
365
pa_memblock_release(memchunk.memblock);
370
if (l < 0 && errno == EINTR)
371
/* Retry right away if we got interrupted */
374
pa_memblock_unref(memchunk.memblock);
376
if (l < 0 && errno == EAGAIN)
377
/* Hmm, apparently the socket was not readable, give up for now. */
380
pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
384
pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
386
/* In some rare occasions, we might receive packets of a very strange
387
* size. This could potentially be possible if the SCO packet was
388
* received partially over-the-air, or more probably due to hardware
389
* issues in our Bluetooth adapter. In these cases, in order to avoid
390
* an assertion failure due to unaligned data, just discard the whole
392
if (!pa_frame_aligned(l, &u->sample_spec)) {
393
pa_log_warn("SCO packet received of unaligned size: %zu", l);
394
pa_memblock_unref(memchunk.memblock);
398
memchunk.length = (size_t) l;
399
u->read_index += (uint64_t) l;
401
for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
402
if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
403
struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
404
pa_rtclock_from_wallclock(tv);
405
tstamp = pa_timeval_load(tv);
411
pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
412
tstamp = pa_rtclock_now();
415
pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
416
pa_smoother_resume(u->read_smoother, tstamp, true);
418
pa_source_post(u->source, &memchunk);
419
pa_memblock_unref(memchunk.memblock);
424
/* Run from IO thread */
425
static void a2dp_prepare_buffer(struct userdata *u) {
426
size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
430
if (u->sbc_info.buffer_size >= min_buffer_size)
433
u->sbc_info.buffer_size = 2 * min_buffer_size;
434
pa_xfree(u->sbc_info.buffer);
435
u->sbc_info.buffer = pa_xmalloc(u->sbc_info.buffer_size);
438
/* Run from IO thread */
439
static int a2dp_process_render(struct userdata *u) {
440
struct sbc_info *sbc_info;
441
struct rtp_header *header;
442
struct rtp_payload *payload;
446
size_t to_write, to_encode;
447
unsigned frame_count;
451
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
454
/* First, render some data */
455
if (!u->write_memchunk.memblock)
456
pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
458
pa_assert(u->write_memchunk.length == u->write_block_size);
460
a2dp_prepare_buffer(u);
462
sbc_info = &u->sbc_info;
463
header = sbc_info->buffer;
464
payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
468
/* Try to create a packet of the full MTU */
470
p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
471
to_encode = u->write_memchunk.length;
473
d = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
474
to_write = sbc_info->buffer_size - sizeof(*header) - sizeof(*payload);
476
while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
480
encoded = sbc_encode(&sbc_info->sbc,
485
if (PA_UNLIKELY(encoded <= 0)) {
486
pa_log_error("SBC encoding error (%li)", (long) encoded);
487
pa_memblock_release(u->write_memchunk.memblock);
491
pa_assert_fp((size_t) encoded <= to_encode);
492
pa_assert_fp((size_t) encoded == sbc_info->codesize);
494
pa_assert_fp((size_t) written <= to_write);
495
pa_assert_fp((size_t) written == sbc_info->frame_length);
497
p = (const uint8_t*) p + encoded;
498
to_encode -= encoded;
500
d = (uint8_t*) d + written;
506
pa_memblock_release(u->write_memchunk.memblock);
508
pa_assert(to_encode == 0);
511
pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
514
/* write it to the fifo */
515
memset(sbc_info->buffer, 0, sizeof(*header) + sizeof(*payload));
518
header->sequence_number = htons(sbc_info->seq_num++);
519
header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
520
header->ssrc = htonl(1);
521
payload->frame_count = frame_count;
523
nbytes = (uint8_t*) d - (uint8_t*) sbc_info->buffer;
528
l = pa_write(u->stream_fd, sbc_info->buffer, nbytes, &u->stream_write_type);
535
/* Retry right away if we got interrupted */
538
else if (errno == EAGAIN)
539
/* Hmm, apparently the socket was not writable, give up for now */
542
pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
547
pa_assert((size_t) l <= nbytes);
549
if ((size_t) l != nbytes) {
550
pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
551
(unsigned long long) l,
552
(unsigned long long) nbytes);
557
u->write_index += (uint64_t) u->write_memchunk.length;
558
pa_memblock_unref(u->write_memchunk.memblock);
559
pa_memchunk_reset(&u->write_memchunk);
569
/* Run from IO thread */
570
static int a2dp_process_push(struct userdata *u) {
572
pa_memchunk memchunk;
575
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
576
pa_assert(u->source);
577
pa_assert(u->read_smoother);
579
memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
580
memchunk.index = memchunk.length = 0;
583
bool found_tstamp = false;
585
struct sbc_info *sbc_info;
586
struct rtp_header *header;
587
struct rtp_payload *payload;
591
size_t to_write, to_decode;
592
size_t total_written = 0;
594
a2dp_prepare_buffer(u);
596
sbc_info = &u->sbc_info;
597
header = sbc_info->buffer;
598
payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
600
l = pa_read(u->stream_fd, sbc_info->buffer, sbc_info->buffer_size, &u->stream_write_type);
604
if (l < 0 && errno == EINTR)
605
/* Retry right away if we got interrupted */
608
else if (l < 0 && errno == EAGAIN)
609
/* Hmm, apparently the socket was not readable, give up for now. */
612
pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
617
pa_assert((size_t) l <= sbc_info->buffer_size);
619
/* TODO: get timestamp from rtp */
621
/* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
622
tstamp = pa_rtclock_now();
625
p = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
626
to_decode = l - sizeof(*header) - sizeof(*payload);
628
d = pa_memblock_acquire(memchunk.memblock);
629
to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
631
while (PA_LIKELY(to_decode > 0)) {
635
decoded = sbc_decode(&sbc_info->sbc,
640
if (PA_UNLIKELY(decoded <= 0)) {
641
pa_log_error("SBC decoding error (%li)", (long) decoded);
642
pa_memblock_release(memchunk.memblock);
643
pa_memblock_unref(memchunk.memblock);
647
total_written += written;
649
/* Reset frame length, it can be changed due to bitpool change */
650
sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
652
pa_assert_fp((size_t) decoded <= to_decode);
653
pa_assert_fp((size_t) decoded == sbc_info->frame_length);
655
pa_assert_fp((size_t) written == sbc_info->codesize);
657
p = (const uint8_t*) p + decoded;
658
to_decode -= decoded;
660
d = (uint8_t*) d + written;
664
u->read_index += (uint64_t) total_written;
665
pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
666
pa_smoother_resume(u->read_smoother, tstamp, true);
668
memchunk.length -= to_write;
670
pa_memblock_release(memchunk.memblock);
672
pa_source_post(u->source, &memchunk);
678
pa_memblock_unref(memchunk.memblock);
683
/* Run from I/O thread */
684
static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
685
struct sbc_info *sbc_info;
689
sbc_info = &u->sbc_info;
691
if (sbc_info->sbc.bitpool == bitpool)
694
if (bitpool > sbc_info->max_bitpool)
695
bitpool = sbc_info->max_bitpool;
696
else if (bitpool < sbc_info->min_bitpool)
697
bitpool = sbc_info->min_bitpool;
699
sbc_info->sbc.bitpool = bitpool;
701
sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
702
sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
704
pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
707
(u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
708
/ sbc_info->frame_length * sbc_info->codesize;
710
u->write_block_size =
711
(u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
712
/ sbc_info->frame_length * sbc_info->codesize;
714
pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
715
pa_sink_set_fixed_latency_within_thread(u->sink,
716
FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
719
/* Run from I/O thread */
720
static void a2dp_reduce_bitpool(struct userdata *u) {
721
struct sbc_info *sbc_info;
726
sbc_info = &u->sbc_info;
728
/* Check if bitpool is already at its limit */
729
if (sbc_info->sbc.bitpool <= BITPOOL_DEC_LIMIT)
732
bitpool = sbc_info->sbc.bitpool - BITPOOL_DEC_STEP;
734
if (bitpool < BITPOOL_DEC_LIMIT)
735
bitpool = BITPOOL_DEC_LIMIT;
737
a2dp_set_bitpool(u, bitpool);
740
static void teardown_stream(struct userdata *u) {
741
if (u->rtpoll_item) {
742
pa_rtpoll_item_free(u->rtpoll_item);
743
u->rtpoll_item = NULL;
746
if (u->stream_event) {
747
u->core->mainloop->io_free(u->stream_event);
748
u->stream_event = NULL;
751
if (u->stream_fd >= 0) {
752
pa_close(u->stream_fd);
756
if (u->read_smoother) {
757
pa_smoother_free(u->read_smoother);
758
u->read_smoother = NULL;
761
if (u->write_memchunk.memblock) {
762
pa_memblock_unref(u->write_memchunk.memblock);
763
pa_memchunk_reset(&u->write_memchunk);
766
pa_log_debug("Audio stream torn down");
769
static int transport_acquire(struct userdata *u, bool optional) {
770
pa_assert(u->transport);
772
if (u->transport_acquire_pending)
775
if (u->transport_acquired) {
776
pa_log_debug("Transport already acquired");
780
u->transport_acquire_pending = true;
782
pa_log_debug("Acquiring transport %s", u->transport->path);
784
u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
785
if (u->stream_fd < 0) {
786
u->transport_acquire_pending = false;
790
u->transport_acquired = true;
791
pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
793
u->transport_acquire_pending = false;
798
static void transport_release(struct userdata *u) {
799
pa_assert(u->transport);
801
/* Ignore if already released */
802
if (!u->transport_acquired)
805
pa_log_debug("Releasing transport %s", u->transport->path);
807
u->transport->release(u->transport);
809
u->transport_acquired = false;
814
/* Run from I/O thread */
815
static void transport_config_mtu(struct userdata *u) {
817
pa_log_debug("Configuring MTU for transport of profile %s",
818
pa_bluetooth_profile_to_string(u->profile));
820
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
821
u->read_block_size = u->read_link_mtu;
822
u->write_block_size = u->write_link_mtu;
825
(u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
826
/ u->sbc_info.frame_length * u->sbc_info.codesize;
828
u->write_block_size =
829
(u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
830
/ u->sbc_info.frame_length * u->sbc_info.codesize;
833
if (USE_SCO_OVER_PCM(u))
837
pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
838
pa_sink_set_fixed_latency_within_thread(u->sink,
839
(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
840
FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
841
pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
845
pa_source_set_fixed_latency_within_thread(u->source,
846
(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
847
FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
848
pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
851
/* Run from I/O thread except in SCO over PCM */
852
static void setup_stream(struct userdata *u) {
853
struct pollfd *pollfd;
856
pa_log_info("Transport %s resuming", u->transport->path);
858
transport_config_mtu(u);
860
pa_make_fd_nonblock(u->stream_fd);
861
pa_make_socket_low_delay(u->stream_fd);
864
if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
865
pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
867
pa_log_debug("Stream properly set up, we're ready to roll!");
869
if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
870
a2dp_set_bitpool(u, u->sbc_info.max_bitpool);
872
u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
873
pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
874
pollfd->fd = u->stream_fd;
875
pollfd->events = pollfd->revents = 0;
877
u->read_index = u->write_index = 0;
881
u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
884
/* Run from IO thread */
885
static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
886
struct userdata *u = PA_SOURCE(o)->userdata;
890
pa_assert(u->source == PA_SOURCE(o));
891
pa_assert(u->transport);
895
case PA_SOURCE_MESSAGE_SET_STATE:
897
switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
899
case PA_SOURCE_SUSPENDED:
900
/* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
901
if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
904
/* Stop the device if the sink is suspended as well */
905
if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
906
transport_release(u);
908
if (u->read_smoother)
909
pa_smoother_pause(u->read_smoother, pa_rtclock_now());
914
case PA_SOURCE_RUNNING:
915
if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
918
/* Resume the device if the sink was suspended as well */
919
if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
920
if (transport_acquire(u, false) < 0)
926
/* We don't resume the smoother here. Instead we
927
* wait until the first packet arrives */
931
case PA_SOURCE_UNLINKED:
933
case PA_SOURCE_INVALID_STATE:
939
case PA_SOURCE_MESSAGE_GET_LATENCY: {
942
if (u->read_smoother) {
943
wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
944
ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
946
*((pa_usec_t*) data) = FIXED_LATENCY_RECORD_A2DP + wi > ri ? FIXED_LATENCY_RECORD_A2DP + wi - ri : 0;
948
*((pa_usec_t*) data) = 0;
955
r = pa_source_process_msg(o, code, data, offset, chunk);
957
return (r < 0 || !failed) ? r : -1;
960
/* Run from main thread */
961
static void source_set_volume_cb(pa_source *s) {
972
pa_assert(u->source == s);
973
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
975
if (u->transport->set_microphone_gain == NULL)
978
gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
980
if (gain > HSP_MAX_GAIN)
983
volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
985
/* increment volume by one to correct rounding errors */
986
if (volume < PA_VOLUME_NORM)
989
pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
991
u->transport->set_microphone_gain(u->transport, gain);
994
/* Run from main thread */
995
static int add_source(struct userdata *u) {
996
pa_source_new_data data;
998
pa_assert(u->transport);
1000
if (USE_SCO_OVER_PCM(u)) {
1001
u->source = u->hsp.sco_source;
1002
pa_proplist_sets(u->source->proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1004
pa_source_new_data_init(&data);
1005
data.module = u->module;
1006
data.card = u->card;
1007
data.driver = __FILE__;
1008
data.name = pa_sprintf_malloc("bluez_source.%s", u->device->address);
1009
data.namereg_fail = false;
1010
pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1011
pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1012
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1013
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1015
connect_ports(u, &data, PA_DIRECTION_INPUT);
1017
if (!u->transport_acquired)
1018
switch (u->profile) {
1019
case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1020
case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1021
data.suspend_cause = PA_SUSPEND_USER;
1023
case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1024
case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1025
case PA_BLUETOOTH_PROFILE_OFF:
1026
pa_assert_not_reached();
1030
u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1031
pa_source_new_data_done(&data);
1033
pa_log_error("Failed to create source");
1037
u->source->userdata = u;
1038
u->source->parent.process_msg = source_process_msg;
1041
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
1042
pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1043
u->source->n_volume_steps = 16;
1049
#define HSP_PREVENT_SUSPEND_STR "bluetooth.hsp.prevent.suspend.transport"
1051
/* Check and update prevent_suspend_transport value from sco sink proplist.
1053
* Return < 0 if sink proplist doesn't contain HSP_PREVENT_SUSPEND_STR value,
1054
* 1 if value is 'true'
1055
* 0 if value is something else. */
1056
static int check_proplist(struct userdata *u) {
1061
pa_assert(u->hsp.sco_sink);
1063
if ((str = pa_proplist_gets(u->hsp.sco_sink->proplist, HSP_PREVENT_SUSPEND_STR))) {
1064
if (pa_streq(str, "true"))
1071
u->prevent_suspend_transport = ret == 1;
1073
pa_log_debug("Set %s %s (ret %d)", HSP_PREVENT_SUSPEND_STR, u->prevent_suspend_transport ? "true" : "false", ret);
1078
/* There are cases where keeping the transport running even when sco sink and source are suspended
1080
* To work with these cases, check sco.sink for bluetooth.hsp.prevent.suspend.transport value, and
1081
* when set to true prevent closing the transport when sink suspends.
1082
* Also, if the sink&source are suspended when sco-sink suspend.transport value changes to true,
1083
* bring sco transport up. When suspend.transport value changes to false while sink&source are suspended,
1084
* tear down the transport. */
1085
static pa_hook_result_t update_allow_release_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1089
if (!u->hsp.sco_sink || u->hsp.sco_sink != s)
1092
if (check_proplist(u) < 0)
1095
if (!USE_SCO_OVER_PCM(u)) {
1096
pa_log_debug("SCO sink not available.");
1100
if (!PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) &&
1101
!PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1103
pa_log_debug("Resuming SCO sink");
1105
/* Clear all suspend bits, effectively resuming SCO sink for a while. */
1106
pa_sink_suspend(s, false, PA_SUSPEND_ALL);
1112
/* Run from IO thread */
1113
static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1114
struct userdata *u = PA_SINK(o)->userdata;
1115
bool failed = false;
1118
pa_assert(u->sink == PA_SINK(o));
1119
pa_assert(u->transport);
1123
case PA_SINK_MESSAGE_SET_STATE:
1125
switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
1127
case PA_SINK_SUSPENDED:
1128
/* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1129
if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
1132
/* Stop the device if the source is suspended as well */
1133
if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1134
/* We deliberately ignore whether stopping
1135
* actually worked. Since the stream_fd is
1136
* closed it doesn't really matter */
1137
transport_release(u);
1142
case PA_SINK_RUNNING:
1143
if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
1146
/* Resume the device if the source was suspended as well */
1147
if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
1148
if (transport_acquire(u, false) < 0)
1156
case PA_SINK_UNLINKED:
1158
case PA_SINK_INVALID_STATE:
1164
case PA_SINK_MESSAGE_GET_LATENCY: {
1167
if (u->read_smoother) {
1168
ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1169
wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
1171
ri = pa_rtclock_now() - u->started_at;
1172
wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1175
*((pa_usec_t*) data) = FIXED_LATENCY_PLAYBACK_A2DP + wi > ri ? FIXED_LATENCY_PLAYBACK_A2DP + wi - ri : 0;
1181
r = pa_sink_process_msg(o, code, data, offset, chunk);
1183
return (r < 0 || !failed) ? r : -1;
1186
/* Run from main thread */
1187
static void sink_set_volume_cb(pa_sink *s) {
1198
pa_assert(u->sink == s);
1199
pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
1201
if (u->transport->set_speaker_gain == NULL)
1204
gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1206
if (gain > HSP_MAX_GAIN)
1207
gain = HSP_MAX_GAIN;
1209
volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1211
/* increment volume by one to correct rounding errors */
1212
if (volume < PA_VOLUME_NORM)
1215
pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1217
u->transport->set_speaker_gain(u->transport, gain);
1220
/* Run from main thread */
1221
static int add_sink(struct userdata *u) {
1222
pa_sink_new_data data;
1224
pa_assert(u->transport);
1226
if (USE_SCO_OVER_PCM(u)) {
1229
u->sink = u->hsp.sco_sink;
1230
p = pa_proplist_new();
1231
pa_proplist_sets(p, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1232
pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1233
pa_proplist_free(p);
1235
pa_sink_new_data_init(&data);
1236
data.module = u->module;
1237
data.card = u->card;
1238
data.driver = __FILE__;
1239
data.name = pa_sprintf_malloc("bluez_sink.%s", u->device->address);
1240
data.namereg_fail = false;
1241
pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1242
pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1243
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1244
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1246
connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1248
if (!u->transport_acquired)
1249
switch (u->profile) {
1250
case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1251
data.suspend_cause = PA_SUSPEND_USER;
1253
case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1254
/* Profile switch should have failed */
1255
case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1256
case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1257
case PA_BLUETOOTH_PROFILE_OFF:
1258
pa_assert_not_reached();
1262
u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1263
pa_sink_new_data_done(&data);
1265
pa_log_error("Failed to create sink");
1269
u->sink->userdata = u;
1270
u->sink->parent.process_msg = sink_process_msg;
1273
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
1274
pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1275
u->sink->n_volume_steps = 16;
1281
/* Run from main thread */
1282
static void transport_config(struct userdata *u) {
1284
pa_log_debug("Configuring transport for profile %s",
1285
pa_bluetooth_profile_to_string(u->profile));
1287
if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1288
u->sample_spec.format = PA_SAMPLE_S16LE;
1289
u->sample_spec.channels = 1;
1290
u->sample_spec.rate = 8000;
1292
sbc_info_t *sbc_info = &u->sbc_info;
1295
pa_assert(u->transport);
1297
u->sample_spec.format = PA_SAMPLE_S16LE;
1298
config = (a2dp_sbc_t *) u->transport->config;
1300
if (sbc_info->sbc_initialized)
1301
sbc_reinit(&sbc_info->sbc, 0);
1303
sbc_init(&sbc_info->sbc, 0);
1304
sbc_info->sbc_initialized = true;
1306
switch (config->frequency) {
1307
case SBC_SAMPLING_FREQ_16000:
1308
sbc_info->sbc.frequency = SBC_FREQ_16000;
1309
u->sample_spec.rate = 16000U;
1311
case SBC_SAMPLING_FREQ_32000:
1312
sbc_info->sbc.frequency = SBC_FREQ_32000;
1313
u->sample_spec.rate = 32000U;
1315
case SBC_SAMPLING_FREQ_44100:
1316
sbc_info->sbc.frequency = SBC_FREQ_44100;
1317
u->sample_spec.rate = 44100U;
1319
case SBC_SAMPLING_FREQ_48000:
1320
sbc_info->sbc.frequency = SBC_FREQ_48000;
1321
u->sample_spec.rate = 48000U;
1324
pa_assert_not_reached();
1327
switch (config->channel_mode) {
1328
case SBC_CHANNEL_MODE_MONO:
1329
sbc_info->sbc.mode = SBC_MODE_MONO;
1330
u->sample_spec.channels = 1;
1332
case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1333
sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1334
u->sample_spec.channels = 2;
1336
case SBC_CHANNEL_MODE_STEREO:
1337
sbc_info->sbc.mode = SBC_MODE_STEREO;
1338
u->sample_spec.channels = 2;
1340
case SBC_CHANNEL_MODE_JOINT_STEREO:
1341
sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
1342
u->sample_spec.channels = 2;
1345
pa_assert_not_reached();
1348
switch (config->allocation_method) {
1349
case SBC_ALLOCATION_SNR:
1350
sbc_info->sbc.allocation = SBC_AM_SNR;
1352
case SBC_ALLOCATION_LOUDNESS:
1353
sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
1356
pa_assert_not_reached();
1359
switch (config->subbands) {
1360
case SBC_SUBBANDS_4:
1361
sbc_info->sbc.subbands = SBC_SB_4;
1363
case SBC_SUBBANDS_8:
1364
sbc_info->sbc.subbands = SBC_SB_8;
1367
pa_assert_not_reached();
1370
switch (config->block_length) {
1371
case SBC_BLOCK_LENGTH_4:
1372
sbc_info->sbc.blocks = SBC_BLK_4;
1374
case SBC_BLOCK_LENGTH_8:
1375
sbc_info->sbc.blocks = SBC_BLK_8;
1377
case SBC_BLOCK_LENGTH_12:
1378
sbc_info->sbc.blocks = SBC_BLK_12;
1380
case SBC_BLOCK_LENGTH_16:
1381
sbc_info->sbc.blocks = SBC_BLK_16;
1384
pa_assert_not_reached();
1387
sbc_info->min_bitpool = config->min_bitpool;
1388
sbc_info->max_bitpool = config->max_bitpool;
1390
/* Set minimum bitpool for source to get the maximum possible block_size */
1391
sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
1392
sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
1393
sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
1395
pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
1396
sbc_info->sbc.allocation, sbc_info->sbc.subbands, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
1400
/* Run from main thread */
1401
static int setup_transport(struct userdata *u) {
1402
pa_bluetooth_transport *t;
1405
pa_assert(!u->transport_acquired);
1406
pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1408
pa_log_debug("profile %s", pa_bluetooth_profile_to_string(u->profile));
1410
/* check if profile has a transport */
1411
t = u->device->transports[u->profile];
1413
pa_log_debug("profile %s transport %p transport state %s",
1414
pa_bluetooth_profile_to_string(u->profile),
1415
t, t ? pa_bluetooth_transport_state_to_string(t->state) : "unknown");
1417
if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1418
pa_log_warn("Profile has no transport");
1424
if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1425
transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1426
else if (transport_acquire(u, false) < 0)
1427
return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1429
transport_config(u);
1434
/* Run from main thread */
1435
static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1436
static const pa_direction_t profile_direction[] = {
1437
[PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1438
[PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1439
[PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1440
[PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1441
[PA_BLUETOOTH_PROFILE_OFF] = 0
1444
return profile_direction[p];
1447
/* Run from main thread */
1448
static int init_profile(struct userdata *u) {
1451
pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1453
pa_log_debug("Initializing profile %s", pa_bluetooth_profile_to_string(u->profile));
1455
if (setup_transport(u) < 0)
1458
pa_assert(u->transport);
1460
pa_log_debug("Transport for profile %s successfully setup",
1461
pa_bluetooth_profile_to_string(u->profile));
1463
if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
1464
if (add_sink(u) < 0)
1467
if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
1468
if (add_source(u) < 0)
1474
/* I/O thread function */
1475
static void thread_func(void *userdata) {
1476
struct userdata *u = userdata;
1477
unsigned do_write = 0;
1478
unsigned pending_read_bytes = 0;
1479
bool writable = false;
1482
pa_assert(u->transport);
1484
pa_log_debug("IO Thread starting up");
1486
if (u->core->realtime_scheduling)
1487
pa_make_realtime(u->core->realtime_priority);
1489
pa_thread_mq_install(&u->thread_mq);
1491
/* Setup the stream only if the transport was already acquired */
1492
if (u->transport_acquired)
1496
struct pollfd *pollfd;
1498
bool disable_timer = true;
1500
pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1502
if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1503
pa_log_info("FD error: %s%s%s%s",
1504
pollfd->revents & POLLERR ? "POLLERR " :"",
1505
pollfd->revents & POLLHUP ? "POLLHUP " :"",
1506
pollfd->revents & POLLPRI ? "POLLPRI " :"",
1507
pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1509
if (pollfd->revents & POLLHUP) {
1513
pending_read_bytes = 0;
1515
pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, 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 == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1532
n_read = a2dp_process_push(u);
1534
n_read = sco_process_push(u);
1540
/* We just read something, so we are supposed to write something, too */
1541
pending_read_bytes += n_read;
1542
do_write += pending_read_bytes / u->write_block_size;
1543
pending_read_bytes = pending_read_bytes % u->write_block_size;
1548
if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1550
if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1551
pa_sink_process_rewind(u->sink, 0);
1554
if (pollfd->revents & POLLOUT)
1557
if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1558
pa_usec_t time_passed;
1559
pa_usec_t audio_sent;
1561
/* Hmm, there is no input stream we could synchronize
1562
* to. So let's do things by time */
1564
time_passed = pa_rtclock_now() - u->started_at;
1565
audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1567
if (audio_sent <= time_passed) {
1568
pa_usec_t audio_to_send = time_passed - audio_sent;
1570
/* Never try to catch up for more than 100ms */
1571
if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1572
pa_usec_t skip_usec;
1573
uint64_t skip_bytes;
1575
skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1576
skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1578
if (skip_bytes > 0) {
1581
pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1582
(unsigned long long) skip_usec,
1583
(unsigned long long) skip_bytes);
1585
pa_sink_render_full(u->sink, skip_bytes, &tmp);
1586
pa_memblock_unref(tmp.memblock);
1587
u->write_index += skip_bytes;
1589
if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1590
a2dp_reduce_bitpool(u);
1595
pending_read_bytes = 0;
1599
if (writable && do_write > 0) {
1602
if (u->write_index <= 0)
1603
u->started_at = pa_rtclock_now();
1605
if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
1606
if ((n_written = a2dp_process_render(u)) < 0)
1609
if ((n_written = sco_process_render(u)) < 0)
1614
pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1616
do_write -= n_written;
1620
if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1621
pa_usec_t sleep_for;
1622
pa_usec_t time_passed, next_write_at;
1625
/* Hmm, there is no input stream we could synchronize
1626
* to. So let's estimate when we need to wake up the latest */
1627
time_passed = pa_rtclock_now() - u->started_at;
1628
next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1629
sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1630
/* 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); */
1632
/* drop stream every 500 ms */
1633
sleep_for = PA_USEC_PER_MSEC * 500;
1635
pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1636
disable_timer = false;
1642
pa_rtpoll_set_timer_disabled(u->rtpoll);
1644
/* Hmm, nothing to do. Let's sleep */
1646
pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1647
(u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1649
if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1650
pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1654
pa_log_debug("IO thread shutdown requested, stopping cleanly");
1655
transport_release(u);
1661
/* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1662
pa_log_debug("IO thread failed");
1663
pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1664
pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1667
pa_log_debug("IO thread shutting down");
1670
static int sco_over_pcm_state_update(struct userdata *u, bool changed)
1673
pa_assert(USE_SCO_OVER_PCM(u));
1675
pa_log_debug("Updating SCO over PCM state (profile %s, changed %s, stream fd %d)",
1676
pa_bluetooth_profile_to_string(u->profile),
1677
changed ? "yes" : "no", u->stream_fd);
1679
if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1680
PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1682
if (u->stream_fd >= 0)
1685
pa_log_debug("Resuming SCO over PCM");
1687
if (init_profile(u) < 0) {
1688
pa_log("Can't resume SCO over PCM");
1698
if (u->stream_fd < 0)
1701
if (check_proplist(u) == 1) {
1702
pa_log_debug("Suspend prevention active, not closing SCO over PCM");
1706
pa_log_debug("Closing SCO over PCM");
1708
transport_release(u);
1714
static void stream_died_cb(pa_mainloop_api *ea, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata)
1716
struct userdata *u = userdata;
1719
pa_assert(u->transport);
1721
pa_log_warn("SCO stream went down");
1723
pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
1727
/* Run from main thread */
1728
static int start_thread(struct userdata *u) {
1730
pa_assert(!u->thread);
1731
pa_assert(!u->rtpoll);
1732
pa_assert(!u->rtpoll_item);
1734
u->rtpoll = pa_rtpoll_new();
1735
pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1737
if (USE_SCO_OVER_PCM(u)) {
1738
if (sco_over_pcm_state_update(u, false) < 0)
1741
pa_log_debug("Installing monitor for SCO stream");
1743
u->stream_event = u->core->mainloop->io_new(u->core->mainloop,
1744
u->stream_fd, PA_IO_EVENT_HANGUP | PA_IO_EVENT_ERROR, stream_died_cb, u);
1745
if (!u->stream_event) {
1746
pa_log_error("Failed to setup monitoring for SCO stream");
1750
pa_sink_ref(u->sink);
1751
pa_source_ref(u->source);
1756
if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1757
pa_log_error("Failed to create IO thread");
1762
pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1763
pa_sink_set_rtpoll(u->sink, u->rtpoll);
1764
pa_sink_put(u->sink);
1766
if (u->sink->set_volume)
1767
u->sink->set_volume(u->sink);
1771
pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1772
pa_source_set_rtpoll(u->source, u->rtpoll);
1773
pa_source_put(u->source);
1775
if (u->source->set_volume)
1776
u->source->set_volume(u->source);
1782
/* Run from main thread */
1783
static void stop_thread(struct userdata *u) {
1786
if (u->sink && !USE_SCO_OVER_PCM(u))
1787
pa_sink_unlink(u->sink);
1789
if (u->source && !USE_SCO_OVER_PCM(u))
1790
pa_source_unlink(u->source);
1793
pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1794
pa_thread_free(u->thread);
1798
if (u->rtpoll_item) {
1799
pa_rtpoll_item_free(u->rtpoll_item);
1800
u->rtpoll_item = NULL;
1804
pa_thread_mq_done(&u->thread_mq);
1805
pa_rtpoll_free(u->rtpoll);
1810
transport_release(u);
1811
/* Do not set transport pointer to NULL. When failing to switch
1812
* profile NULL u->transport would assert. */
1816
pa_sink_unref(u->sink);
1821
pa_source_unref(u->source);
1825
if (u->read_smoother) {
1826
pa_smoother_free(u->read_smoother);
1827
u->read_smoother = NULL;
1831
/* Run from main thread */
1832
static char *cleanup_name(const char *name) {
1838
while ((*name >= 1 && *name <= 32) || *name >= 127)
1841
t = pa_xstrdup(name);
1843
for (s = d = t; *s; s++) {
1845
if (*s <= 32 || *s >= 127 || *s == '_') {
1863
/* Run from main thread */
1864
static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1865
pa_available_t result = PA_AVAILABLE_NO;
1869
pa_assert(u->device);
1871
for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1872
pa_bluetooth_transport *transport;
1874
if (!(get_profile_direction(i) & direction))
1877
if (!(transport = u->device->transports[i]))
1880
switch(transport->state) {
1881
case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1884
case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1885
if (result == PA_AVAILABLE_NO)
1886
result = PA_AVAILABLE_UNKNOWN;
1890
case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1891
return PA_AVAILABLE_YES;
1898
/* Run from main thread */
1899
static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1901
case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1902
return PA_AVAILABLE_NO;
1903
case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1904
return PA_AVAILABLE_YES;
1906
return PA_AVAILABLE_UNKNOWN;
1910
/* Run from main thread */
1911
static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1912
pa_device_port *port;
1913
pa_device_port_new_data port_data;
1914
const char *name_prefix, *input_description, *output_description;
1918
pa_assert(u->device);
1920
name_prefix = "unknown";
1921
input_description = _("Bluetooth Input");
1922
output_description = _("Bluetooth Output");
1924
switch (form_factor_from_class(u->device->class_of_device)) {
1925
case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1926
name_prefix = "headset";
1927
input_description = output_description = _("Headset");
1930
case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1931
name_prefix = "handsfree";
1932
input_description = output_description = _("Handsfree");
1935
case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1936
name_prefix = "microphone";
1937
input_description = _("Microphone");
1938
output_description = _("Bluetooth Output");
1941
case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1942
name_prefix = "speaker";
1943
input_description = _("Bluetooth Input");
1944
output_description = _("Speaker");
1947
case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1948
name_prefix = "headphone";
1949
input_description = _("Bluetooth Input");
1950
output_description = _("Headphone");
1953
case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1954
name_prefix = "portable";
1955
input_description = output_description = _("Portable");
1958
case PA_BLUETOOTH_FORM_FACTOR_CAR:
1959
name_prefix = "car";
1960
input_description = output_description = _("Car");
1963
case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1964
name_prefix = "hifi";
1965
input_description = output_description = _("HiFi");
1968
case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1969
name_prefix = "phone";
1970
input_description = output_description = _("Phone");
1973
case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
1974
name_prefix = "unknown";
1975
input_description = _("Bluetooth Input");
1976
output_description = _("Bluetooth Output");
1980
u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
1981
pa_device_port_new_data_init(&port_data);
1982
pa_device_port_new_data_set_name(&port_data, u->output_port_name);
1983
pa_device_port_new_data_set_description(&port_data, output_description);
1984
pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
1985
pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
1986
pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1987
pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1988
pa_device_port_new_data_done(&port_data);
1990
u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
1991
pa_device_port_new_data_init(&port_data);
1992
pa_device_port_new_data_set_name(&port_data, u->input_port_name);
1993
pa_device_port_new_data_set_description(&port_data, input_description);
1994
pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
1995
pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
1996
pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1997
pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1998
pa_device_port_new_data_done(&port_data);
2001
/* Run from main thread */
2002
static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid, pa_hashmap *ports) {
2003
pa_device_port *input_port, *output_port;
2004
pa_card_profile *cp = NULL;
2005
pa_bluetooth_profile_t *p;
2007
pa_assert(u->input_port_name);
2008
pa_assert(u->output_port_name);
2009
pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2010
pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2012
if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
2013
cp = pa_card_profile_new("a2dp_sink", _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
2017
cp->max_sink_channels = 2;
2018
cp->max_source_channels = 0;
2019
pa_hashmap_put(output_port->profiles, cp->name, cp);
2021
p = PA_CARD_PROFILE_DATA(cp);
2022
*p = PA_BLUETOOTH_PROFILE_A2DP_SINK;
2023
} else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
2024
cp = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
2028
cp->max_sink_channels = 0;
2029
cp->max_source_channels = 2;
2030
pa_hashmap_put(input_port->profiles, cp->name, cp);
2032
p = PA_CARD_PROFILE_DATA(cp);
2033
*p = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
2034
} else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_HS) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF)) {
2035
cp = pa_card_profile_new("headset_head_unit", _("Headset Head Unit (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
2039
cp->max_sink_channels = 1;
2040
cp->max_source_channels = 1;
2041
pa_hashmap_put(input_port->profiles, cp->name, cp);
2042
pa_hashmap_put(output_port->profiles, cp->name, cp);
2044
p = PA_CARD_PROFILE_DATA(cp);
2045
*p = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
2046
} else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG)) {
2047
cp = pa_card_profile_new("headset_audio_gateway", _("Headset Audio Gateway (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
2051
cp->max_sink_channels = 1;
2052
cp->max_source_channels = 1;
2053
pa_hashmap_put(input_port->profiles, cp->name, cp);
2054
pa_hashmap_put(output_port->profiles, cp->name, cp);
2056
p = PA_CARD_PROFILE_DATA(cp);
2057
*p = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
2061
if (u->device->transports[*p])
2062
cp->available = transport_state_to_availability(u->device->transports[*p]->state);
2064
cp->available = PA_AVAILABLE_NO;
2070
/* Run from main thread */
2071
static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
2073
pa_bluetooth_profile_t *p;
2076
pa_assert(new_profile);
2077
pa_assert_se(u = c->userdata);
2079
p = PA_CARD_PROFILE_DATA(new_profile);
2081
pa_log_debug("Setting new profile %s for card (current %s)",
2082
pa_bluetooth_profile_to_string(*p),
2083
pa_bluetooth_profile_to_string(u->profile));
2085
if (*p != PA_BLUETOOTH_PROFILE_OFF) {
2086
const pa_bluetooth_device *d = u->device;
2088
if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2089
pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
2098
if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2099
if (init_profile(u) < 0)
2102
if (u->sink || u->source)
2103
if (start_thread(u) < 0)
2111
pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2116
/* Run from main thread */
2117
static int add_card(struct userdata *u) {
2118
const pa_bluetooth_device *d;
2119
pa_card_new_data data;
2121
pa_bluetooth_form_factor_t ff;
2122
pa_card_profile *cp;
2123
pa_bluetooth_profile_t *p;
2126
const char *default_profile;
2129
pa_assert(u->device);
2133
pa_card_new_data_init(&data);
2134
data.driver = __FILE__;
2135
data.module = u->module;
2137
alias = cleanup_name(d->alias);
2138
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2141
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2142
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2143
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2144
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2146
if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2147
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2149
pa_proplist_sets(data.proplist, "bluez.path", d->path);
2150
pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2151
pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2152
data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2153
data.namereg_fail = false;
2155
create_card_ports(u, data.ports);
2157
PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2158
cp = create_card_profile(u, uuid, data.ports);
2163
if (pa_hashmap_get(data.profiles, cp->name)) {
2164
pa_card_profile_free(cp);
2168
pa_hashmap_put(data.profiles, cp->name, cp);
2171
pa_assert(!pa_hashmap_isempty(data.profiles));
2173
cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2174
cp->available = PA_AVAILABLE_YES;
2175
p = PA_CARD_PROFILE_DATA(cp);
2176
*p = PA_BLUETOOTH_PROFILE_OFF;
2177
pa_hashmap_put(data.profiles, cp->name, cp);
2179
if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2180
if (pa_hashmap_get(data.profiles, default_profile)) {
2181
pa_card_new_data_set_profile(&data, default_profile);
2182
pa_log_debug("Using %s profile as default", default_profile);
2183
u->default_profile = pa_xstrdup(default_profile);
2186
pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2189
u->card = pa_card_new(u->core, &data);
2190
pa_card_new_data_done(&data);
2192
pa_log("Failed to allocate card.");
2196
u->card->userdata = u;
2197
u->card->set_profile = set_profile_cb;
2199
p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2201
if (*p != PA_BLUETOOTH_PROFILE_OFF && (!d->transports[*p] ||
2202
d->transports[*p]->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)) {
2203
pa_log_warn("Default profile not connected, selecting off profile");
2204
u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2205
u->card->save_profile = false;
2208
pa_xfree(u->default_profile);
2209
u->default_profile = NULL;
2212
p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2215
pa_log_debug("Created card (current profile %s)",
2216
pa_bluetooth_profile_to_string(u->profile));
2221
/* Run from main thread */
2222
static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2223
bool acquire = false;
2224
bool release = false;
2225
pa_card_profile *cp;
2226
pa_device_port *port;
2230
pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
2232
pa_log_debug("State of transport for profile %s changed to %s",
2233
pa_bluetooth_profile_to_string(t->profile),
2234
pa_bluetooth_transport_state_to_string(t->state));
2236
pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2238
/* Update port availability */
2239
pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2240
pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2241
pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2242
pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2244
/* Acquire or release transport as needed */
2245
acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2246
release = (t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2248
if (acquire && transport_acquire(u, true) >= 0) {
2250
pa_log_debug("Acquiring transport for profile %s",
2251
pa_bluetooth_profile_to_string(t->profile));
2254
pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2256
/* We remove the IDLE suspend cause, because otherwise
2257
* module-loopback doesn't uncork its streams. FIXME: Messing with
2258
* the IDLE suspend cause here is wrong, the correct way to handle
2259
* this would probably be to uncork the loopback streams not only
2260
* when the other end is unsuspended, but also when the other end's
2261
* suspend cause changes to IDLE only (currently there's no
2262
* notification mechanism for suspend cause changes, though). */
2263
pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2267
pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2269
/* FIXME: See the previous comment. */
2270
pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2274
if (release && u->transport_acquired) {
2275
/* FIXME: this release is racy, since the audio stream might have
2276
* been set up again in the meantime (but not processed yet by PA).
2277
* BlueZ should probably release the transport automatically, and in
2278
* that case we would just mark the transport as released */
2280
pa_log_debug("Releasing transport for profile %s",
2281
pa_bluetooth_profile_to_string(t->profile));
2283
/* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2285
pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2286
pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2290
pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2291
pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2296
/* Run from main thread */
2297
static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2301
if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
2304
pa_log_debug("Unloading module for device %s", d->path);
2305
pa_module_unload(u->core, u->module, true);
2310
static void set_default_profile_cb(pa_mainloop_api *api, pa_defer_event *e, void *user_data) {
2311
struct userdata *u = user_data;
2315
if (!u->default_profile)
2318
pa_log_debug("Setting default profile %s", u->default_profile);
2320
pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, u->default_profile), false) >= 0);
2321
pa_xfree(u->default_profile);
2322
u->default_profile = NULL;
2324
api->defer_enable(e, 0);
2327
/* Run from main thread */
2328
static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2332
pa_log_debug("State of transport for profile %s has changed to %s",
2333
pa_bluetooth_profile_to_string(t->profile),
2334
pa_bluetooth_transport_state_to_string(t->state));
2336
if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT && t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
2337
pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "headset_head_unit"), false) >= 0);
2339
else if (u->profile == PA_BLUETOOTH_PROFILE_OFF && pa_bluetooth_device_any_transport_connected(u->device) && u->default_profile)
2340
u->core->mainloop->defer_enable(u->set_default_profile_event, 1);
2342
else if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2343
pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2345
if (t->device == u->device)
2346
handle_transport_state_change(u, t);
2351
static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2359
if (t != u->transport)
2362
gain = t->speaker_gain;
2363
volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2365
/* increment volume by one to correct rounding errors */
2366
if (volume < PA_VOLUME_NORM)
2369
pa_cvolume_set(&v, u->sample_spec.channels, volume);
2370
pa_sink_volume_changed(u->sink, &v);
2375
static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2383
if (t != u->transport)
2386
gain = t->microphone_gain;
2387
volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2389
/* increment volume by one to correct rounding errors */
2390
if (volume < PA_VOLUME_NORM)
2393
pa_cvolume_set(&v, u->sample_spec.channels, volume);
2394
pa_source_volume_changed(u->source, &v);
2399
static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
2401
pa_sink_assert_ref(s);
2404
pa_log_debug("Sink %s state has changed", s->name);
2406
if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_sink)
2409
sco_over_pcm_state_update(u, true);
2414
static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
2416
pa_source_assert_ref(s);
2419
pa_log_debug("Source %s state has changed", s->name);
2421
if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_source)
2424
sco_over_pcm_state_update(u, true);
2429
/* Run from main thread context */
2430
static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2431
struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
2432
struct userdata *u = m->card->userdata;
2435
case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2436
if (m->card->module->unload_requested)
2439
pa_log_debug("Switching the profile to off due to IO thread failure.");
2440
pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
2442
case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
2443
pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
2450
int pa__init(pa_module* m) {
2457
m->userdata = u = pa_xnew0(struct userdata, 1);
2461
if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2462
pa_log_error("Failed to parse module arguments");
2466
if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2467
pa_log_error("Failed to get device path from module arguments");
2471
if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2472
!(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2473
pa_log("SCO sink not found");
2477
if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2478
!(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2479
pa_log("SCO source not found");
2483
if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2484
pa_bluetooth_discovery_ref(u->discovery);
2486
pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2490
if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2491
pa_log_error("%s is unknown", path);
2497
u->device_connection_changed_slot =
2498
pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2499
PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2501
u->transport_state_changed_slot =
2502
pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2503
PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2505
u->transport_speaker_gain_changed_slot =
2506
pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2508
u->transport_microphone_gain_changed_slot =
2509
pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2511
u->sink_state_changed_slot =
2512
pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED],
2513
PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
2515
u->source_state_changed_slot =
2516
pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED],
2517
PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2519
u->sco_sink_proplist_changed_slot =
2520
pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED],
2521
PA_HOOK_NORMAL, (pa_hook_cb_t) update_allow_release_cb, u);
2523
if (add_card(u) < 0)
2526
if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2529
u->set_default_profile_event = u->core->mainloop->defer_new(u->core->mainloop, set_default_profile_cb, u);
2530
u->core->mainloop->defer_enable(u->set_default_profile_event, 0);
2532
u->msg->parent.process_msg = device_process_msg;
2533
u->msg->card = u->card;
2535
if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2536
if (init_profile(u) < 0)
2539
if (u->sink || u->source)
2540
if (start_thread(u) < 0)
2548
pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2555
pa_modargs_free(ma);
2562
void pa__done(pa_module *m) {
2567
if (!(u = m->userdata))
2572
if (u->device_connection_changed_slot)
2573
pa_hook_slot_free(u->device_connection_changed_slot);
2575
if (u->transport_state_changed_slot)
2576
pa_hook_slot_free(u->transport_state_changed_slot);
2578
if (u->transport_speaker_gain_changed_slot)
2579
pa_hook_slot_free(u->transport_speaker_gain_changed_slot);
2581
if (u->transport_microphone_gain_changed_slot)
2582
pa_hook_slot_free(u->transport_microphone_gain_changed_slot);
2584
if (u->sink_state_changed_slot)
2585
pa_hook_slot_free(u->sink_state_changed_slot);
2587
if (u->source_state_changed_slot)
2588
pa_hook_slot_free(u->source_state_changed_slot);
2590
if (u->sco_sink_proplist_changed_slot)
2591
pa_hook_slot_free(u->sco_sink_proplist_changed_slot);
2593
if (u->sbc_info.buffer)
2594
pa_xfree(u->sbc_info.buffer);
2596
if (u->sbc_info.sbc_initialized)
2597
sbc_finish(&u->sbc_info.sbc);
2603
pa_card_free(u->card);
2606
pa_bluetooth_discovery_unref(u->discovery);
2608
pa_xfree(u->output_port_name);
2609
pa_xfree(u->input_port_name);
2612
pa_modargs_free(u->modargs);
2614
if (u->default_profile)
2615
pa_xfree(u->default_profile);
2617
if (u->set_default_profile_event)
2618
u->core->mainloop->defer_free(u->set_default_profile_event);
2623
int pa__get_n_used(pa_module *m) {
2627
pa_assert_se(u = m->userdata);
2629
return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);