053ef080c7511bdc7c34b1eb91b3f385731bd707
[profile/ivi/pulseaudio-panda.git] / src / modules / module-bt-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
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>
43
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"
49
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
57
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>");
66
67 struct bt_a2dp {
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 */
75
76     int nsamples;                        /* Cumulative number of codec samples */
77     uint16_t seq_num;                    /* Cumulative packet sequence */
78     int frame_count;                     /* Current frames in buffer*/
79 };
80
81 struct userdata {
82     pa_core *core;
83     pa_module *module;
84     pa_sink *sink;
85
86     pa_thread_mq thread_mq;
87     pa_rtpoll *rtpoll;
88     pa_rtpoll_item *rtpoll_item;
89     pa_thread *thread;
90
91     int64_t offset;
92     pa_smoother *smoother;
93
94     pa_memchunk memchunk;
95     pa_mempool *mempool;
96
97     const char *name;
98     const char *addr;
99     const char *profile;
100     int rate;
101     int channels;
102     pa_sample_spec ss;
103
104     int audioservice_fd;
105     int stream_fd;
106
107     int transport;
108     int link_mtu;
109     size_t block_size;
110     pa_usec_t latency;
111
112     struct bt_a2dp a2dp;
113 };
114
115 static const char* const valid_modargs[] = {
116     "name",
117     "addr",
118     "profile",
119     "rate",
120     "channels",
121     NULL
122 };
123
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);
132     }
133     return e;
134 }
135
136 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg) {
137     int e;
138     const char *type;
139
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;
146         }
147         else {
148             e = -EINVAL;
149             pa_log_error("Bogus message type %d received from audio service", inmsg->msg_type);
150         }
151     }
152     else {
153         e = -errno;
154         pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
155     }
156
157     return e;
158 }
159
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));
167         }
168     }
169     return e;
170 }
171
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;
178
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;
189     }
190     getcaps_req->flags = 0;
191     getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
192
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;
197     }
198
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;
203     }
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;
207     }
208
209     if ((u->transport = getcaps_rsp->transport) == BT_CAPABILITIES_TRANSPORT_A2DP)
210         u->a2dp.sbc_capabilities = 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     unsigned int max_bitpool, min_bitpool;
253
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;
270     }
271
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;
285     }
286
287     if (!cap->channel_mode) {
288         pa_log_error("No supported channel modes");
289         return -1;
290     }
291
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;
306     }
307
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;
317     }
318
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;
325
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 //    }
332
333     cap->min_bitpool = min_bitpool;
334     cap->max_bitpool = max_bitpool;
335
336     return 0;
337 }
338
339 static void bt_a2dp_setup(struct bt_a2dp *a2dp) {
340     sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
341
342     if (a2dp->sbc_initialized)
343         sbc_reinit(&a2dp->sbc, 0);
344     else
345         sbc_init(&a2dp->sbc, 0);
346     a2dp->sbc_initialized = TRUE;
347
348     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
349         a2dp->sbc.frequency = SBC_FREQ_16000;
350
351     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
352         a2dp->sbc.frequency = SBC_FREQ_32000;
353
354     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
355         a2dp->sbc.frequency = SBC_FREQ_44100;
356
357     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
358         a2dp->sbc.frequency = SBC_FREQ_48000;
359
360     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
361         a2dp->sbc.mode = SBC_MODE_MONO;
362
363     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
364         a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
365
366     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
367         a2dp->sbc.mode = SBC_MODE_STEREO;
368
369     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
370         a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
371
372     a2dp->sbc.allocation = (active_capabilities.allocation_method == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR : SBC_AM_LOUDNESS);
373
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;
381     }
382
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;
396     }
397
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);
401 }
402
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;
409
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;
415         }
416         u->ss.format = PA_SAMPLE_S16LE;
417     }
418     else
419         u->ss.format = PA_SAMPLE_U8;
420
421     u->ss.rate = u->rate;
422     u->ss.channels = u->channels;
423
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;
431
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;
436     }
437
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;
442     }
443
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;
447     }
448
449     u->transport = setconf_rsp->transport;
450     u->link_mtu = setconf_rsp->link_mtu;
451
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);
458     }
459     else
460         u->block_size = u->link_mtu;
461
462     return 0;
463 }
464
465 static int bt_getstreamfd(struct userdata *u) {
466     int e;
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;
472
473     memset(start_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
474     start_req->h.msg_type = BT_STREAMSTART_REQ;
475
476     e = bt_audioservice_send(u->audioservice_fd, &start_req->h);
477     if (e < 0) {
478         pa_log_error("failed to send BT_STREAMSTART_REQ");
479         return e;
480     }
481
482     e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_STREAMSTART_RSP);
483     if (e < 0) {
484         pa_log_error("failed to expect BT_STREAMSTART_RSP");
485         return e;
486     }
487
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;
491     }
492
493     e = bt_audioservice_expect(u->audioservice_fd, &streamfd_ind->h, BT_STREAMFD_IND);
494     if (e < 0) {
495         pa_log_error("failed to expect BT_STREAMFD_IND");
496         return e;
497     }
498
499     if (u->stream_fd >= 0)
500         pa_close(u->stream_fd);
501
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);
505         return -errno;
506     }
507
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);
511             return -errno;
512         }
513     }
514
515 //   if (setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)) == 0)
516 //       return 0;
517 //   if (setsockopt(u->stream_fd, SOL_SCO, SO_SNDBUF, &period_count, sizeof(period_count)) == 0)
518 //       return 0;
519 //   /* FIXME : handle error codes */
520     pa_make_fd_nonblock(u->stream_fd);
521 //    pa_make_socket_low_delay(u->stream_fd);
522
523     return 0;
524 }
525
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;
528
529     pa_log_debug("got message: %d", code);
530     switch (code) {
531
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());
537                     break;
538                 case PA_SINK_IDLE:
539                 case PA_SINK_RUNNING:
540                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
541                         pa_smoother_resume(u->smoother, pa_rtclock_usec());
542                     break;
543                 case PA_SINK_UNLINKED:
544                 case PA_SINK_INIT:
545                     ;
546             }
547             break;
548
549         case PA_SINK_MESSAGE_GET_LATENCY: {
550             pa_usec_t w, r;
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;
554             return 0;
555         }
556
557     }
558
559     return pa_sink_process_msg(o, code, data, offset, chunk);
560 }
561
562 static void sco_thread_func(void *userdata) {
563     struct userdata *u = userdata;
564     int write_type = 0;
565
566     pa_assert(u);
567
568     pa_log_debug("SCO thread starting up");
569
570     pa_thread_mq_install(&u->thread_mq);
571     pa_rtpoll_install(u->rtpoll);
572
573     pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
574
575     for (;;) {
576         int ret;
577         struct pollfd *pollfd;
578
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);
582             }
583         }
584
585         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
586
587         if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
588             pa_usec_t usec;
589             int64_t n;
590
591             for (;;) {
592                 /* Render some data and write it to the fifo */
593                 ssize_t l;
594                 void *p;
595
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);
601
602                 pa_assert(u->memchunk.length > 0);
603
604                 p = pa_memblock_acquire(u->memchunk.memblock);
605
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");
612
613                 pa_assert(l != 0);
614
615                 if (l < 0) {
616                     if (errno == EINTR) {
617                         pa_log_debug("EINTR");
618                         continue;
619                     }
620                     else if (errno == EAGAIN) {
621                         pa_log_debug("EAGAIN");
622                         goto filled_up;
623                     }
624                     else {
625                         pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
626                         goto fail;
627                     }
628                 } else {
629                     u->offset += l;
630                     pollfd->revents = 0;
631                 }
632             }
633
634 filled_up:
635             n = u->offset;
636 #ifdef SIOCOUTQ
637             {
638                 int l;
639                 if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
640                     n -= l;
641             }
642 #endif
643             usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
644             if (usec > u->latency)
645                 usec -= u->latency;
646             else
647                 usec = 0;
648             pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
649         }
650
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");
656             goto fail;
657         }
658         pa_log_debug("SCO thread waking up");
659
660         if (ret == 0) {
661             pa_log_debug("rtpoll_run == 0");
662             goto finish;
663         }
664
665         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
666         if (pollfd->revents & ~POLLOUT) {
667             pa_log_error("FIFO shutdown.");
668             goto fail;
669         }
670     }
671
672 fail:
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);
677
678 finish:
679     pa_log_debug("SCO thread shutting down");
680 }
681
682 static void a2dp_thread_func(void *userdata) {
683     struct userdata *u = userdata;
684
685     pa_assert(u);
686
687     pa_log_debug("A2DP Thread starting up");
688
689     pa_thread_mq_install(&u->thread_mq);
690     pa_rtpoll_install(u->rtpoll);
691
692     pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
693
694     for (;;) {
695         int ret;
696         struct pollfd *pollfd;
697
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);
701             }
702         }
703
704         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
705
706         if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
707             pa_usec_t usec;
708             int64_t n;
709             ssize_t l;
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));
714
715             do {
716                 /* Render some data */
717                 int frame_size, encoded;
718                 void *p;
719
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);
725
726                 pa_assert(u->memchunk.length > 0);
727
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);
731
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);
735                 if (encoded <= 0) {
736                     pa_log_error("SBC encoding error (%d)", encoded);
737                     goto fail;
738                 }
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");
743
744                 a2dp->count += written;
745                 a2dp->frame_count++;
746                 a2dp->samples += encoded / frame_size;
747                 a2dp->nsamples += encoded / frame_size;
748
749             } while (a2dp->count + written <= u->link_mtu);
750
751             /* write it to the fifo */
752             memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
753             payload->frame_count = a2dp->frame_count;
754             header->v = 2;
755             header->pt = 1;
756             header->sequence_number = htons(a2dp->seq_num);
757             header->timestamp = htonl(a2dp->nsamples);
758             header->ssrc = htonl(1);
759
760 avdtp_write:
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);
763
764             pa_assert(l != 0);
765
766             if (l < 0) {
767                 if (errno == EINTR) {
768                     pa_log_debug("EINTR");
769                     continue;
770                 }
771                 else if (errno == EAGAIN) {
772                     pa_log_debug("EAGAIN");
773                     goto avdtp_write;
774                 }
775                 else {
776                     pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
777                     goto fail;
778                 }
779             }
780
781             u->offset += a2dp->codesize*a2dp->frame_count;
782             pollfd->revents = 0;
783
784             /* Reset buffer of data to send */
785             a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
786             a2dp->frame_count = 0;
787             a2dp->samples = 0;
788             a2dp->seq_num++;
789
790             /* feed the time smoother */
791             n = u->offset;
792 #ifdef SIOCOUTQ
793             {
794                 int ll;
795                 if (ioctl(u->fd, SIOCOUTQ, &ll) >= 0 && ll > 0)
796                     n -= ll;
797             }
798 #endif
799             usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
800             if (usec > u->latency)
801                 usec -= u->latency;
802             else
803                 usec = 0;
804             pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
805         }
806
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");
812             goto fail;
813         }
814         pa_log_debug("A2DP thread waking up");
815
816         if (ret == 0) {
817             pa_log_debug("rtpoll_run == 0");
818             goto finish;
819         }
820
821         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
822         if (pollfd->revents & ~POLLOUT) {
823             pa_log_error("FIFO shutdown.");
824             goto fail;
825         }
826     }
827
828 fail:
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);
833
834 finish:
835     pa_log_debug("A2DP thread shutting down");
836 }
837
838 int pa__init(pa_module* m) {
839     int e;
840     const char *rate, *channels;
841     pa_modargs *ma;
842     pa_sink_new_data data;
843     struct pollfd *pollfd;
844     struct userdata *u;
845
846     pa_assert(m);
847     m->userdata = u = pa_xnew0(struct userdata, 1);
848     u->module = m;
849     u->core = m->core;
850     u->audioservice_fd = -1;
851     u->stream_fd = -1;
852     u->transport = -1;
853     u->offset = 0;
854     u->latency = 0;
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;
862
863     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
864         pa_log_error("failed to parse module arguments");
865         goto fail;
866     }
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");
869         goto fail;
870     }
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");
873         goto fail;
874     }
875     if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
876         pa_log_error("failed to get profile from module arguments");
877         goto fail;
878     }
879     if (pa_modargs_get_value_u32(ma, "rate", &u->rate) < 0) {
880         pa_log_error("failed to get rate from module arguments");
881         goto fail;
882     }
883     if (pa_modargs_get_value_u32(ma, "channels", &u->channels) < 0) {
884         pa_log_error("failed to get channels from module arguments");
885         goto fail;
886     }
887
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");
892         goto fail;
893     }
894     pa_log_debug("connected to the bluetooth audio service");
895
896     /* queries device capabilities */
897     e = bt_getcaps(u);
898     if (e < 0) {
899         pa_log_error("failed to get device capabilities");
900         goto fail;
901     }
902     pa_log_debug("got device capabilities");
903
904     /* configures the connection */
905     e = bt_setconf(u);
906     if (e < 0) {
907         pa_log_error("failed to set config");
908         goto fail;
909     }
910     pa_log_debug("connection to the device configured");
911
912     /* gets the device socket */
913     e = bt_getstreamfd(u);
914     if (e < 0) {
915         pa_log_error("failed to get stream fd (%d)", e);
916         goto fail;
917     }
918     pa_log_debug("got the device socket");
919
920     /* create sink */
921     pa_sink_new_data_init(&data);
922     data.driver = __FILE__;
923     data.module = m;
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);
930     if (!u->sink) {
931         pa_log_error("failed to create sink");
932         goto fail;
933     }
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);
938
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;
943
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");
948             goto fail;
949         }
950     }
951     else {
952         if (!(u->thread = pa_thread_new(sco_thread_func, u))) {
953             pa_log_error("failed to create SCO thread");
954             goto fail;
955         }
956     }
957     pa_sink_put(u->sink);
958
959     pa_modargs_free(ma);
960     return 0;
961
962 fail:
963     if (ma)
964         pa_modargs_free(ma);
965     pa__done(m);
966     return -1;
967 }
968
969 void pa__done(pa_module *m) {
970     struct userdata *u;
971     pa_assert(m);
972
973     if (!(u = m->userdata))
974         return;
975
976     if (u->sink)
977         pa_sink_unlink(u->sink);
978
979     if (u->thread) {
980         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
981         pa_thread_free(u->thread);
982     }
983
984     pa_thread_mq_done(&u->thread_mq);
985
986     if (u->sink)
987         pa_sink_unref(u->sink);
988
989     if (u->rtpoll_item)
990         pa_rtpoll_item_free(u->rtpoll_item);
991
992     if (u->rtpoll)
993         pa_rtpoll_free(u->rtpoll);
994
995     if (u->memchunk.memblock)
996         pa_memblock_unref(u->memchunk.memblock);
997
998     if (u->smoother)
999         pa_smoother_free(u->smoother);
1000
1001     if (u->stream_fd >= 0)
1002         pa_close(u->stream_fd);
1003
1004     if (u->audioservice_fd >= 0)
1005         pa_close(u->audioservice_fd);
1006
1007     pa_xfree(u);
1008 }