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