]> code.delx.au - pulseaudio/blob - src/modules/bluetooth/module-bluetooth-device.c
Merge commit 'origin/master-tx'
[pulseaudio] / src / modules / bluetooth / module-bluetooth-device.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2008 Joao Paulo Rechi Vita
5
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
10
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <string.h>
27 #include <errno.h>
28 #include <poll.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
32
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulse/i18n.h>
37
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/socket-util.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/rtpoll.h>
46 #include <pulsecore/time-smoother.h>
47 #include <pulsecore/rtclock.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
50
51 #include "module-bluetooth-device-symdef.h"
52 #include "ipc.h"
53 #include "sbc.h"
54 #include "rtp.h"
55 #include "bluetooth-util.h"
56
57 #define MAX_BITPOOL 64
58 #define MIN_BITPOOL 2U
59
60 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
61 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
62 PA_MODULE_VERSION(PACKAGE_VERSION);
63 PA_MODULE_LOAD_ONCE(FALSE);
64 PA_MODULE_USAGE(
65 "name=<name for the card/sink/source, to be prefixed> "
66 "card_name=<name for the card> "
67 "sink_name=<name for the sink> "
68 "source_name=<name for the source> "
69 "address=<address of the device> "
70 "profile=<a2dp|hsp> "
71 "rate=<sample rate> "
72 "channels=<number of channels> "
73 "path=<device object path>");
74
75 /*
76 #ifdef NOKIA
77 "sco_sink=<SCO over PCM sink name> "
78 "sco_source=<SCO over PCM source name>"
79 #endif
80 */
81
82 /* TODO: not close fd when entering suspend mode in a2dp */
83
84 static const char* const valid_modargs[] = {
85 "name",
86 "card_name",
87 "sink_name",
88 "source_name",
89 "address",
90 "profile",
91 "rate",
92 "channels",
93 "path",
94 #ifdef NOKIA
95 "sco_sink",
96 "sco_source",
97 #endif
98 NULL
99 };
100
101 struct a2dp_info {
102 sbc_capabilities_t sbc_capabilities;
103 sbc_t sbc; /* Codec data */
104 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
105 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
106
107 void* buffer; /* Codec transfer buffer */
108 size_t buffer_size; /* Size of the buffer */
109
110 uint16_t seq_num; /* Cumulative packet sequence */
111 };
112
113 struct hsp_info {
114 pcm_capabilities_t pcm_capabilities;
115 #ifdef NOKIA
116 pa_sink *sco_sink;
117 pa_source *sco_source;
118 #endif
119 pa_hook_slot *sink_state_changed_slot;
120 pa_hook_slot *source_state_changed_slot;
121 };
122
123 enum profile {
124 PROFILE_A2DP,
125 PROFILE_HSP,
126 PROFILE_OFF
127 };
128
129 struct userdata {
130 pa_core *core;
131 pa_module *module;
132
133 char *address;
134 char *path;
135 pa_bluetooth_discovery *discovery;
136
137 pa_dbus_connection *connection;
138
139 pa_card *card;
140 pa_sink *sink;
141 pa_source *source;
142
143 pa_thread_mq thread_mq;
144 pa_rtpoll *rtpoll;
145 pa_rtpoll_item *rtpoll_item;
146 pa_thread *thread;
147
148 uint64_t read_index, write_index;
149 pa_usec_t started_at;
150 pa_smoother *read_smoother;
151
152 pa_memchunk write_memchunk;
153
154 pa_sample_spec sample_spec, requested_sample_spec;
155
156 int service_fd;
157 int stream_fd;
158
159 size_t link_mtu;
160 size_t block_size;
161
162 struct a2dp_info a2dp;
163 struct hsp_info hsp;
164
165 enum profile profile;
166
167 pa_modargs *modargs;
168
169 int stream_write_type;
170 int service_write_type, service_read_type;
171 };
172
173 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
174 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
175 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
176
177 #ifdef NOKIA
178 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
179 #endif
180
181 static int init_bt(struct userdata *u);
182 static int init_profile(struct userdata *u);
183
184 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
185 ssize_t r;
186
187 pa_assert(u);
188 pa_assert(u->service_fd >= 0);
189 pa_assert(msg);
190 pa_assert(msg->length > 0);
191
192 pa_log_debug("Sending %s -> %s",
193 pa_strnull(bt_audio_strtype(msg->type)),
194 pa_strnull(bt_audio_strname(msg->name)));
195
196 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
197 return 0;
198
199 if (r < 0)
200 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
201 else
202 pa_log_error("Short write()");
203
204 return -1;
205 }
206
207 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
208 ssize_t r;
209
210 pa_assert(u);
211 pa_assert(u->service_fd >= 0);
212 pa_assert(msg);
213
214 if (room <= 0)
215 room = BT_SUGGESTED_BUFFER_SIZE;
216
217 pa_log_debug("Trying to receive message from audio service...");
218
219 /* First, read the header */
220 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
221 goto read_fail;
222
223 if (msg->length < sizeof(*msg)) {
224 pa_log_error("Invalid message size.");
225 return -1;
226 }
227
228 /* Secondly, read the payload */
229 if (msg->length > sizeof(*msg)) {
230
231 size_t remains = msg->length - sizeof(*msg);
232
233 if ((r = pa_loop_read(u->service_fd,
234 (uint8_t*) msg + sizeof(*msg),
235 remains,
236 &u->service_read_type)) != (ssize_t) remains)
237 goto read_fail;
238 }
239
240 pa_log_debug("Received %s <- %s",
241 pa_strnull(bt_audio_strtype(msg->type)),
242 pa_strnull(bt_audio_strname(msg->name)));
243
244 return 0;
245
246 read_fail:
247
248 if (r < 0)
249 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
250 else
251 pa_log_error("Short read()");
252
253 return -1;
254 }
255
256 static ssize_t service_expect(struct userdata*u, bt_audio_msg_header_t *rsp, size_t room, uint8_t expected_name, size_t expected_size) {
257 int r;
258
259 pa_assert(u);
260 pa_assert(u->service_fd >= 0);
261 pa_assert(rsp);
262
263 if ((r = service_recv(u, rsp, room)) < 0)
264 return r;
265
266 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
267 rsp->name != expected_name ||
268 (expected_size > 0 && rsp->length != expected_size)) {
269
270 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
271 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
272 else
273 pa_log_error("Bogus message %s received while %s was expected",
274 pa_strnull(bt_audio_strname(rsp->name)),
275 pa_strnull(bt_audio_strname(expected_name)));
276 return -1;
277 }
278
279 return 0;
280 }
281
282 /* Run from main thread */
283 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
284 uint16_t bytes_left;
285 const codec_capabilities_t *codec;
286
287 pa_assert(u);
288 pa_assert(rsp);
289
290 bytes_left = rsp->h.length - sizeof(*rsp);
291
292 if (bytes_left < sizeof(codec_capabilities_t)) {
293 pa_log_error("Packet too small to store codec information.");
294 return -1;
295 }
296
297 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
298
299 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
300
301 if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
302 (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
303 pa_log_error("Got capabilities for wrong codec.");
304 return -1;
305 }
306
307 if (u->profile == PROFILE_HSP) {
308
309 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
310 return -1;
311
312 pa_assert(codec->type == BT_HFP_CODEC_PCM);
313
314 if (codec->configured && seid == 0)
315 return codec->seid;
316
317 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
318
319 } else if (u->profile == PROFILE_A2DP) {
320
321 while (bytes_left > 0) {
322 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
323 break;
324
325 bytes_left -= codec->length;
326 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
327 }
328
329 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
330 return -1;
331
332 pa_assert(codec->type == BT_A2DP_SBC_SINK);
333
334 if (codec->configured && seid == 0)
335 return codec->seid;
336
337 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
338 }
339
340 return 0;
341 }
342
343 /* Run from main thread */
344 static int get_caps(struct userdata *u, uint8_t seid) {
345 union {
346 struct bt_get_capabilities_req getcaps_req;
347 struct bt_get_capabilities_rsp getcaps_rsp;
348 bt_audio_error_t error;
349 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
350 } msg;
351 int ret;
352
353 pa_assert(u);
354
355 memset(&msg, 0, sizeof(msg));
356 msg.getcaps_req.h.type = BT_REQUEST;
357 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
358 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
359 msg.getcaps_req.seid = seid;
360
361 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
362 if (u->profile == PROFILE_A2DP)
363 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
364 else {
365 pa_assert(u->profile == PROFILE_HSP);
366 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
367 }
368 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
369
370 if (service_send(u, &msg.getcaps_req.h) < 0)
371 return -1;
372
373 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
374 return -1;
375
376 ret = parse_caps(u, seid, &msg.getcaps_rsp);
377 if (ret <= 0)
378 return ret;
379
380 return get_caps(u, ret);
381 }
382
383 /* Run from main thread */
384 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
385
386 switch (freq) {
387 case BT_SBC_SAMPLING_FREQ_16000:
388 case BT_SBC_SAMPLING_FREQ_32000:
389 return 53;
390
391 case BT_SBC_SAMPLING_FREQ_44100:
392
393 switch (mode) {
394 case BT_A2DP_CHANNEL_MODE_MONO:
395 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
396 return 31;
397
398 case BT_A2DP_CHANNEL_MODE_STEREO:
399 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
400 return 53;
401
402 default:
403 pa_log_warn("Invalid channel mode %u", mode);
404 return 53;
405 }
406
407 case BT_SBC_SAMPLING_FREQ_48000:
408
409 switch (mode) {
410 case BT_A2DP_CHANNEL_MODE_MONO:
411 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
412 return 29;
413
414 case BT_A2DP_CHANNEL_MODE_STEREO:
415 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
416 return 51;
417
418 default:
419 pa_log_warn("Invalid channel mode %u", mode);
420 return 51;
421 }
422
423 default:
424 pa_log_warn("Invalid sampling freq %u", freq);
425 return 53;
426 }
427 }
428
429 /* Run from main thread */
430 static int setup_a2dp(struct userdata *u) {
431 sbc_capabilities_t *cap;
432 int i;
433
434 static const struct {
435 uint32_t rate;
436 uint8_t cap;
437 } freq_table[] = {
438 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
439 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
440 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
441 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
442 };
443
444 pa_assert(u);
445 pa_assert(u->profile == PROFILE_A2DP);
446
447 cap = &u->a2dp.sbc_capabilities;
448
449 /* Find the lowest freq that is at least as high as the requested
450 * sampling rate */
451 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
452 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
453 u->sample_spec.rate = freq_table[i].rate;
454 cap->frequency = freq_table[i].cap;
455 break;
456 }
457
458 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
459 for (--i; i >= 0; i--) {
460 if (cap->frequency & freq_table[i].cap) {
461 u->sample_spec.rate = freq_table[i].rate;
462 cap->frequency = freq_table[i].cap;
463 break;
464 }
465 }
466
467 if (i < 0) {
468 pa_log("Not suitable sample rate");
469 return -1;
470 }
471 }
472
473 pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
474
475 if (cap->capability.configured)
476 return 0;
477
478 if (u->sample_spec.channels <= 1) {
479 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
480 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
481 u->sample_spec.channels = 1;
482 } else
483 u->sample_spec.channels = 2;
484 }
485
486 if (u->sample_spec.channels >= 2) {
487 u->sample_spec.channels = 2;
488
489 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
490 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
491 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
492 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
493 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
494 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
495 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
496 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
497 u->sample_spec.channels = 1;
498 } else {
499 pa_log("No supported channel modes");
500 return -1;
501 }
502 }
503
504 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
505 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
506 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
507 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
508 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
509 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
510 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
511 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
512 else {
513 pa_log_error("No supported block lengths");
514 return -1;
515 }
516
517 if (cap->subbands & BT_A2DP_SUBBANDS_8)
518 cap->subbands = BT_A2DP_SUBBANDS_8;
519 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
520 cap->subbands = BT_A2DP_SUBBANDS_4;
521 else {
522 pa_log_error("No supported subbands");
523 return -1;
524 }
525
526 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
527 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
528 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
529 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
530
531 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
532 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
533
534 return 0;
535 }
536
537 /* Run from main thread */
538 static void setup_sbc(struct a2dp_info *a2dp) {
539 sbc_capabilities_t *active_capabilities;
540
541 pa_assert(a2dp);
542
543 active_capabilities = &a2dp->sbc_capabilities;
544
545 if (a2dp->sbc_initialized)
546 sbc_reinit(&a2dp->sbc, 0);
547 else
548 sbc_init(&a2dp->sbc, 0);
549 a2dp->sbc_initialized = TRUE;
550
551 switch (active_capabilities->frequency) {
552 case BT_SBC_SAMPLING_FREQ_16000:
553 a2dp->sbc.frequency = SBC_FREQ_16000;
554 break;
555 case BT_SBC_SAMPLING_FREQ_32000:
556 a2dp->sbc.frequency = SBC_FREQ_32000;
557 break;
558 case BT_SBC_SAMPLING_FREQ_44100:
559 a2dp->sbc.frequency = SBC_FREQ_44100;
560 break;
561 case BT_SBC_SAMPLING_FREQ_48000:
562 a2dp->sbc.frequency = SBC_FREQ_48000;
563 break;
564 default:
565 pa_assert_not_reached();
566 }
567
568 switch (active_capabilities->channel_mode) {
569 case BT_A2DP_CHANNEL_MODE_MONO:
570 a2dp->sbc.mode = SBC_MODE_MONO;
571 break;
572 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
573 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
574 break;
575 case BT_A2DP_CHANNEL_MODE_STEREO:
576 a2dp->sbc.mode = SBC_MODE_STEREO;
577 break;
578 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
579 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
580 break;
581 default:
582 pa_assert_not_reached();
583 }
584
585 switch (active_capabilities->allocation_method) {
586 case BT_A2DP_ALLOCATION_SNR:
587 a2dp->sbc.allocation = SBC_AM_SNR;
588 break;
589 case BT_A2DP_ALLOCATION_LOUDNESS:
590 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
591 break;
592 default:
593 pa_assert_not_reached();
594 }
595
596 switch (active_capabilities->subbands) {
597 case BT_A2DP_SUBBANDS_4:
598 a2dp->sbc.subbands = SBC_SB_4;
599 break;
600 case BT_A2DP_SUBBANDS_8:
601 a2dp->sbc.subbands = SBC_SB_8;
602 break;
603 default:
604 pa_assert_not_reached();
605 }
606
607 switch (active_capabilities->block_length) {
608 case BT_A2DP_BLOCK_LENGTH_4:
609 a2dp->sbc.blocks = SBC_BLK_4;
610 break;
611 case BT_A2DP_BLOCK_LENGTH_8:
612 a2dp->sbc.blocks = SBC_BLK_8;
613 break;
614 case BT_A2DP_BLOCK_LENGTH_12:
615 a2dp->sbc.blocks = SBC_BLK_12;
616 break;
617 case BT_A2DP_BLOCK_LENGTH_16:
618 a2dp->sbc.blocks = SBC_BLK_16;
619 break;
620 default:
621 pa_assert_not_reached();
622 }
623
624 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
625 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
626 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
627 }
628
629 /* Run from main thread */
630 static int set_conf(struct userdata *u) {
631 union {
632 struct bt_open_req open_req;
633 struct bt_open_rsp open_rsp;
634 struct bt_set_configuration_req setconf_req;
635 struct bt_set_configuration_rsp setconf_rsp;
636 bt_audio_error_t error;
637 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
638 } msg;
639
640 memset(&msg, 0, sizeof(msg));
641 msg.open_req.h.type = BT_REQUEST;
642 msg.open_req.h.name = BT_OPEN;
643 msg.open_req.h.length = sizeof(msg.open_req);
644
645 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
646 msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
647 msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
648
649 if (service_send(u, &msg.open_req.h) < 0)
650 return -1;
651
652 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
653 return -1;
654
655 if (u->profile == PROFILE_A2DP ) {
656 u->sample_spec.format = PA_SAMPLE_S16LE;
657
658 if (setup_a2dp(u) < 0)
659 return -1;
660 } else {
661 pa_assert(u->profile == PROFILE_HSP);
662
663 u->sample_spec.format = PA_SAMPLE_S16LE;
664 u->sample_spec.channels = 1;
665 u->sample_spec.rate = 8000;
666 }
667
668 memset(&msg, 0, sizeof(msg));
669 msg.setconf_req.h.type = BT_REQUEST;
670 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
671 msg.setconf_req.h.length = sizeof(msg.setconf_req);
672
673 if (u->profile == PROFILE_A2DP) {
674 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
675 } else {
676 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
677 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
678 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
679 }
680 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
681
682 if (service_send(u, &msg.setconf_req.h) < 0)
683 return -1;
684
685 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
686 return -1;
687
688 u->link_mtu = msg.setconf_rsp.link_mtu;
689
690 /* setup SBC encoder now we agree on parameters */
691 if (u->profile == PROFILE_A2DP) {
692 setup_sbc(&u->a2dp);
693
694 u->block_size =
695 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
696 / u->a2dp.frame_length
697 * u->a2dp.codesize);
698
699 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
700 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
701 } else
702 u->block_size = u->link_mtu;
703
704 return 0;
705 }
706
707 /* from IO thread, except in SCO over PCM */
708 static int start_stream_fd(struct userdata *u) {
709 union {
710 bt_audio_msg_header_t rsp;
711 struct bt_start_stream_req start_req;
712 struct bt_start_stream_rsp start_rsp;
713 struct bt_new_stream_ind streamfd_ind;
714 bt_audio_error_t error;
715 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
716 } msg;
717 struct pollfd *pollfd;
718 int one;
719
720 pa_assert(u);
721 pa_assert(u->rtpoll);
722 pa_assert(!u->rtpoll_item);
723 pa_assert(u->stream_fd < 0);
724
725 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
726 msg.start_req.h.type = BT_REQUEST;
727 msg.start_req.h.name = BT_START_STREAM;
728 msg.start_req.h.length = sizeof(msg.start_req);
729
730 if (service_send(u, &msg.start_req.h) < 0)
731 return -1;
732
733 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
734 return -1;
735
736 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
737 return -1;
738
739 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
740 pa_log("Failed to get stream fd from audio service.");
741 return -1;
742 }
743
744 pa_make_fd_nonblock(u->stream_fd);
745 pa_make_socket_low_delay(u->stream_fd);
746
747 one = 1;
748 if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
749 pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
750
751 pa_log_debug("Stream properly set up, we're ready to roll!");
752
753 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
754 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
755 pollfd->fd = u->stream_fd;
756 pollfd->events = pollfd->revents = 0;
757
758 u->read_index = u->write_index = 0;
759 u->started_at = 0;
760
761 if (u->source)
762 u->read_smoother = pa_smoother_new(
763 PA_USEC_PER_SEC,
764 PA_USEC_PER_SEC*2,
765 TRUE,
766 TRUE,
767 10,
768 pa_rtclock_usec(),
769 TRUE);
770
771 return 0;
772 }
773
774 /* from IO thread */
775 static int stop_stream_fd(struct userdata *u) {
776 union {
777 bt_audio_msg_header_t rsp;
778 struct bt_stop_stream_req start_req;
779 struct bt_stop_stream_rsp start_rsp;
780 bt_audio_error_t error;
781 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
782 } msg;
783 int r = 0;
784
785 pa_assert(u);
786 pa_assert(u->rtpoll);
787 pa_assert(u->rtpoll_item);
788 pa_assert(u->stream_fd >= 0);
789
790 pa_rtpoll_item_free(u->rtpoll_item);
791 u->rtpoll_item = NULL;
792
793 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
794 msg.start_req.h.type = BT_REQUEST;
795 msg.start_req.h.name = BT_STOP_STREAM;
796 msg.start_req.h.length = sizeof(msg.start_req);
797
798 if (service_send(u, &msg.start_req.h) < 0 ||
799 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
800 r = -1;
801
802 pa_close(u->stream_fd);
803 u->stream_fd = -1;
804
805 if (u->read_smoother) {
806 pa_smoother_free(u->read_smoother);
807 u->read_smoother = NULL;
808 }
809
810 return r;
811 }
812
813 /* Run from IO thread */
814 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
815 struct userdata *u = PA_SINK(o)->userdata;
816 pa_bool_t failed = FALSE;
817 int r;
818
819 pa_assert(u->sink == PA_SINK(o));
820
821 switch (code) {
822
823 case PA_SINK_MESSAGE_SET_STATE:
824
825 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
826
827 case PA_SINK_SUSPENDED:
828 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
829
830 /* Stop the device if the source is suspended as well */
831 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
832 /* We deliberately ignore whether stopping
833 * actually worked. Since the stream_fd is
834 * closed it doesn't really matter */
835 stop_stream_fd(u);
836
837 break;
838
839 case PA_SINK_IDLE:
840 case PA_SINK_RUNNING:
841 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
842 break;
843
844 /* Resume the device if the source was suspended as well */
845 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
846 if (start_stream_fd(u) < 0)
847 failed = TRUE;
848 break;
849
850 case PA_SINK_UNLINKED:
851 case PA_SINK_INIT:
852 case PA_SINK_INVALID_STATE:
853 ;
854 }
855 break;
856
857 case PA_SINK_MESSAGE_GET_LATENCY: {
858
859 if (u->read_smoother) {
860 pa_usec_t wi, ri;
861
862 ri = pa_smoother_get(u->read_smoother, pa_rtclock_usec());
863 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
864
865 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
866 } else {
867 pa_usec_t ri, wi;
868
869 ri = pa_rtclock_usec() - u->started_at;
870 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
871
872 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
873 }
874
875 *((pa_usec_t*) data) += u->sink->fixed_latency;
876 return 0;
877 }
878 }
879
880 r = pa_sink_process_msg(o, code, data, offset, chunk);
881
882 return (r < 0 || !failed) ? r : -1;
883 }
884
885 /* Run from IO thread */
886 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
887 struct userdata *u = PA_SOURCE(o)->userdata;
888 pa_bool_t failed = FALSE;
889 int r;
890
891 pa_assert(u->source == PA_SOURCE(o));
892
893 switch (code) {
894
895 case PA_SOURCE_MESSAGE_SET_STATE:
896
897 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
898
899 case PA_SOURCE_SUSPENDED:
900 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
901
902 /* Stop the device if the sink is suspended as well */
903 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
904 stop_stream_fd(u);
905
906 if (u->read_smoother)
907 pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
908 break;
909
910 case PA_SOURCE_IDLE:
911 case PA_SOURCE_RUNNING:
912 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
913 break;
914
915 /* Resume the device if the sink was suspended as well */
916 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
917 if (start_stream_fd(u) < 0)
918 failed = TRUE;
919
920 /* We don't resume the smoother here. Instead we
921 * wait until the first packet arrives */
922 break;
923
924 case PA_SOURCE_UNLINKED:
925 case PA_SOURCE_INIT:
926 case PA_SOURCE_INVALID_STATE:
927 ;
928 }
929 break;
930
931 case PA_SOURCE_MESSAGE_GET_LATENCY: {
932 pa_usec_t wi, ri;
933
934 wi = pa_smoother_get(u->read_smoother, pa_rtclock_usec());
935 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
936
937 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->fixed_latency;
938 return 0;
939 }
940
941 }
942
943 r = pa_source_process_msg(o, code, data, offset, chunk);
944
945 return (r < 0 || !failed) ? r : -1;
946 }
947
948 /* Run from IO thread */
949 static int hsp_process_render(struct userdata *u) {
950 int ret = 0;
951
952 pa_assert(u);
953 pa_assert(u->profile == PROFILE_HSP);
954 pa_assert(u->sink);
955
956 /* First, render some data */
957 if (!u->write_memchunk.memblock)
958 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
959
960 pa_assert(u->write_memchunk.length == u->block_size);
961
962 for (;;) {
963 ssize_t l;
964 const void *p;
965
966 /* Now write that data to the socket. The socket is of type
967 * SEQPACKET, and we generated the data of the MTU size, so this
968 * should just work. */
969
970 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
971 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
972 pa_memblock_release(u->write_memchunk.memblock);
973
974 pa_assert(l != 0);
975
976 if (l < 0) {
977
978 if (errno == EINTR)
979 /* Retry right away if we got interrupted */
980 continue;
981
982 else if (errno == EAGAIN)
983 /* Hmm, apparently the socket was not writable, give up for now */
984 break;
985
986 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
987 ret = -1;
988 break;
989 }
990
991 pa_assert((size_t) l <= u->write_memchunk.length);
992
993 if ((size_t) l != u->write_memchunk.length) {
994 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
995 (unsigned long long) l,
996 (unsigned long long) u->write_memchunk.length);
997 ret = -1;
998 break;
999 }
1000
1001 u->write_index += (uint64_t) u->write_memchunk.length;
1002 pa_memblock_unref(u->write_memchunk.memblock);
1003 pa_memchunk_reset(&u->write_memchunk);
1004
1005 ret = 1;
1006 break;
1007 }
1008
1009 return ret;
1010 }
1011
1012 /* Run from IO thread */
1013 static int hsp_process_push(struct userdata *u) {
1014 int ret = 0;
1015 pa_memchunk memchunk;
1016
1017 pa_assert(u);
1018 pa_assert(u->profile == PROFILE_HSP);
1019 pa_assert(u->source);
1020 pa_assert(u->read_smoother);
1021
1022 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1023 memchunk.index = memchunk.length = 0;
1024
1025 for (;;) {
1026 ssize_t l;
1027 void *p;
1028 struct msghdr m;
1029 struct cmsghdr *cm;
1030 uint8_t aux[1024];
1031 struct iovec iov;
1032 pa_bool_t found_tstamp = FALSE;
1033 pa_usec_t tstamp;
1034
1035 memset(&m, 0, sizeof(m));
1036 memset(&aux, 0, sizeof(aux));
1037 memset(&iov, 0, sizeof(iov));
1038
1039 m.msg_iov = &iov;
1040 m.msg_iovlen = 1;
1041 m.msg_control = aux;
1042 m.msg_controllen = sizeof(aux);
1043
1044 p = pa_memblock_acquire(memchunk.memblock);
1045 iov.iov_base = p;
1046 iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1047 l = recvmsg(u->stream_fd, &m, 0);
1048 pa_memblock_release(memchunk.memblock);
1049
1050 if (l <= 0) {
1051
1052 if (l < 0 && errno == EINTR)
1053 /* Retry right away if we got interrupted */
1054 continue;
1055
1056 else if (l < 0 && errno == EAGAIN)
1057 /* Hmm, apparently the socket was not readable, give up for now. */
1058 break;
1059
1060 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1061 ret = -1;
1062 break;
1063 }
1064
1065 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1066
1067 memchunk.length = (size_t) l;
1068 u->read_index += (uint64_t) l;
1069
1070 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1071 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1072 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1073 pa_rtclock_from_wallclock(tv);
1074 tstamp = pa_timeval_load(tv);
1075 found_tstamp = TRUE;
1076 break;
1077 }
1078
1079 if (!found_tstamp) {
1080 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1081 tstamp = pa_rtclock_usec();
1082 }
1083
1084 pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1085 pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1086
1087 pa_source_post(u->source, &memchunk);
1088
1089 ret = 1;
1090 break;
1091 }
1092
1093 pa_memblock_unref(memchunk.memblock);
1094
1095 return ret;
1096 }
1097
1098 /* Run from IO thread */
1099 static void a2dp_prepare_buffer(struct userdata *u) {
1100 pa_assert(u);
1101
1102 if (u->a2dp.buffer_size >= u->link_mtu)
1103 return;
1104
1105 u->a2dp.buffer_size = 2 * u->link_mtu;
1106 pa_xfree(u->a2dp.buffer);
1107 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1108 }
1109
1110 /* Run from IO thread */
1111 static int a2dp_process_render(struct userdata *u) {
1112 struct a2dp_info *a2dp;
1113 struct rtp_header *header;
1114 struct rtp_payload *payload;
1115 size_t nbytes;
1116 void *d;
1117 const void *p;
1118 size_t to_write, to_encode;
1119 unsigned frame_count;
1120 int ret = 0;
1121
1122 pa_assert(u);
1123 pa_assert(u->profile == PROFILE_A2DP);
1124 pa_assert(u->sink);
1125
1126 /* First, render some data */
1127 if (!u->write_memchunk.memblock)
1128 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1129
1130 pa_assert(u->write_memchunk.length == u->block_size);
1131
1132 a2dp_prepare_buffer(u);
1133
1134 a2dp = &u->a2dp;
1135 header = a2dp->buffer;
1136 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1137
1138 frame_count = 0;
1139
1140 /* Try to create a packet of the full MTU */
1141
1142 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1143 to_encode = u->write_memchunk.length;
1144
1145 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1146 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1147
1148 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1149 size_t written;
1150 ssize_t encoded;
1151
1152 encoded = sbc_encode(&a2dp->sbc,
1153 p, to_encode,
1154 d, to_write,
1155 &written);
1156
1157 if (PA_UNLIKELY(encoded <= 0)) {
1158 pa_log_error("SBC encoding error (%li)", (long) encoded);
1159 pa_memblock_release(u->write_memchunk.memblock);
1160 return -1;
1161 }
1162
1163 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1164 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1165
1166 pa_assert_fp((size_t) encoded <= to_encode);
1167 pa_assert_fp((size_t) encoded == a2dp->codesize);
1168
1169 pa_assert_fp((size_t) written <= to_write);
1170 pa_assert_fp((size_t) written == a2dp->frame_length);
1171
1172 p = (const uint8_t*) p + encoded;
1173 to_encode -= encoded;
1174
1175 d = (uint8_t*) d + written;
1176 to_write -= written;
1177
1178 frame_count++;
1179 }
1180
1181 pa_memblock_release(u->write_memchunk.memblock);
1182
1183 pa_assert(to_encode == 0);
1184
1185 PA_ONCE_BEGIN {
1186 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1187 } PA_ONCE_END;
1188
1189 /* write it to the fifo */
1190 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1191 header->v = 2;
1192 header->pt = 1;
1193 header->sequence_number = htons(a2dp->seq_num++);
1194 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1195 header->ssrc = htonl(1);
1196 payload->frame_count = frame_count;
1197
1198 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1199
1200 for (;;) {
1201 ssize_t l;
1202
1203 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1204
1205 pa_assert(l != 0);
1206
1207 if (l < 0) {
1208
1209 if (errno == EINTR)
1210 /* Retry right away if we got interrupted */
1211 continue;
1212
1213 else if (errno == EAGAIN)
1214 /* Hmm, apparently the socket was not writable, give up for now */
1215 break;
1216
1217 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1218 ret = -1;
1219 break;
1220 }
1221
1222 pa_assert((size_t) l <= nbytes);
1223
1224 if ((size_t) l != nbytes) {
1225 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1226 (unsigned long long) l,
1227 (unsigned long long) nbytes);
1228 ret = -1;
1229 break;
1230 }
1231
1232 u->write_index += (uint64_t) u->write_memchunk.length;
1233 pa_memblock_unref(u->write_memchunk.memblock);
1234 pa_memchunk_reset(&u->write_memchunk);
1235
1236 ret = 1;
1237
1238 break;
1239 }
1240
1241 return ret;
1242 }
1243
1244 static void thread_func(void *userdata) {
1245 struct userdata *u = userdata;
1246 unsigned do_write = 0;
1247 pa_bool_t writable = FALSE;
1248
1249 pa_assert(u);
1250
1251 pa_log_debug("IO Thread starting up");
1252
1253 if (u->core->realtime_scheduling)
1254 pa_make_realtime(u->core->realtime_priority);
1255
1256 if (start_stream_fd(u) < 0)
1257 goto fail;
1258
1259 pa_thread_mq_install(&u->thread_mq);
1260 pa_rtpoll_install(u->rtpoll);
1261
1262 for (;;) {
1263 struct pollfd *pollfd;
1264 int ret;
1265 pa_bool_t disable_timer = TRUE;
1266
1267 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1268
1269 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1270
1271 /* We should send two blocks to the device before we expect
1272 * a response. */
1273
1274 if (u->write_index == 0 && u->read_index <= 0)
1275 do_write = 2;
1276
1277 if (pollfd && (pollfd->revents & POLLIN)) {
1278 int n_read;
1279
1280 if ((n_read = hsp_process_push(u)) < 0)
1281 goto fail;
1282
1283 /* We just read something, so we are supposed to write something, too */
1284 do_write += n_read;
1285 }
1286 }
1287
1288 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1289
1290 if (u->sink->thread_info.rewind_requested)
1291 pa_sink_process_rewind(u->sink, 0);
1292
1293 if (pollfd) {
1294 if (pollfd->revents & POLLOUT)
1295 writable = TRUE;
1296
1297 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1298 pa_usec_t time_passed;
1299 uint64_t should_have_written;
1300
1301 /* Hmm, there is no input stream we could synchronize
1302 * to. So let's do things by time */
1303
1304 time_passed = pa_rtclock_usec() - u->started_at;
1305 should_have_written = pa_usec_to_bytes(time_passed, &u->sample_spec);
1306
1307 do_write = u->write_index <= should_have_written;
1308 }
1309
1310 if (writable && do_write > 0) {
1311 int n_written;
1312
1313 if (u->write_index <= 0)
1314 u->started_at = pa_rtclock_usec();
1315
1316 if (u->profile == PROFILE_A2DP) {
1317 if ((n_written = a2dp_process_render(u)) < 0)
1318 goto fail;
1319 } else {
1320 if ((n_written = hsp_process_render(u)) < 0)
1321 goto fail;
1322 }
1323
1324 do_write -= n_written;
1325 writable = FALSE;
1326 }
1327
1328 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1329 pa_usec_t time_passed, next_write_at, sleep_for;
1330
1331 /* Hmm, there is no input stream we could synchronize
1332 * to. So let's estimate when we need to wake up the latest */
1333
1334 time_passed = pa_rtclock_usec() - u->started_at;
1335 next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1336 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1337
1338 /* 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); */
1339
1340 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1341 disable_timer = FALSE;
1342 }
1343 }
1344 }
1345
1346 if (disable_timer)
1347 pa_rtpoll_set_timer_disabled(u->rtpoll);
1348
1349 /* Hmm, nothing to do. Let's sleep */
1350 if (pollfd)
1351 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1352 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1353
1354 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1355 goto fail;
1356
1357 if (ret == 0)
1358 goto finish;
1359
1360 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1361
1362 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1363 pa_log_info("FD error: %s%s%s%s",
1364 pollfd->revents & POLLERR ? "POLLERR " :"",
1365 pollfd->revents & POLLHUP ? "POLLHUP " :"",
1366 pollfd->revents & POLLPRI ? "POLLPRI " :"",
1367 pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1368 goto fail;
1369 }
1370 }
1371
1372 fail:
1373 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1374 pa_log_debug("IO thread failed");
1375 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1376 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1377
1378 finish:
1379 pa_log_debug("IO thread shutting down");
1380 }
1381
1382 /* Run from main thread */
1383 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1384 DBusError err;
1385 struct userdata *u;
1386
1387 pa_assert(bus);
1388 pa_assert(m);
1389 pa_assert_se(u = userdata);
1390
1391 dbus_error_init(&err);
1392
1393 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1394 dbus_message_get_interface(m),
1395 dbus_message_get_path(m),
1396 dbus_message_get_member(m));
1397
1398 if (!dbus_message_has_path(m, u->path))
1399 goto fail;
1400
1401 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1402 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1403
1404 dbus_uint16_t gain;
1405 pa_cvolume v;
1406
1407 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1408 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1409 goto fail;
1410 }
1411
1412 if (u->profile == PROFILE_HSP) {
1413 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1414
1415 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1416 pa_sink_volume_changed(u->sink, &v);
1417
1418 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1419
1420 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1421 pa_source_volume_changed(u->source, &v);
1422 }
1423 }
1424 }
1425
1426 fail:
1427 dbus_error_free(&err);
1428
1429 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1430 }
1431
1432 /* Run from main thread */
1433 static void sink_set_volume_cb(pa_sink *s) {
1434 struct userdata *u = s->userdata;
1435 DBusMessage *m;
1436 dbus_uint16_t gain;
1437
1438 pa_assert(u);
1439
1440 if (u->profile != PROFILE_HSP)
1441 return;
1442
1443 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1444
1445 if (gain > 15)
1446 gain = 15;
1447
1448 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1449
1450 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1451 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1452 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1453 dbus_message_unref(m);
1454 }
1455
1456 /* Run from main thread */
1457 static void source_set_volume_cb(pa_source *s) {
1458 struct userdata *u = s->userdata;
1459 DBusMessage *m;
1460 dbus_uint16_t gain;
1461
1462 pa_assert(u);
1463
1464 if (u->profile != PROFILE_HSP)
1465 return;
1466
1467 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1468
1469 if (gain > 15)
1470 gain = 15;
1471
1472 pa_cvolume_set(&s->virtual_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1473
1474 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1475 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1476 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1477 dbus_message_unref(m);
1478 }
1479
1480 /* Run from main thread */
1481 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1482 char *t;
1483 const char *n;
1484
1485 pa_assert(type);
1486 pa_assert(ma);
1487 pa_assert(device_id);
1488 pa_assert(namereg_fail);
1489
1490 t = pa_sprintf_malloc("%s_name", type);
1491 n = pa_modargs_get_value(ma, t, NULL);
1492 pa_xfree(t);
1493
1494 if (n) {
1495 *namereg_fail = TRUE;
1496 return pa_xstrdup(n);
1497 }
1498
1499 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1500 *namereg_fail = TRUE;
1501 else {
1502 n = device_id;
1503 *namereg_fail = FALSE;
1504 }
1505
1506 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1507 }
1508
1509 #ifdef NOKIA
1510
1511 static void sco_over_pcm_state_update(struct userdata *u) {
1512 pa_assert(u);
1513 pa_assert(USE_SCO_OVER_PCM(u));
1514
1515 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1516 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1517
1518 if (u->service_fd >= 0)
1519 return;
1520
1521 pa_log_debug("Resuming SCO over PCM");
1522 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1523 pa_log("Can't resume SCO over PCM");
1524
1525 start_stream_fd(u);
1526 } else {
1527
1528 if (u->service_fd < 0)
1529 return;
1530
1531 stop_stream_fd(u);
1532
1533 pa_log_debug("Closing SCO over PCM");
1534 pa_close(u->service_fd);
1535 u->service_fd = -1;
1536 }
1537 }
1538
1539 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1540 pa_assert(c);
1541 pa_sink_assert_ref(s);
1542 pa_assert(u);
1543
1544 if (s != u->hsp.sco_sink)
1545 return PA_HOOK_OK;
1546
1547 sco_over_pcm_state_update(u);
1548
1549 return PA_HOOK_OK;
1550 }
1551
1552 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1553 pa_assert(c);
1554 pa_source_assert_ref(s);
1555 pa_assert(u);
1556
1557 if (s != u->hsp.sco_source)
1558 return PA_HOOK_OK;
1559
1560 sco_over_pcm_state_update(u);
1561
1562 return PA_HOOK_OK;
1563 }
1564
1565 #endif
1566
1567 /* Run from main thread */
1568 static int add_sink(struct userdata *u) {
1569
1570 #ifdef NOKIA
1571 if (USE_SCO_OVER_PCM(u)) {
1572 pa_proplist *p;
1573
1574 u->sink = u->hsp.sco_sink;
1575 p = pa_proplist_new();
1576 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1577 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1578 pa_proplist_free(p);
1579
1580 if (!u->hsp.sink_state_changed_slot)
1581 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);
1582
1583 } else
1584 #endif
1585
1586 {
1587 pa_sink_new_data data;
1588 pa_bool_t b;
1589
1590 pa_sink_new_data_init(&data);
1591 data.driver = __FILE__;
1592 data.module = u->module;
1593 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1594 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1595 data.card = u->card;
1596 data.name = get_name("sink", u->modargs, u->address, &b);
1597 data.namereg_fail = b;
1598
1599 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1600 pa_sink_new_data_done(&data);
1601
1602 if (!u->sink) {
1603 pa_log_error("Failed to create sink");
1604 return -1;
1605 }
1606
1607 u->sink->userdata = u;
1608 u->sink->parent.process_msg = sink_process_msg;
1609
1610 pa_sink_set_max_request(u->sink, u->block_size);
1611 u->sink->fixed_latency =
1612 (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1613 pa_bytes_to_usec(u->block_size, &u->sample_spec);
1614 }
1615
1616 if (u->profile == PROFILE_HSP) {
1617 u->sink->set_volume = sink_set_volume_cb;
1618 u->sink->n_volume_steps = 16;
1619 }
1620
1621 return 0;
1622 }
1623
1624 /* Run from main thread */
1625 static int add_source(struct userdata *u) {
1626
1627 #ifdef NOKIA
1628 if (USE_SCO_OVER_PCM(u)) {
1629 u->source = u->hsp.sco_source;
1630 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
1631
1632 if (!u->hsp.source_state_changed_slot)
1633 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);
1634
1635 } else
1636 #endif
1637
1638 {
1639 pa_source_new_data data;
1640 pa_bool_t b;
1641
1642 pa_source_new_data_init(&data);
1643 data.driver = __FILE__;
1644 data.module = u->module;
1645 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1646 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "hsp");
1647 data.card = u->card;
1648 data.name = get_name("source", u->modargs, u->address, &b);
1649 data.namereg_fail = b;
1650
1651 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1652 pa_source_new_data_done(&data);
1653
1654 if (!u->source) {
1655 pa_log_error("Failed to create source");
1656 return -1;
1657 }
1658
1659 u->source->userdata = u;
1660 u->source->parent.process_msg = source_process_msg;
1661
1662 u->source->fixed_latency =
1663 (/* u->profile == PROFILE_A2DP ? FIXED_LATENCY_RECORD_A2DP : */ FIXED_LATENCY_RECORD_HSP) +
1664 pa_bytes_to_usec(u->block_size, &u->sample_spec);
1665 }
1666
1667 if (u->profile == PROFILE_HSP) {
1668 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1669 u->source->set_volume = source_set_volume_cb;
1670 u->source->n_volume_steps = 16;
1671 }
1672
1673 return 0;
1674 }
1675
1676 /* Run from main thread */
1677 static void shutdown_bt(struct userdata *u) {
1678 pa_assert(u);
1679
1680 if (u->stream_fd >= 0) {
1681 pa_close(u->stream_fd);
1682 u->stream_fd = -1;
1683
1684 u->stream_write_type = 0;
1685 }
1686
1687 if (u->service_fd >= 0) {
1688 pa_close(u->service_fd);
1689 u->service_fd = -1;
1690 u->service_write_type = u->service_write_type = 0;
1691 }
1692
1693 if (u->write_memchunk.memblock) {
1694 pa_memblock_unref(u->write_memchunk.memblock);
1695 pa_memchunk_reset(&u->write_memchunk);
1696 }
1697 }
1698
1699 /* Run from main thread */
1700 static int init_bt(struct userdata *u) {
1701 pa_assert(u);
1702
1703 shutdown_bt(u);
1704
1705 u->stream_write_type = 0;
1706 u->service_write_type = u->service_write_type = 0;
1707
1708 if ((u->service_fd = bt_audio_service_open()) < 0) {
1709 pa_log_error("Couldn't connect to bluetooth audio service");
1710 return -1;
1711 }
1712
1713 pa_log_debug("Connected to the bluetooth audio service");
1714
1715 return 0;
1716 }
1717
1718 /* Run from main thread */
1719 static int setup_bt(struct userdata *u) {
1720 pa_assert(u);
1721
1722 if (get_caps(u, 0) < 0)
1723 return -1;
1724
1725 pa_log_debug("Got device capabilities");
1726
1727 if (set_conf(u) < 0)
1728 return -1;
1729
1730 pa_log_debug("Connection to the device configured");
1731
1732 #ifdef NOKIA
1733 if (USE_SCO_OVER_PCM(u)) {
1734 pa_log_debug("Configured to use SCO over PCM");
1735 return 0;
1736 }
1737 #endif
1738
1739 pa_log_debug("Got the stream socket");
1740
1741 return 0;
1742 }
1743
1744 /* Run from main thread */
1745 static int init_profile(struct userdata *u) {
1746 int r = 0;
1747 pa_assert(u);
1748 pa_assert(u->profile != PROFILE_OFF);
1749
1750 if (setup_bt(u) < 0)
1751 return -1;
1752
1753 if (u->profile == PROFILE_A2DP ||
1754 u->profile == PROFILE_HSP)
1755 if (add_sink(u) < 0)
1756 r = -1;
1757
1758 if (u->profile == PROFILE_HSP)
1759 if (add_source(u) < 0)
1760 r = -1;
1761
1762 return r;
1763 }
1764
1765 /* Run from main thread */
1766 static void stop_thread(struct userdata *u) {
1767 pa_assert(u);
1768
1769 if (u->thread) {
1770 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1771 pa_thread_free(u->thread);
1772 u->thread = NULL;
1773 }
1774
1775 if (u->rtpoll_item) {
1776 pa_rtpoll_item_free(u->rtpoll_item);
1777 u->rtpoll_item = NULL;
1778 }
1779
1780 if (u->hsp.sink_state_changed_slot) {
1781 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1782 u->hsp.sink_state_changed_slot = NULL;
1783 }
1784
1785 if (u->hsp.source_state_changed_slot) {
1786 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1787 u->hsp.source_state_changed_slot = NULL;
1788 }
1789
1790 if (u->sink) {
1791 pa_sink_unref(u->sink);
1792 u->sink = NULL;
1793 }
1794
1795 if (u->source) {
1796 pa_source_unref(u->source);
1797 u->source = NULL;
1798 }
1799
1800 if (u->rtpoll) {
1801 pa_thread_mq_done(&u->thread_mq);
1802
1803 pa_rtpoll_free(u->rtpoll);
1804 u->rtpoll = NULL;
1805 }
1806
1807 if (u->read_smoother) {
1808 pa_smoother_free(u->read_smoother);
1809 u->read_smoother = NULL;
1810 }
1811 }
1812
1813 /* Run from main thread */
1814 static int start_thread(struct userdata *u) {
1815 pa_assert(u);
1816 pa_assert(!u->thread);
1817 pa_assert(!u->rtpoll);
1818 pa_assert(!u->rtpoll_item);
1819
1820 u->rtpoll = pa_rtpoll_new();
1821 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1822
1823 #ifdef NOKIA
1824 if (USE_SCO_OVER_PCM(u)) {
1825 if (start_stream_fd(u) < 0)
1826 return -1;
1827
1828 pa_sink_ref(u->sink);
1829 pa_source_ref(u->source);
1830 /* FIXME: monitor stream_fd error */
1831 return 0;
1832 }
1833 #endif
1834
1835 if (!(u->thread = pa_thread_new(thread_func, u))) {
1836 pa_log_error("Failed to create IO thread");
1837 stop_thread(u);
1838 return -1;
1839 }
1840
1841 if (u->sink) {
1842 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1843 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1844 pa_sink_put(u->sink);
1845
1846 if (u->sink->set_volume)
1847 u->sink->set_volume(u->sink);
1848 }
1849
1850 if (u->source) {
1851 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1852 pa_source_set_rtpoll(u->source, u->rtpoll);
1853 pa_source_put(u->source);
1854
1855 if (u->source->set_volume)
1856 u->source->set_volume(u->source);
1857 }
1858
1859 return 0;
1860 }
1861
1862 /* Run from main thread */
1863 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1864 struct userdata *u;
1865 enum profile *d;
1866 pa_queue *inputs = NULL, *outputs = NULL;
1867 const pa_bluetooth_device *device;
1868
1869 pa_assert(c);
1870 pa_assert(new_profile);
1871 pa_assert_se(u = c->userdata);
1872
1873 d = PA_CARD_PROFILE_DATA(new_profile);
1874
1875 if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1876 pa_log_error("Failed to get device object.");
1877 return -1;
1878 }
1879
1880 if (device->headset_state != PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
1881 pa_log_warn("HSP is not connected, refused to switch profile");
1882 return -1;
1883 }
1884 else if (device->audio_sink_state != PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
1885 pa_log_warn("A2DP is not connected, refused to switch profile");
1886 return -1;
1887 }
1888
1889 if (u->sink) {
1890 inputs = pa_sink_move_all_start(u->sink);
1891 #ifdef NOKIA
1892 if (!USE_SCO_OVER_PCM(u))
1893 #endif
1894 pa_sink_unlink(u->sink);
1895 }
1896
1897 if (u->source) {
1898 outputs = pa_source_move_all_start(u->source);
1899 #ifdef NOKIA
1900 if (!USE_SCO_OVER_PCM(u))
1901 #endif
1902 pa_source_unlink(u->source);
1903 }
1904
1905 stop_thread(u);
1906 shutdown_bt(u);
1907
1908 u->profile = *d;
1909 u->sample_spec = u->requested_sample_spec;
1910
1911 init_bt(u);
1912
1913 if (u->profile != PROFILE_OFF)
1914 init_profile(u);
1915
1916 if (u->sink || u->source)
1917 start_thread(u);
1918
1919 if (inputs) {
1920 if (u->sink)
1921 pa_sink_move_all_finish(u->sink, inputs, FALSE);
1922 else
1923 pa_sink_move_all_fail(inputs);
1924 }
1925
1926 if (outputs) {
1927 if (u->source)
1928 pa_source_move_all_finish(u->source, outputs, FALSE);
1929 else
1930 pa_source_move_all_fail(outputs);
1931 }
1932
1933 return 0;
1934 }
1935
1936 /* Run from main thread */
1937 static int add_card(struct userdata *u, const char *default_profile, const pa_bluetooth_device *device) {
1938 pa_card_new_data data;
1939 pa_bool_t b;
1940 pa_card_profile *p;
1941 enum profile *d;
1942 const char *ff;
1943 char *n;
1944
1945 pa_card_new_data_init(&data);
1946 data.driver = __FILE__;
1947 data.module = u->module;
1948
1949 n = pa_bluetooth_cleanup_name(device->name);
1950 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1951 pa_xfree(n);
1952 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
1953 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1954 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1955 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1956 if ((ff = pa_bluetooth_get_form_factor(device->class)))
1957 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1958 pa_proplist_sets(data.proplist, "bluez.path", device->path);
1959 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
1960 pa_proplist_sets(data.proplist, "bluez.name", device->name);
1961 data.name = get_name("card", u->modargs, device->address, &b);
1962 data.namereg_fail = b;
1963
1964 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1965
1966 /* we base hsp/a2dp availability on UUIDs.
1967 Ideally, it would be based on "Connected" state, but
1968 we can't afford to wait for this information when
1969 we are loaded with profile="hsp", for instance */
1970 if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
1971 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
1972 p->priority = 10;
1973 p->n_sinks = 1;
1974 p->n_sources = 0;
1975 p->max_sink_channels = 2;
1976 p->max_source_channels = 0;
1977
1978 d = PA_CARD_PROFILE_DATA(p);
1979 *d = PROFILE_A2DP;
1980
1981 pa_hashmap_put(data.profiles, p->name, p);
1982 }
1983
1984 if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
1985 pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
1986 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
1987 p->priority = 20;
1988 p->n_sinks = 1;
1989 p->n_sources = 1;
1990 p->max_sink_channels = 1;
1991 p->max_source_channels = 1;
1992
1993 d = PA_CARD_PROFILE_DATA(p);
1994 *d = PROFILE_HSP;
1995
1996 pa_hashmap_put(data.profiles, p->name, p);
1997 }
1998
1999 pa_assert(!pa_hashmap_isempty(data.profiles));
2000
2001 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2002 d = PA_CARD_PROFILE_DATA(p);
2003 *d = PROFILE_OFF;
2004 pa_hashmap_put(data.profiles, p->name, p);
2005
2006 if (default_profile) {
2007 if (pa_hashmap_get(data.profiles, default_profile))
2008 pa_card_new_data_set_profile(&data, default_profile);
2009 else
2010 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2011 }
2012
2013 u->card = pa_card_new(u->core, &data);
2014 pa_card_new_data_done(&data);
2015
2016 if (!u->card) {
2017 pa_log("Failed to allocate card.");
2018 return -1;
2019 }
2020
2021 u->card->userdata = u;
2022 u->card->set_profile = card_set_profile;
2023
2024 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2025 u->profile = *d;
2026
2027 return 0;
2028 }
2029
2030 /* Run from main thread */
2031 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2032 const pa_bluetooth_device *d = NULL;
2033
2034 pa_assert(u);
2035
2036 if (!address && !path) {
2037 pa_log_error("Failed to get device address/path from module arguments.");
2038 return NULL;
2039 }
2040
2041 if (path) {
2042 if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2043 pa_log_error("%s is not a valid BlueZ audio device.", path);
2044 return NULL;
2045 }
2046
2047 if (address && !(pa_streq(d->address, address))) {
2048 pa_log_error("Passed path %s and address %s don't match.", path, address);
2049 return NULL;
2050 }
2051
2052 } else {
2053 if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2054 pa_log_error("%s is not known.", address);
2055 return NULL;
2056 }
2057 }
2058
2059 if (d) {
2060 u->address = pa_xstrdup(d->address);
2061 u->path = pa_xstrdup(d->path);
2062 }
2063
2064 return d;
2065 }
2066
2067 /* Run from main thread */
2068 static int setup_dbus(struct userdata *u) {
2069 DBusError err;
2070
2071 dbus_error_init(&err);
2072
2073 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2074
2075 if (dbus_error_is_set(&err) || !u->connection) {
2076 pa_log("Failed to get D-Bus connection: %s", err.message);
2077 dbus_error_free(&err);
2078 return -1;
2079 }
2080
2081 return 0;
2082 }
2083
2084 int pa__init(pa_module* m) {
2085 pa_modargs *ma;
2086 uint32_t channels;
2087 struct userdata *u;
2088 const char *address, *path;
2089 DBusError err;
2090 char *mike, *speaker;
2091 const pa_bluetooth_device *device;
2092
2093 pa_assert(m);
2094
2095 dbus_error_init(&err);
2096
2097 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2098 pa_log_error("Failed to parse module arguments");
2099 goto fail;
2100 }
2101
2102 m->userdata = u = pa_xnew0(struct userdata, 1);
2103 u->module = m;
2104 u->core = m->core;
2105 u->service_fd = -1;
2106 u->stream_fd = -1;
2107 u->sample_spec = m->core->default_sample_spec;
2108 u->modargs = ma;
2109
2110 #ifdef NOKIA
2111 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2112 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2113 pa_log("SCO sink not found");
2114 goto fail;
2115 }
2116
2117 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2118 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2119 pa_log("SCO source not found");
2120 goto fail;
2121 }
2122 #endif
2123
2124 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2125 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2126 pa_log_error("Failed to get rate from module arguments");
2127 goto fail;
2128 }
2129
2130 channels = u->sample_spec.channels;
2131 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2132 channels <= 0 || channels > PA_CHANNELS_MAX) {
2133 pa_log_error("Failed to get channels from module arguments");
2134 goto fail;
2135 }
2136 u->sample_spec.channels = (uint8_t) channels;
2137 u->requested_sample_spec = u->sample_spec;
2138
2139 address = pa_modargs_get_value(ma, "address", NULL);
2140 path = pa_modargs_get_value(ma, "path", NULL);
2141
2142 if (setup_dbus(u) < 0)
2143 goto fail;
2144
2145 if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2146 goto fail;
2147
2148 if (!(device = find_device(u, address, path)))
2149 goto fail;
2150
2151 /* Add the card structure. This will also initialize the default profile */
2152 if (add_card(u, pa_modargs_get_value(ma, "profile", NULL), device) < 0)
2153 goto fail;
2154
2155 /* Connect to the BT service and query capabilities */
2156 if (init_bt(u) < 0)
2157 goto fail;
2158
2159 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2160 pa_log_error("Failed to add filter function");
2161 goto fail;
2162 }
2163
2164 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2165 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2166
2167 if (pa_dbus_add_matches(
2168 pa_dbus_connection_get(u->connection), &err,
2169 speaker,
2170 mike,
2171 NULL) < 0) {
2172
2173 pa_xfree(speaker);
2174 pa_xfree(mike);
2175
2176 pa_log("Failed to add D-Bus matches: %s", err.message);
2177 goto fail;
2178 }
2179
2180 pa_xfree(speaker);
2181 pa_xfree(mike);
2182
2183 if (u->profile != PROFILE_OFF)
2184 if (init_profile(u) < 0)
2185 goto fail;
2186
2187 if (u->sink || u->source)
2188 if (start_thread(u) < 0)
2189 goto fail;
2190
2191 return 0;
2192
2193 fail:
2194
2195 pa__done(m);
2196
2197 dbus_error_free(&err);
2198
2199 return -1;
2200 }
2201
2202 int pa__get_n_used(pa_module *m) {
2203 struct userdata *u;
2204
2205 pa_assert(m);
2206 pa_assert_se(u = m->userdata);
2207
2208 return
2209 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2210 (u->source ? pa_source_linked_by(u->source) : 0);
2211 }
2212
2213 void pa__done(pa_module *m) {
2214 struct userdata *u;
2215 pa_assert(m);
2216
2217 if (!(u = m->userdata))
2218 return;
2219
2220 if (u->sink
2221 #ifdef NOKIA
2222 && !USE_SCO_OVER_PCM(u)
2223 #endif
2224 )
2225 pa_sink_unlink(u->sink);
2226
2227 if (u->source
2228 #ifdef NOKIA
2229 && !USE_SCO_OVER_PCM(u)
2230 #endif
2231 )
2232 pa_source_unlink(u->source);
2233
2234 stop_thread(u);
2235
2236 if (u->connection) {
2237
2238 if (u->path) {
2239 char *speaker, *mike;
2240 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2241 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2242
2243 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2244 speaker,
2245 mike,
2246 NULL);
2247
2248 pa_xfree(speaker);
2249 pa_xfree(mike);
2250 }
2251
2252 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2253 pa_dbus_connection_unref(u->connection);
2254 }
2255
2256 if (u->card)
2257 pa_card_free(u->card);
2258
2259 if (u->read_smoother)
2260 pa_smoother_free(u->read_smoother);
2261
2262 shutdown_bt(u);
2263
2264 if (u->a2dp.buffer)
2265 pa_xfree(u->a2dp.buffer);
2266
2267 sbc_finish(&u->a2dp.sbc);
2268
2269 if (u->modargs)
2270 pa_modargs_free(u->modargs);
2271
2272 pa_xfree(u->address);
2273 pa_xfree(u->path);
2274
2275 if (u->discovery)
2276 pa_bluetooth_discovery_unref(u->discovery);
2277
2278 pa_xfree(u);
2279 }