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