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