]> code.delx.au - pulseaudio/blob - src/modules/bluetooth/module-bluetooth-device.c
bf9bad6596209447984ea8a59f81164a3b4ed1e0
[pulseaudio] / src / modules / bluetooth / module-bluetooth-device.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2008 Joao Paulo Rechi Vita
5
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public 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 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <string.h>
27 #include <errno.h>
28 #include <poll.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
32
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulsecore/module.h>
37 #include <pulsecore/modargs.h>
38 #include <pulsecore/core-util.h>
39 #include <pulsecore/core-error.h>
40 #include <pulsecore/socket-util.h>
41 #include <pulsecore/thread.h>
42 #include <pulsecore/thread-mq.h>
43 #include <pulsecore/rtpoll.h>
44 #include <pulsecore/time-smoother.h>
45 #include <pulsecore/rtclock.h>
46
47 #include "dbus-util.h"
48 #include "module-bluetooth-device-symdef.h"
49 #include "ipc.h"
50 #include "sbc.h"
51 #include "rtp.h"
52
53 #define DEFAULT_SINK_NAME "bluetooth_sink"
54 #define BUFFER_SIZE 2048
55 #define MAX_BITPOOL 64
56 #define MIN_BITPOOL 2U
57 #define SOL_SCO 17
58 #define SCO_TXBUFS 0x03
59 #define SCO_RXBUFS 0x04
60
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 "sink_name=<name of the device> "
67 "address=<address of the device> "
68 "profile=<a2dp|hsp>");
69
70 struct bt_a2dp {
71 sbc_capabilities_t sbc_capabilities;
72 sbc_t sbc; /* Codec data */
73 pa_bool_t sbc_initialized; /* Keep track if the encoder is initialized */
74 size_t codesize; /* SBC codesize */
75 unsigned samples; /* Number of encoded samples */
76 uint8_t buffer[BUFFER_SIZE]; /* Codec transfer buffer */
77 size_t count; /* Codec transfer buffer counter */
78
79 unsigned total_samples; /* Cumulative number of codec samples */
80 uint16_t seq_num; /* Cumulative packet sequence */
81 unsigned frame_count; /* Current frames in buffer*/
82 };
83
84 struct userdata {
85 pa_core *core;
86 pa_module *module;
87 pa_sink *sink;
88
89 pa_thread_mq thread_mq;
90 pa_rtpoll *rtpoll;
91 pa_rtpoll_item *rtpoll_item;
92 pa_thread *thread;
93
94 uint64_t offset;
95 pa_smoother *smoother;
96
97 char *name;
98 char *addr;
99 char *profile;
100 pa_sample_spec ss;
101
102 int audioservice_fd;
103 int stream_fd;
104
105 uint8_t transport;
106 char *strtransport;
107 size_t link_mtu;
108 size_t block_size;
109 pa_usec_t latency;
110
111 struct bt_a2dp a2dp;
112 };
113
114 static const char* const valid_modargs[] = {
115 "sink_name",
116 "address",
117 "profile",
118 "rate",
119 "channels",
120 NULL
121 };
122
123 static int bt_audioservice_send(int sk, const bt_audio_msg_header_t *msg) {
124 int e;
125 pa_log_debug("sending %s", bt_audio_strmsg(msg->msg_type));
126 if (send(sk, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0)
127 e = 0;
128 else {
129 e = -errno;
130 pa_log_error("Error sending data to audio service: %s(%d)", pa_cstrerror(errno), errno);
131 }
132 return e;
133 }
134
135 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg) {
136 int e;
137 const char *type;
138
139 pa_log_debug("trying to receive msg from audio service...");
140 if (recv(sk, inmsg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0) {
141 type = bt_audio_strmsg(inmsg->msg_type);
142 if (type) {
143 pa_log_debug("Received %s", type);
144 e = 0;
145 }
146 else {
147 e = -EINVAL;
148 pa_log_error("Bogus message type %d received from audio service", inmsg->msg_type);
149 }
150 }
151 else {
152 e = -errno;
153 pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
154 }
155
156 return e;
157 }
158
159 static int bt_audioservice_expect(int sk, bt_audio_msg_header_t *rsp_hdr, int expected_type) {
160 int e = bt_audioservice_recv(sk, rsp_hdr);
161 if (e == 0) {
162 if (rsp_hdr->msg_type != expected_type) {
163 e = -EINVAL;
164 pa_log_error("Bogus message %s received while %s was expected", bt_audio_strmsg(rsp_hdr->msg_type),
165 bt_audio_strmsg(expected_type));
166 }
167 }
168 return e;
169 }
170
171 static int bt_getcaps(struct userdata *u) {
172 int e;
173 union {
174 bt_audio_rsp_msg_header_t rsp_hdr;
175 struct bt_getcapabilities_req getcaps_req;
176 struct bt_getcapabilities_rsp getcaps_rsp;
177 uint8_t buf[BT_AUDIO_IPC_PACKET_SIZE];
178 } msg;
179
180 memset(msg.buf, 0, BT_AUDIO_IPC_PACKET_SIZE);
181 msg.getcaps_req.h.msg_type = BT_GETCAPABILITIES_REQ;
182 strncpy(msg.getcaps_req.device, u->addr, 18);
183 if (strcasecmp(u->profile, "a2dp") == 0)
184 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
185 else if (strcasecmp(u->profile, "hsp") == 0)
186 msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
187 else {
188 pa_log_error("Invalid profile argument: %s", u->profile);
189 return -1;
190 }
191 msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
192
193 e = bt_audioservice_send(u->audioservice_fd, &msg.getcaps_req.h);
194 if (e < 0) {
195 pa_log_error("Failed to send GETCAPABILITIES_REQ");
196 return e;
197 }
198
199 e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp_hdr.msg_h, BT_GETCAPABILITIES_RSP);
200 if (e < 0) {
201 pa_log_error("Failed to expect for GETCAPABILITIES_RSP");
202 return e;
203 }
204 if (msg.rsp_hdr.posix_errno != 0) {
205 pa_log_error("BT_GETCAPABILITIES failed : %s (%d)", pa_cstrerror(msg.rsp_hdr.posix_errno), msg.rsp_hdr.posix_errno);
206 return -msg.rsp_hdr.posix_errno;
207 }
208
209 if ((u->transport = msg.getcaps_rsp.transport) == BT_CAPABILITIES_TRANSPORT_A2DP)
210 u->a2dp.sbc_capabilities = msg.getcaps_rsp.sbc_capabilities;
211
212 return 0;
213 }
214
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;
231 }
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;
243 }
244 default:
245 pa_log_warn("Invalid sampling freq %u", freq);
246 return 53;
247 }
248 }
249
250 static int bt_a2dp_init(struct userdata *u) {
251 sbc_capabilities_t *cap = &u->a2dp.sbc_capabilities;
252 uint8_t max_bitpool, min_bitpool;
253 unsigned i;
254
255 static const struct {
256 uint32_t rate;
257 uint8_t cap;
258 } freq_table[] = {
259 { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
260 { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
261 { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
262 { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
263 };
264
265 /* Find the lowest freq that is at least as high as the requested
266 * sampling rate */
267 for (i = 0; i < PA_ELEMENTSOF(freq_table); i++)
268 if (freq_table[i].rate >= u->ss.rate || i == PA_ELEMENTSOF(freq_table)-1 ) {
269 u->ss.rate = freq_table[i].rate;
270 cap->frequency = freq_table[i].cap;
271 break;
272 }
273
274 if (u->ss.channels >= 2) {
275 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
276 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
277 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
278 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
279 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
280 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
281
282 u->ss.channels = 2;
283 } else {
284 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
285 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
286 }
287
288 if (!cap->channel_mode) {
289 pa_log_error("No supported channel modes");
290 return -1;
291 }
292
293 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
294 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
295 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
296 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
297 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
298 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
299 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
300 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
301 else {
302 pa_log_error("No supported block lengths");
303 return -1;
304 }
305
306 if (cap->subbands & BT_A2DP_SUBBANDS_8)
307 cap->subbands = BT_A2DP_SUBBANDS_8;
308 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
309 cap->subbands = BT_A2DP_SUBBANDS_4;
310 else {
311 pa_log_error("No supported subbands");
312 return -1;
313 }
314
315 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
316 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
317 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
318 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
319
320 min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
321 max_bitpool = (uint8_t) PA_MIN(default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
322
323 cap->min_bitpool = (uint8_t) min_bitpool;
324 cap->max_bitpool = (uint8_t) max_bitpool;
325
326 return 0;
327 }
328
329 static void bt_a2dp_setup(struct bt_a2dp *a2dp) {
330 sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
331
332 if (a2dp->sbc_initialized)
333 sbc_reinit(&a2dp->sbc, 0);
334 else
335 sbc_init(&a2dp->sbc, 0);
336 a2dp->sbc_initialized = TRUE;
337
338 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
339 a2dp->sbc.frequency = SBC_FREQ_16000;
340
341 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
342 a2dp->sbc.frequency = SBC_FREQ_32000;
343
344 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
345 a2dp->sbc.frequency = SBC_FREQ_44100;
346
347 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
348 a2dp->sbc.frequency = SBC_FREQ_48000;
349
350 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
351 a2dp->sbc.mode = SBC_MODE_MONO;
352
353 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
354 a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
355
356 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
357 a2dp->sbc.mode = SBC_MODE_STEREO;
358
359 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
360 a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
361
362 a2dp->sbc.allocation = (uint8_t) (active_capabilities.allocation_method == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR : SBC_AM_LOUDNESS);
363
364 switch (active_capabilities.subbands) {
365 case BT_A2DP_SUBBANDS_4:
366 a2dp->sbc.subbands = SBC_SB_4;
367 break;
368 case BT_A2DP_SUBBANDS_8:
369 a2dp->sbc.subbands = SBC_SB_8;
370 break;
371 }
372
373 switch (active_capabilities.block_length) {
374 case BT_A2DP_BLOCK_LENGTH_4:
375 a2dp->sbc.blocks = SBC_BLK_4;
376 break;
377 case BT_A2DP_BLOCK_LENGTH_8:
378 a2dp->sbc.blocks = SBC_BLK_8;
379 break;
380 case BT_A2DP_BLOCK_LENGTH_12:
381 a2dp->sbc.blocks = SBC_BLK_12;
382 break;
383 case BT_A2DP_BLOCK_LENGTH_16:
384 a2dp->sbc.blocks = SBC_BLK_16;
385 break;
386 }
387
388 a2dp->sbc.bitpool = active_capabilities.max_bitpool;
389 a2dp->codesize = (uint16_t) sbc_get_codesize(&a2dp->sbc);
390 a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
391 }
392
393 static int bt_setconf(struct userdata *u) {
394 int e;
395 union {
396 bt_audio_rsp_msg_header_t rsp_hdr;
397 struct bt_setconfiguration_req setconf_req;
398 struct bt_setconfiguration_rsp setconf_rsp;
399 uint8_t buf[BT_AUDIO_IPC_PACKET_SIZE];
400 } msg;
401
402 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
403 e = bt_a2dp_init(u);
404 if (e < 0) {
405 pa_log_error("a2dp_init error");
406 return e;
407 }
408 u->ss.format = PA_SAMPLE_S16LE;
409 }
410 else
411 u->ss.format = PA_SAMPLE_U8;
412
413 memset(msg.buf, 0, BT_AUDIO_IPC_PACKET_SIZE);
414 msg.setconf_req.h.msg_type = BT_SETCONFIGURATION_REQ;
415 strncpy(msg.setconf_req.device, u->addr, 18);
416 msg.setconf_req.transport = u->transport;
417 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
418 msg.setconf_req.sbc_capabilities = u->a2dp.sbc_capabilities;
419 msg.setconf_req.access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE;
420
421 e = bt_audioservice_send(u->audioservice_fd, &msg.setconf_req.h);
422 if (e < 0) {
423 pa_log_error("Failed to send BT_SETCONFIGURATION_REQ");
424 return e;
425 }
426
427 e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp_hdr.msg_h, BT_SETCONFIGURATION_RSP);
428 if (e < 0) {
429 pa_log_error("Failed to expect BT_SETCONFIGURATION_RSP");
430 return e;
431 }
432
433 if (msg.rsp_hdr.posix_errno != 0) {
434 pa_log_error("BT_SETCONFIGURATION failed : %s(%d)", pa_cstrerror(msg.rsp_hdr.posix_errno), msg.rsp_hdr.posix_errno);
435 return -msg.rsp_hdr.posix_errno;
436 }
437
438 u->transport = msg.setconf_rsp.transport;
439 u->strtransport = (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP ? pa_xstrdup("A2DP") : pa_xstrdup("SCO"));
440 u->link_mtu = msg.setconf_rsp.link_mtu;
441
442 /* setup SBC encoder now we agree on parameters */
443 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
444 bt_a2dp_setup(&u->a2dp);
445 u->block_size = u->a2dp.codesize;
446 pa_log_info("sbc parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
447 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
448 }
449 else
450 u->block_size = u->link_mtu;
451
452 return 0;
453 }
454
455 static int bt_getstreamfd(struct userdata *u) {
456 int e;
457 // uint32_t period_count = io->buffer_size / io->period_size;
458 union {
459 bt_audio_rsp_msg_header_t rsp_hdr;
460 struct bt_streamstart_req start_req;
461 struct bt_streamfd_ind streamfd_ind;
462 uint8_t buf[BT_AUDIO_IPC_PACKET_SIZE];
463 } msg;
464
465 memset(msg.buf, 0, BT_AUDIO_IPC_PACKET_SIZE);
466 msg.start_req.h.msg_type = BT_STREAMSTART_REQ;
467
468 e = bt_audioservice_send(u->audioservice_fd, &msg.start_req.h);
469 if (e < 0) {
470 pa_log_error("Failed to send BT_STREAMSTART_REQ");
471 return e;
472 }
473
474 e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp_hdr.msg_h, BT_STREAMSTART_RSP);
475 if (e < 0) {
476 pa_log_error("Failed to expect BT_STREAMSTART_RSP");
477 return e;
478 }
479
480 if (msg.rsp_hdr.posix_errno != 0) {
481 pa_log_error("BT_START failed : %s(%d)", pa_cstrerror(msg.rsp_hdr.posix_errno), msg.rsp_hdr.posix_errno);
482 return -msg.rsp_hdr.posix_errno;
483 }
484
485 e = bt_audioservice_expect(u->audioservice_fd, &msg.streamfd_ind.h, BT_STREAMFD_IND);
486 if (e < 0) {
487 pa_log_error("Failed to expect BT_STREAMFD_IND");
488 return e;
489 }
490
491 if (u->stream_fd >= 0)
492 pa_close(u->stream_fd);
493
494 u->stream_fd = bt_audio_service_get_data_fd(u->audioservice_fd);
495 if (u->stream_fd < 0) {
496 pa_log_error("Failed to get data fd: %s (%d)",pa_cstrerror(errno), errno);
497 return -errno;
498 }
499
500 // if (setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)) == 0)
501 // return 0;
502 // if (setsockopt(u->stream_fd, SOL_SCO, SO_SNDBUF, &period_count, sizeof(period_count)) == 0)
503 // return 0;
504 // /* FIXME : handle error codes */
505 pa_make_fd_nonblock(u->stream_fd);
506 // pa_make_socket_low_delay(u->stream_fd);
507
508 return 0;
509 }
510
511 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
512 struct userdata *u = PA_SINK(o)->userdata;
513
514 pa_log_debug("got message: %d", code);
515 switch (code) {
516
517 case PA_SINK_MESSAGE_SET_STATE:
518 switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
519 case PA_SINK_SUSPENDED:
520 pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
521 pa_smoother_pause(u->smoother, pa_rtclock_usec());
522 break;
523 case PA_SINK_IDLE:
524 case PA_SINK_RUNNING:
525 if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
526 pa_smoother_resume(u->smoother, pa_rtclock_usec());
527 break;
528 case PA_SINK_UNLINKED:
529 case PA_SINK_INIT:
530 ;
531 }
532 break;
533
534 case PA_SINK_MESSAGE_GET_LATENCY: {
535 pa_usec_t w, r;
536 /* r = pa_smoother_get(u->smoother, pa_rtclock_usec()); */
537 /* /\* w = pa_bytes_to_usec(u->offset + (uint64_t) u->memchunk.length, &u->sink->sample_spec); *\/ */
538 *((pa_usec_t*) data) = /*w > r ? w - r :*/ 0;
539 return 0;
540 }
541
542 }
543
544 return pa_sink_process_msg(o, code, data, offset, chunk);
545 }
546
547 static int sco_process_render(struct userdata *u) {
548 void *p;
549 int ret = 0;
550 pa_memchunk memchunk;
551
552 pa_sink_render_full(u->sink, u->block_size, &memchunk);
553
554 p = pa_memblock_acquire(memchunk.memblock);
555
556 for (;;) {
557 ssize_t l;
558
559 l = pa_loop_write(u->stream_fd, (uint8_t*) p, memchunk.length, NULL);
560 pa_log_debug("Memblock written to socket: %li bytes", (long) l);
561
562 pa_assert(l != 0);
563
564 if (l > 0) {
565 u->offset += (uint64_t) l;
566 break;
567 }
568
569 if (errno == EINTR)
570 pa_log_debug("EINTR");
571 else if (errno == EAGAIN)
572 pa_log_debug("EAGAIN");
573 else {
574 pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
575 ret = -1;
576 break;
577 }
578 }
579
580 pa_memblock_release(memchunk.memblock);
581 pa_memblock_unref(memchunk.memblock);
582
583 return ret;
584 }
585
586 static int a2dp_process_render(struct userdata *u) {
587 int written;
588
589 struct bt_a2dp *a2dp = &u->a2dp;
590 struct rtp_header *header = (void *) a2dp->buffer;
591 struct rtp_payload *payload = (void *) (a2dp->buffer + sizeof(*header));
592
593 pa_assert(u);
594
595 do {
596 /* Render some data */
597 int frame_size, encoded;
598 void *p;
599 pa_memchunk memchunk;
600
601 pa_sink_render_full(u->sink, u->block_size, &memchunk);
602
603 p = pa_memblock_acquire(memchunk.memblock);
604
605 frame_size = (uint16_t) sbc_get_frame_length(&a2dp->sbc);
606 pa_log_debug("SBC frame_size: %d", frame_size);
607
608 encoded = sbc_encode(&a2dp->sbc, p, (int) a2dp->codesize, a2dp->buffer + a2dp->count,
609 (int) (sizeof(a2dp->buffer) - a2dp->count), &written);
610 pa_log_debug("SBC: encoded: %d; written: %d", encoded, written);
611
612 pa_memblock_release(memchunk.memblock);
613 pa_memblock_unref(memchunk.memblock);
614
615 if (encoded <= 0) {
616 pa_log_error("SBC encoding error (%d)", encoded);
617 return -1;
618 }
619
620 a2dp->count += (size_t) written;
621 a2dp->frame_count++;
622 a2dp->samples += (unsigned) encoded / frame_size;
623 a2dp->total_samples += (unsigned) encoded / frame_size;
624
625 } while (a2dp->count + (size_t) written <= u->link_mtu);
626
627 /* write it to the fifo */
628 memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
629 payload->frame_count = a2dp->frame_count;
630 header->v = 2;
631 header->pt = 1;
632 header->sequence_number = htons(a2dp->seq_num);
633 header->timestamp = htonl(a2dp->total_samples);
634 header->ssrc = htonl(1);
635
636 for (;;) {
637 ssize_t l;
638
639 l = pa_loop_write(u->stream_fd, a2dp->buffer, a2dp->count, NULL);
640 pa_log_debug("avdtp_write: requested %lu bytes; written %li bytes", (unsigned long) a2dp->count, (long) l);
641
642 pa_assert(l != 0);
643
644 if (l > 0)
645 break;
646
647 if (errno == EINTR)
648 pa_log_debug("EINTR");
649 else if (errno == EAGAIN)
650 pa_log_debug("EAGAIN");
651 else {
652 pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
653 return -1;
654 }
655 }
656
657 u->offset += a2dp->codesize*a2dp->frame_count;
658
659 /* Reset buffer of data to send */
660 a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
661 a2dp->frame_count = 0;
662 a2dp->samples = 0;
663 a2dp->seq_num++;
664
665 return 0;
666 }
667
668 static void thread_func(void *userdata) {
669 struct userdata *u = userdata;
670
671 pa_assert(u);
672
673 pa_log_debug("IO Thread starting up");
674
675 if (u->core->realtime_scheduling)
676 pa_make_realtime(u->core->realtime_priority);
677
678 pa_thread_mq_install(&u->thread_mq);
679 pa_rtpoll_install(u->rtpoll);
680
681 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
682
683 for (;;) {
684 int ret, l;
685 struct pollfd *pollfd;
686 uint64_t n;
687 pa_usec_t usec;
688
689 if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
690 if (u->sink->thread_info.rewind_requested)
691 pa_sink_process_rewind(u->sink, 0);
692
693 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
694
695 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
696 if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
697 if ((l = a2dp_process_render(u)) < 0)
698 goto fail;
699 } else {
700 if ((l = sco_process_render(u)) < 0)
701 goto fail;
702 }
703 pollfd->revents = 0;
704
705 /* feed the time smoother */
706 n = u->offset;
707 if (ioctl(u->stream_fd, SIOCOUTQ, &l) >= 0 && l > 0)
708 n -= (uint64_t) l;
709 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
710 if (usec > u->latency)
711 usec -= u->latency;
712 else
713 usec = 0;
714 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
715 }
716
717 /* Hmm, nothing to do. Let's sleep */
718 pa_log_debug("IO thread going to sleep");
719 pollfd->events = (short) (PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0);
720 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
721 pa_log_error("rtpoll_run < 0");
722 goto fail;
723 }
724 pa_log_debug("IO thread waking up");
725
726 if (ret == 0) {
727 pa_log_debug("rtpoll_run == 0");
728 goto finish;
729 }
730
731 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
732 if (pollfd->revents & ~POLLOUT) {
733 pa_log_error("FIFO shutdown.");
734 goto fail;
735 }
736 }
737
738 fail:
739 /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
740 pa_log_debug("IO thread failed");
741 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
742 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
743
744 finish:
745 pa_log_debug("IO thread shutting down");
746 }
747
748 int pa__init(pa_module* m) {
749 int e;
750 pa_modargs *ma;
751 uint32_t channels;
752 pa_sink_new_data data;
753 struct pollfd *pollfd;
754 struct userdata *u;
755
756 pa_assert(m);
757 m->userdata = u = pa_xnew0(struct userdata, 1);
758 u->module = m;
759 u->core = m->core;
760 u->audioservice_fd = -1;
761 u->stream_fd = -1;
762 u->transport = (uint8_t) -1;
763 u->offset = 0;
764 u->latency = 0;
765 u->a2dp.sbc_initialized = FALSE;
766 u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
767 u->rtpoll = pa_rtpoll_new();
768 pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
769 u->rtpoll_item = NULL;
770 u->ss = m->core->default_sample_spec;
771
772 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
773 pa_log_error("Failed to parse module arguments");
774 goto fail;
775 }
776 if (!(u->name = pa_xstrdup(pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME)))) {
777 pa_log_error("Failed to get device name from module arguments");
778 goto fail;
779 }
780 if (!(u->addr = pa_xstrdup(pa_modargs_get_value(ma, "address", NULL)))) {
781 pa_log_error("Failed to get device address from module arguments");
782 goto fail;
783 }
784 if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
785 pa_log_error("Failed to get profile from module arguments");
786 goto fail;
787 }
788 if (pa_modargs_get_value_u32(ma, "rate", &u->ss.rate) < 0) {
789 pa_log_error("Failed to get rate from module arguments");
790 goto fail;
791 }
792
793 channels = u->ss.channels;
794 if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0) {
795 pa_log_error("Failed to get channels from module arguments");
796 goto fail;
797 }
798 u->ss.channels = (uint8_t) channels;
799
800 /* connect to the bluez audio service */
801 u->audioservice_fd = bt_audio_service_open();
802 if (u->audioservice_fd <= 0) {
803 pa_log_error("Couldn't connect to bluetooth audio service");
804 goto fail;
805 }
806 pa_log_debug("Connected to the bluetooth audio service");
807
808 /* queries device capabilities */
809 e = bt_getcaps(u);
810 if (e < 0) {
811 pa_log_error("Failed to get device capabilities");
812 goto fail;
813 }
814 pa_log_debug("Got device capabilities");
815
816 /* configures the connection */
817 e = bt_setconf(u);
818 if (e < 0) {
819 pa_log_error("Failed to set config");
820 goto fail;
821 }
822 pa_log_debug("Connection to the device configured");
823
824 /* gets the device socket */
825 e = bt_getstreamfd(u);
826 if (e < 0) {
827 pa_log_error("Failed to get stream fd (%d)", e);
828 goto fail;
829 }
830 pa_log_debug("Got the device socket");
831
832 /* create sink */
833 pa_sink_new_data_init(&data);
834 data.driver = __FILE__;
835 data.module = m;
836 pa_sink_new_data_set_name(&data, u->name);
837 pa_sink_new_data_set_sample_spec(&data, &u->ss);
838 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->name);
839 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Bluetooth %s '%s' (%s)", u->strtransport, u->name, u->addr);
840 pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile);
841 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_API, "bluez");
842 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
843 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_CONNECTOR, "bluetooth");
844 /* pa_proplist_setf(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, "headset"); /\*FIXME*\/ */
845 /* pa_proplist_setf(data.proplist, PA_PROP_DEVICE_VENDOR_PRODUCT_ID, "product_id"); /\*FIXME*\/ */
846 /* pa_proplist_setf(data.proplist, PA_PROP_DEVICE_SERIAL, "serial"); /\*FIXME*\/ */
847 u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
848 pa_sink_new_data_done(&data);
849 if (!u->sink) {
850 pa_log_error("Failed to create sink");
851 goto fail;
852 }
853 u->sink->userdata = u;
854 u->sink->parent.process_msg = sink_process_msg;
855 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
856 pa_sink_set_rtpoll(u->sink, u->rtpoll);
857
858 u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
859 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
860 pollfd->fd = u->stream_fd;
861 pollfd->events = pollfd->revents = 0;
862
863 /* start rt thread */
864 if (!(u->thread = pa_thread_new(thread_func, u))) {
865 pa_log_error("Failed to create IO thread");
866 goto fail;
867 }
868 pa_sink_put(u->sink);
869
870 pa_modargs_free(ma);
871 return 0;
872
873 fail:
874 if (ma)
875 pa_modargs_free(ma);
876
877 pa__done(m);
878 return -1;
879 }
880
881 void pa__done(pa_module *m) {
882 struct userdata *u;
883 pa_assert(m);
884
885 if (!(u = m->userdata))
886 return;
887
888 if (u->sink)
889 pa_sink_unlink(u->sink);
890
891 if (u->thread) {
892 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
893 pa_thread_free(u->thread);
894 }
895
896 if (u->sink)
897 pa_sink_unref(u->sink);
898
899 pa_thread_mq_done(&u->thread_mq);
900
901 if (u->rtpoll_item)
902 pa_rtpoll_item_free(u->rtpoll_item);
903
904 if (u->rtpoll)
905 pa_rtpoll_free(u->rtpoll);
906
907 if (u->smoother)
908 pa_smoother_free(u->smoother);
909
910 pa_xfree(u->name);
911 pa_xfree(u->addr);
912 pa_xfree(u->profile);
913 pa_xfree(u->strtransport);
914
915 if (u->stream_fd >= 0)
916 pa_close(u->stream_fd);
917
918 if (u->audioservice_fd >= 0)
919 pa_close(u->audioservice_fd);
920
921 pa_xfree(u);
922 }