Fix send and recv message sizes.
[profile/ivi/pulseaudio-panda.git] / 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     const char *type, *name;
126     uint16_t length;
127
128     length = msg->length ? msg->length : BT_SUGGESTED_BUFFER_SIZE;
129     type = bt_audio_strtype(msg->type);
130     name = bt_audio_strname(msg->name);
131     pa_log_debug("sending: %s -> %s", type, name);
132     if (send(sk, msg, length, 0) > 0)
133         e = 0;
134     else {
135         e = -errno;
136         pa_log_error("Error sending data to audio service: %s(%d)", pa_cstrerror(errno), errno);
137     }
138     return e;
139 }
140
141 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg, uint16_t expected_length) {
142     int e;
143     const char *type, *name;
144     uint16_t length;
145
146     length = expected_length ? expected_length : BT_SUGGESTED_BUFFER_SIZE;
147
148     pa_log_debug("trying to receive msg from audio service...");
149     if (recv(sk, inmsg, length, 0) > 0) {
150         type = bt_audio_strtype(inmsg->type);
151         name = bt_audio_strname(inmsg->name);
152         if (type && name) {
153             pa_log_debug("Received: %s <- %s", type, name);
154             e = 0;
155         }
156         else {
157             e = -EINVAL;
158             pa_log_error("Bogus message type %d name %d received from audio service",
159                         inmsg->type, inmsg->name);
160         }
161     }
162     else {
163         e = -errno;
164         pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
165     }
166
167     return e;
168 }
169
170 static int bt_audioservice_expect(int sk, bt_audio_msg_header_t *rsp, uint8_t expected_name, uint16_t expected_length) {
171     int e = bt_audioservice_recv(sk, rsp, expected_length);
172
173     if (e < 0) {
174         if (rsp->name != expected_name) {
175             e = -EINVAL;
176             pa_log_error("Bogus message %s received while %s was expected",
177                     bt_audio_strname(rsp->name),
178                     bt_audio_strname(expected_name));
179         }
180     }
181
182     if (rsp->type == BT_ERROR) {
183         bt_audio_error_t *error = (void *) rsp;
184         pa_log_error("%s failed : %s(%d)", bt_audio_strname(rsp->name), pa_cstrerror(error->posix_errno), error->posix_errno);
185         return -error->posix_errno;
186     }
187
188     return e;
189 }
190
191 static int bt_parsecaps(struct userdata *u, struct bt_get_capabilities_rsp *rsp) {
192     uint16_t bytes_left = rsp->h.length - sizeof(*rsp);
193     codec_capabilities_t *codec = (void *) rsp->data;
194
195     u->transport = codec->transport;
196
197     if (codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP)
198         return 0;
199
200     while (bytes_left > 0) {
201         if (codec->type == BT_A2DP_CODEC_SBC)
202             break;
203
204         bytes_left -= codec->length;
205         codec = (void *) (codec + codec->length);
206     }
207
208     if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
209         return -EINVAL;
210
211     memcpy(&u->a2dp.sbc_capabilities, codec, codec->length);
212
213     return 0;
214 }
215
216 static int bt_getcaps(struct userdata *u) {
217     int e;
218     union {
219         bt_audio_msg_header_t rsp;
220         struct bt_get_capabilities_req getcaps_req;
221         struct bt_get_capabilities_rsp getcaps_rsp;
222         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
223     } msg;
224
225     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
226     msg.getcaps_req.h.type = BT_REQUEST;
227     msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
228     msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
229
230     strncpy(msg.getcaps_req.device, u->addr, 18);
231     if (strcasecmp(u->profile, "a2dp") == 0)
232         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
233     else if (strcasecmp(u->profile, "hsp") == 0)
234         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
235     else {
236         pa_log_error("Invalid profile argument: %s", u->profile);
237         return -1;
238     }
239     msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
240
241     e = bt_audioservice_send(u->audioservice_fd, &msg.getcaps_req.h);
242     if (e < 0) {
243         pa_log_error("Failed to send GETCAPABILITIES_REQ");
244         return e;
245     }
246
247     e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp, BT_GET_CAPABILITIES, 0);
248     if (e < 0) {
249         pa_log_error("Failed to expect for GETCAPABILITIES_RSP");
250         return e;
251     }
252
253     return bt_parsecaps(u, &msg.getcaps_rsp);
254 }
255
256 static uint8_t default_bitpool(uint8_t freq, uint8_t mode) {
257     switch (freq) {
258         case BT_SBC_SAMPLING_FREQ_16000:
259         case BT_SBC_SAMPLING_FREQ_32000:
260             return 53;
261         case BT_SBC_SAMPLING_FREQ_44100:
262             switch (mode) {
263                 case BT_A2DP_CHANNEL_MODE_MONO:
264                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
265                     return 31;
266                 case BT_A2DP_CHANNEL_MODE_STEREO:
267                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
268                     return 53;
269                 default:
270                     pa_log_warn("Invalid channel mode %u", mode);
271                     return 53;
272             }
273         case BT_SBC_SAMPLING_FREQ_48000:
274             switch (mode) {
275                 case BT_A2DP_CHANNEL_MODE_MONO:
276                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
277                     return 29;
278                 case BT_A2DP_CHANNEL_MODE_STEREO:
279                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
280                     return 51;
281                 default:
282                     pa_log_warn("Invalid channel mode %u", mode);
283                     return 51;
284             }
285         default:
286             pa_log_warn("Invalid sampling freq %u", freq);
287             return 53;
288     }
289 }
290
291 static int bt_a2dp_init(struct userdata *u) {
292     sbc_capabilities_t *cap = &u->a2dp.sbc_capabilities;
293     uint8_t max_bitpool, min_bitpool;
294     unsigned i;
295
296     static const struct {
297         uint32_t rate;
298         uint8_t cap;
299     } freq_table[] = {
300         { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
301         { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
302         { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
303         { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
304     };
305
306     /* Find the lowest freq that is at least as high as the requested
307      * sampling rate */
308     for (i = 0; i < PA_ELEMENTSOF(freq_table); i++)
309         if (freq_table[i].rate >= u->ss.rate || i == PA_ELEMENTSOF(freq_table)-1 ) {
310             u->ss.rate = freq_table[i].rate;
311             cap->frequency = freq_table[i].cap;
312             break;
313         }
314
315     if (u->ss.channels >= 2) {
316         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
317             cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
318         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
319             cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
320         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
321             cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
322
323         u->ss.channels = 2;
324     } else {
325         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
326             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
327     }
328
329     if (!cap->channel_mode) {
330         pa_log_error("No supported channel modes");
331         return -1;
332     }
333
334     if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
335         cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
336     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
337         cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
338     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
339         cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
340     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
341         cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
342     else {
343         pa_log_error("No supported block lengths");
344         return -1;
345     }
346
347     if (cap->subbands & BT_A2DP_SUBBANDS_8)
348         cap->subbands = BT_A2DP_SUBBANDS_8;
349     else if (cap->subbands & BT_A2DP_SUBBANDS_4)
350         cap->subbands = BT_A2DP_SUBBANDS_4;
351     else {
352         pa_log_error("No supported subbands");
353         return -1;
354     }
355
356     if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
357         cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
358     else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
359         cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
360
361     min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
362     max_bitpool = (uint8_t) PA_MIN(default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
363
364     cap->min_bitpool = (uint8_t) min_bitpool;
365     cap->max_bitpool = (uint8_t) max_bitpool;
366
367     return 0;
368 }
369
370 static void bt_a2dp_setup(struct bt_a2dp *a2dp) {
371     sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
372
373     if (a2dp->sbc_initialized)
374         sbc_reinit(&a2dp->sbc, 0);
375     else
376         sbc_init(&a2dp->sbc, 0);
377     a2dp->sbc_initialized = TRUE;
378
379     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
380         a2dp->sbc.frequency = SBC_FREQ_16000;
381
382     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
383         a2dp->sbc.frequency = SBC_FREQ_32000;
384
385     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
386         a2dp->sbc.frequency = SBC_FREQ_44100;
387
388     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
389         a2dp->sbc.frequency = SBC_FREQ_48000;
390
391     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
392         a2dp->sbc.mode = SBC_MODE_MONO;
393
394     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
395         a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
396
397     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
398         a2dp->sbc.mode = SBC_MODE_STEREO;
399
400     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
401         a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
402
403     a2dp->sbc.allocation = (uint8_t) (active_capabilities.allocation_method == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR : SBC_AM_LOUDNESS);
404
405     switch (active_capabilities.subbands) {
406         case BT_A2DP_SUBBANDS_4:
407             a2dp->sbc.subbands = SBC_SB_4;
408             break;
409         case BT_A2DP_SUBBANDS_8:
410             a2dp->sbc.subbands = SBC_SB_8;
411             break;
412     }
413
414     switch (active_capabilities.block_length) {
415         case BT_A2DP_BLOCK_LENGTH_4:
416             a2dp->sbc.blocks = SBC_BLK_4;
417             break;
418         case BT_A2DP_BLOCK_LENGTH_8:
419             a2dp->sbc.blocks = SBC_BLK_8;
420             break;
421         case BT_A2DP_BLOCK_LENGTH_12:
422             a2dp->sbc.blocks = SBC_BLK_12;
423             break;
424         case BT_A2DP_BLOCK_LENGTH_16:
425             a2dp->sbc.blocks = SBC_BLK_16;
426             break;
427     }
428
429     a2dp->sbc.bitpool = active_capabilities.max_bitpool;
430     a2dp->codesize = (uint16_t) sbc_get_codesize(&a2dp->sbc);
431     a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
432 }
433
434 static int bt_setconf(struct userdata *u) {
435     int e;
436     union {
437         bt_audio_msg_header_t rsp;
438         struct bt_set_configuration_req setconf_req;
439         struct bt_set_configuration_rsp setconf_rsp;
440         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
441     } msg;
442
443     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
444         e = bt_a2dp_init(u);
445         if (e < 0) {
446             pa_log_error("a2dp_init error");
447             return e;
448         }
449         u->ss.format = PA_SAMPLE_S16LE;
450     }
451     else
452         u->ss.format = PA_SAMPLE_U8;
453
454     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
455     msg.setconf_req.h.type = BT_REQUEST;
456     msg.setconf_req.h.name = BT_SET_CONFIGURATION;
457     msg.setconf_req.h.length = sizeof(msg.setconf_req);
458
459     strncpy(msg.setconf_req.device, u->addr, 18);
460     msg.setconf_req.codec.transport = u->transport;
461     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
462         memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities,
463                 sizeof(u->a2dp.sbc_capabilities));
464     msg.setconf_req.access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE;
465
466     e = bt_audioservice_send(u->audioservice_fd, &msg.setconf_req.h);
467     if (e < 0) {
468         pa_log_error("Failed to send BT_SETCONFIGURATION_REQ");
469         return e;
470     }
471
472     e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp, BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp));
473     if (e < 0) {
474         pa_log_error("Failed to expect BT_SETCONFIGURATION_RSP");
475         return e;
476     }
477
478     u->transport = msg.setconf_rsp.transport;
479     u->strtransport = (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP ? pa_xstrdup("A2DP") : pa_xstrdup("SCO"));
480     u->link_mtu = msg.setconf_rsp.link_mtu;
481
482     /* setup SBC encoder now we agree on parameters */
483     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
484         bt_a2dp_setup(&u->a2dp);
485         u->block_size = u->a2dp.codesize;
486         pa_log_info("sbc parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
487                 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
488     }
489     else
490         u->block_size = u->link_mtu;
491
492     return 0;
493 }
494
495 static int bt_getstreamfd(struct userdata *u) {
496     int e;
497 //    uint32_t period_count = io->buffer_size / io->period_size;
498     union {
499         bt_audio_msg_header_t rsp;
500         struct bt_start_stream_req start_req;
501         struct bt_start_stream_rsp start_rsp;
502         struct bt_new_stream_ind streamfd_ind;
503         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
504     } msg;
505
506     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
507     msg.start_req.h.type = BT_REQUEST;
508     msg.start_req.h.name = BT_START_STREAM;
509     msg.start_req.h.length = sizeof(msg.start_req);
510
511     e = bt_audioservice_send(u->audioservice_fd, &msg.start_req.h);
512     if (e < 0) {
513         pa_log_error("Failed to send BT_STREAMSTART_REQ");
514         return e;
515     }
516
517     e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp, BT_START_STREAM, sizeof(msg.start_rsp));
518     if (e < 0) {
519         pa_log_error("Failed to expect BT_STREAMSTART_RSP");
520         return e;
521     }
522
523     e = bt_audioservice_expect(u->audioservice_fd, &msg.rsp, BT_NEW_STREAM, sizeof(msg.streamfd_ind));
524     if (e < 0) {
525         pa_log_error("Failed to expect BT_STREAMFD_IND");
526         return e;
527     }
528
529     if (u->stream_fd >= 0)
530         pa_close(u->stream_fd);
531
532     u->stream_fd = bt_audio_service_get_data_fd(u->audioservice_fd);
533     if (u->stream_fd < 0) {
534         pa_log_error("Failed to get data fd: %s (%d)",pa_cstrerror(errno), errno);
535         return -errno;
536     }
537
538 //   if (setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)) == 0)
539 //       return 0;
540 //   if (setsockopt(u->stream_fd, SOL_SCO, SO_SNDBUF, &period_count, sizeof(period_count)) == 0)
541 //       return 0;
542 //   /* FIXME : handle error codes */
543     pa_make_fd_nonblock(u->stream_fd);
544 //    pa_make_socket_low_delay(u->stream_fd);
545
546     return 0;
547 }
548
549 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
550     struct userdata *u = PA_SINK(o)->userdata;
551
552     pa_log_debug("got message: %d", code);
553     switch (code) {
554
555         case PA_SINK_MESSAGE_SET_STATE:
556             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
557                 case PA_SINK_SUSPENDED:
558                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
559                     pa_smoother_pause(u->smoother, pa_rtclock_usec());
560                     break;
561                 case PA_SINK_IDLE:
562                 case PA_SINK_RUNNING:
563                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
564                         pa_smoother_resume(u->smoother, pa_rtclock_usec());
565                     break;
566                 case PA_SINK_UNLINKED:
567                 case PA_SINK_INIT:
568                     ;
569             }
570             break;
571
572         case PA_SINK_MESSAGE_GET_LATENCY: {
573             pa_usec_t w, r;
574 /*             r = pa_smoother_get(u->smoother, pa_rtclock_usec()); */
575 /* /\*             w = pa_bytes_to_usec(u->offset + (uint64_t) u->memchunk.length, &u->sink->sample_spec); *\/ */
576             *((pa_usec_t*) data) = /*w > r ? w - r :*/ 0;
577             return 0;
578         }
579
580     }
581
582     return pa_sink_process_msg(o, code, data, offset, chunk);
583 }
584
585 static int sco_process_render(struct userdata *u) {
586     void *p;
587     int ret = 0;
588     pa_memchunk memchunk;
589
590     pa_sink_render_full(u->sink, u->block_size, &memchunk);
591
592     p = pa_memblock_acquire(memchunk.memblock);
593
594     for (;;) {
595         ssize_t l;
596
597         l = pa_loop_write(u->stream_fd, (uint8_t*) p, memchunk.length, NULL);
598         pa_log_debug("Memblock written to socket: %li bytes", (long) l);
599
600         pa_assert(l != 0);
601
602         if (l > 0) {
603             u->offset += (uint64_t) l;
604             break;
605         }
606
607         if (errno == EINTR)
608             pa_log_debug("EINTR");
609         else if (errno == EAGAIN)
610             pa_log_debug("EAGAIN");
611         else {
612             pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
613             ret = -1;
614             break;
615         }
616     }
617
618     pa_memblock_release(memchunk.memblock);
619     pa_memblock_unref(memchunk.memblock);
620
621     return ret;
622 }
623
624 static int a2dp_process_render(struct userdata *u) {
625     int written;
626
627     struct bt_a2dp *a2dp = &u->a2dp;
628     struct rtp_header *header = (void *) a2dp->buffer;
629     struct rtp_payload *payload = (void *) (a2dp->buffer + sizeof(*header));
630
631     pa_assert(u);
632
633     do {
634         /* Render some data */
635         int frame_size, encoded;
636         void *p;
637         pa_memchunk memchunk;
638
639         pa_sink_render_full(u->sink, u->block_size, &memchunk);
640
641         p = pa_memblock_acquire(memchunk.memblock);
642
643         frame_size = (uint16_t) sbc_get_frame_length(&a2dp->sbc);
644         pa_log_debug("SBC frame_size: %d", frame_size);
645
646         encoded = sbc_encode(&a2dp->sbc, p, (int) a2dp->codesize, a2dp->buffer + a2dp->count,
647                              (int) (sizeof(a2dp->buffer) - a2dp->count), &written);
648         pa_log_debug("SBC: encoded: %d; written: %d", encoded, written);
649
650         pa_memblock_release(memchunk.memblock);
651         pa_memblock_unref(memchunk.memblock);
652
653         if (encoded <= 0) {
654             pa_log_error("SBC encoding error (%d)", encoded);
655             return -1;
656         }
657
658         a2dp->count += (size_t) written;
659         a2dp->frame_count++;
660         a2dp->samples += (unsigned) encoded / frame_size;
661         a2dp->total_samples += (unsigned) encoded / frame_size;
662
663     } while (a2dp->count + (size_t) written <= u->link_mtu);
664
665     /* write it to the fifo */
666     memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
667     payload->frame_count = a2dp->frame_count;
668     header->v = 2;
669     header->pt = 1;
670     header->sequence_number = htons(a2dp->seq_num);
671     header->timestamp = htonl(a2dp->total_samples);
672     header->ssrc = htonl(1);
673
674     for (;;) {
675         ssize_t l;
676
677         l = pa_loop_write(u->stream_fd, a2dp->buffer, a2dp->count, NULL);
678         pa_log_debug("avdtp_write: requested %lu bytes; written %li bytes", (unsigned long) a2dp->count, (long) l);
679
680         pa_assert(l != 0);
681
682         if (l > 0)
683             break;
684
685         if (errno == EINTR)
686             pa_log_debug("EINTR");
687         else if (errno == EAGAIN)
688             pa_log_debug("EAGAIN");
689         else {
690             pa_log_error("Failed to write data to FIFO: %s", pa_cstrerror(errno));
691             return -1;
692         }
693     }
694
695     u->offset += a2dp->codesize*a2dp->frame_count;
696
697     /* Reset buffer of data to send */
698     a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
699     a2dp->frame_count = 0;
700     a2dp->samples = 0;
701     a2dp->seq_num++;
702
703     return 0;
704 }
705
706 static void thread_func(void *userdata) {
707     struct userdata *u = userdata;
708
709     pa_assert(u);
710
711     pa_log_debug("IO Thread starting up");
712
713     if (u->core->realtime_scheduling)
714         pa_make_realtime(u->core->realtime_priority);
715
716     pa_thread_mq_install(&u->thread_mq);
717     pa_rtpoll_install(u->rtpoll);
718
719     pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
720
721     for (;;) {
722         int ret, l;
723         struct pollfd *pollfd;
724         uint64_t n;
725         pa_usec_t usec;
726
727         if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
728             if (u->sink->thread_info.rewind_requested)
729                 pa_sink_process_rewind(u->sink, 0);
730
731         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
732
733         if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
734             if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
735                 if ((l = a2dp_process_render(u)) < 0)
736                     goto fail;
737             } else {
738                 if ((l = sco_process_render(u)) < 0)
739                     goto fail;
740             }
741             pollfd->revents = 0;
742
743             /* feed the time smoother */
744             n = u->offset;
745             if (ioctl(u->stream_fd, SIOCOUTQ, &l) >= 0 && l > 0)
746                 n -= (uint64_t) l;
747             usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
748             if (usec > u->latency)
749                 usec -= u->latency;
750             else
751                 usec = 0;
752             pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
753         }
754
755         /* Hmm, nothing to do. Let's sleep */
756         pa_log_debug("IO thread going to sleep");
757         pollfd->events = (short) (PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0);
758         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
759             pa_log_error("rtpoll_run < 0");
760             goto fail;
761         }
762         pa_log_debug("IO thread waking up");
763
764         if (ret == 0) {
765             pa_log_debug("rtpoll_run == 0");
766             goto finish;
767         }
768
769         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
770         if (pollfd->revents & ~POLLOUT) {
771             pa_log_error("FIFO shutdown.");
772             goto fail;
773         }
774     }
775
776 fail:
777     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
778     pa_log_debug("IO thread failed");
779     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
780     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
781
782 finish:
783     pa_log_debug("IO thread shutting down");
784 }
785
786 int pa__init(pa_module* m) {
787     int e;
788     pa_modargs *ma;
789     uint32_t channels;
790     pa_sink_new_data data;
791     struct pollfd *pollfd;
792     struct userdata *u;
793
794     pa_assert(m);
795     m->userdata = u = pa_xnew0(struct userdata, 1);
796     u->module = m;
797     u->core = m->core;
798     u->audioservice_fd = -1;
799     u->stream_fd = -1;
800     u->transport = (uint8_t) -1;
801     u->offset = 0;
802     u->latency = 0;
803     u->a2dp.sbc_initialized = FALSE;
804     u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
805     u->rtpoll = pa_rtpoll_new();
806     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
807     u->rtpoll_item = NULL;
808     u->ss = m->core->default_sample_spec;
809
810     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
811         pa_log_error("Failed to parse module arguments");
812         goto fail;
813     }
814     if (!(u->name = pa_xstrdup(pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME)))) {
815         pa_log_error("Failed to get device name from module arguments");
816         goto fail;
817     }
818     if (!(u->addr = pa_xstrdup(pa_modargs_get_value(ma, "address", NULL)))) {
819         pa_log_error("Failed to get device address from module arguments");
820         goto fail;
821     }
822     if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
823         pa_log_error("Failed to get profile from module arguments");
824         goto fail;
825     }
826     if (pa_modargs_get_value_u32(ma, "rate", &u->ss.rate) < 0) {
827         pa_log_error("Failed to get rate from module arguments");
828         goto fail;
829     }
830
831     channels = u->ss.channels;
832     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0) {
833         pa_log_error("Failed to get channels from module arguments");
834         goto fail;
835     }
836     u->ss.channels = (uint8_t) channels;
837
838     /* connect to the bluez audio service */
839     u->audioservice_fd = bt_audio_service_open();
840     if (u->audioservice_fd <= 0) {
841         pa_log_error("Couldn't connect to bluetooth audio service");
842         goto fail;
843     }
844     pa_log_debug("Connected to the bluetooth audio service");
845
846     /* queries device capabilities */
847     e = bt_getcaps(u);
848     if (e < 0) {
849         pa_log_error("Failed to get device capabilities");
850         goto fail;
851     }
852     pa_log_debug("Got device capabilities");
853
854     /* configures the connection */
855     e = bt_setconf(u);
856     if (e < 0) {
857         pa_log_error("Failed to set config");
858         goto fail;
859     }
860     pa_log_debug("Connection to the device configured");
861
862     /* gets the device socket */
863     e = bt_getstreamfd(u);
864     if (e < 0) {
865         pa_log_error("Failed to get stream fd (%d)", e);
866         goto fail;
867     }
868     pa_log_debug("Got the device socket");
869
870     /* create sink */
871     pa_sink_new_data_init(&data);
872     data.driver = __FILE__;
873     data.module = m;
874     pa_sink_new_data_set_name(&data, u->name);
875     pa_sink_new_data_set_sample_spec(&data, &u->ss);
876     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->name);
877     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Bluetooth %s '%s' (%s)", u->strtransport, u->name, u->addr);
878     pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile);
879     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_API, "bluez");
880     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
881     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_CONNECTOR, "bluetooth");
882 /*     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, "headset"); /\*FIXME*\/ */
883 /*     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_VENDOR_PRODUCT_ID, "product_id"); /\*FIXME*\/ */
884 /*     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_SERIAL, "serial"); /\*FIXME*\/ */
885     u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
886     pa_sink_new_data_done(&data);
887     if (!u->sink) {
888         pa_log_error("Failed to create sink");
889         goto fail;
890     }
891     u->sink->userdata = u;
892     u->sink->parent.process_msg = sink_process_msg;
893     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
894     pa_sink_set_rtpoll(u->sink, u->rtpoll);
895
896     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
897     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
898     pollfd->fd = u->stream_fd;
899     pollfd->events = pollfd->revents = 0;
900
901     /* start rt thread */
902     if (!(u->thread = pa_thread_new(thread_func, u))) {
903         pa_log_error("Failed to create IO thread");
904         goto fail;
905     }
906     pa_sink_put(u->sink);
907
908     pa_modargs_free(ma);
909     return 0;
910
911 fail:
912     if (ma)
913         pa_modargs_free(ma);
914
915     pa__done(m);
916     return -1;
917 }
918
919 void pa__done(pa_module *m) {
920     struct userdata *u;
921     pa_assert(m);
922
923     if (!(u = m->userdata))
924         return;
925
926     if (u->sink)
927         pa_sink_unlink(u->sink);
928
929     if (u->thread) {
930         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
931         pa_thread_free(u->thread);
932     }
933
934     if (u->sink)
935         pa_sink_unref(u->sink);
936
937     pa_thread_mq_done(&u->thread_mq);
938
939     if (u->rtpoll_item)
940         pa_rtpoll_item_free(u->rtpoll_item);
941
942     if (u->rtpoll)
943         pa_rtpoll_free(u->rtpoll);
944
945     if (u->smoother)
946         pa_smoother_free(u->smoother);
947
948     pa_xfree(u->name);
949     pa_xfree(u->addr);
950     pa_xfree(u->profile);
951     pa_xfree(u->strtransport);
952
953     if (u->stream_fd >= 0)
954         pa_close(u->stream_fd);
955
956     if (u->audioservice_fd >= 0)
957         pa_close(u->audioservice_fd);
958
959     pa_xfree(u);
960 }