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