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