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