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