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