Refactor a2dp thread execution flow and improve time estimation
[pulseaudio-mirror.git] / src / modules / module-bt-device.c
blobb5eccb3f506f4e97f4884e9933a3d8f24ee0e8ac
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 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
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>
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"
46 #include "bt-ipc.h"
47 #include "bt-sbc.h"
48 #include "bt-rtp.h"
50 #define DEFAULT_SINK_NAME "bluetooth_sink"
51 #define BUFFER_SIZE 2048
52 #define MAX_BITPOOL 64
53 #define MIN_BITPOOL 2
54 #define SOL_SCO 17
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);
62 PA_MODULE_USAGE(
63 "name=<name of the device> "
64 "addr=<address of the device> "
65 "profile=<a2dp|hsp>");
67 struct bt_a2dp {
68 sbc_capabilities_t sbc_capabilities;
69 sbc_t sbc; /* Codec data */
70 int 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*/
81 struct userdata {
82 pa_core *core;
83 pa_module *module;
84 pa_sink *sink;
86 pa_thread_mq thread_mq;
87 pa_rtpoll *rtpoll;
88 pa_rtpoll_item *rtpoll_item;
89 pa_thread *thread;
91 int64_t offset;
92 pa_smoother *smoother;
94 pa_memchunk memchunk;
95 pa_mempool *mempool;
97 const char *name;
98 const char *addr;
99 const char *profile;
100 int rate;
101 int channels;
102 pa_sample_spec ss;
104 int audioservice_fd;
105 int stream_fd;
107 int transport;
108 int link_mtu;
109 size_t block_size;
110 pa_usec_t latency;
112 struct bt_a2dp a2dp;
115 static const char* const valid_modargs[] = {
116 "name",
117 "addr",
118 "profile",
119 "rate",
120 "channels",
121 NULL
124 static int bt_audioservice_send(int sk, const bt_audio_msg_header_t *msg) {
125 int e;
126 pa_log/*_debug*/("sending %s", bt_audio_strmsg(msg->msg_type));
127 if (send(sk, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0)
128 e = 0;
129 else {
130 e = -errno;
131 pa_log_error("Error sending data to audio service: %s(%d)", pa_cstrerror(errno), errno);
133 return e;
136 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg) {
137 int e;
138 const char *type;
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);
143 if (type) {
144 pa_log/*_debug*/("Received %s", type);
145 e = 0;
147 else {
148 e = -EINVAL;
149 pa_log_error("Bogus message type %d received from audio service", inmsg->msg_type);
152 else {
153 e = -errno;
154 pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
157 return e;
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);
162 if (e == 0) {
163 if (rsp_hdr->msg_type != expected_type) {
164 e = -EINVAL;
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));
169 return e;
172 static int bt_getcaps(struct userdata *u) {
173 int e;
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;
186 else {
187 pa_log_error("invalid profile argument: %s", u->profile);
188 return -1;
190 getcaps_req->flags = 0;
191 getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
193 e = bt_audioservice_send(u->audioservice_fd, &getcaps_req->h);
194 if (e < 0) {
195 pa_log_error("failed to send GETCAPABILITIES_REQ");
196 return e;
199 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_GETCAPABILITIES_RSP);
200 if (e < 0) {
201 pa_log_error("failed to expect for GETCAPABILITIES_RSP");
202 return e;
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;
212 return 0;
215 static uint8_t default_bitpool(uint8_t freq, uint8_t mode) {
216 switch (freq) {
217 case BT_SBC_SAMPLING_FREQ_16000:
218 case BT_SBC_SAMPLING_FREQ_32000:
219 return 53;
220 case BT_SBC_SAMPLING_FREQ_44100:
221 switch (mode) {
222 case BT_A2DP_CHANNEL_MODE_MONO:
223 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
224 return 31;
225 case BT_A2DP_CHANNEL_MODE_STEREO:
226 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
227 return 53;
228 default:
229 pa_log_warn("Invalid channel mode %u", mode);
230 return 53;
232 case BT_SBC_SAMPLING_FREQ_48000:
233 switch (mode) {
234 case BT_A2DP_CHANNEL_MODE_MONO:
235 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
236 return 29;
237 case BT_A2DP_CHANNEL_MODE_STEREO:
238 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
239 return 51;
240 default:
241 pa_log_warn("Invalid channel mode %u", mode);
242 return 51;
244 default:
245 pa_log_warn("Invalid sampling freq %u", freq);
246 return 53;
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;
254 switch (u->rate) {
255 case 48000:
256 cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
257 break;
258 case 44100:
259 cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
260 break;
261 case 32000:
262 cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
263 break;
264 case 16000:
265 cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
266 break;
267 default:
268 pa_log_error("Rate %d not supported", u->rate);
269 return -1;
272 // if (cfg->has_channel_mode)
273 // cap->channel_mode = cfg->channel_mode;
274 // else
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;
282 } else {
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");
289 return -1;
292 // if (cfg->has_block_length)
293 // cap->block_length = cfg->block_length;
294 // else
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;
303 else {
304 pa_log_error("No supported block lengths");
305 return -1;
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;
314 else {
315 pa_log_error("No supported subbands");
316 return -1;
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;
328 // else {
329 min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
330 max_bitpool = MIN(default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
331 // }
333 cap->min_bitpool = min_bitpool;
334 cap->max_bitpool = max_bitpool;
336 return 0;
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);
344 else
345 sbc_init(&a2dp->sbc, 0);
346 a2dp->sbc_initialized = 1;
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;
377 break;
378 case BT_A2DP_SUBBANDS_8:
379 a2dp->sbc.subbands = SBC_SB_8;
380 break;
383 switch (active_capabilities.block_length) {
384 case BT_A2DP_BLOCK_LENGTH_4:
385 a2dp->sbc.blocks = SBC_BLK_4;
386 break;
387 case BT_A2DP_BLOCK_LENGTH_8:
388 a2dp->sbc.blocks = SBC_BLK_8;
389 break;
390 case BT_A2DP_BLOCK_LENGTH_12:
391 a2dp->sbc.blocks = SBC_BLK_12;
392 break;
393 case BT_A2DP_BLOCK_LENGTH_16:
394 a2dp->sbc.blocks = SBC_BLK_16;
395 break;
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) {
404 int e;
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) {
411 e = bt_a2dp_init(u);
412 if (e < 0) {
413 pa_log_error("a2dp_init error");
414 return e;
416 u->ss.format = PA_SAMPLE_S16LE;
418 else
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);
433 if (e < 0) {
434 pa_log_error("failed to send BT_SETCONFIGURATION_REQ");
435 return e;
438 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_SETCONFIGURATION_RSP);
439 if (e < 0) {
440 pa_log_error("failed to expect BT_SETCONFIGURATION_RSP");
441 return e;
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/*debug*/("\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);
459 else
460 u->block_size = u->link_mtu;
462 return 0;
465 static int bt_getstreamfd(struct userdata *u) {
466 int e;
467 // uint32_t period_count = io->buffer_size / io->period_size;
468 // struct timeval t = { 0, period_count };
469 char buf[BT_AUDIO_IPC_PACKET_SIZE];
470 struct bt_streamstart_req *start_req = (void*) buf;
471 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
472 struct bt_streamfd_ind *streamfd_ind = (void*) buf;
474 memset(start_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
475 start_req->h.msg_type = BT_STREAMSTART_REQ;
477 e = bt_audioservice_send(u->audioservice_fd, &start_req->h);
478 if (e < 0) {
479 pa_log_error("failed to send BT_STREAMSTART_REQ");
480 return e;
483 e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_STREAMSTART_RSP);
484 if (e < 0) {
485 pa_log_error("failed to expect BT_STREAMSTART_RSP");
486 return e;
489 if (rsp_hdr->posix_errno != 0) {
490 pa_log_error("BT_START failed : %s(%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
491 return -rsp_hdr->posix_errno;
494 e = bt_audioservice_expect(u->audioservice_fd, &streamfd_ind->h, BT_STREAMFD_IND);
495 if (e < 0) {
496 pa_log_error("failed to expect BT_STREAMFD_IND");
497 return e;
500 if (u->stream_fd >= 0)
501 pa_close(u->stream_fd);
503 u->stream_fd = bt_audio_service_get_data_fd(u->audioservice_fd);
504 if (u->stream_fd < 0) {
505 pa_log_error("failed to get data fd: %s (%d)",pa_cstrerror(errno), errno);
506 return -errno;
509 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
510 if (pa_socket_set_sndbuf(u->stream_fd, 10*u->link_mtu) < 0) {
511 pa_log_error("failed to set socket options for A2DP: %s (%d)",pa_cstrerror(errno), errno);
512 return -errno;
516 // if (setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)) == 0)
517 // return 0;
518 // if (setsockopt(u->stream_fd, SOL_SCO, SO_SNDBUF, &period_count, sizeof(period_count)) == 0)
519 // return 0;
520 // /* FIXME : handle error codes */
521 pa_make_fd_nonblock(u->stream_fd);
522 // pa_make_socket_low_delay(u->stream_fd);
524 return 0;
527 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
528 struct userdata *u = PA_SINK(o)->userdata;
530 pa_log/*_debug*/("got message: %d", code);
531 switch (code) {
533 case PA_SINK_MESSAGE_SET_STATE:
534 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
535 case PA_SINK_SUSPENDED:
536 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
537 pa_smoother_pause(u->smoother, pa_rtclock_usec());
538 break;
539 case PA_SINK_IDLE:
540 case PA_SINK_RUNNING:
541 if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
542 pa_smoother_resume(u->smoother, pa_rtclock_usec());
543 break;
544 case PA_SINK_UNLINKED:
545 case PA_SINK_INIT:
548 break;
550 case PA_SINK_MESSAGE_GET_LATENCY: {
551 pa_usec_t w, r;
552 r = pa_smoother_get(u->smoother, pa_rtclock_usec());
553 w = pa_bytes_to_usec(u->offset + u->memchunk.length, &u->sink->sample_spec);
554 *((pa_usec_t*) data) = w > r ? w - r : 0;
555 return 0;
560 return pa_sink_process_msg(o, code, data, offset, chunk);
563 static void thread_func(void *userdata) {
564 struct userdata *u = userdata;
565 int write_type = 0;
567 pa_assert(u);
569 pa_log/*_debug*/("Thread starting up");
571 pa_thread_mq_install(&u->thread_mq);
572 pa_rtpoll_install(u->rtpoll);
574 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
576 for (;;) {
577 int ret;
578 struct pollfd *pollfd;
580 if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
581 if (u->sink->thread_info.rewind_requested) {
582 pa_log("rewind_requested");
583 pa_sink_process_rewind(u->sink, 0);
584 pa_log("rewind_finished");
588 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
590 /* Render some data and write it to the fifo */
591 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
592 pa_usec_t usec;
593 int64_t n;
594 pa_log("Render some data and write it to the fifo");
596 for (;;) {
597 ssize_t l;
598 void *p;
600 u->memchunk.memblock = pa_memblock_new(u->mempool, u->block_size);
601 pa_log("memblock allocated %d", u->block_size);
602 u->memchunk.length = pa_memblock_get_length(u->memchunk.memblock);
603 pa_log("memchunk length %d", u->memchunk.length);
604 pa_sink_render_into_full(u->sink, &u->memchunk);
605 pa_log("rendered");
607 pa_assert(u->memchunk.length > 0);
609 p = pa_memblock_acquire(u->memchunk.memblock);
610 pa_log("memblock acquired");
611 l = pa_write(u->stream_fd, (uint8_t*) p, u->memchunk.length, &write_type);
612 pa_log("memblock written %d bytes", l);
613 pa_memblock_release(u->memchunk.memblock);
614 pa_log("memblock released");
616 pa_assert(l != 0);
618 if (l < 0) {
619 pa_log("l = %d < 0", l);
620 if (errno == EINTR)
621 continue;
622 else if (errno == EAGAIN)
623 goto filled_up;
624 else {
625 pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
626 goto fail;
628 } else {
629 pa_log("l = %d >= 0", l);
630 u->offset += l;
631 pa_memblock_unref(u->memchunk.memblock);
632 pa_log("memblock unrefered");
633 pa_memchunk_reset(&u->memchunk);
634 pa_log("memchunk reseted");
635 pollfd->revents = 0;
639 filled_up:
641 pa_log("filled_up");
642 /* At this spot we know that the socket buffers are fully filled up.
643 * This is the best time to estimate the playback position of the server */
644 n = u->offset;
646 #ifdef SIOCOUTQ
648 int l;
649 if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
650 n -= l;
652 #endif
654 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
655 if (usec > u->latency)
656 usec -= u->latency;
657 else
658 usec = 0;
659 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
662 /* Hmm, nothing to do. Let's sleep */
663 pa_log("let's sleep");
664 pollfd->events = PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0;
666 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
667 pa_log("ret < 0");
668 goto fail;
670 pa_log("waking up");
672 if (ret == 0) {
673 pa_log("ret == 0");
674 goto finish;
677 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
678 if (pollfd->revents & ~POLLOUT) {
679 pa_log("FIFO shutdown.");
680 goto fail;
684 fail:
685 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
686 pa_log("fail");
687 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
688 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
690 finish:
691 pa_log_debug("Thread shutting down");
694 static void a2dp_thread_func(void *userdata) {
695 struct userdata *u = userdata;
697 pa_assert(u);
699 pa_log_debug("A2DP Thread starting up");
701 pa_thread_mq_install(&u->thread_mq);
702 pa_rtpoll_install(u->rtpoll);
704 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
706 for (;;) {
707 int ret;
708 struct pollfd *pollfd;
710 if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
711 if (u->sink->thread_info.rewind_requested) {
712 pa_sink_process_rewind(u->sink, 0);
716 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
718 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
719 pa_usec_t usec;
720 int64_t n;
721 ssize_t l;
722 int write_type = 0, written;
723 struct bt_a2dp *a2dp = &u->a2dp;
724 struct rtp_header *header = (void *) a2dp->buffer;
725 struct rtp_payload *payload = (void *) (a2dp->buffer + sizeof(*header));
727 do {
728 /* Render some data */
729 void *p;
730 int frame_size, encoded;
732 u->memchunk.memblock = pa_memblock_new(u->mempool, u->block_size);
733 pa_log_debug("memblock asked size%d", u->block_size);
734 u->memchunk.length = pa_memblock_get_length(u->memchunk.memblock);
735 pa_log_debug("memchunk length %d", u->memchunk.length);
736 pa_sink_render_into_full(u->sink, &u->memchunk);
737 pa_log_debug("rendered");
739 pa_assert(u->memchunk.length > 0);
741 p = pa_memblock_acquire(u->memchunk.memblock);
742 frame_size = sbc_get_frame_length(&a2dp->sbc);
743 pa_log_debug("frame_size: %d", frame_size);
745 encoded = sbc_encode(&a2dp->sbc, (uint8_t*) p, a2dp->codesize, a2dp->buffer + a2dp->count,
746 sizeof(a2dp->buffer) - a2dp->count, &written);
747 pa_log_debug("encoded: %d", encoded);
748 pa_log_debug("written: %d", written);
749 if (encoded <= 0) {
750 pa_log_error("SBC encoding error (%d)", encoded);
751 goto fail;
753 pa_memblock_release(u->memchunk.memblock);
754 pa_memblock_unref(u->memchunk.memblock);
755 pa_memchunk_reset(&u->memchunk);
756 pa_log_debug("memchunk reseted");
758 a2dp->count += written;
759 a2dp->frame_count++;
760 a2dp->samples += encoded / frame_size;
761 a2dp->nsamples += encoded / frame_size;
763 } while (a2dp->count + written <= u->link_mtu);
765 /* write it to the fifo */
766 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
767 payload->frame_count = a2dp->frame_count;
768 header->v = 2;
769 header->pt = 1;
770 header->sequence_number = htons(a2dp->seq_num);
771 header->timestamp = htonl(a2dp->nsamples);
772 header->ssrc = htonl(1);
774 avdtp_write:
775 l = pa_write(u->stream_fd, a2dp->buffer, a2dp->count, write_type);
776 pa_log_debug("avdtp_write: requested %d bytes; written %d bytes", a2dp->count, l);
778 pa_assert(l != 0);
780 if (l < 0) {
781 if (errno == EINTR) {
782 pa_log_debug("EINTR");
783 continue;
785 else if (errno == EAGAIN) {
786 pa_log_debug("EAGAIN");
787 goto avdtp_write;
789 else {
790 pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
791 goto fail;
795 u->offset += a2dp->codesize*a2dp->frame_count;
796 pollfd->revents = 0;
798 /* Reset buffer of data to send */
799 a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
800 a2dp->frame_count = 0;
801 a2dp->samples = 0;
802 a2dp->seq_num++;
804 /* feed the time smoother */
805 n = u->offset;
806 #ifdef SIOCOUTQ
808 int ll;
809 if (ioctl(u->fd, SIOCOUTQ, &ll) >= 0 && ll > 0)
810 n -= ll;
812 #endif
813 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
814 if (usec > u->latency)
815 usec -= u->latency;
816 else
817 usec = 0;
818 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
821 /* Hmm, nothing to do. Let's sleep */
822 pa_log_debug("A2DP thread going to sleep");
823 pollfd->events = PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0;
824 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
825 pa_log("ret < 0");
826 goto fail;
828 pa_log_debug("A2DP thread waking up");
830 if (ret == 0) {
831 pa_log_warn("ret == 0");
832 goto finish;
835 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
836 if (pollfd->revents & ~POLLOUT) {
837 pa_log_error("FIFO shutdown.");
838 goto fail;
842 fail:
843 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
844 pa_log_debug("A2DP thread failed");
845 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
846 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
848 finish:
849 pa_log_debug("A2DP thread shutting down");
852 int pa__init(pa_module* m) {
853 int e;
854 const char *rate, *channels;
855 pa_modargs *ma;
856 pa_sink_new_data data;
857 struct pollfd *pollfd;
858 struct userdata *u;
860 pa_assert(m);
861 m->userdata = u = pa_xnew0(struct userdata, 1);
862 u->module = m;
863 u->core = m->core;
864 u->audioservice_fd = -1;
865 u->stream_fd = -1;
866 u->transport = -1;
867 u->offset = 0;
868 u->latency = 0;
869 u->a2dp.sbc_initialized = 0;
870 u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
871 u->mempool = pa_mempool_new(FALSE);
872 pa_memchunk_reset(&u->memchunk);
873 u->rtpoll = pa_rtpoll_new();
874 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
875 u->rtpoll_item = NULL;
877 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
878 pa_log_error("failed to parse module arguments");
879 goto fail;
881 if (!(u->name = pa_xstrdup(pa_modargs_get_value(ma, "name", DEFAULT_SINK_NAME)))) {
882 pa_log_error("failed to get device name from module arguments");
883 goto fail;
885 if (!(u->addr = pa_xstrdup(pa_modargs_get_value(ma, "addr", NULL)))) {
886 pa_log_error("failed to get device address from module arguments");
887 goto fail;
889 if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
890 pa_log_error("failed to get profile from module arguments");
891 goto fail;
893 if (pa_modargs_get_value_u32(ma, "rate", &u->rate) < 0) {
894 pa_log_error("failed to get rate from module arguments");
895 goto fail;
897 if (pa_modargs_get_value_u32(ma, "channels", &u->channels) < 0) {
898 pa_log_error("failed to get channels from module arguments");
899 goto fail;
901 pa_log("Loading module-bt-device for %s (%s), profile %s", u->name, u->addr, u->profile);
903 /* connect to the bluez audio service */
904 u->audioservice_fd = bt_audio_service_open();
905 if (u->audioservice_fd <= 0) {
906 pa_log_error("couldn't connect to bluetooth audio service");
907 goto fail;
910 /* queries device capabilities */
911 e = bt_getcaps(u);
912 if (e < 0) {
913 pa_log_error("failed to get device capabilities");
914 goto fail;
917 /* configures the connection */
918 e = bt_setconf(u);
919 if (e < 0) {
920 pa_log_error("failed to set config");
921 goto fail;
924 /* gets the device socket */
925 e = bt_getstreamfd(u);
926 if (e < 0) {
927 pa_log_error("failed to get stream fd (%d)", e);
928 goto fail;
931 /* create sink */
932 pa_sink_new_data_init(&data);
933 data.driver = __FILE__;
934 data.module = m;
935 pa_sink_new_data_set_name(&data, u->name);
936 pa_sink_new_data_set_sample_spec(&data, &u->ss);
937 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->name);
938 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Bluetooth sink '%s' (%s)", u->name, u->addr);
939 u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
940 pa_sink_new_data_done(&data);
941 if (!u->sink) {
942 pa_log_error("failed to create sink");
943 goto fail;
945 u->sink->userdata = u;
946 u->sink->parent.process_msg = sink_process_msg;
947 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
948 pa_sink_set_rtpoll(u->sink, u->rtpoll);
950 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
951 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
952 pollfd->fd = u->stream_fd;
953 pollfd->events = pollfd->revents = 0;
955 /* start rt thread */
956 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
957 if (!(u->thread = pa_thread_new(a2dp_thread_func, u))) {
958 pa_log_error("failed to create thread");
959 goto fail;
962 else {
963 if (!(u->thread = pa_thread_new(thread_func, u))) {
964 pa_log_error("failed to create thread");
965 goto fail;
968 pa_sink_put(u->sink);
970 pa_modargs_free(ma);
971 return 0;
973 fail:
974 if (ma)
975 pa_modargs_free(ma);
976 pa__done(m);
977 return -1;
980 void pa__done(pa_module *m) {
981 pa_log("Unloading module-bt-device");