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