]> code.delx.au - pulseaudio/blob - src/modules/bluetooth/module-bluetooth-device.c
bluetooth: Use profile availability to auto-switch profiles
[pulseaudio] / src / modules / bluetooth / module-bluetooth-device.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2008-2009 Joao Paulo Rechi Vita
5 Copyright 2011-2012 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 <string.h>
28 #include <errno.h>
29 #include <math.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
32
33 #include <pulse/rtclock.h>
34 #include <pulse/sample.h>
35 #include <pulse/timeval.h>
36 #include <pulse/xmalloc.h>
37
38 #include <pulsecore/i18n.h>
39 #include <pulsecore/module.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-rtclock.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/core-error.h>
44 #include <pulsecore/shared.h>
45 #include <pulsecore/socket-util.h>
46 #include <pulsecore/thread.h>
47 #include <pulsecore/thread-mq.h>
48 #include <pulsecore/poll.h>
49 #include <pulsecore/rtpoll.h>
50 #include <pulsecore/time-smoother.h>
51 #include <pulsecore/namereg.h>
52
53 #include <sbc/sbc.h>
54
55 #include "module-bluetooth-device-symdef.h"
56 #include "a2dp-codecs.h"
57 #include "rtp.h"
58 #include "bluetooth-util.h"
59
60 #define BITPOOL_DEC_LIMIT 32
61 #define BITPOOL_DEC_STEP 5
62
63 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(false);
67 PA_MODULE_USAGE(
68 "name=<name for the card/sink/source, to be prefixed> "
69 "card_name=<name for the card> "
70 "card_properties=<properties for the card> "
71 "sink_name=<name for the sink> "
72 "sink_properties=<properties for the sink> "
73 "source_name=<name for the source> "
74 "source_properties=<properties for the source> "
75 "address=<address of the device> "
76 "profile=<a2dp|hsp|hfgw> "
77 "rate=<sample rate> "
78 "channels=<number of channels> "
79 "path=<device object path> "
80 "auto_connect=<automatically connect?> "
81 "sco_sink=<SCO over PCM sink name> "
82 "sco_source=<SCO over PCM source name>");
83
84 /* TODO: not close fd when entering suspend mode in a2dp */
85
86 static const char* const valid_modargs[] = {
87 "name",
88 "card_name",
89 "card_properties",
90 "sink_name",
91 "sink_properties",
92 "source_name",
93 "source_properties",
94 "address",
95 "profile",
96 "rate",
97 "channels",
98 "path",
99 "auto_connect",
100 "sco_sink",
101 "sco_source",
102 NULL
103 };
104
105 struct a2dp_info {
106 sbc_t sbc; /* Codec data */
107 bool sbc_initialized; /* Keep track if the encoder is initialized */
108 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
109
110 void* buffer; /* Codec transfer buffer */
111 size_t buffer_size; /* Size of the buffer */
112
113 uint16_t seq_num; /* Cumulative packet sequence */
114 uint8_t min_bitpool;
115 uint8_t max_bitpool;
116 };
117
118 struct hsp_info {
119 pa_sink *sco_sink;
120 void (*sco_sink_set_volume)(pa_sink *s);
121 pa_source *sco_source;
122 void (*sco_source_set_volume)(pa_source *s);
123 };
124
125 struct bluetooth_msg {
126 pa_msgobject parent;
127 pa_card *card;
128 };
129
130 typedef struct bluetooth_msg bluetooth_msg;
131 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
132 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
133
134 struct userdata {
135 pa_core *core;
136 pa_module *module;
137
138 pa_bluetooth_device *device;
139 pa_hook_slot *uuid_added_slot;
140 char *address;
141 char *path;
142 pa_bluetooth_transport *transport;
143 bool transport_acquired;
144 pa_hook_slot *discovery_slot;
145 pa_hook_slot *sink_state_changed_slot;
146 pa_hook_slot *source_state_changed_slot;
147 pa_hook_slot *transport_state_changed_slot;
148 pa_hook_slot *transport_nrec_changed_slot;
149 pa_hook_slot *transport_microphone_changed_slot;
150 pa_hook_slot *transport_speaker_changed_slot;
151
152 pa_bluetooth_discovery *discovery;
153 bool auto_connect;
154
155 pa_card *card;
156 pa_sink *sink;
157 pa_source *source;
158
159 pa_thread_mq thread_mq;
160 pa_rtpoll *rtpoll;
161 pa_rtpoll_item *rtpoll_item;
162 pa_thread *thread;
163 bluetooth_msg *msg;
164
165 uint64_t read_index, write_index;
166 pa_usec_t started_at;
167 pa_smoother *read_smoother;
168
169 pa_memchunk write_memchunk;
170
171 pa_sample_spec sample_spec, requested_sample_spec;
172
173 int stream_fd;
174
175 size_t read_link_mtu;
176 size_t read_block_size;
177
178 size_t write_link_mtu;
179 size_t write_block_size;
180
181 struct a2dp_info a2dp;
182 struct hsp_info hsp;
183
184 enum profile profile;
185
186 pa_modargs *modargs;
187
188 int stream_write_type;
189 };
190
191 enum {
192 BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
193 BLUETOOTH_MESSAGE_MAX
194 };
195
196 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
197 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
198 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
199 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
200
201 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
202
203 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
204
205 static int init_profile(struct userdata *u);
206
207 /* from IO thread */
208 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
209 {
210 struct a2dp_info *a2dp;
211
212 pa_assert(u);
213
214 a2dp = &u->a2dp;
215
216 if (a2dp->sbc.bitpool == bitpool)
217 return;
218
219 if (bitpool > a2dp->max_bitpool)
220 bitpool = a2dp->max_bitpool;
221 else if (bitpool < a2dp->min_bitpool)
222 bitpool = a2dp->min_bitpool;
223
224 a2dp->sbc.bitpool = bitpool;
225
226 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
227 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
228
229 pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
230
231 u->read_block_size =
232 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
233 / a2dp->frame_length * a2dp->codesize;
234
235 u->write_block_size =
236 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
237 / a2dp->frame_length * a2dp->codesize;
238
239 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
240 pa_sink_set_fixed_latency_within_thread(u->sink,
241 FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
242 }
243
244 /* from IO thread, except in SCO over PCM */
245 static void bt_transport_config_mtu(struct userdata *u) {
246 /* Calculate block sizes */
247 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
248 u->read_block_size = u->read_link_mtu;
249 u->write_block_size = u->write_link_mtu;
250 } else {
251 u->read_block_size =
252 (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
253 / u->a2dp.frame_length * u->a2dp.codesize;
254
255 u->write_block_size =
256 (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
257 / u->a2dp.frame_length * u->a2dp.codesize;
258 }
259
260 if (USE_SCO_OVER_PCM(u))
261 return;
262
263 if (u->sink) {
264 pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
265 pa_sink_set_fixed_latency_within_thread(u->sink,
266 (u->profile == PROFILE_A2DP ?
267 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
268 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
269 }
270
271 if (u->source)
272 pa_source_set_fixed_latency_within_thread(u->source,
273 (u->profile == PROFILE_A2DP_SOURCE ?
274 FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
275 pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
276 }
277
278 /* from IO thread, except in SCO over PCM */
279
280 static void setup_stream(struct userdata *u) {
281 struct pollfd *pollfd;
282 int one;
283
284 pa_log_info("Transport %s resuming", u->transport->path);
285
286 bt_transport_config_mtu(u);
287
288 pa_make_fd_nonblock(u->stream_fd);
289 pa_make_socket_low_delay(u->stream_fd);
290
291 one = 1;
292 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
293 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
294
295 pa_log_debug("Stream properly set up, we're ready to roll!");
296
297 if (u->profile == PROFILE_A2DP)
298 a2dp_set_bitpool(u, u->a2dp.max_bitpool);
299
300 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
301 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
302 pollfd->fd = u->stream_fd;
303 pollfd->events = pollfd->revents = 0;
304
305 u->read_index = u->write_index = 0;
306 u->started_at = 0;
307
308 if (u->source)
309 u->read_smoother = pa_smoother_new(
310 PA_USEC_PER_SEC,
311 PA_USEC_PER_SEC*2,
312 true,
313 true,
314 10,
315 pa_rtclock_now(),
316 true);
317 }
318
319 static void teardown_stream(struct userdata *u) {
320 if (u->rtpoll_item) {
321 pa_rtpoll_item_free(u->rtpoll_item);
322 u->rtpoll_item = NULL;
323 }
324
325 if (u->stream_fd >= 0) {
326 pa_close(u->stream_fd);
327 u->stream_fd = -1;
328 }
329
330 if (u->read_smoother) {
331 pa_smoother_free(u->read_smoother);
332 u->read_smoother = NULL;
333 }
334
335 if (u->write_memchunk.memblock) {
336 pa_memblock_unref(u->write_memchunk.memblock);
337 pa_memchunk_reset(&u->write_memchunk);
338 }
339
340 pa_log_debug("Audio stream torn down");
341 }
342
343 static void bt_transport_release(struct userdata *u) {
344 pa_assert(u->transport);
345
346 /* Ignore if already released */
347 if (!u->transport_acquired)
348 return;
349
350 pa_log_debug("Releasing transport %s", u->transport->path);
351
352 pa_bluetooth_transport_release(u->transport);
353
354 u->transport_acquired = false;
355
356 teardown_stream(u);
357 }
358
359 static int bt_transport_acquire(struct userdata *u, bool optional) {
360 pa_assert(u->transport);
361
362 if (u->transport_acquired)
363 return 0;
364
365 pa_log_debug("Acquiring transport %s", u->transport->path);
366
367 u->stream_fd = pa_bluetooth_transport_acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
368 if (u->stream_fd < 0) {
369 if (!optional)
370 pa_log("Failed to acquire transport %s", u->transport->path);
371 else
372 pa_log_info("Failed optional acquire of transport %s", u->transport->path);
373
374 return -1;
375 }
376
377 u->transport_acquired = true;
378 pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
379
380 return 0;
381 }
382
383 /* Run from IO thread */
384 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
385 struct userdata *u = PA_SINK(o)->userdata;
386 bool failed = false;
387 int r;
388
389 pa_assert(u->sink == PA_SINK(o));
390 pa_assert(u->transport);
391
392 switch (code) {
393
394 case PA_SINK_MESSAGE_SET_STATE:
395
396 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
397
398 case PA_SINK_SUSPENDED:
399 /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
400 if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
401 break;
402
403 /* Stop the device if the source is suspended as well */
404 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
405 /* We deliberately ignore whether stopping
406 * actually worked. Since the stream_fd is
407 * closed it doesn't really matter */
408 bt_transport_release(u);
409
410 break;
411
412 case PA_SINK_IDLE:
413 case PA_SINK_RUNNING:
414 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
415 break;
416
417 /* Resume the device if the source was suspended as well */
418 if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
419 if (bt_transport_acquire(u, false) < 0)
420 failed = true;
421 else
422 setup_stream(u);
423 }
424 break;
425
426 case PA_SINK_UNLINKED:
427 case PA_SINK_INIT:
428 case PA_SINK_INVALID_STATE:
429 ;
430 }
431 break;
432
433 case PA_SINK_MESSAGE_GET_LATENCY: {
434
435 if (u->read_smoother) {
436 pa_usec_t wi, ri;
437
438 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
439 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
440
441 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
442 } else {
443 pa_usec_t ri, wi;
444
445 ri = pa_rtclock_now() - u->started_at;
446 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
447
448 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
449 }
450
451 *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
452 return 0;
453 }
454 }
455
456 r = pa_sink_process_msg(o, code, data, offset, chunk);
457
458 return (r < 0 || !failed) ? r : -1;
459 }
460
461 /* Run from IO thread */
462 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
463 struct userdata *u = PA_SOURCE(o)->userdata;
464 bool failed = false;
465 int r;
466
467 pa_assert(u->source == PA_SOURCE(o));
468 pa_assert(u->transport);
469
470 switch (code) {
471
472 case PA_SOURCE_MESSAGE_SET_STATE:
473
474 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
475
476 case PA_SOURCE_SUSPENDED:
477 /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
478 if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
479 break;
480
481 /* Stop the device if the sink is suspended as well */
482 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
483 bt_transport_release(u);
484
485 if (u->read_smoother)
486 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
487 break;
488
489 case PA_SOURCE_IDLE:
490 case PA_SOURCE_RUNNING:
491 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
492 break;
493
494 /* Resume the device if the sink was suspended as well */
495 if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
496 if (bt_transport_acquire(u, false) < 0)
497 failed = true;
498 else
499 setup_stream(u);
500 }
501 /* We don't resume the smoother here. Instead we
502 * wait until the first packet arrives */
503 break;
504
505 case PA_SOURCE_UNLINKED:
506 case PA_SOURCE_INIT:
507 case PA_SOURCE_INVALID_STATE:
508 ;
509 }
510 break;
511
512 case PA_SOURCE_MESSAGE_GET_LATENCY: {
513 pa_usec_t wi, ri;
514
515 if (u->read_smoother) {
516 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
517 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
518
519 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
520 } else
521 *((pa_usec_t*) data) = 0;
522
523 return 0;
524 }
525
526 }
527
528 r = pa_source_process_msg(o, code, data, offset, chunk);
529
530 return (r < 0 || !failed) ? r : -1;
531 }
532
533 /* Called from main thread context */
534 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
535 struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
536
537 switch (code) {
538 case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
539 if (u->card->module->unload_requested)
540 break;
541
542 pa_log_debug("Switching the profile to off due to IO thread failure.");
543
544 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
545 break;
546 }
547 }
548 return 0;
549 }
550
551 /* Run from IO thread */
552 static int hsp_process_render(struct userdata *u) {
553 int ret = 0;
554
555 pa_assert(u);
556 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
557 pa_assert(u->sink);
558
559 /* First, render some data */
560 if (!u->write_memchunk.memblock)
561 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
562
563 pa_assert(u->write_memchunk.length == u->write_block_size);
564
565 for (;;) {
566 ssize_t l;
567 const void *p;
568
569 /* Now write that data to the socket. The socket is of type
570 * SEQPACKET, and we generated the data of the MTU size, so this
571 * should just work. */
572
573 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
574 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
575 pa_memblock_release(u->write_memchunk.memblock);
576
577 pa_assert(l != 0);
578
579 if (l < 0) {
580
581 if (errno == EINTR)
582 /* Retry right away if we got interrupted */
583 continue;
584
585 else if (errno == EAGAIN)
586 /* Hmm, apparently the socket was not writable, give up for now */
587 break;
588
589 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
590 ret = -1;
591 break;
592 }
593
594 pa_assert((size_t) l <= u->write_memchunk.length);
595
596 if ((size_t) l != u->write_memchunk.length) {
597 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
598 (unsigned long long) l,
599 (unsigned long long) u->write_memchunk.length);
600 ret = -1;
601 break;
602 }
603
604 u->write_index += (uint64_t) u->write_memchunk.length;
605 pa_memblock_unref(u->write_memchunk.memblock);
606 pa_memchunk_reset(&u->write_memchunk);
607
608 ret = 1;
609 break;
610 }
611
612 return ret;
613 }
614
615 /* Run from IO thread */
616 static int hsp_process_push(struct userdata *u) {
617 int ret = 0;
618 pa_memchunk memchunk;
619
620 pa_assert(u);
621 pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
622 pa_assert(u->source);
623 pa_assert(u->read_smoother);
624
625 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
626 memchunk.index = memchunk.length = 0;
627
628 for (;;) {
629 ssize_t l;
630 void *p;
631 struct msghdr m;
632 struct cmsghdr *cm;
633 uint8_t aux[1024];
634 struct iovec iov;
635 bool found_tstamp = false;
636 pa_usec_t tstamp;
637
638 memset(&m, 0, sizeof(m));
639 memset(&aux, 0, sizeof(aux));
640 memset(&iov, 0, sizeof(iov));
641
642 m.msg_iov = &iov;
643 m.msg_iovlen = 1;
644 m.msg_control = aux;
645 m.msg_controllen = sizeof(aux);
646
647 p = pa_memblock_acquire(memchunk.memblock);
648 iov.iov_base = p;
649 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
650 l = recvmsg(u->stream_fd, &m, 0);
651 pa_memblock_release(memchunk.memblock);
652
653 if (l <= 0) {
654
655 if (l < 0 && errno == EINTR)
656 /* Retry right away if we got interrupted */
657 continue;
658
659 else if (l < 0 && errno == EAGAIN)
660 /* Hmm, apparently the socket was not readable, give up for now. */
661 break;
662
663 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
664 ret = -1;
665 break;
666 }
667
668 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
669
670 /* In some rare occasions, we might receive packets of a very strange
671 * size. This could potentially be possible if the SCO packet was
672 * received partially over-the-air, or more probably due to hardware
673 * issues in our Bluetooth adapter. In these cases, in order to avoid
674 * an assertion failure due to unaligned data, just discard the whole
675 * packet */
676 if (!pa_frame_aligned(l, &u->sample_spec)) {
677 pa_log_warn("SCO packet received of unaligned size: %zu", l);
678 break;
679 }
680
681 memchunk.length = (size_t) l;
682 u->read_index += (uint64_t) l;
683
684 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
685 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
686 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
687 pa_rtclock_from_wallclock(tv);
688 tstamp = pa_timeval_load(tv);
689 found_tstamp = true;
690 break;
691 }
692
693 if (!found_tstamp) {
694 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
695 tstamp = pa_rtclock_now();
696 }
697
698 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
699 pa_smoother_resume(u->read_smoother, tstamp, true);
700
701 pa_source_post(u->source, &memchunk);
702
703 ret = l;
704 break;
705 }
706
707 pa_memblock_unref(memchunk.memblock);
708
709 return ret;
710 }
711
712 /* Run from IO thread */
713 static void a2dp_prepare_buffer(struct userdata *u) {
714 size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
715
716 pa_assert(u);
717
718 if (u->a2dp.buffer_size >= min_buffer_size)
719 return;
720
721 u->a2dp.buffer_size = 2 * min_buffer_size;
722 pa_xfree(u->a2dp.buffer);
723 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
724 }
725
726 /* Run from IO thread */
727 static int a2dp_process_render(struct userdata *u) {
728 struct a2dp_info *a2dp;
729 struct rtp_header *header;
730 struct rtp_payload *payload;
731 size_t nbytes;
732 void *d;
733 const void *p;
734 size_t to_write, to_encode;
735 unsigned frame_count;
736 int ret = 0;
737
738 pa_assert(u);
739 pa_assert(u->profile == PROFILE_A2DP);
740 pa_assert(u->sink);
741
742 /* First, render some data */
743 if (!u->write_memchunk.memblock)
744 pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
745
746 pa_assert(u->write_memchunk.length == u->write_block_size);
747
748 a2dp_prepare_buffer(u);
749
750 a2dp = &u->a2dp;
751 header = a2dp->buffer;
752 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
753
754 frame_count = 0;
755
756 /* Try to create a packet of the full MTU */
757
758 p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
759 to_encode = u->write_memchunk.length;
760
761 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
762 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
763
764 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
765 ssize_t written;
766 ssize_t encoded;
767
768 encoded = sbc_encode(&a2dp->sbc,
769 p, to_encode,
770 d, to_write,
771 &written);
772
773 if (PA_UNLIKELY(encoded <= 0)) {
774 pa_log_error("SBC encoding error (%li)", (long) encoded);
775 pa_memblock_release(u->write_memchunk.memblock);
776 return -1;
777 }
778
779 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
780 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
781
782 pa_assert_fp((size_t) encoded <= to_encode);
783 pa_assert_fp((size_t) encoded == a2dp->codesize);
784
785 pa_assert_fp((size_t) written <= to_write);
786 pa_assert_fp((size_t) written == a2dp->frame_length);
787
788 p = (const uint8_t*) p + encoded;
789 to_encode -= encoded;
790
791 d = (uint8_t*) d + written;
792 to_write -= written;
793
794 frame_count++;
795 }
796
797 pa_memblock_release(u->write_memchunk.memblock);
798
799 pa_assert(to_encode == 0);
800
801 PA_ONCE_BEGIN {
802 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
803 } PA_ONCE_END;
804
805 /* write it to the fifo */
806 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
807 header->v = 2;
808 header->pt = 1;
809 header->sequence_number = htons(a2dp->seq_num++);
810 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
811 header->ssrc = htonl(1);
812 payload->frame_count = frame_count;
813
814 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
815
816 for (;;) {
817 ssize_t l;
818
819 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
820
821 pa_assert(l != 0);
822
823 if (l < 0) {
824
825 if (errno == EINTR)
826 /* Retry right away if we got interrupted */
827 continue;
828
829 else if (errno == EAGAIN)
830 /* Hmm, apparently the socket was not writable, give up for now */
831 break;
832
833 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
834 ret = -1;
835 break;
836 }
837
838 pa_assert((size_t) l <= nbytes);
839
840 if ((size_t) l != nbytes) {
841 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
842 (unsigned long long) l,
843 (unsigned long long) nbytes);
844 ret = -1;
845 break;
846 }
847
848 u->write_index += (uint64_t) u->write_memchunk.length;
849 pa_memblock_unref(u->write_memchunk.memblock);
850 pa_memchunk_reset(&u->write_memchunk);
851
852 ret = 1;
853
854 break;
855 }
856
857 return ret;
858 }
859
860 static int a2dp_process_push(struct userdata *u) {
861 int ret = 0;
862 pa_memchunk memchunk;
863
864 pa_assert(u);
865 pa_assert(u->profile == PROFILE_A2DP_SOURCE);
866 pa_assert(u->source);
867 pa_assert(u->read_smoother);
868
869 memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
870 memchunk.index = memchunk.length = 0;
871
872 for (;;) {
873 bool found_tstamp = false;
874 pa_usec_t tstamp;
875 struct a2dp_info *a2dp;
876 struct rtp_header *header;
877 struct rtp_payload *payload;
878 const void *p;
879 void *d;
880 ssize_t l;
881 size_t to_write, to_decode;
882
883 a2dp_prepare_buffer(u);
884
885 a2dp = &u->a2dp;
886 header = a2dp->buffer;
887 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
888
889 l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
890
891 if (l <= 0) {
892
893 if (l < 0 && errno == EINTR)
894 /* Retry right away if we got interrupted */
895 continue;
896
897 else if (l < 0 && errno == EAGAIN)
898 /* Hmm, apparently the socket was not readable, give up for now. */
899 break;
900
901 pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
902 ret = -1;
903 break;
904 }
905
906 pa_assert((size_t) l <= a2dp->buffer_size);
907
908 u->read_index += (uint64_t) l;
909
910 /* TODO: get timestamp from rtp */
911 if (!found_tstamp) {
912 /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
913 tstamp = pa_rtclock_now();
914 }
915
916 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
917 pa_smoother_resume(u->read_smoother, tstamp, true);
918
919 p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
920 to_decode = l - sizeof(*header) - sizeof(*payload);
921
922 d = pa_memblock_acquire(memchunk.memblock);
923 to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
924
925 while (PA_LIKELY(to_decode > 0)) {
926 size_t written;
927 ssize_t decoded;
928
929 decoded = sbc_decode(&a2dp->sbc,
930 p, to_decode,
931 d, to_write,
932 &written);
933
934 if (PA_UNLIKELY(decoded <= 0)) {
935 pa_log_error("SBC decoding error (%li)", (long) decoded);
936 pa_memblock_release(memchunk.memblock);
937 pa_memblock_unref(memchunk.memblock);
938 return -1;
939 }
940
941 /* pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
942 /* pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
943
944 /* Reset frame length, it can be changed due to bitpool change */
945 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
946
947 pa_assert_fp((size_t) decoded <= to_decode);
948 pa_assert_fp((size_t) decoded == a2dp->frame_length);
949
950 pa_assert_fp((size_t) written == a2dp->codesize);
951
952 p = (const uint8_t*) p + decoded;
953 to_decode -= decoded;
954
955 d = (uint8_t*) d + written;
956 to_write -= written;
957 }
958
959 memchunk.length -= to_write;
960
961 pa_memblock_release(memchunk.memblock);
962
963 pa_source_post(u->source, &memchunk);
964
965 ret = l;
966 break;
967 }
968
969 pa_memblock_unref(memchunk.memblock);
970
971 return ret;
972 }
973
974 static void a2dp_reduce_bitpool(struct userdata *u)
975 {
976 struct a2dp_info *a2dp;
977 uint8_t bitpool;
978
979 pa_assert(u);
980
981 a2dp = &u->a2dp;
982
983 /* Check if bitpool is already at its limit */
984 if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
985 return;
986
987 bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
988
989 if (bitpool < BITPOOL_DEC_LIMIT)
990 bitpool = BITPOOL_DEC_LIMIT;
991
992 a2dp_set_bitpool(u, bitpool);
993 }
994
995 static void thread_func(void *userdata) {
996 struct userdata *u = userdata;
997 unsigned do_write = 0;
998 unsigned pending_read_bytes = 0;
999 bool writable = false;
1000
1001 pa_assert(u);
1002 pa_assert(u->transport);
1003
1004 pa_log_debug("IO Thread starting up");
1005
1006 if (u->core->realtime_scheduling)
1007 pa_make_realtime(u->core->realtime_priority);
1008
1009 pa_thread_mq_install(&u->thread_mq);
1010
1011 /* Setup the stream only if the transport was already acquired */
1012 if (u->transport_acquired)
1013 setup_stream(u);
1014
1015 for (;;) {
1016 struct pollfd *pollfd;
1017 int ret;
1018 bool disable_timer = true;
1019
1020 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1021
1022 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1023
1024 /* We should send two blocks to the device before we expect
1025 * a response. */
1026
1027 if (u->write_index == 0 && u->read_index <= 0)
1028 do_write = 2;
1029
1030 if (pollfd && (pollfd->revents & POLLIN)) {
1031 int n_read;
1032
1033 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1034 n_read = hsp_process_push(u);
1035 else
1036 n_read = a2dp_process_push(u);
1037
1038 if (n_read < 0)
1039 goto io_fail;
1040
1041 /* We just read something, so we are supposed to write something, too */
1042 pending_read_bytes += n_read;
1043 do_write += pending_read_bytes / u->write_block_size;
1044 pending_read_bytes = pending_read_bytes % u->write_block_size;
1045 }
1046 }
1047
1048 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1049
1050 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1051 pa_sink_process_rewind(u->sink, 0);
1052
1053 if (pollfd) {
1054 if (pollfd->revents & POLLOUT)
1055 writable = true;
1056
1057 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1058 pa_usec_t time_passed;
1059 pa_usec_t audio_sent;
1060
1061 /* Hmm, there is no input stream we could synchronize
1062 * to. So let's do things by time */
1063
1064 time_passed = pa_rtclock_now() - u->started_at;
1065 audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1066
1067 if (audio_sent <= time_passed) {
1068 pa_usec_t audio_to_send = time_passed - audio_sent;
1069
1070 /* Never try to catch up for more than 100ms */
1071 if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1072 pa_usec_t skip_usec;
1073 uint64_t skip_bytes;
1074
1075 skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1076 skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1077
1078 if (skip_bytes > 0) {
1079 pa_memchunk tmp;
1080
1081 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1082 (unsigned long long) skip_usec,
1083 (unsigned long long) skip_bytes);
1084
1085 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1086 pa_memblock_unref(tmp.memblock);
1087 u->write_index += skip_bytes;
1088
1089 if (u->profile == PROFILE_A2DP)
1090 a2dp_reduce_bitpool(u);
1091 }
1092 }
1093
1094 do_write = 1;
1095 pending_read_bytes = 0;
1096 }
1097 }
1098
1099 if (writable && do_write > 0) {
1100 int n_written;
1101
1102 if (u->write_index <= 0)
1103 u->started_at = pa_rtclock_now();
1104
1105 if (u->profile == PROFILE_A2DP) {
1106 if ((n_written = a2dp_process_render(u)) < 0)
1107 goto io_fail;
1108 } else {
1109 if ((n_written = hsp_process_render(u)) < 0)
1110 goto io_fail;
1111 }
1112
1113 if (n_written == 0)
1114 pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1115
1116 do_write -= n_written;
1117 writable = false;
1118 }
1119
1120 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1121 pa_usec_t sleep_for;
1122 pa_usec_t time_passed, next_write_at;
1123
1124 if (writable) {
1125 /* Hmm, there is no input stream we could synchronize
1126 * to. So let's estimate when we need to wake up the latest */
1127 time_passed = pa_rtclock_now() - u->started_at;
1128 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1129 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1130 /* 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); */
1131 } else
1132 /* drop stream every 500 ms */
1133 sleep_for = PA_USEC_PER_MSEC * 500;
1134
1135 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1136 disable_timer = false;
1137 }
1138 }
1139 }
1140
1141 if (disable_timer)
1142 pa_rtpoll_set_timer_disabled(u->rtpoll);
1143
1144 /* Hmm, nothing to do. Let's sleep */
1145 if (pollfd)
1146 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1147 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1148
1149 if ((ret = pa_rtpoll_run(u->rtpoll, true)) < 0) {
1150 pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1151 goto fail;
1152 }
1153 if (ret == 0) {
1154 pa_log_debug("IO thread shutdown requested, stopping cleanly");
1155 bt_transport_release(u);
1156 goto finish;
1157 }
1158
1159 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1160
1161 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1162 pa_log_info("FD error: %s%s%s%s",
1163 pollfd->revents & POLLERR ? "POLLERR " :"",
1164 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1165 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1166 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1167 goto io_fail;
1168 }
1169
1170 continue;
1171
1172 io_fail:
1173 /* In case of HUP, just tear down the streams */
1174 if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1175 goto fail;
1176
1177 do_write = 0;
1178 pending_read_bytes = 0;
1179 writable = false;
1180
1181 teardown_stream(u);
1182 }
1183
1184 fail:
1185 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1186 pa_log_debug("IO thread failed");
1187 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1188 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1189
1190 finish:
1191 pa_log_debug("IO thread shutting down");
1192 }
1193
1194 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1195 if (state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
1196 return PA_AVAILABLE_NO;
1197 else if (state >= PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
1198 return PA_AVAILABLE_YES;
1199 else
1200 return PA_AVAILABLE_UNKNOWN;
1201 }
1202
1203 static pa_available_t transport_state_to_availability_merged(pa_bluetooth_transport_state_t state1,
1204 pa_bluetooth_transport_state_t state2) {
1205 if (state1 == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED && state2 == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
1206 return PA_AVAILABLE_NO;
1207 else if (state1 >= PA_BLUETOOTH_TRANSPORT_STATE_PLAYING || state2 >= PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
1208 return PA_AVAILABLE_YES;
1209 else
1210 return PA_AVAILABLE_UNKNOWN;
1211 }
1212
1213 /* Run from main thread */
1214 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *transport) {
1215 bool acquire = false;
1216 bool release = false;
1217 enum profile profile;
1218 pa_card_profile *cp;
1219 pa_bluetooth_transport_state_t state;
1220
1221 pa_assert(u);
1222 pa_assert(transport);
1223
1224 profile = transport->profile;
1225 state = transport->state;
1226
1227 /* Update profile availability */
1228 if (!(cp = pa_hashmap_get(u->card->profiles, pa_bt_profile_to_string(profile))))
1229 return;
1230
1231 pa_card_profile_set_available(cp, transport_state_to_availability(state));
1232
1233 /* Update port availability */
1234 switch (profile) {
1235 case PROFILE_HFGW: {
1236 pa_device_port *port;
1237 pa_available_t available = transport_state_to_availability(state);
1238
1239 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1240 pa_device_port_set_available(port, available);
1241
1242 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1243 pa_device_port_set_available(port, available);
1244
1245 acquire = (available == PA_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1246 release = (available != PA_AVAILABLE_YES && u->profile == PROFILE_HFGW);
1247
1248 break;
1249 }
1250
1251 case PROFILE_HSP: {
1252 pa_device_port *port;
1253 pa_available_t available;
1254 pa_bluetooth_transport *other = u->device->transports[PROFILE_A2DP];
1255
1256 if (!other)
1257 available = transport_state_to_availability(state);
1258 else
1259 available = transport_state_to_availability_merged(state, other->state);
1260
1261 pa_assert_se(port = pa_hashmap_get(u->card->ports, "bluetooth-output"));
1262 pa_device_port_set_available(port, available);
1263
1264 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1265 pa_device_port_set_available(port, available);
1266
1267 acquire = (available == PA_AVAILABLE_YES && u->profile == PROFILE_HSP);
1268 release = (available != PA_AVAILABLE_YES && u->profile == PROFILE_HSP);
1269
1270 break;
1271 }
1272
1273 case PROFILE_A2DP_SOURCE: {
1274 pa_device_port *port;
1275 pa_available_t available = transport_state_to_availability(state);
1276
1277 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1278 pa_device_port_set_available(port, available);
1279
1280 acquire = (available == PA_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1281 release = (available != PA_AVAILABLE_YES && u->profile == PROFILE_A2DP_SOURCE);
1282
1283 break;
1284 }
1285
1286 case PROFILE_A2DP: {
1287 pa_device_port *port;
1288 pa_available_t available;
1289 pa_bluetooth_transport *other = u->device->transports[PROFILE_HSP];
1290
1291 if (!other)
1292 available = transport_state_to_availability(state);
1293 else
1294 available = transport_state_to_availability_merged(state, other->state);
1295
1296 pa_assert_se(port = pa_hashmap_get(u->card->ports, "bluetooth-output"));
1297 pa_device_port_set_available(port, available);
1298
1299 acquire = (available == PA_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1300 release = (available != PA_AVAILABLE_YES && u->profile == PROFILE_A2DP);
1301
1302 break;
1303 }
1304
1305 case PROFILE_OFF:
1306 pa_assert_not_reached();
1307 }
1308
1309 /* Acquire or release transport as needed */
1310 if (acquire)
1311 if (bt_transport_acquire(u, true) >= 0) {
1312 if (u->source) {
1313 pa_log_debug("Resuming source %s, because the bluetooth audio state changed to 'playing'.", u->source->name);
1314 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1315 }
1316
1317 if (u->sink) {
1318 pa_log_debug("Resuming sink %s, because the bluetooth audio state changed to 'playing'.", u->sink->name);
1319 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1320 }
1321 }
1322
1323 if (release && u->transport_acquired) {
1324 /* FIXME: this release is racy, since the audio stream might have
1325 been set up again in the meantime (but not processed yet by PA).
1326 BlueZ should probably release the transport automatically, and
1327 in that case we would just mark the transport as released */
1328
1329 /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1330 if (u->source) {
1331 pa_log_debug("Suspending source %s, because the remote end closed the stream.", u->source->name);
1332 pa_source_suspend(u->source, true, PA_SUSPEND_USER);
1333 }
1334
1335 if (u->sink) {
1336 pa_log_debug("Suspending sink %s, because the remote end closed the stream.", u->sink->name);
1337 pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
1338 }
1339 }
1340 }
1341
1342 /* Run from main thread */
1343 static void sink_set_volume_cb(pa_sink *s) {
1344 uint16_t gain;
1345 pa_volume_t volume;
1346 struct userdata *u;
1347 char *k;
1348
1349 pa_assert(s);
1350 pa_assert(s->core);
1351
1352 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1353 u = pa_shared_get(s->core, k);
1354 pa_xfree(k);
1355
1356 pa_assert(u);
1357 pa_assert(u->sink == s);
1358 pa_assert(u->profile == PROFILE_HSP);
1359 pa_assert(u->transport);
1360
1361 gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1362 volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1363
1364 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1365
1366 pa_bluetooth_transport_set_speaker_gain(u->transport, gain);
1367 }
1368
1369 /* Run from main thread */
1370 static void source_set_volume_cb(pa_source *s) {
1371 uint16_t gain;
1372 pa_volume_t volume;
1373 struct userdata *u;
1374 char *k;
1375
1376 pa_assert(s);
1377 pa_assert(s->core);
1378
1379 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1380 u = pa_shared_get(s->core, k);
1381 pa_xfree(k);
1382
1383 pa_assert(u);
1384 pa_assert(u->source == s);
1385 pa_assert(u->profile == PROFILE_HSP);
1386 pa_assert(u->transport);
1387
1388 gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1389 volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1390
1391 pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1392
1393 pa_bluetooth_transport_set_microphone_gain(u->transport, gain);
1394 }
1395
1396 /* Run from main thread */
1397 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, bool *namereg_fail) {
1398 char *t;
1399 const char *n;
1400
1401 pa_assert(type);
1402 pa_assert(ma);
1403 pa_assert(device_id);
1404 pa_assert(namereg_fail);
1405
1406 t = pa_sprintf_malloc("%s_name", type);
1407 n = pa_modargs_get_value(ma, t, NULL);
1408 pa_xfree(t);
1409
1410 if (n) {
1411 *namereg_fail = true;
1412 return pa_xstrdup(n);
1413 }
1414
1415 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1416 *namereg_fail = true;
1417 else {
1418 n = device_id;
1419 *namereg_fail = false;
1420 }
1421
1422 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1423 }
1424
1425 static int sco_over_pcm_state_update(struct userdata *u, bool changed) {
1426 pa_assert(u);
1427 pa_assert(USE_SCO_OVER_PCM(u));
1428
1429 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1430 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1431
1432 if (u->stream_fd >= 0)
1433 return 0;
1434
1435 pa_log_debug("Resuming SCO over PCM");
1436 if (init_profile(u) < 0) {
1437 pa_log("Can't resume SCO over PCM");
1438 return -1;
1439 }
1440
1441 if (bt_transport_acquire(u, false) < 0)
1442 return -1;
1443
1444 setup_stream(u);
1445
1446 return 0;
1447 }
1448
1449 if (changed) {
1450 if (u->stream_fd < 0)
1451 return 0;
1452
1453 pa_log_debug("Closing SCO over PCM");
1454
1455 bt_transport_release(u);
1456 }
1457
1458 return 0;
1459 }
1460
1461 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1462 pa_assert(c);
1463 pa_sink_assert_ref(s);
1464 pa_assert(u);
1465
1466 if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_sink)
1467 return PA_HOOK_OK;
1468
1469 sco_over_pcm_state_update(u, true);
1470
1471 return PA_HOOK_OK;
1472 }
1473
1474 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1475 pa_assert(c);
1476 pa_source_assert_ref(s);
1477 pa_assert(u);
1478
1479 if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_source)
1480 return PA_HOOK_OK;
1481
1482 sco_over_pcm_state_update(u, true);
1483
1484 return PA_HOOK_OK;
1485 }
1486
1487 static pa_hook_result_t transport_nrec_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
1488 pa_proplist *p;
1489
1490 pa_assert(t);
1491 pa_assert(u);
1492
1493 if (t != u->transport)
1494 return PA_HOOK_OK;
1495
1496 p = pa_proplist_new();
1497 pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1498 pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1499 pa_proplist_free(p);
1500
1501 return PA_HOOK_OK;
1502 }
1503
1504 static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t,
1505 struct userdata *u) {
1506 pa_cvolume v;
1507
1508 pa_assert(t);
1509 pa_assert(u);
1510
1511 if (t != u->transport)
1512 return PA_HOOK_OK;
1513
1514 pa_assert(u->source);
1515
1516 pa_cvolume_set(&v, u->sample_spec.channels,
1517 (pa_volume_t) round((double) t->microphone_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1518 pa_source_volume_changed(u->source, &v);
1519
1520 return PA_HOOK_OK;
1521 }
1522
1523 static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t,
1524 struct userdata *u) {
1525 pa_cvolume v;
1526
1527 pa_assert(t);
1528 pa_assert(u);
1529
1530 if (t != u->transport)
1531 return PA_HOOK_OK;
1532
1533 pa_assert(u->sink);
1534
1535 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) round((double) t->speaker_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1536 pa_sink_volume_changed(u->sink, &v);
1537
1538 return PA_HOOK_OK;
1539 }
1540
1541 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1542 union {
1543 pa_sink_new_data *sink_new_data;
1544 pa_source_new_data *source_new_data;
1545 } data;
1546 pa_device_port *port;
1547
1548 if (direction == PA_DIRECTION_OUTPUT)
1549 data.sink_new_data = sink_or_source_new_data;
1550 else
1551 data.source_new_data = sink_or_source_new_data;
1552
1553 switch (u->profile) {
1554 case PROFILE_A2DP:
1555 pa_assert_se(port = pa_hashmap_get(u->card->ports, "bluetooth-output"));
1556 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1557 pa_device_port_ref(port);
1558 break;
1559
1560 case PROFILE_A2DP_SOURCE:
1561 pa_assert_se(port = pa_hashmap_get(u->card->ports, "a2dp-input"));
1562 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1563 pa_device_port_ref(port);
1564 break;
1565
1566 case PROFILE_HSP:
1567 if (direction == PA_DIRECTION_OUTPUT) {
1568 pa_assert_se(port = pa_hashmap_get(u->card->ports, "bluetooth-output"));
1569 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1570 } else {
1571 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hsp-input"));
1572 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1573 }
1574 pa_device_port_ref(port);
1575 break;
1576
1577 case PROFILE_HFGW:
1578 if (direction == PA_DIRECTION_OUTPUT) {
1579 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-output"));
1580 pa_assert_se(pa_hashmap_put(data.sink_new_data->ports, port->name, port) >= 0);
1581 } else {
1582 pa_assert_se(port = pa_hashmap_get(u->card->ports, "hfgw-input"));
1583 pa_assert_se(pa_hashmap_put(data.source_new_data->ports, port->name, port) >= 0);
1584 }
1585 pa_device_port_ref(port);
1586 break;
1587
1588 default:
1589 pa_assert_not_reached();
1590 }
1591 }
1592
1593 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1594 return 0;
1595 }
1596
1597 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1598 return 0;
1599 }
1600
1601 /* Run from main thread */
1602 static int add_sink(struct userdata *u) {
1603 char *k;
1604
1605 pa_assert(u->transport);
1606
1607 if (USE_SCO_OVER_PCM(u)) {
1608 pa_proplist *p;
1609
1610 u->sink = u->hsp.sco_sink;
1611 p = pa_proplist_new();
1612 pa_proplist_sets(p, "bluetooth.protocol", pa_bt_profile_to_string(u->profile));
1613 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1614 pa_proplist_free(p);
1615 } else {
1616 pa_sink_new_data data;
1617 bool b;
1618
1619 pa_sink_new_data_init(&data);
1620 data.driver = __FILE__;
1621 data.module = u->module;
1622 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1623 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bt_profile_to_string(u->profile));
1624 if (u->profile == PROFILE_HSP)
1625 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1626 data.card = u->card;
1627 data.name = get_name("sink", u->modargs, u->address, &b);
1628 data.namereg_fail = b;
1629
1630 if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1631 pa_log("Invalid properties");
1632 pa_sink_new_data_done(&data);
1633 return -1;
1634 }
1635 connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1636
1637 if (!u->transport_acquired)
1638 switch (u->profile) {
1639 case PROFILE_A2DP:
1640 case PROFILE_HSP:
1641 pa_assert_not_reached(); /* Profile switch should have failed */
1642 break;
1643 case PROFILE_HFGW:
1644 data.suspend_cause = PA_SUSPEND_USER;
1645 break;
1646 case PROFILE_A2DP_SOURCE:
1647 case PROFILE_OFF:
1648 pa_assert_not_reached();
1649 }
1650
1651 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1652 pa_sink_new_data_done(&data);
1653
1654 if (!u->sink) {
1655 pa_log_error("Failed to create sink");
1656 return -1;
1657 }
1658
1659 u->sink->userdata = u;
1660 u->sink->parent.process_msg = sink_process_msg;
1661 u->sink->set_port = sink_set_port_cb;
1662 }
1663
1664 if (u->profile == PROFILE_HSP) {
1665 pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1666 u->sink->n_volume_steps = 16;
1667
1668 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1669 pa_shared_set(u->core, k, u);
1670 pa_xfree(k);
1671 }
1672
1673 return 0;
1674 }
1675
1676 /* Run from main thread */
1677 static int add_source(struct userdata *u) {
1678 char *k;
1679
1680 pa_assert(u->transport);
1681
1682 if (USE_SCO_OVER_PCM(u)) {
1683 u->source = u->hsp.sco_source;
1684 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", pa_bt_profile_to_string(u->profile));
1685 } else {
1686 pa_source_new_data data;
1687 bool b;
1688
1689 pa_source_new_data_init(&data);
1690 data.driver = __FILE__;
1691 data.module = u->module;
1692 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1693 pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bt_profile_to_string(u->profile));
1694 if (u->profile == PROFILE_HSP)
1695 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1696
1697 data.card = u->card;
1698 data.name = get_name("source", u->modargs, u->address, &b);
1699 data.namereg_fail = b;
1700
1701 if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1702 pa_log("Invalid properties");
1703 pa_source_new_data_done(&data);
1704 return -1;
1705 }
1706
1707 connect_ports(u, &data, PA_DIRECTION_INPUT);
1708
1709 if (!u->transport_acquired)
1710 switch (u->profile) {
1711 case PROFILE_HSP:
1712 pa_assert_not_reached(); /* Profile switch should have failed */
1713 break;
1714 case PROFILE_A2DP_SOURCE:
1715 case PROFILE_HFGW:
1716 data.suspend_cause = PA_SUSPEND_USER;
1717 break;
1718 case PROFILE_A2DP:
1719 case PROFILE_OFF:
1720 pa_assert_not_reached();
1721 }
1722
1723 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1724 pa_source_new_data_done(&data);
1725
1726 if (!u->source) {
1727 pa_log_error("Failed to create source");
1728 return -1;
1729 }
1730
1731 u->source->userdata = u;
1732 u->source->parent.process_msg = source_process_msg;
1733 u->source->set_port = source_set_port_cb;
1734 }
1735
1736 if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
1737 pa_bluetooth_transport *t = u->transport;
1738 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1739 }
1740
1741 if (u->profile == PROFILE_HSP) {
1742 pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1743 u->source->n_volume_steps = 16;
1744
1745 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1746 pa_shared_set(u->core, k, u);
1747 pa_xfree(k);
1748 }
1749
1750 return 0;
1751 }
1752
1753 static void bt_transport_config_a2dp(struct userdata *u) {
1754 const pa_bluetooth_transport *t;
1755 struct a2dp_info *a2dp = &u->a2dp;
1756 a2dp_sbc_t *config;
1757
1758 t = u->transport;
1759 pa_assert(t);
1760
1761 config = (a2dp_sbc_t *) t->config;
1762
1763 u->sample_spec.format = PA_SAMPLE_S16LE;
1764
1765 if (a2dp->sbc_initialized)
1766 sbc_reinit(&a2dp->sbc, 0);
1767 else
1768 sbc_init(&a2dp->sbc, 0);
1769 a2dp->sbc_initialized = true;
1770
1771 switch (config->frequency) {
1772 case SBC_SAMPLING_FREQ_16000:
1773 a2dp->sbc.frequency = SBC_FREQ_16000;
1774 u->sample_spec.rate = 16000U;
1775 break;
1776 case SBC_SAMPLING_FREQ_32000:
1777 a2dp->sbc.frequency = SBC_FREQ_32000;
1778 u->sample_spec.rate = 32000U;
1779 break;
1780 case SBC_SAMPLING_FREQ_44100:
1781 a2dp->sbc.frequency = SBC_FREQ_44100;
1782 u->sample_spec.rate = 44100U;
1783 break;
1784 case SBC_SAMPLING_FREQ_48000:
1785 a2dp->sbc.frequency = SBC_FREQ_48000;
1786 u->sample_spec.rate = 48000U;
1787 break;
1788 default:
1789 pa_assert_not_reached();
1790 }
1791
1792 switch (config->channel_mode) {
1793 case SBC_CHANNEL_MODE_MONO:
1794 a2dp->sbc.mode = SBC_MODE_MONO;
1795 u->sample_spec.channels = 1;
1796 break;
1797 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1798 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1799 u->sample_spec.channels = 2;
1800 break;
1801 case SBC_CHANNEL_MODE_STEREO:
1802 a2dp->sbc.mode = SBC_MODE_STEREO;
1803 u->sample_spec.channels = 2;
1804 break;
1805 case SBC_CHANNEL_MODE_JOINT_STEREO:
1806 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1807 u->sample_spec.channels = 2;
1808 break;
1809 default:
1810 pa_assert_not_reached();
1811 }
1812
1813 switch (config->allocation_method) {
1814 case SBC_ALLOCATION_SNR:
1815 a2dp->sbc.allocation = SBC_AM_SNR;
1816 break;
1817 case SBC_ALLOCATION_LOUDNESS:
1818 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1819 break;
1820 default:
1821 pa_assert_not_reached();
1822 }
1823
1824 switch (config->subbands) {
1825 case SBC_SUBBANDS_4:
1826 a2dp->sbc.subbands = SBC_SB_4;
1827 break;
1828 case SBC_SUBBANDS_8:
1829 a2dp->sbc.subbands = SBC_SB_8;
1830 break;
1831 default:
1832 pa_assert_not_reached();
1833 }
1834
1835 switch (config->block_length) {
1836 case SBC_BLOCK_LENGTH_4:
1837 a2dp->sbc.blocks = SBC_BLK_4;
1838 break;
1839 case SBC_BLOCK_LENGTH_8:
1840 a2dp->sbc.blocks = SBC_BLK_8;
1841 break;
1842 case SBC_BLOCK_LENGTH_12:
1843 a2dp->sbc.blocks = SBC_BLK_12;
1844 break;
1845 case SBC_BLOCK_LENGTH_16:
1846 a2dp->sbc.blocks = SBC_BLK_16;
1847 break;
1848 default:
1849 pa_assert_not_reached();
1850 }
1851
1852 a2dp->min_bitpool = config->min_bitpool;
1853 a2dp->max_bitpool = config->max_bitpool;
1854
1855 /* Set minimum bitpool for source to get the maximum possible block_size */
1856 a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
1857 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1858 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1859
1860 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
1861 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1862 }
1863
1864 static void bt_transport_config(struct userdata *u) {
1865 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
1866 u->sample_spec.format = PA_SAMPLE_S16LE;
1867 u->sample_spec.channels = 1;
1868 u->sample_spec.rate = 8000;
1869 } else
1870 bt_transport_config_a2dp(u);
1871 }
1872
1873 /* Run from main thread */
1874 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
1875 pa_assert(t);
1876 pa_assert(u);
1877
1878 if (t == u->transport && t->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
1879 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
1880
1881 if (t->device == u->device)
1882 handle_transport_state_change(u, t);
1883
1884 return PA_HOOK_OK;
1885 }
1886
1887 /* Run from main thread */
1888 static int setup_transport(struct userdata *u) {
1889 pa_bluetooth_transport *t;
1890
1891 pa_assert(u);
1892 pa_assert(!u->transport);
1893 pa_assert(u->profile != PROFILE_OFF);
1894
1895 /* check if profile has a transport */
1896 t = u->device->transports[u->profile];
1897 if (!t || t->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1898 pa_log_warn("Profile has no transport");
1899 return -1;
1900 }
1901
1902 u->transport = t;
1903
1904 if (u->profile == PROFILE_A2DP_SOURCE || u->profile == PROFILE_HFGW)
1905 bt_transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1906 else if (bt_transport_acquire(u, false) < 0)
1907 return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1908
1909 bt_transport_config(u);
1910
1911 return 0;
1912 }
1913
1914 /* Run from main thread */
1915 static int init_profile(struct userdata *u) {
1916 int r = 0;
1917 pa_assert(u);
1918 pa_assert(u->profile != PROFILE_OFF);
1919
1920 if (setup_transport(u) < 0)
1921 return -1;
1922
1923 pa_assert(u->transport);
1924
1925 if (u->profile == PROFILE_A2DP ||
1926 u->profile == PROFILE_HSP ||
1927 u->profile == PROFILE_HFGW)
1928 if (add_sink(u) < 0)
1929 r = -1;
1930
1931 if (u->profile == PROFILE_HSP ||
1932 u->profile == PROFILE_A2DP_SOURCE ||
1933 u->profile == PROFILE_HFGW)
1934 if (add_source(u) < 0)
1935 r = -1;
1936
1937 return r;
1938 }
1939
1940 /* Run from main thread */
1941 static void stop_thread(struct userdata *u) {
1942 char *k;
1943
1944 pa_assert(u);
1945
1946 if (u->sink && !USE_SCO_OVER_PCM(u))
1947 pa_sink_unlink(u->sink);
1948
1949 if (u->source && !USE_SCO_OVER_PCM(u))
1950 pa_source_unlink(u->source);
1951
1952 if (u->thread) {
1953 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1954 pa_thread_free(u->thread);
1955 u->thread = NULL;
1956 }
1957
1958 if (u->rtpoll_item) {
1959 pa_rtpoll_item_free(u->rtpoll_item);
1960 u->rtpoll_item = NULL;
1961 }
1962
1963 if (u->rtpoll) {
1964 pa_thread_mq_done(&u->thread_mq);
1965
1966 pa_rtpoll_free(u->rtpoll);
1967 u->rtpoll = NULL;
1968 }
1969
1970 if (u->transport) {
1971 bt_transport_release(u);
1972 u->transport = NULL;
1973 }
1974
1975 if (u->sink) {
1976 if (u->profile == PROFILE_HSP) {
1977 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1978 pa_shared_remove(u->core, k);
1979 pa_xfree(k);
1980 }
1981
1982 pa_sink_unref(u->sink);
1983 u->sink = NULL;
1984 }
1985
1986 if (u->source) {
1987 if (u->profile == PROFILE_HSP) {
1988 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1989 pa_shared_remove(u->core, k);
1990 pa_xfree(k);
1991 }
1992
1993 pa_source_unref(u->source);
1994 u->source = NULL;
1995 }
1996
1997 if (u->read_smoother) {
1998 pa_smoother_free(u->read_smoother);
1999 u->read_smoother = NULL;
2000 }
2001 }
2002
2003 /* Run from main thread */
2004 static int start_thread(struct userdata *u) {
2005 pa_assert(u);
2006 pa_assert(!u->thread);
2007 pa_assert(!u->rtpoll);
2008 pa_assert(!u->rtpoll_item);
2009
2010 u->rtpoll = pa_rtpoll_new();
2011 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2012
2013 if (USE_SCO_OVER_PCM(u)) {
2014 if (sco_over_pcm_state_update(u, false) < 0) {
2015 char *k;
2016
2017 if (u->sink) {
2018 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2019 pa_shared_remove(u->core, k);
2020 pa_xfree(k);
2021 u->sink = NULL;
2022 }
2023 if (u->source) {
2024 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2025 pa_shared_remove(u->core, k);
2026 pa_xfree(k);
2027 u->source = NULL;
2028 }
2029 return -1;
2030 }
2031
2032 pa_sink_ref(u->sink);
2033 pa_source_ref(u->source);
2034 /* FIXME: monitor stream_fd error */
2035 return 0;
2036 }
2037
2038 if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2039 pa_log_error("Failed to create IO thread");
2040 return -1;
2041 }
2042
2043 if (u->sink) {
2044 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2045 pa_sink_set_rtpoll(u->sink, u->rtpoll);
2046 pa_sink_put(u->sink);
2047
2048 if (u->sink->set_volume)
2049 u->sink->set_volume(u->sink);
2050 }
2051
2052 if (u->source) {
2053 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2054 pa_source_set_rtpoll(u->source, u->rtpoll);
2055 pa_source_put(u->source);
2056
2057 if (u->source->set_volume)
2058 u->source->set_volume(u->source);
2059 }
2060
2061 return 0;
2062 }
2063
2064 static void save_sco_volume_callbacks(struct userdata *u) {
2065 pa_assert(u);
2066 pa_assert(USE_SCO_OVER_PCM(u));
2067
2068 u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2069 u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2070 }
2071
2072 static void restore_sco_volume_callbacks(struct userdata *u) {
2073 pa_assert(u);
2074 pa_assert(USE_SCO_OVER_PCM(u));
2075
2076 pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2077 pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2078 }
2079
2080 /* Run from main thread */
2081 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2082 struct userdata *u;
2083 enum profile *d;
2084
2085 pa_assert(c);
2086 pa_assert(new_profile);
2087 pa_assert_se(u = c->userdata);
2088
2089 d = PA_CARD_PROFILE_DATA(new_profile);
2090
2091 if (*d != PROFILE_OFF) {
2092 const pa_bluetooth_device *device = u->device;
2093
2094 if (!device->transports[*d] || device->transports[*d]->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2095 pa_log_warn("Profile not connected, refused to switch profile to %s", new_profile->name);
2096 return -PA_ERR_IO;
2097 }
2098 }
2099
2100 stop_thread(u);
2101
2102 if (USE_SCO_OVER_PCM(u))
2103 restore_sco_volume_callbacks(u);
2104
2105 u->profile = *d;
2106 u->sample_spec = u->requested_sample_spec;
2107
2108 if (USE_SCO_OVER_PCM(u))
2109 save_sco_volume_callbacks(u);
2110
2111 if (u->profile != PROFILE_OFF)
2112 if (init_profile(u) < 0)
2113 goto off;
2114
2115 if (u->sink || u->source)
2116 if (start_thread(u) < 0)
2117 goto off;
2118
2119 return 0;
2120
2121 off:
2122 stop_thread(u);
2123
2124 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
2125
2126 return -PA_ERR_IO;
2127 }
2128
2129 static void create_ports_for_profile(struct userdata *u, pa_hashmap *ports, pa_card_profile *profile) {
2130 pa_bluetooth_device *device = u->device;
2131 pa_device_port *port;
2132 enum profile *d;
2133 pa_bluetooth_transport *transport;
2134 pa_bluetooth_transport_state_t transport_state;
2135
2136 d = PA_CARD_PROFILE_DATA(profile);
2137
2138 pa_assert(*d != PROFILE_OFF);
2139
2140 transport = device->transports[*d];
2141 transport_state = transport ? transport->state : PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED;
2142
2143 switch (*d) {
2144 case PROFILE_A2DP:
2145 if ((port = pa_hashmap_get(ports, "bluetooth-output")) != NULL) {
2146 pa_bluetooth_transport *other = device->transports[PROFILE_HSP];
2147 pa_bluetooth_transport_state_t other_state = other ? other->state : PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED;
2148
2149 port->priority = PA_MAX(port->priority, profile->priority * 100);
2150 port->available = transport_state_to_availability_merged(transport_state, other_state);
2151 pa_hashmap_put(port->profiles, profile->name, profile);
2152 } else {
2153 pa_assert_se(port = pa_device_port_new(u->core, "bluetooth-output", _("Bluetooth Output"), 0));
2154 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2155 port->is_output = 1;
2156 port->is_input = 0;
2157 port->priority = profile->priority * 100;
2158 port->available = transport_state_to_availability(transport_state);
2159 pa_hashmap_put(port->profiles, profile->name, profile);
2160 }
2161
2162 break;
2163
2164 case PROFILE_A2DP_SOURCE:
2165 pa_assert_se(port = pa_device_port_new(u->core, "a2dp-input", _("Bluetooth High Quality (A2DP)"), 0));
2166 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2167 port->is_output = 0;
2168 port->is_input = 1;
2169 port->priority = profile->priority * 100;
2170 port->available = transport_state_to_availability(transport_state);
2171 pa_hashmap_put(port->profiles, profile->name, profile);
2172 break;
2173
2174 case PROFILE_HSP:
2175 if ((port = pa_hashmap_get(ports, "bluetooth-output")) != NULL) {
2176 pa_bluetooth_transport *other = device->transports[PROFILE_A2DP];
2177 pa_bluetooth_transport_state_t other_state = other ? other->state : PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED;
2178
2179 port->priority = PA_MAX(port->priority, profile->priority * 100);
2180 port->available = transport_state_to_availability_merged(transport_state, other_state);
2181 pa_hashmap_put(port->profiles, profile->name, profile);
2182 } else {
2183 pa_assert_se(port = pa_device_port_new(u->core, "bluetooth-output", _("Bluetooth Output"), 0));
2184 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2185 port->is_output = 1;
2186 port->is_input = 0;
2187 port->priority = profile->priority * 100;
2188 port->available = transport_state_to_availability(transport_state);
2189 pa_hashmap_put(port->profiles, profile->name, profile);
2190 }
2191
2192 pa_assert_se(port = pa_device_port_new(u->core, "hsp-input", _("Bluetooth Telephony (HSP/HFP)"), 0));
2193 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2194 port->is_output = 0;
2195 port->is_input = 1;
2196 port->priority = profile->priority * 100;
2197 port->available = transport_state_to_availability(transport_state);
2198 pa_hashmap_put(port->profiles, profile->name, profile);
2199 break;
2200
2201 case PROFILE_HFGW:
2202 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-output", _("Bluetooth Handsfree Gateway"), 0));
2203 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2204 port->is_output = 1;
2205 port->is_input = 0;
2206 port->priority = profile->priority * 100;
2207 port->available = transport_state_to_availability(transport_state);
2208 pa_hashmap_put(port->profiles, profile->name, profile);
2209
2210 pa_assert_se(port = pa_device_port_new(u->core, "hfgw-input", _("Bluetooth Handsfree Gateway"), 0));
2211 pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2212 port->is_output = 0;
2213 port->is_input = 1;
2214 port->priority = profile->priority * 100;
2215 port->available = transport_state_to_availability(transport_state);
2216 pa_hashmap_put(port->profiles, profile->name, profile);
2217 break;
2218
2219 default:
2220 pa_assert_not_reached();
2221 }
2222
2223 }
2224
2225 /* Run from main thread */
2226 static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid) {
2227 pa_card_profile *p = NULL;
2228 enum profile *d;
2229
2230 if (pa_streq(uuid, A2DP_SINK_UUID)) {
2231 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2232 p->priority = 10;
2233 p->n_sinks = 1;
2234 p->n_sources = 0;
2235 p->max_sink_channels = 2;
2236 p->max_source_channels = 0;
2237
2238 d = PA_CARD_PROFILE_DATA(p);
2239 *d = PROFILE_A2DP;
2240 } else if (pa_streq(uuid, A2DP_SOURCE_UUID)) {
2241 p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2242 p->priority = 10;
2243 p->n_sinks = 0;
2244 p->n_sources = 1;
2245 p->max_sink_channels = 0;
2246 p->max_source_channels = 2;
2247
2248 d = PA_CARD_PROFILE_DATA(p);
2249 *d = PROFILE_A2DP_SOURCE;
2250 } else if (pa_streq(uuid, HSP_HS_UUID) || pa_streq(uuid, HFP_HS_UUID)) {
2251 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2252 p->priority = 20;
2253 p->n_sinks = 1;
2254 p->n_sources = 1;
2255 p->max_sink_channels = 1;
2256 p->max_source_channels = 1;
2257
2258 d = PA_CARD_PROFILE_DATA(p);
2259 *d = PROFILE_HSP;
2260 } else if (pa_streq(uuid, HFP_AG_UUID)) {
2261 p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2262 p->priority = 20;
2263 p->n_sinks = 1;
2264 p->n_sources = 1;
2265 p->max_sink_channels = 1;
2266 p->max_source_channels = 1;
2267
2268 d = PA_CARD_PROFILE_DATA(p);
2269 *d = PROFILE_HFGW;
2270 }
2271
2272 if (p) {
2273 pa_bluetooth_transport *t;
2274
2275 if ((t = u->device->transports[*d]))
2276 p->available = transport_state_to_availability(t->state);
2277 }
2278
2279 return p;
2280 }
2281
2282 /* Run from main thread */
2283 static int add_card(struct userdata *u) {
2284 pa_card_new_data data;
2285 bool b;
2286 pa_card_profile *p;
2287 enum profile *d;
2288 const char *ff;
2289 char *n;
2290 const char *default_profile;
2291 const pa_bluetooth_device *device = u->device;
2292 const pa_bluetooth_uuid *uuid;
2293
2294 pa_assert(u);
2295 pa_assert(device);
2296
2297 pa_card_new_data_init(&data);
2298 data.driver = __FILE__;
2299 data.module = u->module;
2300
2301 n = pa_bluetooth_cleanup_name(device->name);
2302 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2303 pa_xfree(n);
2304 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2305 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2306 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2307 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2308 if ((ff = pa_bluetooth_get_form_factor(device->class)))
2309 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2310 pa_proplist_sets(data.proplist, "bluez.path", device->path);
2311 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2312 pa_proplist_sets(data.proplist, "bluez.name", device->name);
2313 data.name = get_name("card", u->modargs, device->address, &b);
2314 data.namereg_fail = b;
2315
2316 if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2317 pa_log("Invalid properties");
2318 pa_card_new_data_done(&data);
2319 return -1;
2320 }
2321
2322 PA_LLIST_FOREACH(uuid, device->uuids) {
2323 p = create_card_profile(u, uuid->uuid);
2324
2325 if (!p)
2326 continue;
2327
2328 if (pa_hashmap_get(data.profiles, p->name)) {
2329 pa_card_profile_free(p);
2330 continue;
2331 }
2332
2333 pa_hashmap_put(data.profiles, p->name, p);
2334 create_ports_for_profile(u, data.ports, p);
2335 }
2336
2337 pa_assert(!pa_hashmap_isempty(data.profiles));
2338
2339 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2340 p->available = PA_AVAILABLE_YES;
2341 d = PA_CARD_PROFILE_DATA(p);
2342 *d = PROFILE_OFF;
2343 pa_hashmap_put(data.profiles, p->name, p);
2344
2345 if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2346 if (pa_hashmap_get(data.profiles, default_profile))
2347 pa_card_new_data_set_profile(&data, default_profile);
2348 else
2349 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2350 }
2351
2352 u->card = pa_card_new(u->core, &data);
2353 pa_card_new_data_done(&data);
2354
2355 if (!u->card) {
2356 pa_log("Failed to allocate card.");
2357 return -1;
2358 }
2359
2360 u->card->userdata = u;
2361 u->card->set_profile = card_set_profile;
2362
2363 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2364
2365 if (*d != PROFILE_OFF && (!device->transports[*d] ||
2366 device->transports[*d]->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)) {
2367 pa_log_warn("Default profile not connected, selecting off profile");
2368 u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2369 u->card->save_profile = false;
2370 }
2371
2372 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2373 u->profile = *d;
2374
2375 if (USE_SCO_OVER_PCM(u))
2376 save_sco_volume_callbacks(u);
2377
2378 return 0;
2379 }
2380
2381 /* Run from main thread */
2382 static pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2383 pa_bluetooth_device *d = NULL;
2384
2385 pa_assert(u);
2386
2387 if (!address && !path) {
2388 pa_log_error("Failed to get device address/path from module arguments.");
2389 return NULL;
2390 }
2391
2392 if (path) {
2393 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2394 pa_log_error("%s is not a valid BlueZ audio device.", path);
2395 return NULL;
2396 }
2397
2398 if (address && !(pa_streq(d->address, address))) {
2399 pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2400 return NULL;
2401 }
2402
2403 } else {
2404 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2405 pa_log_error("%s is not known.", address);
2406 return NULL;
2407 }
2408 }
2409
2410 if (d) {
2411 u->address = pa_xstrdup(d->address);
2412 u->path = pa_xstrdup(d->path);
2413 }
2414
2415 return d;
2416 }
2417
2418 /* Run from main thread */
2419 static pa_hook_result_t uuid_added_cb(pa_bluetooth_discovery *y, const struct pa_bluetooth_hook_uuid_data *data,
2420 struct userdata *u) {
2421 pa_card_profile *p;
2422 pa_hashmap *new_ports;
2423
2424 pa_assert(data);
2425 pa_assert(data->device);
2426 pa_assert(data->uuid);
2427 pa_assert(u);
2428
2429 if (data->device != u->device)
2430 return PA_HOOK_OK;
2431
2432 p = create_card_profile(u, data->uuid);
2433
2434 if (!p)
2435 return PA_HOOK_OK;
2436
2437 if (pa_hashmap_get(u->card->profiles, p->name)) {
2438 pa_card_profile_free(p);
2439 return PA_HOOK_OK;
2440 }
2441
2442 pa_card_add_profile(u->card, p);
2443
2444 new_ports = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2445
2446 create_ports_for_profile(u, new_ports, p);
2447
2448 pa_card_add_ports(u->card, new_ports);
2449
2450 pa_hashmap_free(new_ports, (pa_free_cb_t) pa_device_port_unref);
2451
2452 return PA_HOOK_OK;
2453 }
2454
2455 /* Run from main thread */
2456 static pa_hook_result_t discovery_hook_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2457 pa_assert(u);
2458 pa_assert(d);
2459
2460 if (d != u->device)
2461 return PA_HOOK_OK;
2462
2463 if (d->dead)
2464 pa_log_debug("Device %s removed: unloading module", d->path);
2465 else if (!pa_bluetooth_device_any_audio_connected(d))
2466 pa_log_debug("Unloading module, because device %s doesn't have any audio profiles connected anymore.", d->path);
2467 else
2468 return PA_HOOK_OK;
2469
2470 pa_module_unload(u->core, u->module, true);
2471
2472 return PA_HOOK_OK;
2473 }
2474
2475 int pa__init(pa_module* m) {
2476 pa_modargs *ma;
2477 uint32_t channels;
2478 struct userdata *u;
2479 const char *address, *path;
2480 pa_bluetooth_device *device;
2481
2482 pa_assert(m);
2483
2484 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2485 pa_log_error("Failed to parse module arguments");
2486 goto fail;
2487 }
2488
2489 m->userdata = u = pa_xnew0(struct userdata, 1);
2490 u->module = m;
2491 u->core = m->core;
2492 u->stream_fd = -1;
2493 u->sample_spec = m->core->default_sample_spec;
2494 u->modargs = ma;
2495
2496 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2497 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2498 pa_log("SCO sink not found");
2499 goto fail;
2500 }
2501
2502 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2503 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2504 pa_log("SCO source not found");
2505 goto fail;
2506 }
2507
2508 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2509 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2510 pa_log_error("Failed to get rate from module arguments");
2511 goto fail;
2512 }
2513
2514 u->auto_connect = true;
2515 if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2516 pa_log("Failed to parse auto_connect= argument");
2517 goto fail;
2518 }
2519
2520 channels = u->sample_spec.channels;
2521 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2522 channels <= 0 || channels > PA_CHANNELS_MAX) {
2523 pa_log_error("Failed to get channels from module arguments");
2524 goto fail;
2525 }
2526 u->sample_spec.channels = (uint8_t) channels;
2527 u->requested_sample_spec = u->sample_spec;
2528
2529 address = pa_modargs_get_value(ma, "address", NULL);
2530 path = pa_modargs_get_value(ma, "path", NULL);
2531
2532 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2533 goto fail;
2534
2535 if (!(device = find_device(u, address, path)))
2536 goto fail;
2537
2538 u->device = device;
2539
2540 u->discovery_slot =
2541 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2542 PA_HOOK_NORMAL, (pa_hook_cb_t) discovery_hook_cb, u);
2543
2544 u->uuid_added_slot =
2545 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_UUID_ADDED),
2546 PA_HOOK_NORMAL, (pa_hook_cb_t) uuid_added_cb, u);
2547
2548 u->sink_state_changed_slot =
2549 pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED],
2550 PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
2551
2552 u->source_state_changed_slot =
2553 pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED],
2554 PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2555
2556 u->transport_state_changed_slot =
2557 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2558 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2559
2560 u->transport_nrec_changed_slot =
2561 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_NREC_CHANGED),
2562 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_nrec_changed_cb, u);
2563
2564 u->transport_microphone_changed_slot =
2565 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED),
2566 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2567
2568 u->transport_speaker_changed_slot =
2569 pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED),
2570 PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2571
2572 /* Add the card structure. This will also initialize the default profile */
2573 if (add_card(u) < 0)
2574 goto fail;
2575
2576 if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2577 goto fail;
2578
2579 u->msg->parent.process_msg = device_process_msg;
2580 u->msg->card = u->card;
2581
2582 if (u->profile != PROFILE_OFF)
2583 if (init_profile(u) < 0)
2584 goto off;
2585
2586 if (u->sink || u->source)
2587 if (start_thread(u) < 0)
2588 goto off;
2589
2590 return 0;
2591
2592 off:
2593 stop_thread(u);
2594
2595 pa_assert_se(pa_card_set_profile(u->card, "off", false) >= 0);
2596
2597 return 0;
2598
2599 fail:
2600
2601 pa__done(m);
2602
2603 return -1;
2604 }
2605
2606 int pa__get_n_used(pa_module *m) {
2607 struct userdata *u;
2608
2609 pa_assert(m);
2610 pa_assert_se(u = m->userdata);
2611
2612 return
2613 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2614 (u->source ? pa_source_linked_by(u->source) : 0);
2615 }
2616
2617 void pa__done(pa_module *m) {
2618 struct userdata *u;
2619
2620 pa_assert(m);
2621
2622 if (!(u = m->userdata))
2623 return;
2624
2625 stop_thread(u);
2626
2627 if (u->discovery_slot)
2628 pa_hook_slot_free(u->discovery_slot);
2629
2630 if (u->uuid_added_slot)
2631 pa_hook_slot_free(u->uuid_added_slot);
2632
2633 if (u->sink_state_changed_slot)
2634 pa_hook_slot_free(u->sink_state_changed_slot);
2635
2636 if (u->source_state_changed_slot)
2637 pa_hook_slot_free(u->source_state_changed_slot);
2638
2639 if (u->transport_state_changed_slot)
2640 pa_hook_slot_free(u->transport_state_changed_slot);
2641
2642 if (u->transport_nrec_changed_slot)
2643 pa_hook_slot_free(u->transport_nrec_changed_slot);
2644
2645 if (u->transport_microphone_changed_slot)
2646 pa_hook_slot_free(u->transport_microphone_changed_slot);
2647
2648 if (u->transport_speaker_changed_slot)
2649 pa_hook_slot_free(u->transport_speaker_changed_slot);
2650
2651 if (USE_SCO_OVER_PCM(u))
2652 restore_sco_volume_callbacks(u);
2653
2654 if (u->msg)
2655 pa_xfree(u->msg);
2656
2657 if (u->card)
2658 pa_card_free(u->card);
2659
2660 if (u->a2dp.buffer)
2661 pa_xfree(u->a2dp.buffer);
2662
2663 sbc_finish(&u->a2dp.sbc);
2664
2665 if (u->modargs)
2666 pa_modargs_free(u->modargs);
2667
2668 pa_xfree(u->address);
2669 pa_xfree(u->path);
2670
2671 if (u->discovery)
2672 pa_bluetooth_discovery_unref(u->discovery);
2673
2674 pa_xfree(u);
2675 }