]> code.delx.au - pulseaudio/blob - src/modules/bluetooth/module-bluez5-device.c
bluetooth: Handle changes to BlueZ 5 transports state
[pulseaudio] / src / modules / bluetooth / module-bluez5-device.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2008-2013 João Paulo Rechi Vita
5 Copyright 2011-2013 BMW Car IT GmbH.
6
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.
11
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.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with PulseAudio; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 USA.
21 ***/
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <errno.h>
28
29 #include <arpa/inet.h>
30 #include <sbc/sbc.h>
31
32 #include <pulse/rtclock.h>
33 #include <pulse/timeval.h>
34
35 #include <pulsecore/core-error.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/socket-util.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/time-smoother.h>
46
47 #include "a2dp-codecs.h"
48 #include "bluez5-util.h"
49 #include "rtp.h"
50
51 #include "module-bluez5-device-symdef.h"
52
53 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
54 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
55 PA_MODULE_VERSION(PACKAGE_VERSION);
56 PA_MODULE_LOAD_ONCE(false);
57 PA_MODULE_USAGE("path=<device object path>");
58
59 #define MAX_PLAYBACK_CATCH_UP_USEC (100 * PA_USEC_PER_MSEC)
60 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
61 #define FIXED_LATENCY_RECORD_A2DP (25 * PA_USEC_PER_MSEC)
62
63 #define BITPOOL_DEC_LIMIT 32
64 #define BITPOOL_DEC_STEP 5
65
66 static const char* const valid_modargs[] = {
67 "path",
68 NULL
69 };
70
71 enum {
72 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
73 BLUETOOTH_MESSAGE_MAX
74 };
75
76 typedef struct bluetooth_msg {
77 pa_msgobject parent;
78 pa_card *card;
79 } bluetooth_msg;
80 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
81 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
82
83 typedef struct sbc_info {
84 sbc_t sbc; /* Codec data */
85 bool sbc_initialized; /* Keep track if the encoder is initialized */
86 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
87 uint16_t seq_num; /* Cumulative packet sequence */
88 uint8_t min_bitpool;
89 uint8_t max_bitpool;
90
91 void* buffer; /* Codec transfer buffer */
92 size_t buffer_size; /* Size of the buffer */
93 } sbc_info_t;
94
95 struct userdata {
96 pa_module *module;
97 pa_core *core;
98
99 pa_hook_slot *device_connection_changed_slot;
100 pa_hook_slot *transport_state_changed_slot;
101
102 pa_bluetooth_discovery *discovery;
103 pa_bluetooth_device *device;
104 pa_bluetooth_transport *transport;
105 bool transport_acquired;
106
107 pa_card *card;
108 pa_sink *sink;
109 pa_source *source;
110 pa_bluetooth_profile_t profile;
111 char *output_port_name;
112 char *input_port_name;
113
114 pa_thread *thread;
115 pa_thread_mq thread_mq;
116 pa_rtpoll *rtpoll;
117 pa_rtpoll_item *rtpoll_item;
118 bluetooth_msg *msg;
119
120 int stream_fd;
121 int stream_write_type;
122 size_t read_link_mtu;
123 size_t write_link_mtu;
124 size_t read_block_size;
125 size_t write_block_size;
126 uint64_t read_index;
127 uint64_t write_index;
128 pa_usec_t started_at;
129 pa_smoother *read_smoother;
130 pa_memchunk write_memchunk;
131 pa_sample_spec sample_spec;
132 struct sbc_info sbc_info;
133 };
134
135 typedef enum pa_bluetooth_form_factor {
136 PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
137 PA_BLUETOOTH_FORM_FACTOR_HEADSET,
138 PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
139 PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
140 PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
141 PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
142 PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
143 PA_BLUETOOTH_FORM_FACTOR_CAR,
144 PA_BLUETOOTH_FORM_FACTOR_HIFI,
145 PA_BLUETOOTH_FORM_FACTOR_PHONE,
146 } pa_bluetooth_form_factor_t;
147
148 /* Run from main thread */
149 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
150 unsigned major, minor;
151 pa_bluetooth_form_factor_t r;
152
153 static const pa_bluetooth_form_factor_t table[] = {
154 [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
155 [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
156 [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
157 [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
158 [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
159 [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
160 [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
161 [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
162 };
163
164 /*
165 * See Bluetooth Assigned Numbers:
166 * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
167 */
168 major = (class_of_device >> 8) & 0x1F;
169 minor = (class_of_device >> 2) & 0x3F;
170
171 switch (major) {
172 case 2:
173 return PA_BLUETOOTH_FORM_FACTOR_PHONE;
174 case 4:
175 break;
176 default:
177 pa_log_debug("Unknown Bluetooth major device class %u", major);
178 return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
179 }
180
181 r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
182
183 if (!r)
184 pa_log_debug("Unknown Bluetooth minor device class %u", minor);
185
186 return r;
187 }
188
189 /* Run from main thread */
190 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
191 switch (ff) {
192 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
193 return "unknown";
194 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
195 return "headset";
196 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
197 return "hands-free";
198 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
199 return "microphone";
200 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
201 return "speaker";
202 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
203 return "headphone";
204 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
205 return "portable";
206 case PA_BLUETOOTH_FORM_FACTOR_CAR:
207 return "car";
208 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
209 return "hifi";
210 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
211 return "phone";
212 }
213
214 pa_assert_not_reached();
215 }
216
217 /* Run from main thread */
218 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
219 pa_device_port *port;
220
221 if (direction == PA_DIRECTION_OUTPUT) {
222 pa_sink_new_data *sink_new_data = new_data;
223
224 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
225 pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
226 pa_device_port_ref(port);
227 } else {
228 pa_source_new_data *source_new_data = new_data;
229
230 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
231 pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
232 pa_device_port_ref(port);
233 }
234 }
235
236 /* Run from IO thread */
237 static void a2dp_prepare_buffer(struct userdata *u) {
238 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
239
240 pa_assert(u);
241
242 if (u->sbc_info.buffer_size >= min_buffer_size)
243 return;
244
245 u->sbc_info.buffer_size = 2 * min_buffer_size;
246 pa_xfree(u->sbc_info.buffer);
247 u->sbc_info.buffer = pa_xmalloc(u->sbc_info.buffer_size);
248 }
249
250 /* Run from IO thread */
251 static int a2dp_process_render(struct userdata *u) {
252 struct sbc_info *sbc_info;
253 struct rtp_header *header;
254 struct rtp_payload *payload;
255 size_t nbytes;
256 void *d;
257 const void *p;
258 size_t to_write, to_encode;
259 unsigned frame_count;
260 int ret = 0;
261
262 pa_assert(u);
263 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
264 pa_assert(u->sink);
265
266 /* First, render some data */
267 if (!u->write_memchunk.memblock)
268 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
269
270 pa_assert(u->write_memchunk.length == u->write_block_size);
271
272 a2dp_prepare_buffer(u);
273
274 sbc_info = &u->sbc_info;
275 header = sbc_info->buffer;
276 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
277
278 frame_count = 0;
279
280 /* Try to create a packet of the full MTU */
281
282 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
283 to_encode = u->write_memchunk.length;
284
285 d = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
286 to_write = sbc_info->buffer_size - sizeof(*header) - sizeof(*payload);
287
288 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
289 ssize_t written;
290 ssize_t encoded;
291
292 encoded = sbc_encode(&sbc_info->sbc,
293 p, to_encode,
294 d, to_write,
295 &written);
296
297 if (PA_UNLIKELY(encoded <= 0)) {
298 pa_log_error("SBC encoding error (%li)", (long) encoded);
299 pa_memblock_release(u->write_memchunk.memblock);
300 return -1;
301 }
302
303 pa_assert_fp((size_t) encoded <= to_encode);
304 pa_assert_fp((size_t) encoded == sbc_info->codesize);
305
306 pa_assert_fp((size_t) written <= to_write);
307 pa_assert_fp((size_t) written == sbc_info->frame_length);
308
309 p = (const uint8_t*) p + encoded;
310 to_encode -= encoded;
311
312 d = (uint8_t*) d + written;
313 to_write -= written;
314
315 frame_count++;
316 }
317
318 pa_memblock_release(u->write_memchunk.memblock);
319
320 pa_assert(to_encode == 0);
321
322 PA_ONCE_BEGIN {
323 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
324 } PA_ONCE_END;
325
326 /* write it to the fifo */
327 memset(sbc_info->buffer, 0, sizeof(*header) + sizeof(*payload));
328 header->v = 2;
329 header->pt = 1;
330 header->sequence_number = htons(sbc_info->seq_num++);
331 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
332 header->ssrc = htonl(1);
333 payload->frame_count = frame_count;
334
335 nbytes = (uint8_t*) d - (uint8_t*) sbc_info->buffer;
336
337 for (;;) {
338 ssize_t l;
339
340 l = pa_write(u->stream_fd, sbc_info->buffer, nbytes, &u->stream_write_type);
341
342 pa_assert(l != 0);
343
344 if (l < 0) {
345
346 if (errno == EINTR)
347 /* Retry right away if we got interrupted */
348 continue;
349
350 else if (errno == EAGAIN)
351 /* Hmm, apparently the socket was not writable, give up for now */
352 break;
353
354 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
355 ret = -1;
356 break;
357 }
358
359 pa_assert((size_t) l <= nbytes);
360
361 if ((size_t) l != nbytes) {
362 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
363 (unsigned long long) l,
364 (unsigned long long) nbytes);
365 ret = -1;
366 break;
367 }
368
369 u->write_index += (uint64_t) u->write_memchunk.length;
370 pa_memblock_unref(u->write_memchunk.memblock);
371 pa_memchunk_reset(&u->write_memchunk);
372
373 ret = 1;
374
375 break;
376 }
377
378 return ret;
379 }
380
381 /* Run from IO thread */
382 static int a2dp_process_push(struct userdata *u) {
383 int ret = 0;
384 pa_memchunk memchunk;
385
386 pa_assert(u);
387 pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
388 pa_assert(u->source);
389 pa_assert(u->read_smoother);
390
391 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
392 memchunk.index = memchunk.length = 0;
393
394 for (;;) {
395 bool found_tstamp = false;
396 pa_usec_t tstamp;
397 struct sbc_info *sbc_info;
398 struct rtp_header *header;
399 struct rtp_payload *payload;
400 const void *p;
401 void *d;
402 ssize_t l;
403 size_t to_write, to_decode;
404
405 a2dp_prepare_buffer(u);
406
407 sbc_info = &u->sbc_info;
408 header = sbc_info->buffer;
409 payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
410
411 l = pa_read(u->stream_fd, sbc_info->buffer, sbc_info->buffer_size, &u->stream_write_type);
412
413 if (l <= 0) {
414
415 if (l < 0 && errno == EINTR)
416 /* Retry right away if we got interrupted */
417 continue;
418
419 else if (l < 0 && errno == EAGAIN)
420 /* Hmm, apparently the socket was not readable, give up for now. */
421 break;
422
423 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
424 ret = -1;
425 break;
426 }
427
428 pa_assert((size_t) l <= sbc_info->buffer_size);
429
430 u->read_index += (uint64_t) l;
431
432 /* TODO: get timestamp from rtp */
433 if (!found_tstamp) {
434 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
435 tstamp = pa_rtclock_now();
436 }
437
438 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
439 pa_smoother_resume(u->read_smoother, tstamp, true);
440
441 p = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
442 to_decode = l - sizeof(*header) - sizeof(*payload);
443
444 d = pa_memblock_acquire(memchunk.memblock);
445 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
446
447 while (PA_LIKELY(to_decode > 0)) {
448 size_t written;
449 ssize_t decoded;
450
451 decoded = sbc_decode(&sbc_info->sbc,
452 p, to_decode,
453 d, to_write,
454 &written);
455
456 if (PA_UNLIKELY(decoded <= 0)) {
457 pa_log_error("SBC decoding error (%li)", (long) decoded);
458 pa_memblock_release(memchunk.memblock);
459 pa_memblock_unref(memchunk.memblock);
460 return -1;
461 }
462
463 /* Reset frame length, it can be changed due to bitpool change */
464 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
465
466 pa_assert_fp((size_t) decoded <= to_decode);
467 pa_assert_fp((size_t) decoded == sbc_info->frame_length);
468
469 pa_assert_fp((size_t) written == sbc_info->codesize);
470
471 p = (const uint8_t*) p + decoded;
472 to_decode -= decoded;
473
474 d = (uint8_t*) d + written;
475 to_write -= written;
476 }
477
478 memchunk.length -= to_write;
479
480 pa_memblock_release(memchunk.memblock);
481
482 pa_source_post(u->source, &memchunk);
483
484 ret = l;
485 break;
486 }
487
488 pa_memblock_unref(memchunk.memblock);
489
490 return ret;
491 }
492
493 /* Run from I/O thread */
494 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
495 struct sbc_info *sbc_info;
496
497 pa_assert(u);
498
499 sbc_info = &u->sbc_info;
500
501 if (sbc_info->sbc.bitpool == bitpool)
502 return;
503
504 if (bitpool > sbc_info->max_bitpool)
505 bitpool = sbc_info->max_bitpool;
506 else if (bitpool < sbc_info->min_bitpool)
507 bitpool = sbc_info->min_bitpool;
508
509 sbc_info->sbc.bitpool = bitpool;
510
511 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
512 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
513
514 pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
515
516 u->read_block_size =
517 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
518 / sbc_info->frame_length * sbc_info->codesize;
519
520 u->write_block_size =
521 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
522 / sbc_info->frame_length * sbc_info->codesize;
523
524 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
525 pa_sink_set_fixed_latency_within_thread(u->sink,
526 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
527 }
528
529 /* Run from I/O thread */
530 static void a2dp_reduce_bitpool(struct userdata *u) {
531 struct sbc_info *sbc_info;
532 uint8_t bitpool;
533
534 pa_assert(u);
535
536 sbc_info = &u->sbc_info;
537
538 /* Check if bitpool is already at its limit */
539 if (sbc_info->sbc.bitpool <= BITPOOL_DEC_LIMIT)
540 return;
541
542 bitpool = sbc_info->sbc.bitpool - BITPOOL_DEC_STEP;
543
544 if (bitpool < BITPOOL_DEC_LIMIT)
545 bitpool = BITPOOL_DEC_LIMIT;
546
547 a2dp_set_bitpool(u, bitpool);
548 }
549
550 static void teardown_stream(struct userdata *u) {
551 if (u->rtpoll_item) {
552 pa_rtpoll_item_free(u->rtpoll_item);
553 u->rtpoll_item = NULL;
554 }
555
556 if (u->stream_fd >= 0) {
557 pa_close(u->stream_fd);
558 u->stream_fd = -1;
559 }
560
561 if (u->read_smoother) {
562 pa_smoother_free(u->read_smoother);
563 u->read_smoother = NULL;
564 }
565
566 if (u->write_memchunk.memblock) {
567 pa_memblock_unref(u->write_memchunk.memblock);
568 pa_memchunk_reset(&u->write_memchunk);
569 }
570
571 pa_log_debug("Audio stream torn down");
572 }
573
574 static int transport_acquire(struct userdata *u, bool optional) {
575 pa_assert(u->transport);
576
577 if (u->transport_acquired)
578 return 0;
579
580 pa_log_debug("Acquiring transport %s", u->transport->path);
581
582 u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
583 if (u->stream_fd < 0)
584 return -1;
585
586 u->transport_acquired = true;
587 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
588
589 return 0;
590 }
591
592 static void transport_release(struct userdata *u) {
593 pa_assert(u->transport);
594
595 /* Ignore if already released */
596 if (!u->transport_acquired)
597 return;
598
599 pa_log_debug("Releasing transport %s", u->transport->path);
600
601 u->transport->release(u->transport);
602
603 u->transport_acquired = false;
604
605 teardown_stream(u);
606 }
607
608 /* Run from I/O thread */
609 static void transport_config_mtu(struct userdata *u) {
610 u->read_block_size =
611 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
612 / u->sbc_info.frame_length * u->sbc_info.codesize;
613
614 u->write_block_size =
615 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
616 / u->sbc_info.frame_length * u->sbc_info.codesize;
617
618 if (u->sink) {
619 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
620 pa_sink_set_fixed_latency_within_thread(u->sink,
621 FIXED_LATENCY_PLAYBACK_A2DP +
622 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
623 }
624
625 if (u->source)
626 pa_source_set_fixed_latency_within_thread(u->source,
627 FIXED_LATENCY_RECORD_A2DP +
628 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
629 }
630
631 /* Run from I/O thread */
632 static void setup_stream(struct userdata *u) {
633 struct pollfd *pollfd;
634 int one;
635
636 pa_log_info("Transport %s resuming", u->transport->path);
637
638 transport_config_mtu(u);
639
640 pa_make_fd_nonblock(u->stream_fd);
641 pa_make_socket_low_delay(u->stream_fd);
642
643 one = 1;
644 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
645 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
646
647 pa_log_debug("Stream properly set up, we're ready to roll!");
648
649 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
650 a2dp_set_bitpool(u, u->sbc_info.max_bitpool);
651
652 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
653 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
654 pollfd->fd = u->stream_fd;
655 pollfd->events = pollfd->revents = 0;
656
657 u->read_index = u->write_index = 0;
658 u->started_at = 0;
659
660 if (u->source)
661 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
662 }
663
664 /* Run from IO thread */
665 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
666 struct userdata *u = PA_SOURCE(o)->userdata;
667 bool failed = false;
668 int r;
669
670 pa_assert(u->source == PA_SOURCE(o));
671 pa_assert(u->transport);
672
673 switch (code) {
674
675 case PA_SOURCE_MESSAGE_SET_STATE:
676
677 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
678
679 case PA_SOURCE_SUSPENDED:
680 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
681 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
682 break;
683
684 /* Stop the device if the sink is suspended as well */
685 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
686 transport_release(u);
687
688 if (u->read_smoother)
689 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
690
691 break;
692
693 case PA_SOURCE_IDLE:
694 case PA_SOURCE_RUNNING:
695 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
696 break;
697
698 /* Resume the device if the sink was suspended as well */
699 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
700 if (transport_acquire(u, false) < 0)
701 failed = true;
702 else
703 setup_stream(u);
704 }
705
706 /* We don't resume the smoother here. Instead we
707 * wait until the first packet arrives */
708
709 break;
710
711 case PA_SOURCE_UNLINKED:
712 case PA_SOURCE_INIT:
713 case PA_SOURCE_INVALID_STATE:
714 break;
715 }
716
717 break;
718
719 case PA_SOURCE_MESSAGE_GET_LATENCY: {
720 pa_usec_t wi, ri;
721
722 if (u->read_smoother) {
723 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
724 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
725
726 *((pa_usec_t*) data) = FIXED_LATENCY_RECORD_A2DP + wi > ri ? FIXED_LATENCY_RECORD_A2DP + wi - ri : 0;
727 } else
728 *((pa_usec_t*) data) = 0;
729
730 return 0;
731 }
732
733 }
734
735 r = pa_source_process_msg(o, code, data, offset, chunk);
736
737 return (r < 0 || !failed) ? r : -1;
738 }
739
740 /* Run from main thread */
741 static int add_source(struct userdata *u) {
742 pa_source_new_data data;
743
744 pa_assert(u->transport);
745
746 pa_source_new_data_init(&data);
747 data.module = u->module;
748 data.card = u->card;
749 data.driver = __FILE__;
750 data.name = pa_sprintf_malloc("bluez_source.%s", u->device->address);
751 data.namereg_fail = false;
752 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
753 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
754
755 connect_ports(u, &data, PA_DIRECTION_INPUT);
756
757 if (!u->transport_acquired)
758 switch (u->profile) {
759 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
760 data.suspend_cause = PA_SUSPEND_USER;
761 break;
762 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
763 case PA_BLUETOOTH_PROFILE_OFF:
764 pa_assert_not_reached();
765 break;
766 }
767
768 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
769 pa_source_new_data_done(&data);
770 if (!u->source) {
771 pa_log_error("Failed to create source");
772 return -1;
773 }
774
775 u->source->userdata = u;
776 u->source->parent.process_msg = source_process_msg;
777
778 return 0;
779 }
780
781 /* Run from IO thread */
782 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
783 struct userdata *u = PA_SINK(o)->userdata;
784 bool failed = false;
785 int r;
786
787 pa_assert(u->sink == PA_SINK(o));
788 pa_assert(u->transport);
789
790 switch (code) {
791
792 case PA_SINK_MESSAGE_SET_STATE:
793
794 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
795
796 case PA_SINK_SUSPENDED:
797 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
798 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
799 break;
800
801 /* Stop the device if the source is suspended as well */
802 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
803 /* We deliberately ignore whether stopping
804 * actually worked. Since the stream_fd is
805 * closed it doesn't really matter */
806 transport_release(u);
807
808 break;
809
810 case PA_SINK_IDLE:
811 case PA_SINK_RUNNING:
812 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
813 break;
814
815 /* Resume the device if the source was suspended as well */
816 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
817 if (transport_acquire(u, false) < 0)
818 failed = true;
819 else
820 setup_stream(u);
821 }
822
823 break;
824
825 case PA_SINK_UNLINKED:
826 case PA_SINK_INIT:
827 case PA_SINK_INVALID_STATE:
828 break;
829 }
830
831 break;
832
833 case PA_SINK_MESSAGE_GET_LATENCY: {
834 pa_usec_t wi, ri;
835
836 if (u->read_smoother) {
837 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
838 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
839 } else {
840 ri = pa_rtclock_now() - u->started_at;
841 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
842 }
843
844 *((pa_usec_t*) data) = FIXED_LATENCY_PLAYBACK_A2DP + wi > ri ? FIXED_LATENCY_PLAYBACK_A2DP + wi - ri : 0;
845
846 return 0;
847 }
848 }
849
850 r = pa_sink_process_msg(o, code, data, offset, chunk);
851
852 return (r < 0 || !failed) ? r : -1;
853 }
854
855 /* Run from main thread */
856 static int add_sink(struct userdata *u) {
857 pa_sink_new_data data;
858
859 pa_assert(u->transport);
860
861 pa_sink_new_data_init(&data);
862 data.module = u->module;
863 data.card = u->card;
864 data.driver = __FILE__;
865 data.name = pa_sprintf_malloc("bluez_sink.%s", u->device->address);
866 data.namereg_fail = false;
867 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
868 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
869
870 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
871
872 if (!u->transport_acquired)
873 switch (u->profile) {
874 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
875 /* Profile switch should have failed */
876 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
877 case PA_BLUETOOTH_PROFILE_OFF:
878 pa_assert_not_reached();
879 break;
880 }
881
882 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
883 pa_sink_new_data_done(&data);
884 if (!u->sink) {
885 pa_log_error("Failed to create sink");
886 return -1;
887 }
888
889 u->sink->userdata = u;
890 u->sink->parent.process_msg = sink_process_msg;
891
892 return 0;
893 }
894
895 /* Run from main thread */
896 static void transport_config(struct userdata *u) {
897 sbc_info_t *sbc_info = &u->sbc_info;
898 a2dp_sbc_t *config;
899
900 pa_assert(u->transport);
901
902 u->sample_spec.format = PA_SAMPLE_S16LE;
903 config = (a2dp_sbc_t *) u->transport->config;
904
905 if (sbc_info->sbc_initialized)
906 sbc_reinit(&sbc_info->sbc, 0);
907 else
908 sbc_init(&sbc_info->sbc, 0);
909 sbc_info->sbc_initialized = true;
910
911 switch (config->frequency) {
912 case SBC_SAMPLING_FREQ_16000:
913 sbc_info->sbc.frequency = SBC_FREQ_16000;
914 u->sample_spec.rate = 16000U;
915 break;
916 case SBC_SAMPLING_FREQ_32000:
917 sbc_info->sbc.frequency = SBC_FREQ_32000;
918 u->sample_spec.rate = 32000U;
919 break;
920 case SBC_SAMPLING_FREQ_44100:
921 sbc_info->sbc.frequency = SBC_FREQ_44100;
922 u->sample_spec.rate = 44100U;
923 break;
924 case SBC_SAMPLING_FREQ_48000:
925 sbc_info->sbc.frequency = SBC_FREQ_48000;
926 u->sample_spec.rate = 48000U;
927 break;
928 default:
929 pa_assert_not_reached();
930 }
931
932 switch (config->channel_mode) {
933 case SBC_CHANNEL_MODE_MONO:
934 sbc_info->sbc.mode = SBC_MODE_MONO;
935 u->sample_spec.channels = 1;
936 break;
937 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
938 sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
939 u->sample_spec.channels = 2;
940 break;
941 case SBC_CHANNEL_MODE_STEREO:
942 sbc_info->sbc.mode = SBC_MODE_STEREO;
943 u->sample_spec.channels = 2;
944 break;
945 case SBC_CHANNEL_MODE_JOINT_STEREO:
946 sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
947 u->sample_spec.channels = 2;
948 break;
949 default:
950 pa_assert_not_reached();
951 }
952
953 switch (config->allocation_method) {
954 case SBC_ALLOCATION_SNR:
955 sbc_info->sbc.allocation = SBC_AM_SNR;
956 break;
957 case SBC_ALLOCATION_LOUDNESS:
958 sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
959 break;
960 default:
961 pa_assert_not_reached();
962 }
963
964 switch (config->subbands) {
965 case SBC_SUBBANDS_4:
966 sbc_info->sbc.subbands = SBC_SB_4;
967 break;
968 case SBC_SUBBANDS_8:
969 sbc_info->sbc.subbands = SBC_SB_8;
970 break;
971 default:
972 pa_assert_not_reached();
973 }
974
975 switch (config->block_length) {
976 case SBC_BLOCK_LENGTH_4:
977 sbc_info->sbc.blocks = SBC_BLK_4;
978 break;
979 case SBC_BLOCK_LENGTH_8:
980 sbc_info->sbc.blocks = SBC_BLK_8;
981 break;
982 case SBC_BLOCK_LENGTH_12:
983 sbc_info->sbc.blocks = SBC_BLK_12;
984 break;
985 case SBC_BLOCK_LENGTH_16:
986 sbc_info->sbc.blocks = SBC_BLK_16;
987 break;
988 default:
989 pa_assert_not_reached();
990 }
991
992 sbc_info->min_bitpool = config->min_bitpool;
993 sbc_info->max_bitpool = config->max_bitpool;
994
995 /* Set minimum bitpool for source to get the maximum possible block_size */
996 sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
997 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
998 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
999
1000 pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
1001 sbc_info->sbc.allocation, sbc_info->sbc.subbands, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
1002 }
1003
1004 /* Run from main thread */
1005 static int setup_transport(struct userdata *u) {
1006 pa_bluetooth_transport *t;
1007
1008 pa_assert(u);
1009 pa_assert(!u->transport);
1010 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1011
1012 /* check if profile has a transport */
1013 t = u->device->transports[u->profile];
1014 if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1015 pa_log_warn("Profile has no transport");
1016 return -1;
1017 }
1018
1019 u->transport = t;
1020
1021 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1022 transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1023 else if (transport_acquire(u, false) < 0)
1024 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1025
1026 transport_config(u);
1027
1028 return 0;
1029 }
1030
1031 /* Run from main thread */
1032 static int init_profile(struct userdata *u) {
1033 int r = 0;
1034 pa_assert(u);
1035 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1036
1037 if (setup_transport(u) < 0)
1038 return -1;
1039
1040 pa_assert(u->transport);
1041
1042 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1043 if (add_sink(u) < 0)
1044 r = -1;
1045
1046 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1047 if (add_source(u) < 0)
1048 r = -1;
1049
1050 return r;
1051 }
1052
1053 /* I/O thread function */
1054 static void thread_func(void *userdata) {
1055 struct userdata *u = userdata;
1056 unsigned do_write = 0;
1057 unsigned pending_read_bytes = 0;
1058 bool writable = false;
1059
1060 pa_assert(u);
1061 pa_assert(u->transport);
1062
1063 pa_log_debug("IO Thread starting up");
1064
1065 if (u->core->realtime_scheduling)
1066 pa_make_realtime(u->core->realtime_priority);
1067
1068 pa_thread_mq_install(&u->thread_mq);
1069
1070 /* Setup the stream only if the transport was already acquired */
1071 if (u->transport_acquired)
1072 setup_stream(u);
1073
1074 for (;;) {
1075 struct pollfd *pollfd;
1076 int ret;
1077 bool disable_timer = true;
1078
1079 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1080
1081 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1082
1083 /* We should send two blocks to the device before we expect
1084 * a response. */
1085
1086 if (u->write_index == 0 && u->read_index <= 0)
1087 do_write = 2;
1088
1089 if (pollfd && (pollfd->revents & POLLIN)) {
1090 int n_read;
1091
1092 n_read = a2dp_process_push(u);
1093
1094 if (n_read < 0)
1095 goto io_fail;
1096
1097 /* We just read something, so we are supposed to write something, too */
1098 pending_read_bytes += n_read;
1099 do_write += pending_read_bytes / u->write_block_size;
1100 pending_read_bytes = pending_read_bytes % u->write_block_size;
1101 }
1102 }
1103
1104 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1105
1106 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1107 pa_sink_process_rewind(u->sink, 0);
1108
1109 if (pollfd) {
1110 if (pollfd->revents & POLLOUT)
1111 writable = true;
1112
1113 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1114 pa_usec_t time_passed;
1115 pa_usec_t audio_sent;
1116
1117 /* Hmm, there is no input stream we could synchronize
1118 * to. So let's do things by time */
1119
1120 time_passed = pa_rtclock_now() - u->started_at;
1121 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1122
1123 if (audio_sent <= time_passed) {
1124 pa_usec_t audio_to_send = time_passed - audio_sent;
1125
1126 /* Never try to catch up for more than 100ms */
1127 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1128 pa_usec_t skip_usec;
1129 uint64_t skip_bytes;
1130
1131 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1132 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1133
1134 if (skip_bytes > 0) {
1135 pa_memchunk tmp;
1136
1137 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1138 (unsigned long long) skip_usec,
1139 (unsigned long long) skip_bytes);
1140
1141 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1142 pa_memblock_unref(tmp.memblock);
1143 u->write_index += skip_bytes;
1144
1145 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1146 a2dp_reduce_bitpool(u);
1147 }
1148 }
1149
1150 do_write = 1;
1151 pending_read_bytes = 0;
1152 }
1153 }
1154
1155 if (writable && do_write > 0) {
1156 int n_written;
1157
1158 if (u->write_index <= 0)
1159 u->started_at = pa_rtclock_now();
1160
1161 if ((n_written = a2dp_process_render(u)) < 0)
1162 goto io_fail;
1163
1164 if (n_written == 0)
1165 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1166
1167 do_write -= n_written;
1168 writable = false;
1169 }
1170
1171 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1172 pa_usec_t sleep_for;
1173 pa_usec_t time_passed, next_write_at;
1174
1175 if (writable) {
1176 /* Hmm, there is no input stream we could synchronize
1177 * to. So let's estimate when we need to wake up the latest */
1178 time_passed = pa_rtclock_now() - u->started_at;
1179 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1180 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1181 /* 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); */
1182 } else
1183 /* drop stream every 500 ms */
1184 sleep_for = PA_USEC_PER_MSEC * 500;
1185
1186 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1187 disable_timer = false;
1188 }
1189 }
1190 }
1191
1192 if (disable_timer)
1193 pa_rtpoll_set_timer_disabled(u->rtpoll);
1194
1195 /* Hmm, nothing to do. Let's sleep */
1196 if (pollfd)
1197 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1198 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1199
1200 if ((ret = pa_rtpoll_run(u->rtpoll, true)) < 0) {
1201 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1202 goto fail;
1203 }
1204 if (ret == 0) {
1205 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1206 transport_release(u);
1207 goto finish;
1208 }
1209
1210 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1211
1212 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1213 pa_log_info("FD error: %s%s%s%s",
1214 pollfd->revents & POLLERR ? "POLLERR " :"",
1215 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1216 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1217 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1218 goto io_fail;
1219 }
1220
1221 continue;
1222
1223 io_fail:
1224 /* In case of HUP, just tear down the streams */
1225 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1226 goto fail;
1227
1228 do_write = 0;
1229 pending_read_bytes = 0;
1230 writable = false;
1231
1232 teardown_stream(u);
1233 }
1234
1235 fail:
1236 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1237 pa_log_debug("IO thread failed");
1238 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1239 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1240
1241 finish:
1242 pa_log_debug("IO thread shutting down");
1243 }
1244
1245 /* Run from main thread */
1246 static int start_thread(struct userdata *u) {
1247 pa_assert(u);
1248 pa_assert(!u->thread);
1249 pa_assert(!u->rtpoll);
1250 pa_assert(!u->rtpoll_item);
1251
1252 u->rtpoll = pa_rtpoll_new();
1253 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1254
1255 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1256 pa_log_error("Failed to create IO thread");
1257 return -1;
1258 }
1259
1260 if (u->sink) {
1261 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1262 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1263 pa_sink_put(u->sink);
1264
1265 if (u->sink->set_volume)
1266 u->sink->set_volume(u->sink);
1267 }
1268
1269 if (u->source) {
1270 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1271 pa_source_set_rtpoll(u->source, u->rtpoll);
1272 pa_source_put(u->source);
1273
1274 if (u->source->set_volume)
1275 u->source->set_volume(u->source);
1276 }
1277
1278 return 0;
1279 }
1280
1281 /* Run from main thread */
1282 static void stop_thread(struct userdata *u) {
1283 pa_assert(u);
1284
1285 if (u->sink)
1286 pa_sink_unlink(u->sink);
1287
1288 if (u->source)
1289 pa_source_unlink(u->source);
1290
1291 if (u->thread) {
1292 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1293 pa_thread_free(u->thread);
1294 u->thread = NULL;
1295 }
1296
1297 if (u->rtpoll_item) {
1298 pa_rtpoll_item_free(u->rtpoll_item);
1299 u->rtpoll_item = NULL;
1300 }
1301
1302 if (u->rtpoll) {
1303 pa_thread_mq_done(&u->thread_mq);
1304 pa_rtpoll_free(u->rtpoll);
1305 u->rtpoll = NULL;
1306 }
1307
1308 if (u->transport) {
1309 transport_release(u);
1310 u->transport = NULL;
1311 }
1312
1313 if (u->sink) {
1314 pa_sink_unref(u->sink);
1315 u->sink = NULL;
1316 }
1317
1318 if (u->source) {
1319 pa_source_unref(u->source);
1320 u->source = NULL;
1321 }
1322
1323 if (u->read_smoother) {
1324 pa_smoother_free(u->read_smoother);
1325 u->read_smoother = NULL;
1326 }
1327 }
1328
1329 /* Run from main thread */
1330 static char *cleanup_name(const char *name) {
1331 char *t, *s, *d;
1332 bool space = false;
1333
1334 pa_assert(name);
1335
1336 while ((*name >= 1 && *name <= 32) || *name >= 127)
1337 name++;
1338
1339 t = pa_xstrdup(name);
1340
1341 for (s = d = t; *s; s++) {
1342
1343 if (*s <= 32 || *s >= 127 || *s == '_') {
1344 space = true;
1345 continue;
1346 }
1347
1348 if (space) {
1349 *(d++) = ' ';
1350 space = false;
1351 }
1352
1353 *(d++) = *s;
1354 }
1355
1356 *d = 0;
1357
1358 return t;
1359 }
1360
1361 /* Run from main thread */
1362 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1363 static const pa_direction_t profile_direction[] = {
1364 [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1365 [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1366 [PA_BLUETOOTH_PROFILE_OFF] = 0
1367 };
1368
1369 return profile_direction[p];
1370 }
1371
1372 /* Run from main thread */
1373 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1374 pa_available_t result = PA_AVAILABLE_NO;
1375 unsigned i;
1376
1377 pa_assert(u);
1378 pa_assert(u->device);
1379
1380 for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1381 pa_bluetooth_transport *transport;
1382
1383 if (!(get_profile_direction(i) & direction))
1384 continue;
1385
1386 if (!(transport = u->device->transports[i]))
1387 continue;
1388
1389 switch(transport->state) {
1390 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1391 continue;
1392
1393 case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1394 if (result == PA_AVAILABLE_NO)
1395 result = PA_AVAILABLE_UNKNOWN;
1396
1397 break;
1398
1399 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1400 return PA_AVAILABLE_YES;
1401 }
1402 }
1403
1404 return result;
1405 }
1406
1407 /* Run from main thread */
1408 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1409 switch (state) {
1410 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1411 return PA_AVAILABLE_NO;
1412 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1413 return PA_AVAILABLE_YES;
1414 default:
1415 return PA_AVAILABLE_UNKNOWN;
1416 }
1417 }
1418
1419 /* Run from main thread */
1420 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1421 pa_device_port *port;
1422 pa_device_port_new_data port_data;
1423 const char *name_prefix, *input_description, *output_description;
1424
1425 pa_assert(u);
1426 pa_assert(ports);
1427 pa_assert(u->device);
1428
1429 name_prefix = "unknown";
1430 input_description = _("Bluetooth Input");
1431 output_description = _("Bluetooth Output");
1432
1433 switch (form_factor_from_class(u->device->class_of_device)) {
1434 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1435 name_prefix = "headset";
1436 input_description = output_description = _("Headset");
1437 break;
1438
1439 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1440 name_prefix = "handsfree";
1441 input_description = output_description = _("Handsfree");
1442 break;
1443
1444 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1445 name_prefix = "microphone";
1446 input_description = _("Microphone");
1447 output_description = _("Bluetooth Output");
1448 break;
1449
1450 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1451 name_prefix = "speaker";
1452 input_description = _("Bluetooth Input");
1453 output_description = _("Speaker");
1454 break;
1455
1456 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1457 name_prefix = "headphone";
1458 input_description = _("Bluetooth Input");
1459 output_description = _("Headphone");
1460 break;
1461
1462 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1463 name_prefix = "portable";
1464 input_description = output_description = _("Portable");
1465 break;
1466
1467 case PA_BLUETOOTH_FORM_FACTOR_CAR:
1468 name_prefix = "car";
1469 input_description = output_description = _("Car");
1470 break;
1471
1472 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1473 name_prefix = "hifi";
1474 input_description = output_description = _("HiFi");
1475 break;
1476
1477 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1478 name_prefix = "phone";
1479 input_description = output_description = _("Phone");
1480 break;
1481
1482 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
1483 name_prefix = "unknown";
1484 input_description = _("Bluetooth Input");
1485 output_description = _("Bluetooth Output");
1486 break;
1487 }
1488
1489 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
1490 pa_device_port_new_data_init(&port_data);
1491 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
1492 pa_device_port_new_data_set_description(&port_data, output_description);
1493 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
1494 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
1495 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1496 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1497 pa_device_port_new_data_done(&port_data);
1498
1499 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
1500 pa_device_port_new_data_init(&port_data);
1501 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
1502 pa_device_port_new_data_set_description(&port_data, input_description);
1503 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
1504 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
1505 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1506 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1507 pa_device_port_new_data_done(&port_data);
1508 }
1509
1510 /* Run from main thread */
1511 static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid, pa_hashmap *ports) {
1512 pa_device_port *input_port, *output_port;
1513 pa_card_profile *cp = NULL;
1514 pa_bluetooth_profile_t *p;
1515
1516 pa_assert(u->input_port_name);
1517 pa_assert(u->output_port_name);
1518 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
1519 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
1520
1521 if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
1522 /* TODO: Change this profile's name to a2dp_sink, to reflect the remote
1523 * device's role and be consistent with the a2dp source profile */
1524 cp = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
1525 cp->priority = 10;
1526 cp->n_sinks = 1;
1527 cp->n_sources = 0;
1528 cp->max_sink_channels = 2;
1529 cp->max_source_channels = 0;
1530 pa_hashmap_put(output_port->profiles, cp->name, cp);
1531
1532 p = PA_CARD_PROFILE_DATA(cp);
1533 *p = PA_BLUETOOTH_PROFILE_A2DP_SINK;
1534 } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
1535 cp = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
1536 cp->priority = 10;
1537 cp->n_sinks = 0;
1538 cp->n_sources = 1;
1539 cp->max_sink_channels = 0;
1540 cp->max_source_channels = 2;
1541 pa_hashmap_put(input_port->profiles, cp->name, cp);
1542
1543 p = PA_CARD_PROFILE_DATA(cp);
1544 *p = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
1545 }
1546
1547 if (cp && u->device->transports[*p])
1548 cp->available = transport_state_to_availability(u->device->transports[*p]->state);
1549
1550 return cp;
1551 }
1552
1553 /* Run from main thread */
1554 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
1555 struct userdata *u;
1556 pa_bluetooth_profile_t *p;
1557
1558 pa_assert(c);
1559 pa_assert(new_profile);
1560 pa_assert_se(u = c->userdata);
1561
1562 p = PA_CARD_PROFILE_DATA(new_profile);
1563
1564 if (*p != PA_BLUETOOTH_PROFILE_OFF) {
1565 const pa_bluetooth_device *d = u->device;
1566
1567 if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1568 pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
1569 return -PA_ERR_IO;
1570 }
1571 }
1572
1573 stop_thread(u);
1574
1575 u->profile = *p;
1576
1577 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
1578 if (init_profile(u) < 0)
1579 goto off;
1580
1581 if (u->sink || u->source)
1582 if (start_thread(u) < 0)
1583 goto off;
1584
1585 return 0;
1586
1587 off:
1588 stop_thread(u);
1589
1590 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1591
1592 return -PA_ERR_IO;
1593 }
1594
1595 /* Run from main thread */
1596 static int add_card(struct userdata *u) {
1597 const pa_bluetooth_device *d;
1598 pa_card_new_data data;
1599 char *alias;
1600 pa_bluetooth_form_factor_t ff;
1601 pa_card_profile *cp;
1602 pa_bluetooth_profile_t *p;
1603 const char *uuid;
1604 void *state;
1605
1606 pa_assert(u);
1607 pa_assert(u->device);
1608
1609 d = u->device;
1610
1611 pa_card_new_data_init(&data);
1612 data.driver = __FILE__;
1613 data.module = u->module;
1614
1615 alias = cleanup_name(d->alias);
1616 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
1617 pa_xfree(alias);
1618
1619 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
1620 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1621 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1622 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1623
1624 if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
1625 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
1626
1627 pa_proplist_sets(data.proplist, "bluez.path", d->path);
1628 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
1629 pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
1630 data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
1631 data.namereg_fail = false;
1632
1633 create_card_ports(u, data.ports);
1634
1635 PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
1636 cp = create_card_profile(u, uuid, data.ports);
1637
1638 if (!cp)
1639 continue;
1640
1641 if (pa_hashmap_get(data.profiles, cp->name)) {
1642 pa_card_profile_free(cp);
1643 continue;
1644 }
1645
1646 pa_hashmap_put(data.profiles, cp->name, cp);
1647 }
1648
1649 pa_assert(!pa_hashmap_isempty(data.profiles));
1650
1651 cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
1652 cp->available = PA_AVAILABLE_YES;
1653 p = PA_CARD_PROFILE_DATA(cp);
1654 *p = PA_BLUETOOTH_PROFILE_OFF;
1655 pa_hashmap_put(data.profiles, cp->name, cp);
1656
1657 u->card = pa_card_new(u->core, &data);
1658 pa_card_new_data_done(&data);
1659 if (!u->card) {
1660 pa_log("Failed to allocate card.");
1661 return -1;
1662 }
1663
1664 u->card->userdata = u;
1665 u->card->set_profile = set_profile_cb;
1666
1667 p = PA_CARD_PROFILE_DATA(u->card->active_profile);
1668 u->profile = *p;
1669
1670 return 0;
1671 }
1672
1673 /* Run from main thread */
1674 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
1675 bool acquire = false;
1676 bool release = false;
1677 pa_card_profile *cp;
1678 pa_device_port *port;
1679
1680 pa_assert(u);
1681 pa_assert(t);
1682
1683 /* Update profile availability */
1684 if (!(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile))))
1685 return;
1686 pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
1687
1688 /* Update port availability */
1689 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
1690 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
1691 pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
1692 pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
1693
1694 /* Acquire or release transport as needed */
1695 acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
1696 release = (t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
1697
1698 if (acquire && transport_acquire(u, true) >= 0) {
1699 if (u->source) {
1700 pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
1701 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1702 }
1703
1704 if (u->sink) {
1705 pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
1706 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1707 }
1708 }
1709
1710 if (release && u->transport_acquired) {
1711 /* FIXME: this release is racy, since the audio stream might have
1712 * been set up again in the meantime (but not processed yet by PA).
1713 * BlueZ should probably release the transport automatically, and in
1714 * that case we would just mark the transport as released */
1715
1716 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1717 if (u->source) {
1718 pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
1719 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
1720 }
1721
1722 if (u->sink) {
1723 pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
1724 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
1725 }
1726 }
1727 }
1728
1729 /* Run from main thread */
1730 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
1731 pa_assert(d);
1732 pa_assert(u);
1733
1734 if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
1735 return PA_HOOK_OK;
1736
1737 pa_log_debug("Unloading module for device %s", d->path);
1738 pa_module_unload(u->core, u->module, true);
1739
1740 return PA_HOOK_OK;
1741 }
1742
1743 /* Run from main thread */
1744 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
1745 pa_assert(t);
1746 pa_assert(u);
1747
1748 if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
1749 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1750
1751 if (t->device == u->device)
1752 handle_transport_state_change(u, t);
1753
1754 return PA_HOOK_OK;
1755 }
1756
1757 /* Run from main thread context */
1758 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1759 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
1760
1761 switch (code) {
1762 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
1763 if (u->card->module->unload_requested)
1764 break;
1765
1766 pa_log_debug("Switching the profile to off due to IO thread failure.");
1767 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1768 break;
1769 }
1770
1771 return 0;
1772 }
1773
1774 int pa__init(pa_module* m) {
1775 struct userdata *u;
1776 const char *path;
1777 pa_modargs *ma;
1778
1779 pa_assert(m);
1780
1781 m->userdata = u = pa_xnew0(struct userdata, 1);
1782 u->module = m;
1783 u->core = m->core;
1784
1785 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1786 pa_log_error("Failed to parse module arguments");
1787 goto fail;
1788 }
1789
1790 if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
1791 pa_log_error("Failed to get device path from module arguments");
1792 goto fail;
1793 }
1794
1795 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
1796 goto fail;
1797
1798 if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
1799 pa_log_error("%s is unknown", path);
1800 goto fail;
1801 }
1802
1803 pa_modargs_free(ma);
1804
1805 u->device_connection_changed_slot =
1806 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
1807 PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
1808
1809 u->transport_state_changed_slot =
1810 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
1811 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
1812
1813 if (add_card(u) < 0)
1814 goto fail;
1815
1816 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
1817 goto fail;
1818
1819 u->msg->parent.process_msg = device_process_msg;
1820 u->msg->card = u->card;
1821
1822 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
1823 if (init_profile(u) < 0)
1824 goto off;
1825
1826 if (u->sink || u->source)
1827 if (start_thread(u) < 0)
1828 goto off;
1829
1830 return 0;
1831
1832 off:
1833 stop_thread(u);
1834
1835 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1836
1837 return 0;
1838
1839 fail:
1840
1841 if (ma)
1842 pa_modargs_free(ma);
1843
1844 pa__done(m);
1845
1846 return -1;
1847 }
1848
1849 void pa__done(pa_module *m) {
1850 struct userdata *u;
1851
1852 pa_assert(m);
1853
1854 if (!(u = m->userdata))
1855 return;
1856
1857 stop_thread(u);
1858
1859 if (u->device_connection_changed_slot)
1860 pa_hook_slot_free(u->device_connection_changed_slot);
1861
1862 if (u->transport_state_changed_slot)
1863 pa_hook_slot_free(u->transport_state_changed_slot);
1864
1865 if (u->sbc_info.buffer)
1866 pa_xfree(u->sbc_info.buffer);
1867
1868 if (u->sbc_info.sbc_initialized)
1869 sbc_finish(&u->sbc_info.sbc);
1870
1871 if (u->msg)
1872 pa_xfree(u->msg);
1873
1874 if (u->card)
1875 pa_card_free(u->card);
1876
1877 if (u->discovery)
1878 pa_bluetooth_discovery_unref(u->discovery);
1879
1880 pa_xfree(u->output_port_name);
1881 pa_xfree(u->input_port_name);
1882
1883 pa_xfree(u);
1884 }