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