]> code.delx.au - pulseaudio/blob - src/modules/bluetooth/module-bluez5-device.c
bluetooth: Process source 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 IO thread */
664 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
665 struct userdata *u = PA_SOURCE(o)->userdata;
666 bool failed = false;
667 int r;
668
669 pa_assert(u->source == PA_SOURCE(o));
670 pa_assert(u->transport);
671
672 switch (code) {
673
674 case PA_SOURCE_MESSAGE_SET_STATE:
675
676 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
677
678 case PA_SOURCE_SUSPENDED:
679 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
680 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
681 break;
682
683 /* Stop the device if the sink is suspended as well */
684 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
685 transport_release(u);
686
687 if (u->read_smoother)
688 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
689
690 break;
691
692 case PA_SOURCE_IDLE:
693 case PA_SOURCE_RUNNING:
694 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
695 break;
696
697 /* Resume the device if the sink was suspended as well */
698 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
699 if (transport_acquire(u, false) < 0)
700 failed = true;
701 else
702 setup_stream(u);
703 }
704
705 /* We don't resume the smoother here. Instead we
706 * wait until the first packet arrives */
707
708 break;
709
710 case PA_SOURCE_UNLINKED:
711 case PA_SOURCE_INIT:
712 case PA_SOURCE_INVALID_STATE:
713 break;
714 }
715
716 break;
717
718 case PA_SOURCE_MESSAGE_GET_LATENCY: {
719 pa_usec_t wi, ri;
720
721 if (u->read_smoother) {
722 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
723 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
724
725 *((pa_usec_t*) data) = FIXED_LATENCY_RECORD_A2DP + wi > ri ? FIXED_LATENCY_RECORD_A2DP + wi - ri : 0;
726 } else
727 *((pa_usec_t*) data) = 0;
728
729 return 0;
730 }
731
732 }
733
734 r = pa_source_process_msg(o, code, data, offset, chunk);
735
736 return (r < 0 || !failed) ? r : -1;
737 }
738
739 /* Run from main thread */
740 static int add_source(struct userdata *u) {
741 pa_source_new_data data;
742
743 pa_assert(u->transport);
744
745 pa_source_new_data_init(&data);
746 data.module = u->module;
747 data.card = u->card;
748 data.driver = __FILE__;
749 data.name = pa_sprintf_malloc("bluez_source.%s", u->device->address);
750 data.namereg_fail = false;
751 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
752 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
753
754 connect_ports(u, &data, PA_DIRECTION_INPUT);
755
756 if (!u->transport_acquired)
757 switch (u->profile) {
758 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
759 data.suspend_cause = PA_SUSPEND_USER;
760 break;
761 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
762 case PA_BLUETOOTH_PROFILE_OFF:
763 pa_assert_not_reached();
764 break;
765 }
766
767 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
768 pa_source_new_data_done(&data);
769 if (!u->source) {
770 pa_log_error("Failed to create source");
771 return -1;
772 }
773
774 u->source->userdata = u;
775 u->source->parent.process_msg = source_process_msg;
776
777 return 0;
778 }
779
780 /* Run from IO thread */
781 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
782 struct userdata *u = PA_SINK(o)->userdata;
783 bool failed = false;
784 int r;
785
786 pa_assert(u->sink == PA_SINK(o));
787 pa_assert(u->transport);
788
789 switch (code) {
790
791 case PA_SINK_MESSAGE_SET_STATE:
792
793 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
794
795 case PA_SINK_SUSPENDED:
796 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
797 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
798 break;
799
800 /* Stop the device if the source is suspended as well */
801 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
802 /* We deliberately ignore whether stopping
803 * actually worked. Since the stream_fd is
804 * closed it doesn't really matter */
805 transport_release(u);
806
807 break;
808
809 case PA_SINK_IDLE:
810 case PA_SINK_RUNNING:
811 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
812 break;
813
814 /* Resume the device if the source was suspended as well */
815 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
816 if (transport_acquire(u, false) < 0)
817 failed = true;
818 else
819 setup_stream(u);
820 }
821
822 break;
823
824 case PA_SINK_UNLINKED:
825 case PA_SINK_INIT:
826 case PA_SINK_INVALID_STATE:
827 break;
828 }
829
830 break;
831
832 case PA_SINK_MESSAGE_GET_LATENCY: {
833 pa_usec_t wi, ri;
834
835 if (u->read_smoother) {
836 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
837 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
838 } else {
839 ri = pa_rtclock_now() - u->started_at;
840 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
841 }
842
843 *((pa_usec_t*) data) = FIXED_LATENCY_PLAYBACK_A2DP + wi > ri ? FIXED_LATENCY_PLAYBACK_A2DP + wi - ri : 0;
844
845 return 0;
846 }
847 }
848
849 r = pa_sink_process_msg(o, code, data, offset, chunk);
850
851 return (r < 0 || !failed) ? r : -1;
852 }
853
854 /* Run from main thread */
855 static int add_sink(struct userdata *u) {
856 pa_sink_new_data data;
857
858 pa_assert(u->transport);
859
860 pa_sink_new_data_init(&data);
861 data.module = u->module;
862 data.card = u->card;
863 data.driver = __FILE__;
864 data.name = pa_sprintf_malloc("bluez_sink.%s", u->device->address);
865 data.namereg_fail = false;
866 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
867 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
868
869 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
870
871 if (!u->transport_acquired)
872 switch (u->profile) {
873 case PA_BLUETOOTH_PROFILE_A2DP_SINK:
874 /* Profile switch should have failed */
875 case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
876 case PA_BLUETOOTH_PROFILE_OFF:
877 pa_assert_not_reached();
878 break;
879 }
880
881 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
882 pa_sink_new_data_done(&data);
883 if (!u->sink) {
884 pa_log_error("Failed to create sink");
885 return -1;
886 }
887
888 u->sink->userdata = u;
889 u->sink->parent.process_msg = sink_process_msg;
890
891 return 0;
892 }
893
894 /* Run from main thread */
895 static void transport_config(struct userdata *u) {
896 sbc_info_t *sbc_info = &u->sbc_info;
897 a2dp_sbc_t *config;
898
899 pa_assert(u->transport);
900
901 u->sample_spec.format = PA_SAMPLE_S16LE;
902 config = (a2dp_sbc_t *) u->transport->config;
903
904 if (sbc_info->sbc_initialized)
905 sbc_reinit(&sbc_info->sbc, 0);
906 else
907 sbc_init(&sbc_info->sbc, 0);
908 sbc_info->sbc_initialized = true;
909
910 switch (config->frequency) {
911 case SBC_SAMPLING_FREQ_16000:
912 sbc_info->sbc.frequency = SBC_FREQ_16000;
913 u->sample_spec.rate = 16000U;
914 break;
915 case SBC_SAMPLING_FREQ_32000:
916 sbc_info->sbc.frequency = SBC_FREQ_32000;
917 u->sample_spec.rate = 32000U;
918 break;
919 case SBC_SAMPLING_FREQ_44100:
920 sbc_info->sbc.frequency = SBC_FREQ_44100;
921 u->sample_spec.rate = 44100U;
922 break;
923 case SBC_SAMPLING_FREQ_48000:
924 sbc_info->sbc.frequency = SBC_FREQ_48000;
925 u->sample_spec.rate = 48000U;
926 break;
927 default:
928 pa_assert_not_reached();
929 }
930
931 switch (config->channel_mode) {
932 case SBC_CHANNEL_MODE_MONO:
933 sbc_info->sbc.mode = SBC_MODE_MONO;
934 u->sample_spec.channels = 1;
935 break;
936 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
937 sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
938 u->sample_spec.channels = 2;
939 break;
940 case SBC_CHANNEL_MODE_STEREO:
941 sbc_info->sbc.mode = SBC_MODE_STEREO;
942 u->sample_spec.channels = 2;
943 break;
944 case SBC_CHANNEL_MODE_JOINT_STEREO:
945 sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
946 u->sample_spec.channels = 2;
947 break;
948 default:
949 pa_assert_not_reached();
950 }
951
952 switch (config->allocation_method) {
953 case SBC_ALLOCATION_SNR:
954 sbc_info->sbc.allocation = SBC_AM_SNR;
955 break;
956 case SBC_ALLOCATION_LOUDNESS:
957 sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
958 break;
959 default:
960 pa_assert_not_reached();
961 }
962
963 switch (config->subbands) {
964 case SBC_SUBBANDS_4:
965 sbc_info->sbc.subbands = SBC_SB_4;
966 break;
967 case SBC_SUBBANDS_8:
968 sbc_info->sbc.subbands = SBC_SB_8;
969 break;
970 default:
971 pa_assert_not_reached();
972 }
973
974 switch (config->block_length) {
975 case SBC_BLOCK_LENGTH_4:
976 sbc_info->sbc.blocks = SBC_BLK_4;
977 break;
978 case SBC_BLOCK_LENGTH_8:
979 sbc_info->sbc.blocks = SBC_BLK_8;
980 break;
981 case SBC_BLOCK_LENGTH_12:
982 sbc_info->sbc.blocks = SBC_BLK_12;
983 break;
984 case SBC_BLOCK_LENGTH_16:
985 sbc_info->sbc.blocks = SBC_BLK_16;
986 break;
987 default:
988 pa_assert_not_reached();
989 }
990
991 sbc_info->min_bitpool = config->min_bitpool;
992 sbc_info->max_bitpool = config->max_bitpool;
993
994 /* Set minimum bitpool for source to get the maximum possible block_size */
995 sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
996 sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
997 sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
998
999 pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
1000 sbc_info->sbc.allocation, sbc_info->sbc.subbands, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
1001 }
1002
1003 /* Run from main thread */
1004 static int setup_transport(struct userdata *u) {
1005 pa_bluetooth_transport *t;
1006
1007 pa_assert(u);
1008 pa_assert(!u->transport);
1009 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1010
1011 /* check if profile has a transport */
1012 t = u->device->transports[u->profile];
1013 if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1014 pa_log_warn("Profile has no transport");
1015 return -1;
1016 }
1017
1018 u->transport = t;
1019
1020 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1021 transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1022 else if (transport_acquire(u, false) < 0)
1023 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1024
1025 transport_config(u);
1026
1027 return 0;
1028 }
1029
1030 /* Run from main thread */
1031 static int init_profile(struct userdata *u) {
1032 int r = 0;
1033 pa_assert(u);
1034 pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1035
1036 if (setup_transport(u) < 0)
1037 return -1;
1038
1039 pa_assert(u->transport);
1040
1041 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1042 if (add_sink(u) < 0)
1043 r = -1;
1044
1045 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1046 if (add_source(u) < 0)
1047 r = -1;
1048
1049 return r;
1050 }
1051
1052 /* I/O thread function */
1053 static void thread_func(void *userdata) {
1054 struct userdata *u = userdata;
1055 unsigned do_write = 0;
1056 unsigned pending_read_bytes = 0;
1057 bool writable = false;
1058
1059 pa_assert(u);
1060 pa_assert(u->transport);
1061
1062 pa_log_debug("IO Thread starting up");
1063
1064 if (u->core->realtime_scheduling)
1065 pa_make_realtime(u->core->realtime_priority);
1066
1067 pa_thread_mq_install(&u->thread_mq);
1068
1069 /* Setup the stream only if the transport was already acquired */
1070 if (u->transport_acquired)
1071 setup_stream(u);
1072
1073 for (;;) {
1074 struct pollfd *pollfd;
1075 int ret;
1076 bool disable_timer = true;
1077
1078 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1079
1080 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1081
1082 /* We should send two blocks to the device before we expect
1083 * a response. */
1084
1085 if (u->write_index == 0 && u->read_index <= 0)
1086 do_write = 2;
1087
1088 if (pollfd && (pollfd->revents & POLLIN)) {
1089 int n_read;
1090
1091 n_read = a2dp_process_push(u);
1092
1093 if (n_read < 0)
1094 goto io_fail;
1095
1096 /* We just read something, so we are supposed to write something, too */
1097 pending_read_bytes += n_read;
1098 do_write += pending_read_bytes / u->write_block_size;
1099 pending_read_bytes = pending_read_bytes % u->write_block_size;
1100 }
1101 }
1102
1103 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1104
1105 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1106 pa_sink_process_rewind(u->sink, 0);
1107
1108 if (pollfd) {
1109 if (pollfd->revents & POLLOUT)
1110 writable = true;
1111
1112 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1113 pa_usec_t time_passed;
1114 pa_usec_t audio_sent;
1115
1116 /* Hmm, there is no input stream we could synchronize
1117 * to. So let's do things by time */
1118
1119 time_passed = pa_rtclock_now() - u->started_at;
1120 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1121
1122 if (audio_sent <= time_passed) {
1123 pa_usec_t audio_to_send = time_passed - audio_sent;
1124
1125 /* Never try to catch up for more than 100ms */
1126 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1127 pa_usec_t skip_usec;
1128 uint64_t skip_bytes;
1129
1130 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1131 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1132
1133 if (skip_bytes > 0) {
1134 pa_memchunk tmp;
1135
1136 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1137 (unsigned long long) skip_usec,
1138 (unsigned long long) skip_bytes);
1139
1140 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1141 pa_memblock_unref(tmp.memblock);
1142 u->write_index += skip_bytes;
1143
1144 if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1145 a2dp_reduce_bitpool(u);
1146 }
1147 }
1148
1149 do_write = 1;
1150 pending_read_bytes = 0;
1151 }
1152 }
1153
1154 if (writable && do_write > 0) {
1155 int n_written;
1156
1157 if (u->write_index <= 0)
1158 u->started_at = pa_rtclock_now();
1159
1160 if ((n_written = a2dp_process_render(u)) < 0)
1161 goto io_fail;
1162
1163 if (n_written == 0)
1164 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1165
1166 do_write -= n_written;
1167 writable = false;
1168 }
1169
1170 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1171 pa_usec_t sleep_for;
1172 pa_usec_t time_passed, next_write_at;
1173
1174 if (writable) {
1175 /* Hmm, there is no input stream we could synchronize
1176 * to. So let's estimate when we need to wake up the latest */
1177 time_passed = pa_rtclock_now() - u->started_at;
1178 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1179 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1180 /* 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); */
1181 } else
1182 /* drop stream every 500 ms */
1183 sleep_for = PA_USEC_PER_MSEC * 500;
1184
1185 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1186 disable_timer = false;
1187 }
1188 }
1189 }
1190
1191 if (disable_timer)
1192 pa_rtpoll_set_timer_disabled(u->rtpoll);
1193
1194 /* Hmm, nothing to do. Let's sleep */
1195 if (pollfd)
1196 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1197 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1198
1199 if ((ret = pa_rtpoll_run(u->rtpoll, true)) < 0) {
1200 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1201 goto fail;
1202 }
1203 if (ret == 0) {
1204 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1205 transport_release(u);
1206 goto finish;
1207 }
1208
1209 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1210
1211 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1212 pa_log_info("FD error: %s%s%s%s",
1213 pollfd->revents & POLLERR ? "POLLERR " :"",
1214 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1215 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1216 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1217 goto io_fail;
1218 }
1219
1220 continue;
1221
1222 io_fail:
1223 /* In case of HUP, just tear down the streams */
1224 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1225 goto fail;
1226
1227 do_write = 0;
1228 pending_read_bytes = 0;
1229 writable = false;
1230
1231 teardown_stream(u);
1232 }
1233
1234 fail:
1235 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1236 pa_log_debug("IO thread failed");
1237 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1238 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1239
1240 finish:
1241 pa_log_debug("IO thread shutting down");
1242 }
1243
1244 /* Run from main thread */
1245 static int start_thread(struct userdata *u) {
1246 pa_assert(u);
1247 pa_assert(!u->thread);
1248 pa_assert(!u->rtpoll);
1249 pa_assert(!u->rtpoll_item);
1250
1251 u->rtpoll = pa_rtpoll_new();
1252 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1253
1254 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1255 pa_log_error("Failed to create IO thread");
1256 return -1;
1257 }
1258
1259 if (u->sink) {
1260 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1261 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1262 pa_sink_put(u->sink);
1263
1264 if (u->sink->set_volume)
1265 u->sink->set_volume(u->sink);
1266 }
1267
1268 if (u->source) {
1269 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1270 pa_source_set_rtpoll(u->source, u->rtpoll);
1271 pa_source_put(u->source);
1272
1273 if (u->source->set_volume)
1274 u->source->set_volume(u->source);
1275 }
1276
1277 return 0;
1278 }
1279
1280 /* Run from main thread */
1281 static void stop_thread(struct userdata *u) {
1282 pa_assert(u);
1283
1284 if (u->sink)
1285 pa_sink_unlink(u->sink);
1286
1287 if (u->source)
1288 pa_source_unlink(u->source);
1289
1290 if (u->thread) {
1291 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1292 pa_thread_free(u->thread);
1293 u->thread = NULL;
1294 }
1295
1296 if (u->rtpoll_item) {
1297 pa_rtpoll_item_free(u->rtpoll_item);
1298 u->rtpoll_item = NULL;
1299 }
1300
1301 if (u->rtpoll) {
1302 pa_thread_mq_done(&u->thread_mq);
1303 pa_rtpoll_free(u->rtpoll);
1304 u->rtpoll = NULL;
1305 }
1306
1307 if (u->transport) {
1308 transport_release(u);
1309 u->transport = NULL;
1310 }
1311
1312 if (u->sink) {
1313 pa_sink_unref(u->sink);
1314 u->sink = NULL;
1315 }
1316
1317 if (u->source) {
1318 pa_source_unref(u->source);
1319 u->source = NULL;
1320 }
1321
1322 if (u->read_smoother) {
1323 pa_smoother_free(u->read_smoother);
1324 u->read_smoother = NULL;
1325 }
1326 }
1327
1328 /* Run from main thread */
1329 static char *cleanup_name(const char *name) {
1330 char *t, *s, *d;
1331 bool space = false;
1332
1333 pa_assert(name);
1334
1335 while ((*name >= 1 && *name <= 32) || *name >= 127)
1336 name++;
1337
1338 t = pa_xstrdup(name);
1339
1340 for (s = d = t; *s; s++) {
1341
1342 if (*s <= 32 || *s >= 127 || *s == '_') {
1343 space = true;
1344 continue;
1345 }
1346
1347 if (space) {
1348 *(d++) = ' ';
1349 space = false;
1350 }
1351
1352 *(d++) = *s;
1353 }
1354
1355 *d = 0;
1356
1357 return t;
1358 }
1359
1360 /* Run from main thread */
1361 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1362 static const pa_direction_t profile_direction[] = {
1363 [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1364 [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1365 [PA_BLUETOOTH_PROFILE_OFF] = 0
1366 };
1367
1368 return profile_direction[p];
1369 }
1370
1371 /* Run from main thread */
1372 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1373 pa_available_t result = PA_AVAILABLE_NO;
1374 unsigned i;
1375
1376 pa_assert(u);
1377 pa_assert(u->device);
1378
1379 for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1380 pa_bluetooth_transport *transport;
1381
1382 if (!(get_profile_direction(i) & direction))
1383 continue;
1384
1385 if (!(transport = u->device->transports[i]))
1386 continue;
1387
1388 switch(transport->state) {
1389 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1390 continue;
1391
1392 case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1393 if (result == PA_AVAILABLE_NO)
1394 result = PA_AVAILABLE_UNKNOWN;
1395
1396 break;
1397
1398 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1399 return PA_AVAILABLE_YES;
1400 }
1401 }
1402
1403 return result;
1404 }
1405
1406 /* Run from main thread */
1407 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1408 switch (state) {
1409 case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1410 return PA_AVAILABLE_NO;
1411 case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1412 return PA_AVAILABLE_YES;
1413 default:
1414 return PA_AVAILABLE_UNKNOWN;
1415 }
1416 }
1417
1418 /* Run from main thread */
1419 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1420 pa_device_port *port;
1421 pa_device_port_new_data port_data;
1422 const char *name_prefix, *input_description, *output_description;
1423
1424 pa_assert(u);
1425 pa_assert(ports);
1426 pa_assert(u->device);
1427
1428 name_prefix = "unknown";
1429 input_description = _("Bluetooth Input");
1430 output_description = _("Bluetooth Output");
1431
1432 switch (form_factor_from_class(u->device->class_of_device)) {
1433 case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1434 name_prefix = "headset";
1435 input_description = output_description = _("Headset");
1436 break;
1437
1438 case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1439 name_prefix = "handsfree";
1440 input_description = output_description = _("Handsfree");
1441 break;
1442
1443 case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1444 name_prefix = "microphone";
1445 input_description = _("Microphone");
1446 output_description = _("Bluetooth Output");
1447 break;
1448
1449 case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1450 name_prefix = "speaker";
1451 input_description = _("Bluetooth Input");
1452 output_description = _("Speaker");
1453 break;
1454
1455 case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1456 name_prefix = "headphone";
1457 input_description = _("Bluetooth Input");
1458 output_description = _("Headphone");
1459 break;
1460
1461 case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1462 name_prefix = "portable";
1463 input_description = output_description = _("Portable");
1464 break;
1465
1466 case PA_BLUETOOTH_FORM_FACTOR_CAR:
1467 name_prefix = "car";
1468 input_description = output_description = _("Car");
1469 break;
1470
1471 case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1472 name_prefix = "hifi";
1473 input_description = output_description = _("HiFi");
1474 break;
1475
1476 case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1477 name_prefix = "phone";
1478 input_description = output_description = _("Phone");
1479 break;
1480
1481 case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
1482 name_prefix = "unknown";
1483 input_description = _("Bluetooth Input");
1484 output_description = _("Bluetooth Output");
1485 break;
1486 }
1487
1488 u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
1489 pa_device_port_new_data_init(&port_data);
1490 pa_device_port_new_data_set_name(&port_data, u->output_port_name);
1491 pa_device_port_new_data_set_description(&port_data, output_description);
1492 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
1493 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
1494 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1495 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1496 pa_device_port_new_data_done(&port_data);
1497
1498 u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
1499 pa_device_port_new_data_init(&port_data);
1500 pa_device_port_new_data_set_name(&port_data, u->input_port_name);
1501 pa_device_port_new_data_set_description(&port_data, input_description);
1502 pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
1503 pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
1504 pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1505 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1506 pa_device_port_new_data_done(&port_data);
1507 }
1508
1509 /* Run from main thread */
1510 static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid, pa_hashmap *ports) {
1511 pa_device_port *input_port, *output_port;
1512 pa_card_profile *cp = NULL;
1513 pa_bluetooth_profile_t *p;
1514
1515 pa_assert(u->input_port_name);
1516 pa_assert(u->output_port_name);
1517 pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
1518 pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
1519
1520 if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
1521 /* TODO: Change this profile's name to a2dp_sink, to reflect the remote
1522 * device's role and be consistent with the a2dp source profile */
1523 cp = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
1524 cp->priority = 10;
1525 cp->n_sinks = 1;
1526 cp->n_sources = 0;
1527 cp->max_sink_channels = 2;
1528 cp->max_source_channels = 0;
1529 pa_hashmap_put(output_port->profiles, cp->name, cp);
1530
1531 p = PA_CARD_PROFILE_DATA(cp);
1532 *p = PA_BLUETOOTH_PROFILE_A2DP_SINK;
1533 } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
1534 cp = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
1535 cp->priority = 10;
1536 cp->n_sinks = 0;
1537 cp->n_sources = 1;
1538 cp->max_sink_channels = 0;
1539 cp->max_source_channels = 2;
1540 pa_hashmap_put(input_port->profiles, cp->name, cp);
1541
1542 p = PA_CARD_PROFILE_DATA(cp);
1543 *p = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
1544 }
1545
1546 if (cp && u->device->transports[*p])
1547 cp->available = transport_state_to_availability(u->device->transports[*p]->state);
1548
1549 return cp;
1550 }
1551
1552 /* Run from main thread */
1553 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
1554 struct userdata *u;
1555 pa_bluetooth_profile_t *p;
1556
1557 pa_assert(c);
1558 pa_assert(new_profile);
1559 pa_assert_se(u = c->userdata);
1560
1561 p = PA_CARD_PROFILE_DATA(new_profile);
1562
1563 if (*p != PA_BLUETOOTH_PROFILE_OFF) {
1564 const pa_bluetooth_device *d = u->device;
1565
1566 if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1567 pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
1568 return -PA_ERR_IO;
1569 }
1570 }
1571
1572 stop_thread(u);
1573
1574 u->profile = *p;
1575
1576 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
1577 if (init_profile(u) < 0)
1578 goto off;
1579
1580 if (u->sink || u->source)
1581 if (start_thread(u) < 0)
1582 goto off;
1583
1584 return 0;
1585
1586 off:
1587 stop_thread(u);
1588
1589 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1590
1591 return -PA_ERR_IO;
1592 }
1593
1594 /* Run from main thread */
1595 static int add_card(struct userdata *u) {
1596 const pa_bluetooth_device *d;
1597 pa_card_new_data data;
1598 char *alias;
1599 pa_bluetooth_form_factor_t ff;
1600 pa_card_profile *cp;
1601 pa_bluetooth_profile_t *p;
1602 const char *uuid;
1603 void *state;
1604
1605 pa_assert(u);
1606 pa_assert(u->device);
1607
1608 d = u->device;
1609
1610 pa_card_new_data_init(&data);
1611 data.driver = __FILE__;
1612 data.module = u->module;
1613
1614 alias = cleanup_name(d->alias);
1615 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
1616 pa_xfree(alias);
1617
1618 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
1619 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1620 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1621 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1622
1623 if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
1624 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
1625
1626 pa_proplist_sets(data.proplist, "bluez.path", d->path);
1627 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
1628 pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
1629 data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
1630 data.namereg_fail = false;
1631
1632 create_card_ports(u, data.ports);
1633
1634 PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
1635 cp = create_card_profile(u, uuid, data.ports);
1636
1637 if (!cp)
1638 continue;
1639
1640 if (pa_hashmap_get(data.profiles, cp->name)) {
1641 pa_card_profile_free(cp);
1642 continue;
1643 }
1644
1645 pa_hashmap_put(data.profiles, cp->name, cp);
1646 }
1647
1648 pa_assert(!pa_hashmap_isempty(data.profiles));
1649
1650 cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
1651 cp->available = PA_AVAILABLE_YES;
1652 p = PA_CARD_PROFILE_DATA(cp);
1653 *p = PA_BLUETOOTH_PROFILE_OFF;
1654 pa_hashmap_put(data.profiles, cp->name, cp);
1655
1656 u->card = pa_card_new(u->core, &data);
1657 pa_card_new_data_done(&data);
1658 if (!u->card) {
1659 pa_log("Failed to allocate card.");
1660 return -1;
1661 }
1662
1663 u->card->userdata = u;
1664 u->card->set_profile = set_profile_cb;
1665
1666 p = PA_CARD_PROFILE_DATA(u->card->active_profile);
1667 u->profile = *p;
1668
1669 return 0;
1670 }
1671
1672 /* Run from main thread */
1673 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
1674 pa_assert(d);
1675 pa_assert(u);
1676
1677 if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
1678 return PA_HOOK_OK;
1679
1680 pa_log_debug("Unloading module for device %s", d->path);
1681 pa_module_unload(u->core, u->module, true);
1682
1683 return PA_HOOK_OK;
1684 }
1685
1686 /* Run from main thread context */
1687 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1688 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
1689
1690 switch (code) {
1691 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
1692 if (u->card->module->unload_requested)
1693 break;
1694
1695 pa_log_debug("Switching the profile to off due to IO thread failure.");
1696 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1697 break;
1698 }
1699
1700 return 0;
1701 }
1702
1703 int pa__init(pa_module* m) {
1704 struct userdata *u;
1705 const char *path;
1706 pa_modargs *ma;
1707
1708 pa_assert(m);
1709
1710 m->userdata = u = pa_xnew0(struct userdata, 1);
1711 u->module = m;
1712 u->core = m->core;
1713
1714 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1715 pa_log_error("Failed to parse module arguments");
1716 goto fail;
1717 }
1718
1719 if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
1720 pa_log_error("Failed to get device path from module arguments");
1721 goto fail;
1722 }
1723
1724 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
1725 goto fail;
1726
1727 if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
1728 pa_log_error("%s is unknown", path);
1729 goto fail;
1730 }
1731
1732 pa_modargs_free(ma);
1733
1734 u->device_connection_changed_slot =
1735 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
1736 PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
1737
1738 if (add_card(u) < 0)
1739 goto fail;
1740
1741 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
1742 goto fail;
1743
1744 u->msg->parent.process_msg = device_process_msg;
1745 u->msg->card = u->card;
1746
1747 if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
1748 if (init_profile(u) < 0)
1749 goto off;
1750
1751 if (u->sink || u->source)
1752 if (start_thread(u) < 0)
1753 goto off;
1754
1755 return 0;
1756
1757 off:
1758 stop_thread(u);
1759
1760 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1761
1762 return 0;
1763
1764 fail:
1765
1766 if (ma)
1767 pa_modargs_free(ma);
1768
1769 pa__done(m);
1770
1771 return -1;
1772 }
1773
1774 void pa__done(pa_module *m) {
1775 struct userdata *u;
1776
1777 pa_assert(m);
1778
1779 if (!(u = m->userdata))
1780 return;
1781
1782 stop_thread(u);
1783
1784 if (u->device_connection_changed_slot)
1785 pa_hook_slot_free(u->device_connection_changed_slot);
1786
1787 if (u->sbc_info.buffer)
1788 pa_xfree(u->sbc_info.buffer);
1789
1790 if (u->sbc_info.sbc_initialized)
1791 sbc_finish(&u->sbc_info.sbc);
1792
1793 if (u->msg)
1794 pa_xfree(u->msg);
1795
1796 if (u->card)
1797 pa_card_free(u->card);
1798
1799 if (u->discovery)
1800 pa_bluetooth_discovery_unref(u->discovery);
1801
1802 pa_xfree(u->output_port_name);
1803 pa_xfree(u->input_port_name);
1804
1805 pa_xfree(u);
1806 }