bluetooth: don't access outside array range
[pulseaudio-raopUDP/pulseaudio-raop-alac.git] / src / modules / bluetooth / module-bluetooth-device.c
blob2c4f29c89589bc89d2c7140bfb7e78ec3837a486
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;
136 const pa_bluetooth_device* device;
138 pa_dbus_connection *connection;
140 pa_card *card;
141 pa_sink *sink;
142 pa_source *source;
144 pa_thread_mq thread_mq;
145 pa_rtpoll *rtpoll;
146 pa_rtpoll_item *rtpoll_item;
147 pa_thread *thread;
149 uint64_t read_index, write_index;
150 pa_usec_t started_at;
151 pa_smoother *read_smoother;
153 pa_memchunk write_memchunk;
155 pa_sample_spec sample_spec, requested_sample_spec;
157 int service_fd;
158 int stream_fd;
160 size_t link_mtu;
161 size_t block_size;
163 struct a2dp_info a2dp;
164 struct hsp_info hsp;
166 enum profile profile;
168 pa_modargs *modargs;
170 int stream_write_type, stream_read_type;
171 int service_write_type, service_read_type;
174 #ifdef NOKIA
175 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
176 #endif
178 static int init_bt(struct userdata *u);
179 static int init_profile(struct userdata *u);
181 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
182 ssize_t r;
184 pa_assert(u);
185 pa_assert(u->service_fd >= 0);
186 pa_assert(msg);
187 pa_assert(msg->length > 0);
189 pa_log_debug("Sending %s -> %s",
190 pa_strnull(bt_audio_strtype(msg->type)),
191 pa_strnull(bt_audio_strname(msg->name)));
193 if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
194 return 0;
196 if (r < 0)
197 pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
198 else
199 pa_log_error("Short write()");
201 return -1;
204 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
205 ssize_t r;
207 pa_assert(u);
208 pa_assert(u->service_fd >= 0);
209 pa_assert(msg);
211 if (room <= 0)
212 room = BT_SUGGESTED_BUFFER_SIZE;
214 pa_log_debug("Trying to receive message from audio service...");
216 /* First, read the header */
217 if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
218 goto read_fail;
220 if (msg->length < sizeof(*msg)) {
221 pa_log_error("Invalid message size.");
222 return -1;
225 /* Secondly, read the payload */
226 if (msg->length > sizeof(*msg)) {
228 size_t remains = msg->length - sizeof(*msg);
230 if ((r = pa_loop_read(u->service_fd,
231 (uint8_t*) msg + sizeof(*msg),
232 remains,
233 &u->service_read_type)) != (ssize_t) remains)
234 goto read_fail;
237 pa_log_debug("Received %s <- %s",
238 pa_strnull(bt_audio_strtype(msg->type)),
239 pa_strnull(bt_audio_strname(msg->name)));
241 return 0;
243 read_fail:
245 if (r < 0)
246 pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
247 else
248 pa_log_error("Short read()");
250 return -1;
253 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) {
254 int r;
256 pa_assert(u);
257 pa_assert(u->service_fd >= 0);
258 pa_assert(rsp);
260 if ((r = service_recv(u, rsp, room)) < 0)
261 return r;
263 if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
264 rsp->name != expected_name ||
265 (expected_size > 0 && rsp->length != expected_size)) {
267 if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
268 pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
269 else
270 pa_log_error("Bogus message %s received while %s was expected",
271 pa_strnull(bt_audio_strname(rsp->name)),
272 pa_strnull(bt_audio_strname(expected_name)));
273 return -1;
276 return 0;
279 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
280 uint16_t bytes_left;
281 const codec_capabilities_t *codec;
283 pa_assert(u);
284 pa_assert(rsp);
286 bytes_left = rsp->h.length - sizeof(*rsp);
288 if (bytes_left < sizeof(codec_capabilities_t)) {
289 pa_log_error("Packet too small to store codec information.");
290 return -1;
293 codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
295 pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
297 if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
298 (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
299 pa_log_error("Got capabilities for wrong codec.");
300 return -1;
303 if (u->profile == PROFILE_HSP) {
305 if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
306 return -1;
308 pa_assert(codec->type == BT_HFP_CODEC_PCM);
310 if (codec->configured && seid == 0)
311 return codec->seid;
313 memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
315 } else if (u->profile == PROFILE_A2DP) {
317 while (bytes_left > 0) {
318 if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
319 break;
321 bytes_left -= codec->length;
322 codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
325 if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
326 return -1;
328 pa_assert(codec->type == BT_A2DP_SBC_SINK);
330 if (codec->configured && seid == 0)
331 return codec->seid;
333 memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
336 return 0;
339 static int get_caps(struct userdata *u, uint8_t seid) {
340 union {
341 struct bt_get_capabilities_req getcaps_req;
342 struct bt_get_capabilities_rsp getcaps_rsp;
343 bt_audio_error_t error;
344 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
345 } msg;
346 int ret;
348 pa_assert(u);
350 memset(&msg, 0, sizeof(msg));
351 msg.getcaps_req.h.type = BT_REQUEST;
352 msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
353 msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
354 msg.getcaps_req.seid = seid;
356 pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
357 if (u->profile == PROFILE_A2DP)
358 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
359 else {
360 pa_assert(u->profile == PROFILE_HSP);
361 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
363 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
365 if (service_send(u, &msg.getcaps_req.h) < 0)
366 return -1;
368 if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
369 return -1;
371 ret = parse_caps(u, seid, &msg.getcaps_rsp);
372 if (ret <= 0)
373 return ret;
375 return get_caps(u, ret);
378 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
380 switch (freq) {
381 case BT_SBC_SAMPLING_FREQ_16000:
382 case BT_SBC_SAMPLING_FREQ_32000:
383 return 53;
385 case BT_SBC_SAMPLING_FREQ_44100:
387 switch (mode) {
388 case BT_A2DP_CHANNEL_MODE_MONO:
389 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
390 return 31;
392 case BT_A2DP_CHANNEL_MODE_STEREO:
393 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
394 return 53;
396 default:
397 pa_log_warn("Invalid channel mode %u", mode);
398 return 53;
401 case BT_SBC_SAMPLING_FREQ_48000:
403 switch (mode) {
404 case BT_A2DP_CHANNEL_MODE_MONO:
405 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
406 return 29;
408 case BT_A2DP_CHANNEL_MODE_STEREO:
409 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
410 return 51;
412 default:
413 pa_log_warn("Invalid channel mode %u", mode);
414 return 51;
417 default:
418 pa_log_warn("Invalid sampling freq %u", freq);
419 return 53;
423 static int setup_a2dp(struct userdata *u) {
424 sbc_capabilities_t *cap;
425 int i;
427 static const struct {
428 uint32_t rate;
429 uint8_t cap;
430 } freq_table[] = {
431 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
432 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
433 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
434 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
437 pa_assert(u);
438 pa_assert(u->profile == PROFILE_A2DP);
440 cap = &u->a2dp.sbc_capabilities;
442 /* Find the lowest freq that is at least as high as the requested
443 * sampling rate */
444 for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
445 if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
446 u->sample_spec.rate = freq_table[i].rate;
447 cap->frequency = freq_table[i].cap;
448 break;
451 if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
452 for (--i; i >= 0; i--) {
453 if (cap->frequency & freq_table[i].cap) {
454 u->sample_spec.rate = freq_table[i].rate;
455 cap->frequency = freq_table[i].cap;
456 break;
460 if (i < 0) {
461 pa_log("Not suitable sample rate");
462 return -1;
466 pa_assert(i < PA_ELEMENTSOF(freq_table));
468 if (cap->capability.configured)
469 return 0;
471 if (u->sample_spec.channels <= 1) {
472 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
473 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
474 u->sample_spec.channels = 1;
475 } else
476 u->sample_spec.channels = 2;
479 if (u->sample_spec.channels >= 2) {
480 u->sample_spec.channels = 2;
482 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
483 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
484 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
485 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
486 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
487 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
488 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
489 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
490 u->sample_spec.channels = 1;
491 } else {
492 pa_log("No supported channel modes");
493 return -1;
497 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
498 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
499 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
500 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
501 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
502 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
503 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
504 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
505 else {
506 pa_log_error("No supported block lengths");
507 return -1;
510 if (cap->subbands & BT_A2DP_SUBBANDS_8)
511 cap->subbands = BT_A2DP_SUBBANDS_8;
512 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
513 cap->subbands = BT_A2DP_SUBBANDS_4;
514 else {
515 pa_log_error("No supported subbands");
516 return -1;
519 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
520 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
521 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
522 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
524 cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
525 cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
527 return 0;
530 static void setup_sbc(struct a2dp_info *a2dp) {
531 sbc_capabilities_t *active_capabilities;
533 pa_assert(a2dp);
535 active_capabilities = &a2dp->sbc_capabilities;
537 if (a2dp->sbc_initialized)
538 sbc_reinit(&a2dp->sbc, 0);
539 else
540 sbc_init(&a2dp->sbc, 0);
541 a2dp->sbc_initialized = TRUE;
543 switch (active_capabilities->frequency) {
544 case BT_SBC_SAMPLING_FREQ_16000:
545 a2dp->sbc.frequency = SBC_FREQ_16000;
546 break;
547 case BT_SBC_SAMPLING_FREQ_32000:
548 a2dp->sbc.frequency = SBC_FREQ_32000;
549 break;
550 case BT_SBC_SAMPLING_FREQ_44100:
551 a2dp->sbc.frequency = SBC_FREQ_44100;
552 break;
553 case BT_SBC_SAMPLING_FREQ_48000:
554 a2dp->sbc.frequency = SBC_FREQ_48000;
555 break;
556 default:
557 pa_assert_not_reached();
560 switch (active_capabilities->channel_mode) {
561 case BT_A2DP_CHANNEL_MODE_MONO:
562 a2dp->sbc.mode = SBC_MODE_MONO;
563 break;
564 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
565 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
566 break;
567 case BT_A2DP_CHANNEL_MODE_STEREO:
568 a2dp->sbc.mode = SBC_MODE_STEREO;
569 break;
570 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
571 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
572 break;
573 default:
574 pa_assert_not_reached();
577 switch (active_capabilities->allocation_method) {
578 case BT_A2DP_ALLOCATION_SNR:
579 a2dp->sbc.allocation = SBC_AM_SNR;
580 break;
581 case BT_A2DP_ALLOCATION_LOUDNESS:
582 a2dp->sbc.allocation = SBC_AM_LOUDNESS;
583 break;
584 default:
585 pa_assert_not_reached();
588 switch (active_capabilities->subbands) {
589 case BT_A2DP_SUBBANDS_4:
590 a2dp->sbc.subbands = SBC_SB_4;
591 break;
592 case BT_A2DP_SUBBANDS_8:
593 a2dp->sbc.subbands = SBC_SB_8;
594 break;
595 default:
596 pa_assert_not_reached();
599 switch (active_capabilities->block_length) {
600 case BT_A2DP_BLOCK_LENGTH_4:
601 a2dp->sbc.blocks = SBC_BLK_4;
602 break;
603 case BT_A2DP_BLOCK_LENGTH_8:
604 a2dp->sbc.blocks = SBC_BLK_8;
605 break;
606 case BT_A2DP_BLOCK_LENGTH_12:
607 a2dp->sbc.blocks = SBC_BLK_12;
608 break;
609 case BT_A2DP_BLOCK_LENGTH_16:
610 a2dp->sbc.blocks = SBC_BLK_16;
611 break;
612 default:
613 pa_assert_not_reached();
616 a2dp->sbc.bitpool = active_capabilities->max_bitpool;
617 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
618 a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
621 static int set_conf(struct userdata *u) {
622 union {
623 struct bt_open_req open_req;
624 struct bt_open_rsp open_rsp;
625 struct bt_set_configuration_req setconf_req;
626 struct bt_set_configuration_rsp setconf_rsp;
627 bt_audio_error_t error;
628 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
629 } msg;
631 memset(&msg, 0, sizeof(msg));
632 msg.open_req.h.type = BT_REQUEST;
633 msg.open_req.h.name = BT_OPEN;
634 msg.open_req.h.length = sizeof(msg.open_req);
636 pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
637 msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
638 msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
640 if (service_send(u, &msg.open_req.h) < 0)
641 return -1;
643 if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
644 return -1;
646 if (u->profile == PROFILE_A2DP ) {
647 u->sample_spec.format = PA_SAMPLE_S16LE;
649 if (setup_a2dp(u) < 0)
650 return -1;
651 } else {
652 pa_assert(u->profile == PROFILE_HSP);
654 u->sample_spec.format = PA_SAMPLE_S16LE;
655 u->sample_spec.channels = 1;
656 u->sample_spec.rate = 8000;
659 memset(&msg, 0, sizeof(msg));
660 msg.setconf_req.h.type = BT_REQUEST;
661 msg.setconf_req.h.name = BT_SET_CONFIGURATION;
662 msg.setconf_req.h.length = sizeof(msg.setconf_req);
664 if (u->profile == PROFILE_A2DP) {
665 memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
666 } else {
667 msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
668 msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
669 msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
671 msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
673 if (service_send(u, &msg.setconf_req.h) < 0)
674 return -1;
676 if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
677 return -1;
679 u->link_mtu = msg.setconf_rsp.link_mtu;
681 /* setup SBC encoder now we agree on parameters */
682 if (u->profile == PROFILE_A2DP) {
683 setup_sbc(&u->a2dp);
685 u->block_size =
686 ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
687 / u->a2dp.frame_length
688 * u->a2dp.codesize);
690 pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
691 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
692 } else
693 u->block_size = u->link_mtu;
695 return 0;
698 /* from IO thread, except in SCO over PCM */
699 static int start_stream_fd(struct userdata *u) {
700 union {
701 bt_audio_msg_header_t rsp;
702 struct bt_start_stream_req start_req;
703 struct bt_start_stream_rsp start_rsp;
704 struct bt_new_stream_ind streamfd_ind;
705 bt_audio_error_t error;
706 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
707 } msg;
708 struct pollfd *pollfd;
710 pa_assert(u);
711 pa_assert(u->rtpoll);
712 pa_assert(!u->rtpoll_item);
713 pa_assert(u->stream_fd < 0);
715 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
716 msg.start_req.h.type = BT_REQUEST;
717 msg.start_req.h.name = BT_START_STREAM;
718 msg.start_req.h.length = sizeof(msg.start_req);
720 if (service_send(u, &msg.start_req.h) < 0)
721 return -1;
723 if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
724 return -1;
726 if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
727 return -1;
729 if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
730 pa_log("Failed to get stream fd from audio service.");
731 return -1;
734 pa_make_fd_nonblock(u->stream_fd);
735 pa_make_socket_low_delay(u->stream_fd);
737 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
738 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
739 pollfd->fd = u->stream_fd;
740 pollfd->events = pollfd->revents = 0;
742 u->read_index = 0;
743 u->write_index = 0;
745 return 0;
748 /* from IO thread */
749 static int stop_stream_fd(struct userdata *u) {
750 union {
751 bt_audio_msg_header_t rsp;
752 struct bt_stop_stream_req start_req;
753 struct bt_stop_stream_rsp start_rsp;
754 bt_audio_error_t error;
755 uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
756 } msg;
757 int r = 0;
759 pa_assert(u);
760 pa_assert(u->rtpoll);
761 pa_assert(u->rtpoll_item);
762 pa_assert(u->stream_fd >= 0);
764 pa_rtpoll_item_free(u->rtpoll_item);
765 u->rtpoll_item = NULL;
767 memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
768 msg.start_req.h.type = BT_REQUEST;
769 msg.start_req.h.name = BT_STOP_STREAM;
770 msg.start_req.h.length = sizeof(msg.start_req);
772 if (service_send(u, &msg.start_req.h) < 0 ||
773 service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
774 r = -1;
776 pa_close(u->stream_fd);
777 u->stream_fd = -1;
779 return r;
782 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
783 struct userdata *u = PA_SINK(o)->userdata;
784 pa_bool_t failed = FALSE;
785 int r;
787 pa_assert(u->sink == PA_SINK(o));
789 pa_log_debug("got message: %d", code);
790 switch (code) {
792 case PA_SINK_MESSAGE_SET_STATE:
794 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
796 case PA_SINK_SUSPENDED:
797 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
799 /* Stop the device if the source is suspended as well */
800 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
801 /* We deliberately ignore whether stopping
802 * actually worked. Since the stream_fd is
803 * closed it doesn't really matter */
804 stop_stream_fd(u);
806 break;
808 case PA_SINK_IDLE:
809 case PA_SINK_RUNNING:
810 if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
811 break;
813 /* Resume the device if the source was suspended as well */
814 if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
815 if (start_stream_fd(u) < 0)
816 failed = TRUE;
818 u->started_at = pa_rtclock_usec();
819 break;
821 case PA_SINK_UNLINKED:
822 case PA_SINK_INIT:
823 case PA_SINK_INVALID_STATE:
826 break;
828 case PA_SINK_MESSAGE_GET_LATENCY: {
829 *((pa_usec_t*) data) = 0;
830 return 0;
834 r = pa_sink_process_msg(o, code, data, offset, chunk);
836 return (r < 0 || !failed) ? r : -1;
839 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
840 struct userdata *u = PA_SOURCE(o)->userdata;
841 pa_bool_t failed = FALSE;
842 int r;
844 pa_assert(u->source == PA_SOURCE(o));
846 pa_log_debug("got message: %d", code);
847 switch (code) {
849 case PA_SOURCE_MESSAGE_SET_STATE:
851 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
853 case PA_SOURCE_SUSPENDED:
854 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
856 /* Stop the device if the sink is suspended as well */
857 if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
858 stop_stream_fd(u);
860 pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
861 break;
863 case PA_SOURCE_IDLE:
864 case PA_SOURCE_RUNNING:
865 if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
866 break;
868 /* Resume the device if the sink was suspended as well */
869 if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
870 if (start_stream_fd(u) < 0)
871 failed = TRUE;
873 pa_smoother_resume(u->read_smoother, pa_rtclock_usec());
874 break;
876 case PA_SOURCE_UNLINKED:
877 case PA_SOURCE_INIT:
878 case PA_SOURCE_INVALID_STATE:
881 break;
883 case PA_SOURCE_MESSAGE_GET_LATENCY: {
884 *((pa_usec_t*) data) = 0;
885 return 0;
890 r = pa_source_process_msg(o, code, data, offset, chunk);
892 return (r < 0 || !failed) ? r : -1;
895 static int hsp_process_render(struct userdata *u) {
896 int ret = 0;
898 pa_assert(u);
899 pa_assert(u->profile == PROFILE_HSP);
900 pa_assert(u->sink);
902 /* First, render some data */
903 if (!u->write_memchunk.memblock)
904 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
906 pa_assert(u->write_memchunk.length == u->block_size);
908 for (;;) {
909 ssize_t l;
910 const void *p;
912 /* Now write that data to the socket. The socket is of type
913 * SEQPACKET, and we generated the data of the MTU size, so this
914 * should just work. */
916 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
917 l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
918 pa_memblock_release(u->write_memchunk.memblock);
920 pa_assert(l != 0);
922 if (l < 0) {
924 if (errno == EINTR)
925 /* Retry right away if we got interrupted */
926 continue;
928 else if (errno == EAGAIN)
929 /* Hmm, apparently the socket was not writable, give up for now */
930 break;
932 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
933 ret = -1;
934 break;
937 pa_assert((size_t) l <= u->write_memchunk.length);
939 if ((size_t) l != u->write_memchunk.length) {
940 pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
941 (unsigned long long) l,
942 (unsigned long long) u->write_memchunk.length);
943 ret = -1;
944 break;
947 u->write_index += (uint64_t) u->write_memchunk.length;
948 pa_memblock_unref(u->write_memchunk.memblock);
949 pa_memchunk_reset(&u->write_memchunk);
951 break;
954 return ret;
957 static int hsp_process_push(struct userdata *u) {
958 int ret = 0;
959 pa_memchunk memchunk;
961 pa_assert(u);
962 pa_assert(u->profile == PROFILE_HSP);
963 pa_assert(u->source);
965 memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
966 memchunk.index = memchunk.length = 0;
968 for (;;) {
969 ssize_t l;
970 void *p;
972 p = pa_memblock_acquire(memchunk.memblock);
973 l = pa_read(u->stream_fd, p, pa_memblock_get_length(memchunk.memblock), &u->stream_read_type);
974 pa_memblock_release(memchunk.memblock);
976 if (l <= 0) {
978 if (l < 0 && errno == EINTR)
979 /* Retry right away if we got interrupted */
980 continue;
982 else if (l < 0 && errno == EAGAIN)
983 /* Hmm, apparently the socket was not readable, give up for now. */
984 break;
986 pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
987 ret = -1;
988 break;
991 pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
993 memchunk.length = (size_t) l;
994 u->read_index += (uint64_t) l;
996 pa_source_post(u->source, &memchunk);
997 break;
1000 pa_memblock_unref(memchunk.memblock);
1002 return ret;
1005 static void a2dp_prepare_buffer(struct userdata *u) {
1006 pa_assert(u);
1008 if (u->a2dp.buffer_size >= u->link_mtu)
1009 return;
1011 u->a2dp.buffer_size = 2 * u->link_mtu;
1012 pa_xfree(u->a2dp.buffer);
1013 u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1016 static int a2dp_process_render(struct userdata *u) {
1017 struct a2dp_info *a2dp;
1018 struct rtp_header *header;
1019 struct rtp_payload *payload;
1020 size_t nbytes;
1021 void *d;
1022 const void *p;
1023 size_t to_write, to_encode;
1024 unsigned frame_count;
1025 int ret = 0;
1027 pa_assert(u);
1028 pa_assert(u->profile == PROFILE_A2DP);
1029 pa_assert(u->sink);
1031 /* First, render some data */
1032 if (!u->write_memchunk.memblock)
1033 pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1035 pa_assert(u->write_memchunk.length == u->block_size);
1037 a2dp_prepare_buffer(u);
1039 a2dp = &u->a2dp;
1040 header = a2dp->buffer;
1041 payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1043 frame_count = 0;
1045 /* Try to create a packet of the full MTU */
1047 p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1048 to_encode = u->write_memchunk.length;
1050 d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1051 to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1053 while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1054 size_t written;
1055 ssize_t encoded;
1057 encoded = sbc_encode(&a2dp->sbc,
1058 p, to_encode,
1059 d, to_write,
1060 &written);
1062 if (PA_UNLIKELY(encoded <= 0)) {
1063 pa_log_error("SBC encoding error (%li)", (long) encoded);
1064 pa_memblock_release(u->write_memchunk.memblock);
1065 return -1;
1068 /* pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1069 /* pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1071 pa_assert_fp((size_t) encoded <= to_encode);
1072 pa_assert_fp((size_t) encoded == a2dp->codesize);
1074 pa_assert_fp((size_t) written <= to_write);
1075 pa_assert_fp((size_t) written == a2dp->frame_length);
1077 p = (const uint8_t*) p + encoded;
1078 to_encode -= encoded;
1080 d = (uint8_t*) d + written;
1081 to_write -= written;
1083 frame_count++;
1086 pa_memblock_release(u->write_memchunk.memblock);
1088 pa_assert(to_encode == 0);
1090 PA_ONCE_BEGIN {
1091 pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1092 } PA_ONCE_END;
1094 /* write it to the fifo */
1095 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1096 header->v = 2;
1097 header->pt = 1;
1098 header->sequence_number = htons(a2dp->seq_num++);
1099 header->timestamp = htonl(u->write_index / pa_frame_size(&u->sink->sample_spec));
1100 header->ssrc = htonl(1);
1101 payload->frame_count = frame_count;
1103 nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1105 for (;;) {
1106 ssize_t l;
1108 l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1110 pa_assert(l != 0);
1112 if (l < 0) {
1114 if (errno == EINTR)
1115 /* Retry right away if we got interrupted */
1116 continue;
1118 else if (errno == EAGAIN)
1119 /* Hmm, apparently the socket was not writable, give up for now */
1120 break;
1122 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1123 ret = -1;
1124 break;
1127 pa_assert((size_t) l <= nbytes);
1129 if ((size_t) l != nbytes) {
1130 pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1131 (unsigned long long) l,
1132 (unsigned long long) nbytes);
1133 ret = -1;
1134 break;
1137 u->write_index += (uint64_t) u->write_memchunk.length;
1138 pa_memblock_unref(u->write_memchunk.memblock);
1139 pa_memchunk_reset(&u->write_memchunk);
1141 break;
1144 return ret;
1147 static void thread_func(void *userdata) {
1148 struct userdata *u = userdata;
1149 pa_bool_t do_write = FALSE, writable = FALSE;
1151 pa_assert(u);
1153 pa_log_debug("IO Thread starting up");
1155 if (u->core->realtime_scheduling)
1156 pa_make_realtime(u->core->realtime_priority);
1158 if (start_stream_fd(u) < 0)
1159 goto fail;
1161 pa_thread_mq_install(&u->thread_mq);
1162 pa_rtpoll_install(u->rtpoll);
1164 pa_smoother_set_time_offset(u->read_smoother, pa_rtclock_usec());
1166 for (;;) {
1167 struct pollfd *pollfd;
1168 int ret;
1169 pa_bool_t disable_timer = TRUE;
1171 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1173 if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1175 if (pollfd && (pollfd->revents & POLLIN)) {
1177 if (hsp_process_push(u) < 0)
1178 goto fail;
1180 /* We just read something, so we are supposed to write something, too */
1181 do_write = TRUE;
1185 if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1187 if (u->sink->thread_info.rewind_requested)
1188 pa_sink_process_rewind(u->sink, 0);
1190 if (pollfd) {
1191 if (pollfd->revents & POLLOUT)
1192 writable = TRUE;
1194 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write && writable) {
1195 pa_usec_t time_passed;
1196 uint64_t should_have_written;
1198 /* Hmm, there is no input stream we could synchronize
1199 * to. So let's do things by time */
1201 time_passed = pa_rtclock_usec() - u->started_at;
1202 should_have_written = pa_usec_to_bytes(time_passed, &u->sink->sample_spec);
1204 do_write = u->write_index <= should_have_written ;
1205 /* pa_log_debug("Time has come: %s", pa_yes_no(do_write)); */
1208 if (writable && do_write) {
1209 if (u->write_index == 0)
1210 u->started_at = pa_rtclock_usec();
1212 if (u->profile == PROFILE_A2DP) {
1213 if (a2dp_process_render(u) < 0)
1214 goto fail;
1215 } else {
1216 if (hsp_process_render(u) < 0)
1217 goto fail;
1220 do_write = FALSE;
1221 writable = FALSE;
1224 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write) {
1225 pa_usec_t time_passed, next_write_at, sleep_for;
1227 /* Hmm, there is no input stream we could synchronize
1228 * to. So let's estimate when we need to wake up the latest */
1230 time_passed = pa_rtclock_usec() - u->started_at;
1231 next_write_at = pa_bytes_to_usec(u->write_index, &u->sink->sample_spec);
1232 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1234 /* 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); */
1236 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1237 disable_timer = FALSE;
1242 if (disable_timer)
1243 pa_rtpoll_set_timer_disabled(u->rtpoll);
1245 /* Hmm, nothing to do. Let's sleep */
1246 if (pollfd)
1247 pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1248 (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1250 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1251 goto fail;
1253 if (ret == 0)
1254 goto finish;
1256 pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1258 if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1259 pa_log_error("FD error.");
1260 goto fail;
1264 fail:
1265 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1266 pa_log_debug("IO thread failed");
1267 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1268 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1270 finish:
1271 pa_log_debug("IO thread shutting down");
1274 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1275 DBusError err;
1276 struct userdata *u;
1278 pa_assert(bus);
1279 pa_assert(m);
1280 pa_assert_se(u = userdata);
1282 dbus_error_init(&err);
1284 pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1285 dbus_message_get_interface(m),
1286 dbus_message_get_path(m),
1287 dbus_message_get_member(m));
1289 if (!dbus_message_has_path(m, u->path))
1290 goto fail;
1292 if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1293 dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1295 dbus_uint16_t gain;
1296 pa_cvolume v;
1298 if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1299 pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1300 goto fail;
1303 if (u->profile == PROFILE_HSP) {
1304 if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1306 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1307 pa_sink_volume_changed(u->sink, &v);
1309 } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1311 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1312 pa_source_volume_changed(u->source, &v);
1317 fail:
1318 dbus_error_free(&err);
1320 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1323 static void sink_set_volume_cb(pa_sink *s) {
1324 struct userdata *u = s->userdata;
1325 DBusMessage *m;
1326 dbus_uint16_t gain;
1328 pa_assert(u);
1330 if (u->profile != PROFILE_HSP)
1331 return;
1333 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1335 if (gain > 15)
1336 gain = 15;
1338 pa_cvolume_set(&s->virtual_volume, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1340 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1341 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1342 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1343 dbus_message_unref(m);
1346 static void source_set_volume_cb(pa_source *s) {
1347 struct userdata *u = s->userdata;
1348 DBusMessage *m;
1349 dbus_uint16_t gain;
1351 pa_assert(u);
1353 if (u->profile != PROFILE_HSP)
1354 return;
1356 gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1358 if (gain > 15)
1359 gain = 15;
1361 pa_cvolume_set(&s->virtual_volume, u->source->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1363 pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1364 pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1365 pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1366 dbus_message_unref(m);
1369 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1370 char *t;
1371 const char *n;
1373 pa_assert(type);
1374 pa_assert(ma);
1375 pa_assert(device_id);
1376 pa_assert(namereg_fail);
1378 t = pa_sprintf_malloc("%s_name", type);
1379 n = pa_modargs_get_value(ma, t, NULL);
1380 pa_xfree(t);
1382 if (n) {
1383 *namereg_fail = TRUE;
1384 return pa_xstrdup(n);
1387 if ((n = pa_modargs_get_value(ma, "name", NULL)))
1388 *namereg_fail = TRUE;
1389 else {
1390 n = device_id;
1391 *namereg_fail = FALSE;
1394 return pa_sprintf_malloc("bluez_%s.%s", type, n);
1397 #ifdef NOKIA
1399 static void sco_over_pcm_state_update(struct userdata *u) {
1400 pa_assert(u);
1401 pa_assert(USE_SCO_OVER_PCM(u));
1403 if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1404 PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1406 if (u->service_fd >= 0)
1407 return;
1409 pa_log_debug("Resuming SCO over PCM");
1410 if ((init_bt(u) < 0) || (init_profile(u) < 0))
1411 pa_log("Can't resume SCO over PCM");
1413 start_stream_fd(u);
1414 } else {
1416 if (u->service_fd < 0)
1417 return;
1419 stop_stream_fd(u);
1421 pa_log_debug("Closing SCO over PCM");
1422 pa_close(u->service_fd);
1423 u->service_fd = -1;
1427 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1428 pa_assert(c);
1429 pa_sink_assert_ref(s);
1430 pa_assert(u);
1432 if (s != u->hsp.sco_sink)
1433 return PA_HOOK_OK;
1435 sco_over_pcm_state_update(u);
1437 return PA_HOOK_OK;
1440 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1441 pa_assert(c);
1442 pa_source_assert_ref(s);
1443 pa_assert(u);
1445 if (s != u->hsp.sco_source)
1446 return PA_HOOK_OK;
1448 sco_over_pcm_state_update(u);
1450 return PA_HOOK_OK;
1453 #endif
1455 static int add_sink(struct userdata *u) {
1457 #ifdef NOKIA
1458 if (USE_SCO_OVER_PCM(u)) {
1459 pa_proplist *p;
1461 u->sink = u->hsp.sco_sink;
1462 p = pa_proplist_new();
1463 pa_proplist_sets(p, "bluetooth.protocol", "sco");
1464 pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1465 pa_proplist_free(p);
1467 if (!u->hsp.sink_state_changed_slot)
1468 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);
1470 } else
1471 #endif
1474 pa_sink_new_data data;
1475 pa_bool_t b;
1477 pa_sink_new_data_init(&data);
1478 data.driver = __FILE__;
1479 data.module = u->module;
1480 pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1481 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1482 data.card = u->card;
1483 data.name = get_name("sink", u->modargs, u->address, &b);
1484 data.namereg_fail = b;
1486 u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1487 pa_sink_new_data_done(&data);
1489 if (!u->sink) {
1490 pa_log_error("Failed to create sink");
1491 return -1;
1494 u->sink->userdata = u;
1495 u->sink->parent.process_msg = sink_process_msg;
1498 if (u->profile == PROFILE_HSP) {
1499 u->sink->set_volume = sink_set_volume_cb;
1500 u->sink->n_volume_steps = 16;
1503 return 0;
1506 static int add_source(struct userdata *u) {
1508 #ifdef NOKIA
1509 if (USE_SCO_OVER_PCM(u)) {
1510 u->source = u->hsp.sco_source;
1511 pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "sco");
1513 if (!u->hsp.source_state_changed_slot)
1514 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);
1516 } else
1517 #endif
1520 pa_source_new_data data;
1521 pa_bool_t b;
1523 pa_source_new_data_init(&data);
1524 data.driver = __FILE__;
1525 data.module = u->module;
1526 pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1527 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1528 data.card = u->card;
1529 data.name = get_name("source", u->modargs, u->address, &b);
1530 data.namereg_fail = b;
1532 u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1533 pa_source_new_data_done(&data);
1535 if (!u->source) {
1536 pa_log_error("Failed to create source");
1537 return -1;
1540 u->source->userdata = u;
1541 u->source->parent.process_msg = source_process_msg;
1544 if (u->profile == PROFILE_HSP) {
1545 pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1546 u->source->set_volume = source_set_volume_cb;
1547 u->source->n_volume_steps = 16;
1550 return 0;
1553 static void shutdown_bt(struct userdata *u) {
1554 pa_assert(u);
1556 if (u->stream_fd >= 0) {
1557 pa_close(u->stream_fd);
1558 u->stream_fd = -1;
1560 u->stream_write_type = 0;
1561 u->stream_read_type = 0;
1564 if (u->service_fd >= 0) {
1565 pa_close(u->service_fd);
1566 u->service_fd = -1;
1569 if (u->write_memchunk.memblock) {
1570 pa_memblock_unref(u->write_memchunk.memblock);
1571 pa_memchunk_reset(&u->write_memchunk);
1575 static int init_bt(struct userdata *u) {
1576 pa_assert(u);
1578 shutdown_bt(u);
1580 u->stream_write_type = u->stream_read_type = 0;
1581 u->service_write_type = u->service_write_type = 0;
1583 if ((u->service_fd = bt_audio_service_open()) < 0) {
1584 pa_log_error("Couldn't connect to bluetooth audio service");
1585 return -1;
1588 pa_log_debug("Connected to the bluetooth audio service");
1590 return 0;
1593 static int setup_bt(struct userdata *u) {
1594 pa_assert(u);
1596 if (get_caps(u, 0) < 0)
1597 return -1;
1599 pa_log_debug("Got device capabilities");
1601 if (set_conf(u) < 0)
1602 return -1;
1604 pa_log_debug("Connection to the device configured");
1606 #ifdef NOKIA
1607 if (USE_SCO_OVER_PCM(u)) {
1608 pa_log_debug("Configured to use SCO over PCM");
1609 return 0;
1611 #endif
1613 pa_log_debug("Got the stream socket");
1615 return 0;
1618 static int init_profile(struct userdata *u) {
1619 int r = 0;
1620 pa_assert(u);
1621 pa_assert(u->profile != PROFILE_OFF);
1623 if (setup_bt(u) < 0)
1624 return -1;
1626 if (u->profile == PROFILE_A2DP ||
1627 u->profile == PROFILE_HSP)
1628 if (add_sink(u) < 0)
1629 r = -1;
1631 if (u->profile == PROFILE_HSP)
1632 if (add_source(u) < 0)
1633 r = -1;
1635 return r;
1638 static void stop_thread(struct userdata *u) {
1639 pa_assert(u);
1641 if (u->thread) {
1642 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1643 pa_thread_free(u->thread);
1644 u->thread = NULL;
1647 if (u->rtpoll_item) {
1648 pa_rtpoll_item_free(u->rtpoll_item);
1649 u->rtpoll_item = NULL;
1652 if (u->hsp.sink_state_changed_slot) {
1653 pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1654 u->hsp.sink_state_changed_slot = NULL;
1657 if (u->hsp.source_state_changed_slot) {
1658 pa_hook_slot_free(u->hsp.source_state_changed_slot);
1659 u->hsp.source_state_changed_slot = NULL;
1662 if (u->sink) {
1663 pa_sink_unref(u->sink);
1664 u->sink = NULL;
1667 if (u->source) {
1668 pa_source_unref(u->source);
1669 u->source = NULL;
1672 if (u->rtpoll) {
1673 pa_thread_mq_done(&u->thread_mq);
1675 pa_rtpoll_free(u->rtpoll);
1676 u->rtpoll = NULL;
1680 static int start_thread(struct userdata *u) {
1681 pa_assert(u);
1682 pa_assert(!u->thread);
1683 pa_assert(!u->rtpoll);
1684 pa_assert(!u->rtpoll_item);
1686 u->rtpoll = pa_rtpoll_new();
1687 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1689 #ifdef NOKIA
1690 if (USE_SCO_OVER_PCM(u)) {
1691 if (start_stream_fd(u) < 0)
1692 return -1;
1694 pa_sink_ref(u->sink);
1695 pa_source_ref(u->source);
1696 /* FIXME: monitor stream_fd error */
1697 return 0;
1699 #endif
1701 if (!(u->thread = pa_thread_new(thread_func, u))) {
1702 pa_log_error("Failed to create IO thread");
1703 stop_thread(u);
1704 return -1;
1707 if (u->sink) {
1708 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1709 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1710 pa_sink_put(u->sink);
1712 if (u->sink->set_volume)
1713 u->sink->set_volume(u->sink);
1716 if (u->source) {
1717 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1718 pa_source_set_rtpoll(u->source, u->rtpoll);
1719 pa_source_put(u->source);
1721 if (u->source->set_volume)
1722 u->source->set_volume(u->source);
1725 return 0;
1728 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1729 struct userdata *u;
1730 enum profile *d;
1731 pa_queue *inputs = NULL, *outputs = NULL;
1733 pa_assert(c);
1734 pa_assert(new_profile);
1735 pa_assert_se(u = c->userdata);
1737 d = PA_CARD_PROFILE_DATA(new_profile);
1739 if (u->device->headset_connected <= 0 && *d == PROFILE_HSP) {
1740 pa_log_warn("HSP is not connected, refused to switch profile");
1741 return -1;
1743 else if (u->device->audio_sink_connected <= 0 && *d == PROFILE_A2DP) {
1744 pa_log_warn("A2DP is not connected, refused to switch profile");
1745 return -1;
1748 if (u->sink) {
1749 inputs = pa_sink_move_all_start(u->sink);
1750 #ifdef NOKIA
1751 if (!USE_SCO_OVER_PCM(u))
1752 #endif
1753 pa_sink_unlink(u->sink);
1756 if (u->source) {
1757 outputs = pa_source_move_all_start(u->source);
1758 #ifdef NOKIA
1759 if (!USE_SCO_OVER_PCM(u))
1760 #endif
1761 pa_source_unlink(u->source);
1764 stop_thread(u);
1765 shutdown_bt(u);
1767 u->profile = *d;
1768 u->sample_spec = u->requested_sample_spec;
1770 init_bt(u);
1772 if (u->profile != PROFILE_OFF)
1773 init_profile(u);
1775 if (u->sink || u->source)
1776 start_thread(u);
1778 if (inputs) {
1779 if (u->sink)
1780 pa_sink_move_all_finish(u->sink, inputs, FALSE);
1781 else
1782 pa_sink_move_all_fail(inputs);
1785 if (outputs) {
1786 if (u->source)
1787 pa_source_move_all_finish(u->source, outputs, FALSE);
1788 else
1789 pa_source_move_all_fail(outputs);
1792 return 0;
1795 static int add_card(struct userdata *u, const char *default_profile, const pa_bluetooth_device *device) {
1796 pa_card_new_data data;
1797 pa_bool_t b;
1798 pa_card_profile *p;
1799 enum profile *d;
1800 const char *ff;
1801 char *n;
1803 pa_card_new_data_init(&data);
1804 data.driver = __FILE__;
1805 data.module = u->module;
1807 n = pa_bluetooth_cleanup_name(device->name);
1808 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1809 pa_xfree(n);
1810 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
1811 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1812 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1813 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1814 if ((ff = pa_bluetooth_get_form_factor(device->class)))
1815 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1816 pa_proplist_sets(data.proplist, "bluez.path", device->path);
1817 pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
1818 pa_proplist_sets(data.proplist, "bluez.name", device->name);
1819 data.name = get_name("card", u->modargs, device->address, &b);
1820 data.namereg_fail = b;
1822 data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1824 if (device->audio_sink_info_valid > 0) {
1825 p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
1826 p->priority = 10;
1827 p->n_sinks = 1;
1828 p->n_sources = 0;
1829 p->max_sink_channels = 2;
1830 p->max_source_channels = 0;
1832 d = PA_CARD_PROFILE_DATA(p);
1833 *d = PROFILE_A2DP;
1835 pa_hashmap_put(data.profiles, p->name, p);
1838 if (device->headset_info_valid > 0) {
1839 p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
1840 p->priority = 20;
1841 p->n_sinks = 1;
1842 p->n_sources = 1;
1843 p->max_sink_channels = 1;
1844 p->max_source_channels = 1;
1846 d = PA_CARD_PROFILE_DATA(p);
1847 *d = PROFILE_HSP;
1849 pa_hashmap_put(data.profiles, p->name, p);
1852 pa_assert(!pa_hashmap_isempty(data.profiles));
1854 p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
1855 d = PA_CARD_PROFILE_DATA(p);
1856 *d = PROFILE_OFF;
1857 pa_hashmap_put(data.profiles, p->name, p);
1859 if (default_profile) {
1860 if (pa_hashmap_get(data.profiles, default_profile))
1861 pa_card_new_data_set_profile(&data, default_profile);
1862 else
1863 pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
1866 u->card = pa_card_new(u->core, &data);
1867 pa_card_new_data_done(&data);
1869 if (!u->card) {
1870 pa_log("Failed to allocate card.");
1871 return -1;
1874 u->card->userdata = u;
1875 u->card->set_profile = card_set_profile;
1877 d = PA_CARD_PROFILE_DATA(u->card->active_profile);
1878 u->profile = *d;
1880 return 0;
1883 static const pa_bluetooth_device* find_device(struct userdata *u, pa_bluetooth_discovery *y, const char *address, const char *path) {
1884 const pa_bluetooth_device *d = NULL;
1886 pa_assert(u);
1887 pa_assert(y);
1889 if (!address && !path) {
1890 pa_log_error("Failed to get device address/path from module arguments.");
1891 return NULL;
1894 if (path) {
1895 if (!(d = pa_bluetooth_discovery_get_by_path(y, path))) {
1896 pa_log_error("%s is not a valid BlueZ audio device.", path);
1897 return NULL;
1900 if (address && !(pa_streq(d->address, address))) {
1901 pa_log_error("Passed path %s and address %s don't match.", path, address);
1902 return NULL;
1905 } else {
1906 if (!(d = pa_bluetooth_discovery_get_by_address(y, address))) {
1907 pa_log_error("%s is not known.", address);
1908 return NULL;
1912 if (d) {
1913 u->address = pa_xstrdup(d->address);
1914 u->path = pa_xstrdup(d->path);
1917 return d;
1920 static int setup_dbus(struct userdata *u) {
1921 DBusError err;
1923 dbus_error_init(&err);
1925 u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
1927 if (dbus_error_is_set(&err) || !u->connection) {
1928 pa_log("Failed to get D-Bus connection: %s", err.message);
1929 dbus_error_free(&err);
1930 return -1;
1933 return 0;
1936 int pa__init(pa_module* m) {
1937 pa_modargs *ma;
1938 uint32_t channels;
1939 struct userdata *u;
1940 const char *address, *path;
1941 pa_bluetooth_discovery *y = NULL;
1942 DBusError err;
1943 char *mike, *speaker;
1945 pa_assert(m);
1947 dbus_error_init(&err);
1949 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1950 pa_log_error("Failed to parse module arguments");
1951 goto fail;
1954 m->userdata = u = pa_xnew0(struct userdata, 1);
1955 u->module = m;
1956 u->core = m->core;
1957 u->service_fd = -1;
1958 u->stream_fd = -1;
1959 u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
1960 u->sample_spec = m->core->default_sample_spec;
1961 u->modargs = ma;
1963 #ifdef NOKIA
1964 if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
1965 !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
1966 pa_log("SCO sink not found");
1967 goto fail;
1970 if (pa_modargs_get_value(ma, "sco_source", NULL) &&
1971 !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
1972 pa_log("SCO source not found");
1973 goto fail;
1975 #endif
1977 if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
1978 u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
1979 pa_log_error("Failed to get rate from module arguments");
1980 goto fail;
1983 channels = u->sample_spec.channels;
1984 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
1985 channels <= 0 || channels > PA_CHANNELS_MAX) {
1986 pa_log_error("Failed to get channels from module arguments");
1987 goto fail;
1989 u->sample_spec.channels = (uint8_t) channels;
1990 u->requested_sample_spec = u->sample_spec;
1992 address = pa_modargs_get_value(ma, "address", NULL);
1993 path = pa_modargs_get_value(ma, "path", NULL);
1995 if (setup_dbus(u) < 0)
1996 goto fail;
1998 if (!(y = pa_bluetooth_discovery_get(m->core)))
1999 goto fail;
2001 if (!(u->device = find_device(u, y, address, path))) /* should discovery ref be kept? */
2002 goto fail;
2004 /* Add the card structure. This will also initialize the default profile */
2005 if (add_card(u, pa_modargs_get_value(ma, "profile", NULL), u->device) < 0)
2006 goto fail;
2008 pa_bluetooth_discovery_unref(y);
2009 y = NULL;
2011 /* Connect to the BT service and query capabilities */
2012 if (init_bt(u) < 0)
2013 goto fail;
2015 if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2016 pa_log_error("Failed to add filter function");
2017 goto fail;
2020 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2021 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2023 if (pa_dbus_add_matches(
2024 pa_dbus_connection_get(u->connection), &err,
2025 speaker,
2026 mike,
2027 NULL) < 0) {
2029 pa_xfree(speaker);
2030 pa_xfree(mike);
2032 pa_log("Failed to add D-Bus matches: %s", err.message);
2033 goto fail;
2036 pa_xfree(speaker);
2037 pa_xfree(mike);
2039 if (u->profile != PROFILE_OFF)
2040 if (init_profile(u) < 0)
2041 goto fail;
2043 if (u->sink || u->source)
2044 if (start_thread(u) < 0)
2045 goto fail;
2047 return 0;
2049 fail:
2051 if (y)
2052 pa_bluetooth_discovery_unref(y);
2054 pa__done(m);
2056 dbus_error_free(&err);
2058 return -1;
2061 int pa__get_n_used(pa_module *m) {
2062 struct userdata *u;
2064 pa_assert(m);
2065 pa_assert_se(u = m->userdata);
2067 return
2068 (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2069 (u->source ? pa_source_linked_by(u->source) : 0);
2072 void pa__done(pa_module *m) {
2073 struct userdata *u;
2074 pa_assert(m);
2076 if (!(u = m->userdata))
2077 return;
2079 if (u->sink
2080 #ifdef NOKIA
2081 && !USE_SCO_OVER_PCM(u)
2082 #endif
2084 pa_sink_unlink(u->sink);
2086 if (u->source
2087 #ifdef NOKIA
2088 && !USE_SCO_OVER_PCM(u)
2089 #endif
2091 pa_source_unlink(u->source);
2093 stop_thread(u);
2095 if (u->connection) {
2097 if (u->path) {
2098 char *speaker, *mike;
2099 speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2100 mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2102 pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2103 speaker,
2104 mike,
2105 NULL);
2107 pa_xfree(speaker);
2108 pa_xfree(mike);
2111 dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2112 pa_dbus_connection_unref(u->connection);
2115 if (u->card)
2116 pa_card_free(u->card);
2118 if (u->read_smoother)
2119 pa_smoother_free(u->read_smoother);
2121 shutdown_bt(u);
2123 if (u->a2dp.buffer)
2124 pa_xfree(u->a2dp.buffer);
2126 sbc_finish(&u->a2dp.sbc);
2128 if (u->modargs)
2129 pa_modargs_free(u->modargs);
2131 pa_xfree(u->address);
2132 pa_xfree(u->path);
2134 pa_xfree(u);