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 published
8 by the Free Software Foundation; either version 2 of the License,
9 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 License
17 along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
30 #include <pulse/xmalloc.h>
31 #include <pulse/timeval.h>
32 #include <pulse/sample.h>
33 #include <pulsecore/module.h>
34 #include <pulsecore/modargs.h>
35 #include <pulsecore/core-util.h>
36 #include <pulsecore/core-error.h>
37 #include <pulsecore/socket-util.h>
38 #include <pulsecore/thread.h>
39 #include <pulsecore/thread-mq.h>
40 #include <pulsecore/rtpoll.h>
41 #include <pulsecore/time-smoother.h>
42 #include <pulsecore/rtclock.h>
44 #include "dbus-util.h"
45 #include "module-bt-device-symdef.h"
50 #define DEFAULT_SINK_NAME "bluetooth_sink"
51 #define BUFFER_SIZE 2048
52 #define MAX_BITPOOL 64
55 #define SCO_TXBUFS 0x03
56 #define SCO_RXBUFS 0x04
58 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
59 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
60 PA_MODULE_VERSION(PACKAGE_VERSION);
61 PA_MODULE_LOAD_ONCE(FALSE);
63 "name=<name of the device> "
64 "addr=<address of the device> "
65 "profile=<a2dp|hsp>");
68 sbc_capabilities_t sbc_capabilities;
69 sbc_t sbc; /* Codec data */
70 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
71 int codesize; /* SBC codesize */
72 int samples; /* Number of encoded samples */
73 uint8_t buffer[BUFFER_SIZE]; /* Codec transfer buffer */
74 int count; /* Codec transfer buffer counter */
76 int nsamples; /* Cumulative number of codec samples */
77 uint16_t seq_num; /* Cumulative packet sequence */
78 int frame_count; /* Current frames in buffer*/
86 pa_thread_mq thread_mq;
88 pa_rtpoll_item *rtpoll_item;
92 pa_smoother *smoother;
115 static const char* const valid_modargs[] = {
124 static int bt_audioservice_send(int sk, const bt_audio_msg_header_t *msg) {
126 pa_log_debug("sending %s", bt_audio_strmsg(msg->msg_type));
127 if (send(sk, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0)
131 pa_log_error("Error sending data to audio service: %s(%d)", pa_cstrerror(errno), errno);
136 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg) {
140 pa_log_debug("trying to receive msg from audio service...");
141 if (recv(sk, inmsg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0) {
142 type = bt_audio_strmsg(inmsg->msg_type);
144 pa_log_debug("Received %s", type);
149 pa_log_error("Bogus message type %d received from audio service", inmsg->msg_type);
154 pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
160 static int bt_audioservice_expect(int sk, bt_audio_msg_header_t *rsp_hdr, int expected_type) {
161 int e = bt_audioservice_recv(sk, rsp_hdr);
163 if (rsp_hdr->msg_type != expected_type) {
165 pa_log_error("Bogus message %s received while %s was expected", bt_audio_strmsg(rsp_hdr->msg_type),
166 bt_audio_strmsg(expected_type));
172 static int bt_getcaps(struct userdata *u) {
174 char buf[BT_AUDIO_IPC_PACKET_SIZE];
175 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
176 struct bt_getcapabilities_req *getcaps_req = (void*) buf;
177 struct bt_getcapabilities_rsp *getcaps_rsp = (void*) buf;
179 memset(getcaps_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
180 getcaps_req->h.msg_type = BT_GETCAPABILITIES_REQ;
181 strncpy(getcaps_req->device, u->addr, 18);
182 if (strcasecmp(u->profile, "a2dp") == 0)
183 getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
184 else if (strcasecmp(u->profile, "hsp") == 0)
185 getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_SCO;
187 pa_log_error("invalid profile argument: %s", u->profile);
190 getcaps_req->flags = 0;
191 getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
193 e = bt_audioservice_send(u->audioservice_fd, &getcaps_req->h);
195 pa_log_error("failed to send GETCAPABILITIES_REQ");
199 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_GETCAPABILITIES_RSP);
201 pa_log_error("failed to expect for GETCAPABILITIES_RSP");
204 if (rsp_hdr->posix_errno != 0) {
205 pa_log_error("BT_GETCAPABILITIES failed : %s (%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
206 return -rsp_hdr->posix_errno;
209 if ((u->transport = getcaps_rsp->transport) == BT_CAPABILITIES_TRANSPORT_A2DP)
210 u->a2dp.sbc_capabilities = getcaps_rsp->sbc_capabilities;
215 static uint8_t default_bitpool(uint8_t freq, uint8_t mode) {
217 case BT_SBC_SAMPLING_FREQ_16000:
218 case BT_SBC_SAMPLING_FREQ_32000:
220 case BT_SBC_SAMPLING_FREQ_44100:
222 case BT_A2DP_CHANNEL_MODE_MONO:
223 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
225 case BT_A2DP_CHANNEL_MODE_STEREO:
226 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
229 pa_log_warn("Invalid channel mode %u", mode);
232 case BT_SBC_SAMPLING_FREQ_48000:
234 case BT_A2DP_CHANNEL_MODE_MONO:
235 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
237 case BT_A2DP_CHANNEL_MODE_STEREO:
238 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
241 pa_log_warn("Invalid channel mode %u", mode);
245 pa_log_warn("Invalid sampling freq %u", freq);
250 static int bt_a2dp_init(struct userdata *u) {
251 sbc_capabilities_t *cap = &u->a2dp.sbc_capabilities;
252 unsigned int max_bitpool, min_bitpool;
256 cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
259 cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
262 cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
265 cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
268 pa_log_error("Rate %d not supported", u->rate);
272 // if (cfg->has_channel_mode)
273 // cap->channel_mode = cfg->channel_mode;
275 if (u->channels == 2) {
276 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
277 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
278 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
279 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
280 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
281 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
283 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
284 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
287 if (!cap->channel_mode) {
288 pa_log_error("No supported channel modes");
292 // if (cfg->has_block_length)
293 // cap->block_length = cfg->block_length;
295 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
296 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
297 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
298 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
299 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
300 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
301 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
302 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
304 pa_log_error("No supported block lengths");
308 // if (cfg->has_subbands)
309 // cap->subbands = cfg->subbands;
310 if (cap->subbands & BT_A2DP_SUBBANDS_8)
311 cap->subbands = BT_A2DP_SUBBANDS_8;
312 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
313 cap->subbands = BT_A2DP_SUBBANDS_4;
315 pa_log_error("No supported subbands");
319 // if (cfg->has_allocation_method)
320 // cap->allocation_method = cfg->allocation_method;
321 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
322 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
323 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
324 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
326 // if (cfg->has_bitpool)
327 // min_bitpool = max_bitpool = cfg->bitpool;
329 min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
330 max_bitpool = MIN(default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
333 cap->min_bitpool = min_bitpool;
334 cap->max_bitpool = max_bitpool;
339 static void bt_a2dp_setup(struct bt_a2dp *a2dp) {
340 sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
342 if (a2dp->sbc_initialized)
343 sbc_reinit(&a2dp->sbc, 0);
345 sbc_init(&a2dp->sbc, 0);
346 a2dp->sbc_initialized = TRUE;
348 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
349 a2dp->sbc.frequency = SBC_FREQ_16000;
351 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
352 a2dp->sbc.frequency = SBC_FREQ_32000;
354 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
355 a2dp->sbc.frequency = SBC_FREQ_44100;
357 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
358 a2dp->sbc.frequency = SBC_FREQ_48000;
360 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
361 a2dp->sbc.mode = SBC_MODE_MONO;
363 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
364 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
366 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
367 a2dp->sbc.mode = SBC_MODE_STEREO;
369 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
370 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
372 a2dp->sbc.allocation = (active_capabilities.allocation_method == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR : SBC_AM_LOUDNESS);
374 switch (active_capabilities.subbands) {
375 case BT_A2DP_SUBBANDS_4:
376 a2dp->sbc.subbands = SBC_SB_4;
378 case BT_A2DP_SUBBANDS_8:
379 a2dp->sbc.subbands = SBC_SB_8;
383 switch (active_capabilities.block_length) {
384 case BT_A2DP_BLOCK_LENGTH_4:
385 a2dp->sbc.blocks = SBC_BLK_4;
387 case BT_A2DP_BLOCK_LENGTH_8:
388 a2dp->sbc.blocks = SBC_BLK_8;
390 case BT_A2DP_BLOCK_LENGTH_12:
391 a2dp->sbc.blocks = SBC_BLK_12;
393 case BT_A2DP_BLOCK_LENGTH_16:
394 a2dp->sbc.blocks = SBC_BLK_16;
398 a2dp->sbc.bitpool = active_capabilities.max_bitpool;
399 a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
400 a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
403 static int bt_setconf(struct userdata *u) {
405 char buf[BT_AUDIO_IPC_PACKET_SIZE];
406 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
407 struct bt_setconfiguration_req *setconf_req = (void*) buf;
408 struct bt_setconfiguration_rsp *setconf_rsp = (void*) buf;
410 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
413 pa_log_error("a2dp_init error");
416 u->ss.format = PA_SAMPLE_S16LE;
419 u->ss.format = PA_SAMPLE_U8;
421 u->ss.rate = u->rate;
422 u->ss.channels = u->channels;
424 memset(setconf_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
425 setconf_req->h.msg_type = BT_SETCONFIGURATION_REQ;
426 strncpy(setconf_req->device, u->addr, 18);
427 setconf_req->transport = u->transport;
428 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
429 setconf_req->sbc_capabilities = u->a2dp.sbc_capabilities;
430 setconf_req->access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE;
432 e = bt_audioservice_send(u->audioservice_fd, &setconf_req->h);
434 pa_log_error("failed to send BT_SETCONFIGURATION_REQ");
438 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_SETCONFIGURATION_RSP);
440 pa_log_error("failed to expect BT_SETCONFIGURATION_RSP");
444 if (rsp_hdr->posix_errno != 0) {
445 pa_log_error("BT_SETCONFIGURATION failed : %s(%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
446 return -rsp_hdr->posix_errno;
449 u->transport = setconf_rsp->transport;
450 u->link_mtu = setconf_rsp->link_mtu;
452 /* setup SBC encoder now we agree on parameters */
453 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
454 bt_a2dp_setup(&u->a2dp);
455 u->block_size = u->a2dp.codesize;
456 pa_log_info("sbc parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
457 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
460 u->block_size = u->link_mtu;
465 static int bt_getstreamfd(struct userdata *u) {
467 // uint32_t period_count = io->buffer_size / io->period_size;
468 char buf[BT_AUDIO_IPC_PACKET_SIZE];
469 struct bt_streamstart_req *start_req = (void*) buf;
470 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
471 struct bt_streamfd_ind *streamfd_ind = (void*) buf;
473 memset(start_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
474 start_req->h.msg_type = BT_STREAMSTART_REQ;
476 e = bt_audioservice_send(u->audioservice_fd, &start_req->h);
478 pa_log_error("failed to send BT_STREAMSTART_REQ");
482 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_STREAMSTART_RSP);
484 pa_log_error("failed to expect BT_STREAMSTART_RSP");
488 if (rsp_hdr->posix_errno != 0) {
489 pa_log_error("BT_START failed : %s(%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
490 return -rsp_hdr->posix_errno;
493 e = bt_audioservice_expect(u->audioservice_fd, &streamfd_ind->h, BT_STREAMFD_IND);
495 pa_log_error("failed to expect BT_STREAMFD_IND");
499 if (u->stream_fd >= 0)
500 pa_close(u->stream_fd);
502 u->stream_fd = bt_audio_service_get_data_fd(u->audioservice_fd);
503 if (u->stream_fd < 0) {
504 pa_log_error("failed to get data fd: %s (%d)",pa_cstrerror(errno), errno);
508 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
509 if (pa_socket_set_sndbuf(u->stream_fd, 10*u->link_mtu) < 0) {
510 pa_log_error("failed to set socket options for A2DP: %s (%d)",pa_cstrerror(errno), errno);
515 // if (setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)) == 0)
517 // if (setsockopt(u->stream_fd, SOL_SCO, SO_SNDBUF, &period_count, sizeof(period_count)) == 0)
519 // /* FIXME : handle error codes */
520 pa_make_fd_nonblock(u->stream_fd);
521 // pa_make_socket_low_delay(u->stream_fd);
526 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
527 struct userdata *u = PA_SINK(o)->userdata;
529 pa_log_debug("got message: %d", code);
532 case PA_SINK_MESSAGE_SET_STATE:
533 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
534 case PA_SINK_SUSPENDED:
535 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
536 pa_smoother_pause(u->smoother, pa_rtclock_usec());
539 case PA_SINK_RUNNING:
540 if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
541 pa_smoother_resume(u->smoother, pa_rtclock_usec());
543 case PA_SINK_UNLINKED:
549 case PA_SINK_MESSAGE_GET_LATENCY: {
551 r = pa_smoother_get(u->smoother, pa_rtclock_usec());
552 w = pa_bytes_to_usec(u->offset + u->memchunk.length, &u->sink->sample_spec);
553 *((pa_usec_t*) data) = w > r ? w - r : 0;
559 return pa_sink_process_msg(o, code, data, offset, chunk);
562 static void sco_thread_func(void *userdata) {
563 struct userdata *u = userdata;
568 pa_log_debug("SCO thread starting up");
570 pa_thread_mq_install(&u->thread_mq);
571 pa_rtpoll_install(u->rtpoll);
573 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
577 struct pollfd *pollfd;
579 if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
580 if (u->sink->thread_info.rewind_requested) {
581 pa_sink_process_rewind(u->sink, 0);
585 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
587 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
592 /* Render some data and write it to the fifo */
596 u->memchunk.memblock = pa_memblock_new(u->mempool, u->block_size);
597 pa_log_debug("memblock asked size %d", u->block_size);
598 u->memchunk.length = pa_memblock_get_length(u->memchunk.memblock);
599 pa_log_debug("memchunk length %d", u->memchunk.length);
600 pa_sink_render_into_full(u->sink, &u->memchunk);
602 pa_assert(u->memchunk.length > 0);
604 p = pa_memblock_acquire(u->memchunk.memblock);
606 l = pa_write(u->stream_fd, (uint8_t*) p, u->memchunk.length, &write_type);
607 pa_log_debug("memblock written to socket: %d bytes", l);
608 pa_memblock_release(u->memchunk.memblock);
609 pa_memblock_unref(u->memchunk.memblock);
610 pa_memchunk_reset(&u->memchunk);
611 pa_log("memchunk reseted");
616 if (errno == EINTR) {
617 pa_log_debug("EINTR");
620 else if (errno == EAGAIN) {
621 pa_log_debug("EAGAIN");
625 pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
639 if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
643 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
644 if (usec > u->latency)
648 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
651 /* Hmm, nothing to do. Let's sleep */
652 pa_log_debug("SCO thread going to sleep");
653 pollfd->events = PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0;
654 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
655 pa_log("rtpoll_run < 0");
658 pa_log_debug("SCO thread waking up");
661 pa_log_debug("rtpoll_run == 0");
665 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
666 if (pollfd->revents & ~POLLOUT) {
667 pa_log_error("FIFO shutdown.");
673 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
674 pa_log_debug("SCO thread failed");
675 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
676 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
679 pa_log_debug("SCO thread shutting down");
682 static void a2dp_thread_func(void *userdata) {
683 struct userdata *u = userdata;
687 pa_log_debug("A2DP Thread starting up");
689 pa_thread_mq_install(&u->thread_mq);
690 pa_rtpoll_install(u->rtpoll);
692 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
696 struct pollfd *pollfd;
698 if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
699 if (u->sink->thread_info.rewind_requested) {
700 pa_sink_process_rewind(u->sink, 0);
704 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
706 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
710 int write_type = 0, written;
711 struct bt_a2dp *a2dp = &u->a2dp;
712 struct rtp_header *header = (void *) a2dp->buffer;
713 struct rtp_payload *payload = (void *) (a2dp->buffer + sizeof(*header));
716 /* Render some data */
717 int frame_size, encoded;
720 u->memchunk.memblock = pa_memblock_new(u->mempool, u->block_size);
721 pa_log_debug("memblock asked size %d", u->block_size);
722 u->memchunk.length = pa_memblock_get_length(u->memchunk.memblock);
723 pa_log_debug("memchunk length %d", u->memchunk.length);
724 pa_sink_render_into_full(u->sink, &u->memchunk);
726 pa_assert(u->memchunk.length > 0);
728 p = pa_memblock_acquire(u->memchunk.memblock);
729 frame_size = sbc_get_frame_length(&a2dp->sbc);
730 pa_log_debug("SBC frame_size: %d", frame_size);
732 encoded = sbc_encode(&a2dp->sbc, (uint8_t*) p, a2dp->codesize, a2dp->buffer + a2dp->count,
733 sizeof(a2dp->buffer) - a2dp->count, &written);
734 pa_log_debug("SBC: encoded: %d; written: %d", encoded, written);
736 pa_log_error("SBC encoding error (%d)", encoded);
739 pa_memblock_release(u->memchunk.memblock);
740 pa_memblock_unref(u->memchunk.memblock);
741 pa_memchunk_reset(&u->memchunk);
742 pa_log_debug("memchunk reseted");
744 a2dp->count += written;
746 a2dp->samples += encoded / frame_size;
747 a2dp->nsamples += encoded / frame_size;
749 } while (a2dp->count + written <= u->link_mtu);
751 /* write it to the fifo */
752 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
753 payload->frame_count = a2dp->frame_count;
756 header->sequence_number = htons(a2dp->seq_num);
757 header->timestamp = htonl(a2dp->nsamples);
758 header->ssrc = htonl(1);
761 l = pa_write(u->stream_fd, a2dp->buffer, a2dp->count, write_type);
762 pa_log_debug("avdtp_write: requested %d bytes; written %d bytes", a2dp->count, l);
767 if (errno == EINTR) {
768 pa_log_debug("EINTR");
771 else if (errno == EAGAIN) {
772 pa_log_debug("EAGAIN");
776 pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
781 u->offset += a2dp->codesize*a2dp->frame_count;
784 /* Reset buffer of data to send */
785 a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
786 a2dp->frame_count = 0;
790 /* feed the time smoother */
795 if (ioctl(u->fd, SIOCOUTQ, &ll) >= 0 && ll > 0)
799 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
800 if (usec > u->latency)
804 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
807 /* Hmm, nothing to do. Let's sleep */
808 pa_log_debug("A2DP thread going to sleep");
809 pollfd->events = PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0;
810 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
811 pa_log_error("rtpoll_run < 0");
814 pa_log_debug("A2DP thread waking up");
817 pa_log_debug("rtpoll_run == 0");
821 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
822 if (pollfd->revents & ~POLLOUT) {
823 pa_log_error("FIFO shutdown.");
829 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
830 pa_log_debug("A2DP thread failed");
831 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
832 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
835 pa_log_debug("A2DP thread shutting down");
838 int pa__init(pa_module* m) {
840 const char *rate, *channels;
842 pa_sink_new_data data;
843 struct pollfd *pollfd;
847 m->userdata = u = pa_xnew0(struct userdata, 1);
850 u->audioservice_fd = -1;
855 u->a2dp.sbc_initialized = FALSE;
856 u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
857 u->mempool = pa_mempool_new(FALSE);
858 pa_memchunk_reset(&u->memchunk);
859 u->rtpoll = pa_rtpoll_new();
860 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
861 u->rtpoll_item = NULL;
863 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
864 pa_log_error("failed to parse module arguments");
867 if (!(u->name = pa_xstrdup(pa_modargs_get_value(ma, "name", DEFAULT_SINK_NAME)))) {
868 pa_log_error("failed to get device name from module arguments");
871 if (!(u->addr = pa_xstrdup(pa_modargs_get_value(ma, "addr", NULL)))) {
872 pa_log_error("failed to get device address from module arguments");
875 if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
876 pa_log_error("failed to get profile from module arguments");
879 if (pa_modargs_get_value_u32(ma, "rate", &u->rate) < 0) {
880 pa_log_error("failed to get rate from module arguments");
883 if (pa_modargs_get_value_u32(ma, "channels", &u->channels) < 0) {
884 pa_log_error("failed to get channels from module arguments");
888 /* connect to the bluez audio service */
889 u->audioservice_fd = bt_audio_service_open();
890 if (u->audioservice_fd <= 0) {
891 pa_log_error("couldn't connect to bluetooth audio service");
894 pa_log_debug("connected to the bluetooth audio service");
896 /* queries device capabilities */
899 pa_log_error("failed to get device capabilities");
902 pa_log_debug("got device capabilities");
904 /* configures the connection */
907 pa_log_error("failed to set config");
910 pa_log_debug("connection to the device configured");
912 /* gets the device socket */
913 e = bt_getstreamfd(u);
915 pa_log_error("failed to get stream fd (%d)", e);
918 pa_log_debug("got the device socket");
921 pa_sink_new_data_init(&data);
922 data.driver = __FILE__;
924 pa_sink_new_data_set_name(&data, u->name);
925 pa_sink_new_data_set_sample_spec(&data, &u->ss);
926 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->name);
927 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Bluetooth sink '%s' (%s)", u->name, u->addr);
928 u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
929 pa_sink_new_data_done(&data);
931 pa_log_error("failed to create sink");
934 u->sink->userdata = u;
935 u->sink->parent.process_msg = sink_process_msg;
936 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
937 pa_sink_set_rtpoll(u->sink, u->rtpoll);
939 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
940 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
941 pollfd->fd = u->stream_fd;
942 pollfd->events = pollfd->revents = 0;
944 /* start rt thread */
945 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
946 if (!(u->thread = pa_thread_new(a2dp_thread_func, u))) {
947 pa_log_error("failed to create A2DP thread");
952 if (!(u->thread = pa_thread_new(sco_thread_func, u))) {
953 pa_log_error("failed to create SCO thread");
957 pa_sink_put(u->sink);
969 void pa__done(pa_module *m) {
973 if (!(u = m->userdata))
977 pa_sink_unlink(u->sink);
980 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
981 pa_thread_free(u->thread);
984 pa_thread_mq_done(&u->thread_mq);
987 pa_sink_unref(u->sink);
990 pa_rtpoll_item_free(u->rtpoll_item);
993 pa_rtpoll_free(u->rtpoll);
995 if (u->memchunk.memblock)
996 pa_memblock_unref(u->memchunk.memblock);
997 /* TODO: free mempool */
1000 pa_smoother_free(u->smoother);
1009 pa_xfree(u->profile);
1011 if (u->stream_fd >= 0)
1012 pa_close(u->stream_fd);
1014 if (u->audioservice_fd >= 0)
1015 pa_close(u->audioservice_fd);