Query and make use of the current configuration.
[pulseaudio-mirror.git] / src / modules / bluetooth / module-bluetooth-device.c
blobbcb65a4759e17cba99afba3e7b8aa09516f607bb
1 /***
2 This file is part of PulseAudio.
4 Copyright 2008 Joao Paulo Rechi Vita
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.
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.
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 ***/
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
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>
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulse/i18n.h>
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>
50 #include <modules/dbus-util.h>
52 #include "module-bluetooth-device-symdef.h"
53 #include "ipc.h"
54 #include "sbc.h"
55 #include "rtp.h"
56 #include "bluetooth-util.h"
58 #define MAX_BITPOOL 64
59 #define MIN_BITPOOL 2U
61 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION);
64 PA_MODULE_LOAD_ONCE(FALSE);
65 PA_MODULE_USAGE(
66 "name=<name for the card/sink/source, to be prefixed> "
67 "card_name=<name for the card> "
68 "sink_name=<name for the sink> "
69 "source_name=<name for the source> "
70 "address=<address of the device> "
71 "profile=<a2dp|hsp> "
72 "rate=<sample rate> "
73 "channels=<number of channels> "
74 "path=<device object path>");
77 #ifdef NOKIA
78 "sco_sink=<SCO over PCM sink name> "
79 "sco_source=<SCO over PCM source name>"
80 #endif
83 /* TODO: not close fd when entering suspend mode in a2dp */
85 static const char* const valid_modargs[] = {
86 "name",
87 "card_name",
88 "sink_name",
89 "source_name",
90 "address",
91 "profile",
92 "rate",
93 "channels",
94 "path",
95 #ifdef NOKIA
96 "sco_sink",
97 "sco_source",
98 #endif
99 NULL
102 struct a2dp_info {
103 sbc_capabilities_t sbc_capabilities;
104 sbc_t sbc; /* Codec data */
105 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
106 size_t codesize, frame_length; /* SBC Codesize, frame_length. We simply cache those values here */
108 void* buffer; /* Codec transfer buffer */
109 size_t buffer_size; /* Size of the buffer */
111 uint16_t seq_num; /* Cumulative packet sequence */
114 struct hsp_info {
115 pcm_capabilities_t pcm_capabilities;
116 #ifdef NOKIA
117 pa_sink *sco_sink;
118 pa_source *sco_source;
119 #endif
120 pa_hook_slot *sink_state_changed_slot;
121 pa_hook_slot *source_state_changed_slot;
124 enum profile {
125 PROFILE_A2DP,
126 PROFILE_HSP,
127 PROFILE_OFF
130 struct userdata {
131 pa_core *core;
132 pa_module *module;
134 char *address;
135 char *path;
137 pa_dbus_connection *connection;
139 pa_card *card;
140 pa_sink *sink;
141 pa_source *source;
143 pa_thread_mq thread_mq;
144 pa_rtpoll *rtpoll;
145 pa_rtpoll_item *rtpoll_item;
146 pa_thread *thread;
148 uint64_t read_index, write_index;
149 pa_usec_t started_at;
150 pa_smoother *read_smoother;
152 pa_memchunk write_memchunk;
154 pa_sample_spec sample_spec, requested_sample_spec;
156 int service_fd;
157 int stream_fd;
159 size_t link_mtu;
160 size_t block_size;
162 struct a2dp_info a2dp;
163 struct hsp_info hsp;
165 enum profile profile;
167 pa_modargs *modargs;
169 int stream_write_type, stream_read_type;
170 int service_write_type, service_read_type;
173 #ifdef NOKIA
174 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
175 #endif
177 static int init_bt(struct userdata *u);
178 static int init_profile(struct userdata *u);
180 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
181 ssize_t r;
183 pa_assert(u);
184 pa_assert(u->service_fd >= 0);
185 pa_assert(msg);
186 pa_assert(msg->length > 0);
188 pa_log_debug("Sending %s -> %s",
189 pa_strnull(bt_audio_strtype(msg->type)),
190 pa_strnull(bt_audio_strname(msg->name)));
192 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
193 return 0;
195 if (r < 0)
196 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
197 else
198 pa_log_error("Short write()");
200 return -1;
203 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
204 ssize_t r;
206 pa_assert(u);
207 pa_assert(u->service_fd >= 0);
208 pa_assert(msg);
210 if (room <= 0)
211 room = BT_SUGGESTED_BUFFER_SIZE;
213 pa_log_debug("Trying to receive message from audio service...");
215 /* First, read the header */
216 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
217 goto read_fail;
219 if (msg->length < sizeof(*msg)) {
220 pa_log_error("Invalid message size.");
221 return -1;
224 /* Secondly, read the payload */
225 if (msg->length > sizeof(*msg)) {
227 size_t remains = msg->length - sizeof(*msg);
229 if ((r = pa_loop_read(u->service_fd,
230 (uint8_t*) msg + sizeof(*msg),
231 remains,
232 &u->service_read_type)) != (ssize_t) remains)
233 goto read_fail;
236 pa_log_debug("Received %s <- %s",
237 pa_strnull(bt_audio_strtype(msg->type)),
238 pa_strnull(bt_audio_strname(msg->name)));
240 return 0;
242 read_fail:
244 if (r < 0)
245 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
246 else
247 pa_log_error("Short read()");
249 return -1;
252 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) {
253 int r;
255 pa_assert(u);
256 pa_assert(u->service_fd >= 0);
257 pa_assert(rsp);
259 if ((r = service_recv(u, rsp, room)) < 0)
260 return r;
262 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
263 rsp->name != expected_name ||
264 (expected_size > 0 && rsp->length != expected_size)) {
266 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
267 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
268 else
269 pa_log_error("Bogus message %s received while %s was expected",
270 pa_strnull(bt_audio_strname(rsp->name)),
271 pa_strnull(bt_audio_strname(expected_name)));
272 return -1;
275 return 0;
278 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
279 uint16_t bytes_left;
280 const codec_capabilities_t *codec;
282 pa_assert(u);
283 pa_assert(rsp);
285 bytes_left = rsp->h.length - sizeof(*rsp);
287 if (bytes_left < sizeof(codec_capabilities_t)) {
288 pa_log_error("Packet too small to store codec information.");
289 return -1;
292 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
294 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
296 if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
297 (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
298 pa_log_error("Got capabilities for wrong codec.");
299 return -1;
302 if (u->profile == PROFILE_HSP) {
304 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
305 return -1;
307 pa_assert(codec->type == BT_HFP_CODEC_PCM);
309 if (codec->configured && seid == 0)
310 return codec->seid;
312 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
314 } else if (u->profile == PROFILE_A2DP) {
316 while (bytes_left > 0) {
317 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
318 break;
320 bytes_left -= codec->length;
321 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
324 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
325 return -1;
327 pa_assert(codec->type == BT_A2DP_SBC_SINK);
329 if (codec->configured && seid == 0)
330 return codec->seid;
332 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
335 return 0;
338 static int get_caps(struct userdata *u, uint8_t seid) {
339 union {
340 struct bt_get_capabilities_req getcaps_req;
341 struct bt_get_capabilities_rsp getcaps_rsp;
342 bt_audio_error_t error;
343 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
344 } msg;
345 int ret;
347 pa_assert(u);
349 memset(&msg, 0, sizeof(msg));
350 msg.getcaps_req.h.type = BT_REQUEST;
351 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
352 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
353 msg.getcaps_req.seid = seid;
355 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
356 if (u->profile == PROFILE_A2DP)
357 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
358 else {
359 pa_assert(u->profile == PROFILE_HSP);
360 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
362 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
364 if (service_send(u, &msg.getcaps_req.h) < 0)
365 return -1;
367 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
368 return -1;
370 ret = parse_caps(u, seid, &msg.getcaps_rsp);
371 if (ret <= 0)
372 return ret;
374 return get_caps(u, ret);
377 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
379 switch (freq) {
380 case BT_SBC_SAMPLING_FREQ_16000:
381 case BT_SBC_SAMPLING_FREQ_32000:
382 return 53;
384 case BT_SBC_SAMPLING_FREQ_44100:
386 switch (mode) {
387 case BT_A2DP_CHANNEL_MODE_MONO:
388 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
389 return 31;
391 case BT_A2DP_CHANNEL_MODE_STEREO:
392 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
393 return 53;
395 default:
396 pa_log_warn("Invalid channel mode %u", mode);
397 return 53;
400 case BT_SBC_SAMPLING_FREQ_48000:
402 switch (mode) {
403 case BT_A2DP_CHANNEL_MODE_MONO:
404 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
405 return 29;
407 case BT_A2DP_CHANNEL_MODE_STEREO:
408 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
409 return 51;
411 default:
412 pa_log_warn("Invalid channel mode %u", mode);
413 return 51;
416 default:
417 pa_log_warn("Invalid sampling freq %u", freq);
418 return 53;
422 static int setup_a2dp(struct userdata *u) {
423 sbc_capabilities_t *cap;
424 int i;
426 static const struct {
427 uint32_t rate;
428 uint8_t cap;
429 } freq_table[] = {
430 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
431 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
432 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
433 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
436 pa_assert(u);
437 pa_assert(u->profile == PROFILE_A2DP);
439 cap = &u->a2dp.sbc_capabilities;
441 /* Find the lowest freq that is at least as high as the requested
442 * sampling rate */
443 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
444 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
445 u->sample_spec.rate = freq_table[i].rate;
446 cap->frequency = freq_table[i].cap;
447 break;
450 if ((unsigned) i >= PA_ELEMENTSOF(freq_table)) {
451 for (; i >= 0; i--) {
452 if (cap->frequency & freq_table[i].cap) {
453 u->sample_spec.rate = freq_table[i].rate;
454 cap->frequency = freq_table[i].cap;
455 break;
459 if (i < 0) {
460 pa_log("Not suitable sample rate");
461 return -1;
465 if (u->sample_spec.channels <= 1) {
466 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
467 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
468 u->sample_spec.channels = 1;
469 } else
470 u->sample_spec.channels = 2;
473 if (u->sample_spec.channels >= 2) {
474 u->sample_spec.channels = 2;
476 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
477 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
478 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
479 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
480 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
481 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
482 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
483 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
484 u->sample_spec.channels = 1;
485 } else {
486 pa_log("No supported channel modes");
487 return -1;
491 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
492 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
493 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
494 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
495 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
496 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
497 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
498 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
499 else {
500 pa_log_error("No supported block lengths");
501 return -1;
504 if (cap->subbands & BT_A2DP_SUBBANDS_8)
505 cap->subbands = BT_A2DP_SUBBANDS_8;
506 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
507 cap->subbands = BT_A2DP_SUBBANDS_4;
508 else {
509 pa_log_error("No supported subbands");
510 return -1;
513 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
514 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
515 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
516 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
518 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
519 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
521 return 0;
524 static void setup_sbc(struct a2dp_info *a2dp) {
525 sbc_capabilities_t *active_capabilities;
527 pa_assert(a2dp);
529 active_capabilities = &a2dp->sbc_capabilities;
531 if (a2dp->sbc_initialized)
532 sbc_reinit(&a2dp->sbc, 0);
533 else
534 sbc_init(&a2dp->sbc, 0);
535 a2dp->sbc_initialized = TRUE;
537 switch (active_capabilities->frequency) {
538 case BT_SBC_SAMPLING_FREQ_16000:
539 a2dp->sbc.frequency = SBC_FREQ_16000;
540 break;
541 case BT_SBC_SAMPLING_FREQ_32000:
542 a2dp->sbc.frequency = SBC_FREQ_32000;
543 break;
544 case BT_SBC_SAMPLING_FREQ_44100:
545 a2dp->sbc.frequency = SBC_FREQ_44100;
546 break;
547 case BT_SBC_SAMPLING_FREQ_48000:
548 a2dp->sbc.frequency = SBC_FREQ_48000;
549 break;
550 default:
551 pa_assert_not_reached();
554 switch (active_capabilities->channel_mode) {
555 case BT_A2DP_CHANNEL_MODE_MONO:
556 a2dp->sbc.mode = SBC_MODE_MONO;
557 break;
558 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
559 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
560 break;
561 case BT_A2DP_CHANNEL_MODE_STEREO:
562 a2dp->sbc.mode = SBC_MODE_STEREO;
563 break;
564 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
565 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
566 break;
567 default:
568 pa_assert_not_reached();
571 switch (active_capabilities->allocation_method) {
572 case BT_A2DP_ALLOCATION_SNR:
573 a2dp->sbc.allocation = SBC_AM_SNR;
574 break;
575 case BT_A2DP_ALLOCATION_LOUDNESS:
576 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
577 break;
578 default:
579 pa_assert_not_reached();
582 switch (active_capabilities->subbands) {
583 case BT_A2DP_SUBBANDS_4:
584 a2dp->sbc.subbands = SBC_SB_4;
585 break;
586 case BT_A2DP_SUBBANDS_8:
587 a2dp->sbc.subbands = SBC_SB_8;
588 break;
589 default:
590 pa_assert_not_reached();
593 switch (active_capabilities->block_length) {
594 case BT_A2DP_BLOCK_LENGTH_4:
595 a2dp->sbc.blocks = SBC_BLK_4;
596 break;
597 case BT_A2DP_BLOCK_LENGTH_8:
598 a2dp->sbc.blocks = SBC_BLK_8;
599 break;
600 case BT_A2DP_BLOCK_LENGTH_12:
601 a2dp->sbc.blocks = SBC_BLK_12;
602 break;
603 case BT_A2DP_BLOCK_LENGTH_16:
604 a2dp->sbc.blocks = SBC_BLK_16;
605 break;
606 default:
607 pa_assert_not_reached();
610 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
611 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
612 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
615 static int set_conf(struct userdata *u) {
616 union {
617 struct bt_open_req open_req;
618 struct bt_open_rsp open_rsp;
619 struct bt_set_configuration_req setconf_req;
620 struct bt_set_configuration_rsp setconf_rsp;
621 bt_audio_error_t error;
622 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
623 } msg;
625 memset(&msg, 0, sizeof(msg));
626 msg.open_req.h.type = BT_REQUEST;
627 msg.open_req.h.name = BT_OPEN;
628 msg.open_req.h.length = sizeof(msg.open_req);
630 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
631 msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
632 msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
634 if (service_send(u, &msg.open_req.h) < 0)
635 return -1;
637 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
638 return -1;
640 if (u->profile == PROFILE_A2DP ) {
641 u->sample_spec.format = PA_SAMPLE_S16LE;
643 if (setup_a2dp(u) < 0)
644 return -1;
645 } else {
646 pa_assert(u->profile == PROFILE_HSP);
648 u->sample_spec.format = PA_SAMPLE_S16LE;
649 u->sample_spec.channels = 1;
650 u->sample_spec.rate = 8000;
653 memset(&msg, 0, sizeof(msg));
654 msg.setconf_req.h.type = BT_REQUEST;
655 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
656 msg.setconf_req.h.length = sizeof(msg.setconf_req);
658 if (u->profile == PROFILE_A2DP) {
659 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
660 } else {
661 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
662 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
663 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
665 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
667 if (service_send(u, &msg.setconf_req.h) < 0)
668 return -1;
670 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
671 return -1;
673 u->link_mtu = msg.setconf_rsp.link_mtu;
675 /* setup SBC encoder now we agree on parameters */
676 if (u->profile == PROFILE_A2DP) {
677 setup_sbc(&u->a2dp);
679 u->block_size =
680 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
681 / u->a2dp.frame_length
682 * u->a2dp.codesize);
684 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
685 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
686 } else
687 u->block_size = u->link_mtu;
689 return 0;
692 /* from IO thread, except in SCO over PCM */
693 static int start_stream_fd(struct userdata *u) {
694 union {
695 bt_audio_msg_header_t rsp;
696 struct bt_start_stream_req start_req;
697 struct bt_start_stream_rsp start_rsp;
698 struct bt_new_stream_ind streamfd_ind;
699 bt_audio_error_t error;
700 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
701 } msg;
702 struct pollfd *pollfd;
704 pa_assert(u);
705 pa_assert(u->rtpoll);
706 pa_assert(!u->rtpoll_item);
707 pa_assert(u->stream_fd < 0);
709 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
710 msg.start_req.h.type = BT_REQUEST;
711 msg.start_req.h.name = BT_START_STREAM;
712 msg.start_req.h.length = sizeof(msg.start_req);
714 if (service_send(u, &msg.start_req.h) < 0)
715 return -1;
717 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
718 return -1;
720 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
721 return -1;
723 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
724 pa_log("Failed to get stream fd from audio service.");
725 return -1;
728 pa_make_fd_nonblock(u->stream_fd);
729 pa_make_socket_low_delay(u->stream_fd);
731 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
732 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
733 pollfd->fd = u->stream_fd;
734 pollfd->events = pollfd->revents = 0;
736 u->read_index = 0;
737 u->write_index = 0;
739 return 0;
742 /* from IO thread */
743 static int stop_stream_fd(struct userdata *u) {
744 union {
745 bt_audio_msg_header_t rsp;
746 struct bt_stop_stream_req start_req;
747 struct bt_stop_stream_rsp start_rsp;
748 bt_audio_error_t error;
749 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
750 } msg;
751 int r = 0;
753 pa_assert(u);
754 pa_assert(u->rtpoll);
755 pa_assert(u->rtpoll_item);
756 pa_assert(u->stream_fd >= 0);
758 pa_rtpoll_item_free(u->rtpoll_item);
759 u->rtpoll_item = NULL;
761 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
762 msg.start_req.h.type = BT_REQUEST;
763 msg.start_req.h.name = BT_STOP_STREAM;
764 msg.start_req.h.length = sizeof(msg.start_req);
766 if (service_send(u, &msg.start_req.h) < 0 ||
767 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
768 r = -1;
770 pa_close(u->stream_fd);
771 u->stream_fd = -1;
773 return r;
776 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
777 struct userdata *u = PA_SINK(o)->userdata;
778 pa_bool_t failed = FALSE;
779 int r;
781 pa_assert(u->sink == PA_SINK(o));
783 pa_log_debug("got message: %d", code);
784 switch (code) {
786 case PA_SINK_MESSAGE_SET_STATE:
788 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
790 case PA_SINK_SUSPENDED:
791 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
793 /* Stop the device if the source is suspended as well */
794 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
795 /* We deliberately ignore whether stopping
796 * actually worked. Since the stream_fd is
797 * closed it doesn't really matter */
798 stop_stream_fd(u);
800 break;
802 case PA_SINK_IDLE:
803 case PA_SINK_RUNNING:
804 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
805 break;
807 /* Resume the device if the source was suspended as well */
808 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
809 if (start_stream_fd(u) < 0)
810 failed = TRUE;
812 u->started_at = pa_rtclock_usec();
813 break;
815 case PA_SINK_UNLINKED:
816 case PA_SINK_INIT:
817 case PA_SINK_INVALID_STATE:
820 break;
822 case PA_SINK_MESSAGE_GET_LATENCY: {
823 *((pa_usec_t*) data) = 0;
824 return 0;
828 r = pa_sink_process_msg(o, code, data, offset, chunk);
830 return (r < 0 || !failed) ? r : -1;
833 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
834 struct userdata *u = PA_SOURCE(o)->userdata;
835 pa_bool_t failed = FALSE;
836 int r;
838 pa_assert(u->source == PA_SOURCE(o));
840 pa_log_debug("got message: %d", code);
841 switch (code) {
843 case PA_SOURCE_MESSAGE_SET_STATE:
845 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
847 case PA_SOURCE_SUSPENDED:
848 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
850 /* Stop the device if the sink is suspended as well */
851 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
852 stop_stream_fd(u);
854 pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
855 break;
857 case PA_SOURCE_IDLE:
858 case PA_SOURCE_RUNNING:
859 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
860 break;
862 /* Resume the device if the sink was suspended as well */
863 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
864 if (start_stream_fd(u) < 0)
865 failed = TRUE;
867 pa_smoother_resume(u->read_smoother, pa_rtclock_usec());
868 break;
870 case PA_SOURCE_UNLINKED:
871 case PA_SOURCE_INIT:
872 case PA_SOURCE_INVALID_STATE:
875 break;
877 case PA_SOURCE_MESSAGE_GET_LATENCY: {
878 *((pa_usec_t*) data) = 0;
879 return 0;
884 r = pa_source_process_msg(o, code, data, offset, chunk);
886 return (r < 0 || !failed) ? r : -1;
889 static int hsp_process_render(struct userdata *u) {
890 int ret = 0;
892 pa_assert(u);
893 pa_assert(u->profile == PROFILE_HSP);
894 pa_assert(u->sink);
896 /* First, render some data */
897 if (!u->write_memchunk.memblock)
898 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
900 pa_assert(u->write_memchunk.length == u->block_size);
902 for (;;) {
903 ssize_t l;
904 const void *p;
906 /* Now write that data to the socket. The socket is of type
907 * SEQPACKET, and we generated the data of the MTU size, so this
908 * should just work. */
910 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
911 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
912 pa_memblock_release(u->write_memchunk.memblock);
914 pa_assert(l != 0);
916 if (l < 0) {
918 if (errno == EINTR)
919 /* Retry right away if we got interrupted */
920 continue;
922 else if (errno == EAGAIN)
923 /* Hmm, apparently the socket was not writable, give up for now */
924 break;
926 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
927 ret = -1;
928 break;
931 pa_assert((size_t) l <= u->write_memchunk.length);
933 if ((size_t) l != u->write_memchunk.length) {
934 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
935 (unsigned long long) l,
936 (unsigned long long) u->write_memchunk.length);
937 ret = -1;
938 break;
941 u->write_index += (uint64_t) u->write_memchunk.length;
942 pa_memblock_unref(u->write_memchunk.memblock);
943 pa_memchunk_reset(&u->write_memchunk);
945 break;
948 return ret;
951 static int hsp_process_push(struct userdata *u) {
952 int ret = 0;
953 pa_memchunk memchunk;
955 pa_assert(u);
956 pa_assert(u->profile == PROFILE_HSP);
957 pa_assert(u->source);
959 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
960 memchunk.index = memchunk.length = 0;
962 for (;;) {
963 ssize_t l;
964 void *p;
966 p = pa_memblock_acquire(memchunk.memblock);
967 l = pa_read(u->stream_fd, p, pa_memblock_get_length(memchunk.memblock), &u->stream_read_type);
968 pa_memblock_release(memchunk.memblock);
970 if (l <= 0) {
972 if (l < 0 && errno == EINTR)
973 /* Retry right away if we got interrupted */
974 continue;
976 else if (l < 0 && errno == EAGAIN)
977 /* Hmm, apparently the socket was not readable, give up for now. */
978 break;
980 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
981 ret = -1;
982 break;
985 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
987 memchunk.length = (size_t) l;
988 u->read_index += (uint64_t) l;
990 pa_source_post(u->source, &memchunk);
991 break;
994 pa_memblock_unref(memchunk.memblock);
996 return ret;
999 static void a2dp_prepare_buffer(struct userdata *u) {
1000 pa_assert(u);
1002 if (u->a2dp.buffer_size >= u->link_mtu)
1003 return;
1005 u->a2dp.buffer_size = 2 * u->link_mtu;
1006 pa_xfree(u->a2dp.buffer);
1007 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1010 static int a2dp_process_render(struct userdata *u) {
1011 struct a2dp_info *a2dp;
1012 struct rtp_header *header;
1013 struct rtp_payload *payload;
1014 size_t nbytes;
1015 void *d;
1016 const void *p;
1017 size_t to_write, to_encode;
1018 unsigned frame_count;
1019 int ret = 0;
1021 pa_assert(u);
1022 pa_assert(u->profile == PROFILE_A2DP);
1023 pa_assert(u->sink);
1025 /* First, render some data */
1026 if (!u->write_memchunk.memblock)
1027 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1029 pa_assert(u->write_memchunk.length == u->block_size);
1031 a2dp_prepare_buffer(u);
1033 a2dp = &u->a2dp;
1034 header = a2dp->buffer;
1035 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1037 frame_count = 0;
1039 /* Try to create a packet of the full MTU */
1041 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1042 to_encode = u->write_memchunk.length;
1044 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1045 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1047 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1048 size_t written;
1049 ssize_t encoded;
1051 encoded = sbc_encode(&a2dp->sbc,
1052 p, to_encode,
1053 d, to_write,
1054 &written);
1056 if (PA_UNLIKELY(encoded <= 0)) {
1057 pa_log_error("SBC encoding error (%li)", (long) encoded);
1058 pa_memblock_release(u->write_memchunk.memblock);
1059 return -1;
1062 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1063 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1065 pa_assert_fp((size_t) encoded <= to_encode);
1066 pa_assert_fp((size_t) encoded == a2dp->codesize);
1068 pa_assert_fp((size_t) written <= to_write);
1069 pa_assert_fp((size_t) written == a2dp->frame_length);
1071 p = (const uint8_t*) p + encoded;
1072 to_encode -= encoded;
1074 d = (uint8_t*) d + written;
1075 to_write -= written;
1077 frame_count++;
1080 pa_memblock_release(u->write_memchunk.memblock);
1082 pa_assert(to_encode == 0);
1084 PA_ONCE_BEGIN {
1085 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1086 } PA_ONCE_END;
1088 /* write it to the fifo */
1089 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1090 header->v = 2;
1091 header->pt = 1;
1092 header->sequence_number = htons(a2dp->seq_num++);
1093 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sink->sample_spec));
1094 header->ssrc = htonl(1);
1095 payload->frame_count = frame_count;
1097 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1099 for (;;) {
1100 ssize_t l;
1102 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1104 pa_assert(l != 0);
1106 if (l < 0) {
1108 if (errno == EINTR)
1109 /* Retry right away if we got interrupted */
1110 continue;
1112 else if (errno == EAGAIN)
1113 /* Hmm, apparently the socket was not writable, give up for now */
1114 break;
1116 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1117 ret = -1;
1118 break;
1121 pa_assert((size_t) l <= nbytes);
1123 if ((size_t) l != nbytes) {
1124 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1125 (unsigned long long) l,
1126 (unsigned long long) nbytes);
1127 ret = -1;
1128 break;
1131 u->write_index += (uint64_t) u->write_memchunk.length;
1132 pa_memblock_unref(u->write_memchunk.memblock);
1133 pa_memchunk_reset(&u->write_memchunk);
1135 break;
1138 return ret;
1141 static void thread_func(void *userdata) {
1142 struct userdata *u = userdata;
1143 pa_bool_t do_write = FALSE, writable = FALSE;
1145 pa_assert(u);
1147 pa_log_debug("IO Thread starting up");
1149 if (u->core->realtime_scheduling)
1150 pa_make_realtime(u->core->realtime_priority);
1152 if (start_stream_fd(u) < 0)
1153 goto fail;
1155 pa_thread_mq_install(&u->thread_mq);
1156 pa_rtpoll_install(u->rtpoll);
1158 pa_smoother_set_time_offset(u->read_smoother, pa_rtclock_usec());
1160 for (;;) {
1161 struct pollfd *pollfd;
1162 int ret;
1163 pa_bool_t disable_timer = TRUE;
1165 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1167 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1169 if (pollfd && (pollfd->revents & POLLIN)) {
1171 if (hsp_process_push(u) < 0)
1172 goto fail;
1174 /* We just read something, so we are supposed to write something, too */
1175 do_write = TRUE;
1179 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1181 if (u->sink->thread_info.rewind_requested)
1182 pa_sink_process_rewind(u->sink, 0);
1184 if (pollfd) {
1185 if (pollfd->revents & POLLOUT)
1186 writable = TRUE;
1188 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write && writable) {
1189 pa_usec_t time_passed;
1190 uint64_t should_have_written;
1192 /* Hmm, there is no input stream we could synchronize
1193 * to. So let's do things by time */
1195 time_passed = pa_rtclock_usec() - u->started_at;
1196 should_have_written = pa_usec_to_bytes(time_passed, &u->sink->sample_spec);
1198 do_write = u->write_index <= should_have_written ;
1199 /* pa_log_debug("Time has come: %s", pa_yes_no(do_write)); */
1202 if (writable && do_write) {
1203 if (u->write_index == 0)
1204 u->started_at = pa_rtclock_usec();
1206 if (u->profile == PROFILE_A2DP) {
1207 if (a2dp_process_render(u) < 0)
1208 goto fail;
1209 } else {
1210 if (hsp_process_render(u) < 0)
1211 goto fail;
1214 do_write = FALSE;
1215 writable = FALSE;
1218 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write) {
1219 pa_usec_t time_passed, next_write_at, sleep_for;
1221 /* Hmm, there is no input stream we could synchronize
1222 * to. So let's estimate when we need to wake up the latest */
1224 time_passed = pa_rtclock_usec() - u->started_at;
1225 next_write_at = pa_bytes_to_usec(u->write_index, &u->sink->sample_spec);
1226 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1228 /* 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); */
1230 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1231 disable_timer = FALSE;
1236 if (disable_timer)
1237 pa_rtpoll_set_timer_disabled(u->rtpoll);
1239 /* Hmm, nothing to do. Let's sleep */
1240 if (pollfd)
1241 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1242 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1244 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1245 goto fail;
1247 if (ret == 0)
1248 goto finish;
1250 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1252 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1253 pa_log_error("FD error.");
1254 goto fail;
1258 fail:
1259 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1260 pa_log_debug("IO thread failed");
1261 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1262 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1264 finish:
1265 pa_log_debug("IO thread shutting down");
1268 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1269 DBusError err;
1270 struct userdata *u;
1272 pa_assert(bus);
1273 pa_assert(m);
1274 pa_assert_se(u = userdata);
1276 dbus_error_init(&err);
1278 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1279 dbus_message_get_interface(m),
1280 dbus_message_get_path(m),
1281 dbus_message_get_member(m));
1283 if (!dbus_message_has_path(m, u->path))
1284 goto fail;
1286 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1287 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1289 dbus_uint16_t gain;
1290 pa_cvolume v;
1292 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1293 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1294 goto fail;
1297 if (u->profile == PROFILE_HSP) {
1298 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1300 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1301 pa_sink_volume_changed(u->sink, &v);
1303 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1305 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1306 pa_source_volume_changed(u->source, &v);
1311 fail:
1312 dbus_error_free(&err);
1314 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1317 static void sink_set_volume_cb(pa_sink *s) {
1318 struct userdata *u = s->userdata;
1319 DBusMessage *m;
1320 dbus_uint16_t gain;
1322 pa_assert(u);
1324 if (u->profile != PROFILE_HSP)
1325 return;
1327 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1329 if (gain > 15)
1330 gain = 15;
1332 pa_cvolume_set(&s->virtual_volume, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1334 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1335 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1336 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1337 dbus_message_unref(m);
1340 static void source_set_volume_cb(pa_source *s) {
1341 struct userdata *u = s->userdata;
1342 DBusMessage *m;
1343 dbus_uint16_t gain;
1345 pa_assert(u);
1347 if (u->profile != PROFILE_HSP)
1348 return;
1350 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1352 if (gain > 15)
1353 gain = 15;
1355 pa_cvolume_set(&s->virtual_volume, u->source->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1357 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1358 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1359 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1360 dbus_message_unref(m);
1363 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1364 char *t;
1365 const char *n;
1367 pa_assert(type);
1368 pa_assert(ma);
1369 pa_assert(device_id);
1370 pa_assert(namereg_fail);
1372 t = pa_sprintf_malloc("%s_name", type);
1373 n = pa_modargs_get_value(ma, t, NULL);
1374 pa_xfree(t);
1376 if (n) {
1377 *namereg_fail = TRUE;
1378 return pa_xstrdup(n);
1381 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1382 *namereg_fail = TRUE;
1383 else {
1384 n = device_id;
1385 *namereg_fail = FALSE;
1388 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1391 #ifdef NOKIA
1393 static void sco_over_pcm_state_update(struct userdata *u) {
1394 pa_assert(u);
1395 pa_assert(USE_SCO_OVER_PCM(u));
1397 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1398 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1400 if (u->service_fd >= 0)
1401 return;
1403 pa_log_debug("Resuming SCO over PCM");
1404 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1405 pa_log("Can't resume SCO over PCM");
1407 start_stream_fd(u);
1408 } else {
1410 if (u->service_fd < 0)
1411 return;
1413 stop_stream_fd(u);
1415 pa_log_debug("Closing SCO over PCM");
1416 pa_close(u->service_fd);
1417 u->service_fd = -1;
1421 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1422 pa_assert(c);
1423 pa_sink_assert_ref(s);
1424 pa_assert(u);
1426 if (s != u->hsp.sco_sink)
1427 return PA_HOOK_OK;
1429 sco_over_pcm_state_update(u);
1431 return PA_HOOK_OK;
1434 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1435 pa_assert(c);
1436 pa_source_assert_ref(s);
1437 pa_assert(u);
1439 if (s != u->hsp.sco_source)
1440 return PA_HOOK_OK;
1442 sco_over_pcm_state_update(u);
1444 return PA_HOOK_OK;
1447 #endif
1449 static int add_sink(struct userdata *u) {
1451 #ifdef NOKIA
1452 if (USE_SCO_OVER_PCM(u)) {
1453 pa_proplist *p;
1455 u->sink = u->hsp.sco_sink;
1456 p = pa_proplist_new();
1457 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1458 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1459 pa_proplist_free(p);
1461 if (!u->hsp.sink_state_changed_slot)
1462 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);
1464 } else
1465 #endif
1468 pa_sink_new_data data;
1469 pa_bool_t b;
1471 pa_sink_new_data_init(&data);
1472 data.driver = __FILE__;
1473 data.module = u->module;
1474 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1475 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1476 data.card = u->card;
1477 data.name = get_name("sink", u->modargs, u->address, &b);
1478 data.namereg_fail = b;
1480 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1481 pa_sink_new_data_done(&data);
1483 if (!u->sink) {
1484 pa_log_error("Failed to create sink");
1485 return -1;
1488 u->sink->userdata = u;
1489 u->sink->parent.process_msg = sink_process_msg;
1492 if (u->profile == PROFILE_HSP) {
1493 u->sink->set_volume = sink_set_volume_cb;
1494 u->sink->n_volume_steps = 16;
1497 return 0;
1500 static int add_source(struct userdata *u) {
1502 #ifdef NOKIA
1503 if (USE_SCO_OVER_PCM(u)) {
1504 u->source = u->hsp.sco_source;
1505 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "sco");
1507 if (!u->hsp.source_state_changed_slot)
1508 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);
1510 } else
1511 #endif
1514 pa_source_new_data data;
1515 pa_bool_t b;
1517 pa_source_new_data_init(&data);
1518 data.driver = __FILE__;
1519 data.module = u->module;
1520 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1521 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1522 data.card = u->card;
1523 data.name = get_name("source", u->modargs, u->address, &b);
1524 data.namereg_fail = b;
1526 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1527 pa_source_new_data_done(&data);
1529 if (!u->source) {
1530 pa_log_error("Failed to create source");
1531 return -1;
1534 u->source->userdata = u;
1535 u->source->parent.process_msg = source_process_msg;
1538 if (u->profile == PROFILE_HSP) {
1539 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1540 u->source->set_volume = source_set_volume_cb;
1541 u->source->n_volume_steps = 16;
1544 return 0;
1547 static void shutdown_bt(struct userdata *u) {
1548 pa_assert(u);
1550 if (u->stream_fd >= 0) {
1551 pa_close(u->stream_fd);
1552 u->stream_fd = -1;
1554 u->stream_write_type = 0;
1555 u->stream_read_type = 0;
1558 if (u->service_fd >= 0) {
1559 pa_close(u->service_fd);
1560 u->service_fd = -1;
1563 if (u->write_memchunk.memblock) {
1564 pa_memblock_unref(u->write_memchunk.memblock);
1565 pa_memchunk_reset(&u->write_memchunk);
1569 static int init_bt(struct userdata *u) {
1570 pa_assert(u);
1572 shutdown_bt(u);
1574 u->stream_write_type = u->stream_read_type = 0;
1575 u->service_write_type = u->service_write_type = 0;
1577 if ((u->service_fd = bt_audio_service_open()) < 0) {
1578 pa_log_error("Couldn't connect to bluetooth audio service");
1579 return -1;
1582 pa_log_debug("Connected to the bluetooth audio service");
1584 return 0;
1587 static int setup_bt(struct userdata *u) {
1588 pa_assert(u);
1590 if (get_caps(u, 0) < 0)
1591 return -1;
1593 pa_log_debug("Got device capabilities");
1595 if (set_conf(u) < 0)
1596 return -1;
1598 pa_log_debug("Connection to the device configured");
1600 #ifdef NOKIA
1601 if (USE_SCO_OVER_PCM(u)) {
1602 pa_log_debug("Configured to use SCO over PCM");
1603 return 0;
1605 #endif
1607 pa_log_debug("Got the stream socket");
1609 return 0;
1612 static int init_profile(struct userdata *u) {
1613 int r = 0;
1614 pa_assert(u);
1615 pa_assert(u->profile != PROFILE_OFF);
1617 if (setup_bt(u) < 0)
1618 return -1;
1620 if (u->profile == PROFILE_A2DP ||
1621 u->profile == PROFILE_HSP)
1622 if (add_sink(u) < 0)
1623 r = -1;
1625 if (u->profile == PROFILE_HSP)
1626 if (add_source(u) < 0)
1627 r = -1;
1629 return r;
1632 static void stop_thread(struct userdata *u) {
1633 pa_assert(u);
1635 if (u->thread) {
1636 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1637 pa_thread_free(u->thread);
1638 u->thread = NULL;
1641 if (u->rtpoll_item) {
1642 pa_rtpoll_item_free(u->rtpoll_item);
1643 u->rtpoll_item = NULL;
1646 if (u->hsp.sink_state_changed_slot) {
1647 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1648 u->hsp.sink_state_changed_slot = NULL;
1651 if (u->hsp.source_state_changed_slot) {
1652 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1653 u->hsp.source_state_changed_slot = NULL;
1656 if (u->sink) {
1657 pa_sink_unref(u->sink);
1658 u->sink = NULL;
1661 if (u->source) {
1662 pa_source_unref(u->source);
1663 u->source = NULL;
1666 if (u->rtpoll) {
1667 pa_thread_mq_done(&u->thread_mq);
1669 pa_rtpoll_free(u->rtpoll);
1670 u->rtpoll = NULL;
1674 static int start_thread(struct userdata *u) {
1675 pa_assert(u);
1676 pa_assert(!u->thread);
1677 pa_assert(!u->rtpoll);
1678 pa_assert(!u->rtpoll_item);
1680 u->rtpoll = pa_rtpoll_new();
1681 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1683 #ifdef NOKIA
1684 if (USE_SCO_OVER_PCM(u)) {
1685 if (start_stream_fd(u) < 0)
1686 return -1;
1688 pa_sink_ref(u->sink);
1689 pa_source_ref(u->source);
1690 /* FIXME: monitor stream_fd error */
1691 return 0;
1693 #endif
1695 if (!(u->thread = pa_thread_new(thread_func, u))) {
1696 pa_log_error("Failed to create IO thread");
1697 stop_thread(u);
1698 return -1;
1701 if (u->sink) {
1702 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1703 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1704 pa_sink_put(u->sink);
1706 if (u->sink->set_volume)
1707 u->sink->set_volume(u->sink);
1710 if (u->source) {
1711 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1712 pa_source_set_rtpoll(u->source, u->rtpoll);
1713 pa_source_put(u->source);
1715 if (u->source->set_volume)
1716 u->source->set_volume(u->source);
1719 return 0;
1722 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1723 struct userdata *u;
1724 enum profile *d;
1725 pa_queue *inputs = NULL, *outputs = NULL;
1727 pa_assert(c);
1728 pa_assert(new_profile);
1729 pa_assert_se(u = c->userdata);
1731 d = PA_CARD_PROFILE_DATA(new_profile);
1733 if (u->sink) {
1734 inputs = pa_sink_move_all_start(u->sink);
1735 #ifdef NOKIA
1736 if (!USE_SCO_OVER_PCM(u))
1737 #endif
1738 pa_sink_unlink(u->sink);
1741 if (u->source) {
1742 outputs = pa_source_move_all_start(u->source);
1743 #ifdef NOKIA
1744 if (!USE_SCO_OVER_PCM(u))
1745 #endif
1746 pa_source_unlink(u->source);
1749 stop_thread(u);
1750 shutdown_bt(u);
1752 u->profile = *d;
1753 u->sample_spec = u->requested_sample_spec;
1755 init_bt(u);
1757 if (u->profile != PROFILE_OFF)
1758 init_profile(u);
1760 if (u->sink || u->source)
1761 start_thread(u);
1763 if (inputs) {
1764 if (u->sink)
1765 pa_sink_move_all_finish(u->sink, inputs, FALSE);
1766 else
1767 pa_sink_move_all_fail(inputs);
1770 if (outputs) {
1771 if (u->source)
1772 pa_source_move_all_finish(u->source, outputs, FALSE);
1773 else
1774 pa_source_move_all_fail(outputs);
1777 return 0;
1780 static int add_card(struct userdata *u, const char *default_profile, const pa_bluetooth_device *device) {
1781 pa_card_new_data data;
1782 pa_bool_t b;
1783 pa_card_profile *p;
1784 enum profile *d;
1785 const char *ff;
1786 char *n;
1788 pa_card_new_data_init(&data);
1789 data.driver = __FILE__;
1790 data.module = u->module;
1792 n = pa_bluetooth_cleanup_name(device->name);
1793 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1794 pa_xfree(n);
1795 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
1796 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1797 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1798 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1799 if ((ff = pa_bluetooth_get_form_factor(device->class)))
1800 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1801 pa_proplist_sets(data.proplist, "bluez.path", device->path);
1802 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
1803 pa_proplist_sets(data.proplist, "bluez.name", device->name);
1804 data.name = get_name("card", u->modargs, device->address, &b);
1805 data.namereg_fail = b;
1807 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1809 if (device->audio_sink_info_valid > 0) {
1810 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
1811 p->priority = 10;
1812 p->n_sinks = 1;
1813 p->n_sources = 0;
1814 p->max_sink_channels = 2;
1815 p->max_source_channels = 0;
1817 d = PA_CARD_PROFILE_DATA(p);
1818 *d = PROFILE_A2DP;
1820 pa_hashmap_put(data.profiles, p->name, p);
1823 if (device->headset_info_valid > 0) {
1824 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
1825 p->priority = 20;
1826 p->n_sinks = 1;
1827 p->n_sources = 1;
1828 p->max_sink_channels = 1;
1829 p->max_source_channels = 1;
1831 d = PA_CARD_PROFILE_DATA(p);
1832 *d = PROFILE_HSP;
1834 pa_hashmap_put(data.profiles, p->name, p);
1837 pa_assert(!pa_hashmap_isempty(data.profiles));
1839 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
1840 d = PA_CARD_PROFILE_DATA(p);
1841 *d = PROFILE_OFF;
1842 pa_hashmap_put(data.profiles, p->name, p);
1844 if (default_profile) {
1845 if (pa_hashmap_get(data.profiles, default_profile))
1846 pa_card_new_data_set_profile(&data, default_profile);
1847 else
1848 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
1851 u->card = pa_card_new(u->core, &data);
1852 pa_card_new_data_done(&data);
1854 if (!u->card) {
1855 pa_log("Failed to allocate card.");
1856 return -1;
1859 u->card->userdata = u;
1860 u->card->set_profile = card_set_profile;
1862 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
1863 u->profile = *d;
1865 return 0;
1868 static const pa_bluetooth_device* find_device(struct userdata *u, pa_bluetooth_discovery *y, const char *address, const char *path) {
1869 const pa_bluetooth_device *d = NULL;
1871 pa_assert(u);
1872 pa_assert(y);
1874 if (!address && !path) {
1875 pa_log_error("Failed to get device address/path from module arguments.");
1876 return NULL;
1879 if (path) {
1880 if (!(d = pa_bluetooth_discovery_get_by_path(y, path))) {
1881 pa_log_error("%s is not a valid BlueZ audio device.", path);
1882 return NULL;
1885 if (address && !(pa_streq(d->address, address))) {
1886 pa_log_error("Passed path %s and address %s don't match.", path, address);
1887 return NULL;
1890 } else {
1891 if (!(d = pa_bluetooth_discovery_get_by_address(y, address))) {
1892 pa_log_error("%s is not known.", address);
1893 return NULL;
1897 if (d) {
1898 u->address = pa_xstrdup(d->address);
1899 u->path = pa_xstrdup(d->path);
1902 return d;
1905 static int setup_dbus(struct userdata *u) {
1906 DBusError err;
1908 dbus_error_init(&err);
1910 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
1912 if (dbus_error_is_set(&err) || !u->connection) {
1913 pa_log("Failed to get D-Bus connection: %s", err.message);
1914 dbus_error_free(&err);
1915 return -1;
1918 return 0;
1921 int pa__init(pa_module* m) {
1922 pa_modargs *ma;
1923 uint32_t channels;
1924 struct userdata *u;
1925 const char *address, *path;
1926 const pa_bluetooth_device *d;
1927 pa_bluetooth_discovery *y = NULL;
1928 DBusError err;
1929 char *mike, *speaker;
1931 pa_assert(m);
1933 dbus_error_init(&err);
1935 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1936 pa_log_error("Failed to parse module arguments");
1937 goto fail;
1940 m->userdata = u = pa_xnew0(struct userdata, 1);
1941 u->module = m;
1942 u->core = m->core;
1943 u->service_fd = -1;
1944 u->stream_fd = -1;
1945 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
1946 u->sample_spec = m->core->default_sample_spec;
1947 u->modargs = ma;
1949 #ifdef NOKIA
1950 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
1951 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
1952 pa_log("SCO sink not found");
1953 goto fail;
1956 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
1957 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
1958 pa_log("SCO source not found");
1959 goto fail;
1961 #endif
1963 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
1964 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
1965 pa_log_error("Failed to get rate from module arguments");
1966 goto fail;
1969 channels = u->sample_spec.channels;
1970 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
1971 channels <= 0 || channels > PA_CHANNELS_MAX) {
1972 pa_log_error("Failed to get channels from module arguments");
1973 goto fail;
1975 u->sample_spec.channels = (uint8_t) channels;
1976 u->requested_sample_spec = u->sample_spec;
1978 address = pa_modargs_get_value(ma, "address", NULL);
1979 path = pa_modargs_get_value(ma, "path", NULL);
1981 if (setup_dbus(u) < 0)
1982 goto fail;
1984 if (!(y = pa_bluetooth_discovery_get(m->core)))
1985 goto fail;
1987 if (!(d = find_device(u, y, address, path)))
1988 goto fail;
1990 /* Add the card structure. This will also initialize the default profile */
1991 if (add_card(u, pa_modargs_get_value(ma, "profile", NULL), d) < 0)
1992 goto fail;
1994 pa_bluetooth_discovery_unref(y);
1995 y = NULL;
1997 /* Connect to the BT service and query capabilities */
1998 if (init_bt(u) < 0)
1999 goto fail;
2001 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2002 pa_log_error("Failed to add filter function");
2003 goto fail;
2006 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2007 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2009 if (pa_dbus_add_matches(
2010 pa_dbus_connection_get(u->connection), &err,
2011 speaker,
2012 mike,
2013 NULL) < 0) {
2015 pa_xfree(speaker);
2016 pa_xfree(mike);
2018 pa_log("Failed to add D-Bus matches: %s", err.message);
2019 goto fail;
2022 pa_xfree(speaker);
2023 pa_xfree(mike);
2025 if (u->profile != PROFILE_OFF)
2026 if (init_profile(u) < 0)
2027 goto fail;
2029 if (u->sink || u->source)
2030 if (start_thread(u) < 0)
2031 goto fail;
2033 return 0;
2035 fail:
2037 if (y)
2038 pa_bluetooth_discovery_unref(y);
2040 pa__done(m);
2042 dbus_error_free(&err);
2044 return -1;
2047 int pa__get_n_used(pa_module *m) {
2048 struct userdata *u;
2050 pa_assert(m);
2051 pa_assert_se(u = m->userdata);
2053 return
2054 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2055 (u->source ? pa_source_linked_by(u->source) : 0);
2058 void pa__done(pa_module *m) {
2059 struct userdata *u;
2060 pa_assert(m);
2062 if (!(u = m->userdata))
2063 return;
2065 if (u->sink
2066 #ifdef NOKIA
2067 && !USE_SCO_OVER_PCM(u)
2068 #endif
2070 pa_sink_unlink(u->sink);
2072 if (u->source
2073 #ifdef NOKIA
2074 && !USE_SCO_OVER_PCM(u)
2075 #endif
2077 pa_source_unlink(u->source);
2079 stop_thread(u);
2081 if (u->connection) {
2083 if (u->path) {
2084 char *speaker, *mike;
2085 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2086 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2088 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2089 speaker,
2090 mike,
2091 NULL);
2093 pa_xfree(speaker);
2094 pa_xfree(mike);
2097 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2098 pa_dbus_connection_unref(u->connection);
2101 if (u->card)
2102 pa_card_free(u->card);
2104 if (u->read_smoother)
2105 pa_smoother_free(u->read_smoother);
2107 shutdown_bt(u);
2109 if (u->a2dp.buffer)
2110 pa_xfree(u->a2dp.buffer);
2112 sbc_finish(&u->a2dp.sbc);
2114 if (u->modargs)
2115 pa_modargs_free(u->modargs);
2117 pa_xfree(u->address);
2118 pa_xfree(u->path);
2120 pa_xfree(u);