3a756847bd31a3141335e90ac1eb77a00d6d772e
[profile/ivi/pulseaudio.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/core-error.h>
34 #include <pulsecore/module.h>
35 #include <pulsecore/modargs.h>
36 #include <pulsecore/thread.h>
37 #include <pulsecore/thread-mq.h>
38 #include <pulsecore/rtpoll.h>
39 #include <pulsecore/time-smoother.h>
40 #include <pulsecore/rtclock.h>
41
42 #include "dbus-util.h"
43 #include "module-bt-device-symdef.h"
44 #include "bt-ipc.h"
45 #include "bt-sbc.h"
46
47 #define DEFAULT_SINK_NAME "bt_sink"
48 #define BUFFER_SIZE 2048
49 #define MAX_BITPOOL 64
50 #define MIN_BITPOOL 2
51
52 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
53 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
54 PA_MODULE_VERSION(PACKAGE_VERSION);
55 PA_MODULE_LOAD_ONCE(FALSE);
56 PA_MODULE_USAGE(
57         "name=<name of the device> "
58         "addr=<address of the device> "
59         "profile=<a2dp|hsp>");
60
61 struct bt_a2dp {
62     sbc_capabilities_t sbc_capabilities;
63     sbc_t sbc;                           /* Codec data */
64     int sbc_initialized;                 /* Keep track if the encoder is initialized */
65     int codesize;                        /* SBC codesize */
66     int samples;                         /* Number of encoded samples */
67     uint8_t buffer[BUFFER_SIZE];         /* Codec transfer buffer */
68     int count;                           /* Codec transfer buffer counter */
69
70     int nsamples;                        /* Cumulative number of codec samples */
71     uint16_t seq_num;                    /* Cumulative packet sequence */
72     int frame_count;                     /* Current frames in buffer*/
73 };
74
75 struct userdata {
76     pa_core *core;
77     pa_module *module;
78     pa_sink *sink;
79
80     pa_thread_mq thread_mq;
81     pa_rtpoll *rtpoll;
82     pa_rtpoll_item *rtpoll_item;
83     pa_thread *thread;
84
85     int64_t offset;
86     pa_smoother *smoother;
87
88     pa_memchunk memchunk;
89
90     const char *name;
91     const char *addr;
92     const char *profile;
93     int rate;
94     int channels;
95     pa_sample_spec ss;
96
97     int audioservice_fd;
98     int stream_fd;
99
100     int transport;
101     int link_mtu;
102     size_t block_size;
103     pa_usec_t latency;
104
105     struct bt_a2dp a2dp;
106 };
107
108 static const char* const valid_modargs[] = {
109     "name",
110     "addr",
111     "profile",
112     "rate",
113     "channels",
114     NULL
115 };
116
117 static int bt_audioservice_send(int sk, const bt_audio_msg_header_t *msg) {
118     int e;
119     pa_log/*_debug*/("sending %s", bt_audio_strmsg(msg->msg_type));
120     if (send(sk, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0)
121         e = 0;
122     else {
123         e = -errno;
124         pa_log_error("Error sending data to audio service: %s(%d)", pa_cstrerror(errno), errno);
125     }
126     return e;
127 }
128
129 static int bt_audioservice_recv(int sk, bt_audio_msg_header_t *inmsg) {
130     int e;
131     const char *type;
132
133     pa_log/*_debug*/("trying to receive msg from audio service...");
134     if (recv(sk, inmsg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0) {
135         type = bt_audio_strmsg(inmsg->msg_type);
136         if (type) {
137             pa_log/*_debug*/("Received %s", type);
138             e = 0;
139         }
140         else {
141             e = -EINVAL;
142             pa_log_error("Bogus message type %d received from audio service", inmsg->msg_type);
143         }
144     }
145     else {
146         e = -errno;
147         pa_log_error("Error receiving data from audio service: %s(%d)", pa_cstrerror(errno), errno);
148     }
149
150     return e;
151 }
152
153 static int bt_audioservice_expect(int sk, bt_audio_msg_header_t *rsp_hdr, int expected_type) {
154     int e = bt_audioservice_recv(sk, rsp_hdr);
155     if (e == 0) {
156         if (rsp_hdr->msg_type != expected_type) {
157             e = -EINVAL;
158             pa_log_error("Bogus message %s received while %s was expected", bt_audio_strmsg(rsp_hdr->msg_type),
159                     bt_audio_strmsg(expected_type));
160         }
161     }
162     return e;
163 }
164
165 static int bt_getcaps(struct userdata *u) {
166     int e;
167     char buf[BT_AUDIO_IPC_PACKET_SIZE];
168     bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
169     struct bt_getcapabilities_req *getcaps_req = (void*) buf;
170     struct bt_getcapabilities_rsp *getcaps_rsp = (void*) buf;
171
172     memset(getcaps_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
173     getcaps_req->h.msg_type = BT_GETCAPABILITIES_REQ;
174     strncpy(getcaps_req->device, u->addr, 18);
175     if (strcasecmp(u->profile, "a2dp") == 0)
176         getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
177     else if (strcasecmp(u->profile, "hsp") == 0)
178         getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_SCO;
179     else {
180         pa_log_error("invalid profile argument: %s", u->profile);
181         return -1;
182     }
183     getcaps_req->flags = 0;
184     getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
185
186     e = bt_audioservice_send(u->audioservice_fd, &getcaps_req->h);
187     if (e < 0) {
188         pa_log_error("failed to send GETCAPABILITIES_REQ");
189         return e;
190     }
191
192     e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_GETCAPABILITIES_RSP);
193     if (e < 0) {
194         pa_log_error("failed to expect for GETCAPABILITIES_RSP");
195         return e;
196     }
197     if (rsp_hdr->posix_errno != 0) {
198         pa_log_error("BT_GETCAPABILITIES failed : %s (%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
199         return -rsp_hdr->posix_errno;
200     }
201
202     if ((u->transport = getcaps_rsp->transport) == BT_CAPABILITIES_TRANSPORT_A2DP)
203         u->a2dp.sbc_capabilities = getcaps_rsp->sbc_capabilities;
204
205     return 0;
206 }
207
208 static uint8_t default_bitpool(uint8_t freq, uint8_t mode) {
209     switch (freq) {
210         case BT_SBC_SAMPLING_FREQ_16000:
211         case BT_SBC_SAMPLING_FREQ_32000:
212             return 53;
213         case BT_SBC_SAMPLING_FREQ_44100:
214             switch (mode) {
215                 case BT_A2DP_CHANNEL_MODE_MONO:
216                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
217                     return 31;
218                 case BT_A2DP_CHANNEL_MODE_STEREO:
219                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
220                     return 53;
221                 default:
222                     pa_log_warn("Invalid channel mode %u", mode);
223                     return 53;
224             }
225         case BT_SBC_SAMPLING_FREQ_48000:
226             switch (mode) {
227                 case BT_A2DP_CHANNEL_MODE_MONO:
228                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
229                     return 29;
230                 case BT_A2DP_CHANNEL_MODE_STEREO:
231                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
232                     return 51;
233                 default:
234                     pa_log_warn("Invalid channel mode %u", mode);
235                     return 51;
236             }
237         default:
238             pa_log_warn("Invalid sampling freq %u", freq);
239             return 53;
240     }
241 }
242
243 static int bt_a2dp_init(struct userdata *u) {
244     sbc_capabilities_t *cap = &u->a2dp.sbc_capabilities;
245     unsigned int max_bitpool, min_bitpool, rate, channels;
246
247     switch (u->rate) {
248         case 48000:
249             cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
250             break;
251         case 44100:
252             cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
253             break;
254         case 32000:
255             cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
256             break;
257         case 16000:
258             cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
259             break;
260         default:
261             pa_log_error("Rate %d not supported", rate);
262             return -1;
263     }
264
265 //    if (cfg->has_channel_mode)
266 //        cap->channel_mode = cfg->channel_mode;
267 //    else 
268     if (channels == 2) {
269         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
270             cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
271         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
272             cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
273         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
274             cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
275     } else {
276         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
277             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
278     }
279
280     if (!cap->channel_mode) {
281         pa_log_error("No supported channel modes");
282         return -1;
283     }
284
285 //    if (cfg->has_block_length)
286 //        cap->block_length = cfg->block_length;
287 //    else 
288     if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
289         cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
290     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
291         cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
292     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
293         cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
294     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
295         cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
296     else {
297         pa_log_error("No supported block lengths");
298         return -1;
299     }
300
301 //    if (cfg->has_subbands)
302 //        cap->subbands = cfg->subbands;
303     if (cap->subbands & BT_A2DP_SUBBANDS_8)
304         cap->subbands = BT_A2DP_SUBBANDS_8;
305     else if (cap->subbands & BT_A2DP_SUBBANDS_4)
306         cap->subbands = BT_A2DP_SUBBANDS_4;
307     else {
308         pa_log_error("No supported subbands");
309         return -1;
310     }
311
312 //    if (cfg->has_allocation_method)
313 //        cap->allocation_method = cfg->allocation_method;
314     if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
315         cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
316     else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
317         cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
318
319 //    if (cfg->has_bitpool)
320 //        min_bitpool = max_bitpool = cfg->bitpool;
321 //    else {
322     min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
323     max_bitpool = MIN(default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
324 //    }
325
326     cap->min_bitpool = min_bitpool;
327     cap->max_bitpool = max_bitpool;
328
329     return 0;
330 }
331
332 static void bt_a2dp_setup(struct bt_a2dp *a2dp) {
333     sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
334
335     if (a2dp->sbc_initialized)
336         sbc_reinit(&a2dp->sbc, 0);
337     else
338         sbc_init(&a2dp->sbc, 0);
339     a2dp->sbc_initialized = 1;
340
341     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
342         a2dp->sbc.frequency = SBC_FREQ_16000;
343
344     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
345         a2dp->sbc.frequency = SBC_FREQ_32000;
346
347     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
348         a2dp->sbc.frequency = SBC_FREQ_44100;
349
350     if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
351         a2dp->sbc.frequency = SBC_FREQ_48000;
352
353     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
354         a2dp->sbc.mode = SBC_MODE_MONO;
355
356     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
357         a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
358
359     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
360         a2dp->sbc.mode = SBC_MODE_STEREO;
361
362     if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
363         a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
364
365     a2dp->sbc.allocation = active_capabilities.allocation_method == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR : SBC_AM_LOUDNESS;
366
367     switch (active_capabilities.subbands) {
368         case BT_A2DP_SUBBANDS_4:
369             a2dp->sbc.subbands = SBC_SB_4;
370             break;
371         case BT_A2DP_SUBBANDS_8:
372             a2dp->sbc.subbands = SBC_SB_8;
373             break;
374     }
375
376     switch (active_capabilities.block_length) {
377         case BT_A2DP_BLOCK_LENGTH_4:
378             a2dp->sbc.blocks = SBC_BLK_4;
379             break;
380         case BT_A2DP_BLOCK_LENGTH_8:
381             a2dp->sbc.blocks = SBC_BLK_8;
382             break;
383         case BT_A2DP_BLOCK_LENGTH_12:
384             a2dp->sbc.blocks = SBC_BLK_12;
385             break;
386         case BT_A2DP_BLOCK_LENGTH_16:
387             a2dp->sbc.blocks = SBC_BLK_16;
388             break;
389     }
390
391     a2dp->sbc.bitpool = active_capabilities.max_bitpool;
392     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
393 //    a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
394 }
395
396 static int bt_setconf(struct userdata *u) {
397     int e;
398     char buf[BT_AUDIO_IPC_PACKET_SIZE];
399     bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
400     struct bt_setconfiguration_req *setconf_req = (void*) buf;
401     struct bt_setconfiguration_rsp *setconf_rsp = (void*) buf;
402
403     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
404         e = bt_a2dp_init(u);
405         if (e < 0) {
406             pa_log_error("a2dp_init error");
407             return e;
408         }
409     }
410
411     memset(setconf_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
412     setconf_req->h.msg_type = BT_SETCONFIGURATION_REQ;
413     strncpy(setconf_req->device, u->addr, 18);
414     setconf_req->transport = u->transport;
415     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
416         setconf_req->sbc_capabilities = u->a2dp.sbc_capabilities;
417     setconf_req->access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE;
418
419     e = bt_audioservice_send(u->audioservice_fd, &setconf_req->h);
420     if (e < 0) {
421         pa_log_error("failed to send BT_SETCONFIGURATION_REQ");
422         return e;
423     }
424
425     e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_SETCONFIGURATION_RSP);
426     if (e < 0) {
427         pa_log_error("failed to expect BT_SETCONFIGURATION_RSP");
428         return e;
429     }
430
431     if (rsp_hdr->posix_errno != 0) {
432         pa_log_error("BT_SETCONFIGURATION failed : %s(%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
433         return -rsp_hdr->posix_errno;
434     }
435
436     u->transport = setconf_rsp->transport;
437     u->block_size = u->link_mtu = setconf_rsp->link_mtu;
438
439     /* setup SBC encoder now we agree on parameters */
440     if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
441         bt_a2dp_setup(&u->a2dp);
442         pa_log/*debug*/("\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
443                 u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
444     }
445
446     return 0;
447 }
448
449 static int bt_getstreamfd(struct userdata *u) {
450     int e/*, opt_name*/;
451     char buf[BT_AUDIO_IPC_PACKET_SIZE];
452     struct bt_streamstart_req *start_req = (void*) buf;
453     bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
454     struct bt_streamfd_ind *streamfd_ind = (void*) buf;
455
456     memset(start_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
457     start_req->h.msg_type = BT_STREAMSTART_REQ;
458
459     e = bt_audioservice_send(u->audioservice_fd, &start_req->h);
460     if (e < 0) {
461         pa_log_error("failed to send BT_STREAMSTART_REQ");
462         return e;
463     }
464
465     e = bt_audioservice_expect(u->audioservice_fd, &rsp_hdr->msg_h, BT_STREAMSTART_RSP);
466     if (e < 0) {
467         pa_log_error("failed to expect BT_STREAMSTART_RSP");
468         return e;
469     }
470
471     if (rsp_hdr->posix_errno != 0) {
472         pa_log_error("BT_START failed : %s(%d)", pa_cstrerror(rsp_hdr->posix_errno), rsp_hdr->posix_errno);
473         return -rsp_hdr->posix_errno;
474     }
475
476     e = bt_audioservice_expect(u->audioservice_fd, &streamfd_ind->h, BT_STREAMFD_IND);
477     if (e < 0) {
478         pa_log_error("failed to expect BT_STREAMFD_IND");
479         return e;
480     }
481
482     if (u->stream_fd >= 0)
483         pa_close(u->stream_fd);
484
485     u->stream_fd = bt_audio_service_get_data_fd(u->audioservice_fd);
486     if (u->stream_fd < 0) {
487         pa_log_error("failed to get data fd");
488         return -errno;
489     }
490
491 //    if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
492 //        opt_name = SO_SNDTIMEO;
493 //        if (setsockopt(u->stream_fd, SOL_SOCKET, opt_name, &t, sizeof(t)) < 0) {
494 //            pa_log_error("failed to set socket options for A2DP");
495 //            return -errno;
496 //        }
497 //    }
498 //    else {
499 //        opt_name = SCO_TXBUFS;
500 //        if (setsockopt(u->stream_fd, SOL_SCO, opt_name, &period_count, sizeof(period_count)) == 0)
501 //            return 0;
502 //        opt_name = SO_SNDBUF;
503 //        if (setsockopt(u->stream_fd, SOL_SCO, opt_name, &period_count, sizeof(period_count)) == 0)
504 //            return 0;
505 //        /* FIXME : handle error codes */
506 //    }
507
508     return 0;
509 }
510
511 static int bt_hw_constraint(struct userdata *u) {
512     /*TODO: A2DP */
513     u->ss.format = PA_SAMPLE_S16LE;
514     u->ss.rate = 8000;
515     u->ss.channels = 1;
516     return 0;
517 }
518
519 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
520     struct userdata *u = PA_SINK(o)->userdata;
521
522     switch (code) {
523
524         case PA_SINK_MESSAGE_SET_STATE:
525             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
526                 case PA_SINK_SUSPENDED:
527                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
528                     pa_smoother_pause(u->smoother, pa_rtclock_usec());
529                     break;
530                 case PA_SINK_IDLE:
531                 case PA_SINK_RUNNING:
532                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
533                         pa_smoother_resume(u->smoother, pa_rtclock_usec());
534                     break;
535                 case PA_SINK_UNLINKED:
536                 case PA_SINK_INIT:
537                     ;
538             }
539             break;
540
541         case PA_SINK_MESSAGE_GET_LATENCY: {
542             pa_usec_t w, r;
543             r = pa_smoother_get(u->smoother, pa_rtclock_usec());
544             w = pa_bytes_to_usec(u->offset + u->memchunk.length, &u->sink->sample_spec);
545             *((pa_usec_t*) data) = w > r ? w - r : 0;
546             break;
547         }
548
549     }
550
551     return pa_sink_process_msg(o, code, data, offset, chunk);
552 }
553
554 static void thread_func(void *userdata) {
555     struct userdata *u = userdata;
556     int write_type = 0;
557
558     pa_assert(u);
559
560     pa_log/*_debug*/("Thread starting up");
561
562     pa_thread_mq_install(&u->thread_mq);
563     pa_rtpoll_install(u->rtpoll);
564
565     pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
566
567     for (;;) {
568         int ret;
569
570         if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
571             if (u->sink->thread_info.rewind_requested)
572                 pa_sink_process_rewind(u->sink, 0);
573
574         if (u->rtpoll_item) {
575             struct pollfd *pollfd;
576             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
577
578             /* Render some data and write it to the fifo */
579             if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
580                 pa_usec_t usec;
581                 int64_t n;
582
583                 for (;;) {
584                     ssize_t l;
585                     void *p;
586
587                     if (u->memchunk.length <= 0)
588                         pa_sink_render(u->sink, u->block_size, &u->memchunk);
589
590                     pa_assert(u->memchunk.length > 0);
591
592                     p = pa_memblock_acquire(u->memchunk.memblock);
593                     l = pa_write(u->stream_fd, (uint8_t*) p + u->memchunk.index, u->memchunk.length, &write_type);
594                     pa_memblock_release(u->memchunk.memblock);
595
596                     pa_assert(l != 0);
597
598                     if (l < 0) {
599
600                         if (errno == EINTR)
601                             continue;
602                         else if (errno == EAGAIN) {
603
604                             /* OK, we filled all socket buffers up
605                              * now. */
606                             goto filled_up;
607
608                         } else {
609                             pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
610                             goto fail;
611                         }
612
613                     } else {
614                         u->offset += l;
615
616                         u->memchunk.index += l;
617                         u->memchunk.length -= l;
618
619                         if (u->memchunk.length <= 0) {
620                             pa_memblock_unref(u->memchunk.memblock);
621                             pa_memchunk_reset(&u->memchunk);
622                         }
623
624                         pollfd->revents = 0;
625
626                         if (u->memchunk.length > 0)
627
628                             /* OK, we wrote less that we asked for,
629                              * hence we can assume that the socket
630                              * buffers are full now */
631                             goto filled_up;
632                     }
633                 }
634
635             filled_up:
636
637                 /* At this spot we know that the socket buffers are
638                  * fully filled up. This is the best time to estimate
639                  * the playback position of the server */
640
641                 n = u->offset;
642
643 //#ifdef SIOCOUTQ
644 //                {
645 //                    int l;
646 //                    if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
647 //                        n -= l;
648 //                }
649 //#endif
650
651                 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
652
653                 if (usec > u->latency)
654                     usec -= u->latency;
655                 else
656                     usec = 0;
657
658                 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
659             }
660
661             /* Hmm, nothing to do. Let's sleep */
662             pollfd->events = PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0;
663         }
664
665         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
666             goto fail;
667
668         if (ret == 0)
669             goto finish;
670
671         if (u->rtpoll_item) {
672             struct pollfd* pollfd;
673
674             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
675
676             if (pollfd->revents & ~POLLOUT) {
677                 pa_log("FIFO shutdown.");
678                 goto fail;
679             }
680         }
681     }
682
683 fail:
684     /* If this was no regular exit from the loop we have to continue
685      * processing messages until we received PA_MESSAGE_SHUTDOWN */
686     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
687     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
688
689 finish:
690     pa_log_debug("Thread shutting down");
691 }
692
693 int pa__init(pa_module* m) {
694     int e;
695     const char *rate, *channels;
696     pa_modargs *ma;
697     pa_sink_new_data data;
698     struct pollfd *pollfd;
699     struct userdata *u;
700
701     pa_assert(m);
702     m->userdata = u = pa_xnew0(struct userdata, 1);
703     u->module = m;
704     u->core = m->core;
705     u->audioservice_fd = -1;
706     u->stream_fd = -1;
707     u->transport = -1;
708     u->offset = 0;
709     u->latency = 0;
710     u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
711     pa_memchunk_reset(&u->memchunk);
712     u->rtpoll = pa_rtpoll_new();
713     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
714     u->rtpoll_item = NULL;
715
716     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
717         pa_log_error("failed to parse module arguments");
718         goto fail;
719     }
720     if (!(u->name = pa_xstrdup(pa_modargs_get_value(ma, "name", DEFAULT_SINK_NAME)))) {
721         pa_log_error("failed to get device name from module arguments");
722         goto fail;
723     }
724     if (!(u->addr = pa_xstrdup(pa_modargs_get_value(ma, "addr", NULL)))) {
725         pa_log_error("failed to get device address from module arguments");
726         goto fail;
727     }
728     if (!(u->profile = pa_xstrdup(pa_modargs_get_value(ma, "profile", NULL)))) {
729         pa_log_error("failed to get profile from module arguments");
730         goto fail;
731     }
732     if (pa_modargs_get_value_u32(ma, "rate", &u->rate) < 0) {
733         pa_log_error("failed to get rate from module arguments");
734         goto fail;
735     }
736     if (pa_modargs_get_value_u32(ma, "channels", &u->channels) < 0) {
737         pa_log_error("failed to get channels from module arguments");
738         goto fail;
739     }
740     pa_log("Loading module-bt-device for %s (%s), profile %s", u->name, u->addr, u->profile);
741
742     /* connect to the bluez audio service */
743     u->audioservice_fd = bt_audio_service_open();
744     if (u->audioservice_fd <= 0) {
745         pa_log_error("couldn't connect to bluetooth audio service");
746         goto fail;
747     }
748
749     /* queries device capabilities */
750     e = bt_getcaps(u);
751     if (e < 0) {
752         pa_log_error("failed to get device capabilities");
753         goto fail;
754     }
755
756     /* configures the connection */
757     e = bt_setconf(u);
758     if (e < 0) {
759         pa_log_error("failed to set config");
760         goto fail;
761     }
762
763     /* gets the device socket */
764     e = bt_getstreamfd(u);
765     if (e < 0) {
766         pa_log_error("failed to get stream fd (%d)", e);
767         goto fail;
768     }
769     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
770     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
771     pollfd->fd = u->stream_fd;
772     pollfd->events = pollfd->revents = 0;
773
774     /* configure hw supported sample specs */
775     e = bt_hw_constraint(u);
776     if (e < 0) {
777         pa_log_error("failed to configure sample spec");
778         goto fail;
779     }
780
781     /* create sink */
782     pa_sink_new_data_init(&data);
783     data.driver = __FILE__;
784     data.module = m;
785     pa_sink_new_data_set_name(&data, u->name);
786     pa_sink_new_data_set_sample_spec(&data, &u->ss);
787     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->name);
788     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Bluetooth sink '%s' (%s)", u->name, u->addr);
789     u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY|PA_SINK_NETWORK);
790     pa_sink_new_data_done(&data);
791     if (!u->sink) {
792         pa_log_error("failed to create sink");
793         goto fail;
794     }
795     u->sink->userdata = u;
796     u->sink->parent.process_msg = sink_process_msg;
797     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
798     pa_sink_set_rtpoll(u->sink, u->rtpoll);
799
800     /* start rt thread */
801     if (!(u->thread = pa_thread_new(thread_func, u))) {
802         pa_log_error("failed to create thread");
803         goto fail;
804     }
805     pa_sink_put(u->sink);
806
807     pa_modargs_free(ma);
808     return 0;
809
810 fail:
811     if (ma)
812         pa_modargs_free(ma);
813     pa__done(m);
814     return -1;
815 }
816
817 void pa__done(pa_module *m) {
818     pa_log("Unloading module-bt-device");
819 }
820