bluetooth: SCO over PCM
[profile/ivi/pulseaudio.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
8   published by the Free Software Foundation; either version 2 of the
9   License, 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
17   License 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 #include <pulsecore/namereg.h>
47
48 #include <modules/dbus-util.h>
49
50 #include "module-bluetooth-device-symdef.h"
51 #include "ipc.h"
52 #include "sbc.h"
53 #include "rtp.h"
54 #include "bluetooth-util.h"
55
56 #define MAX_BITPOOL 64
57 #define MIN_BITPOOL 2U
58 #define SOL_SCO 17
59 #define SCO_TXBUFS 0x03
60 #define SCO_RXBUFS 0x04
61
62 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
63 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
64 PA_MODULE_VERSION(PACKAGE_VERSION);
65 PA_MODULE_LOAD_ONCE(FALSE);
66 PA_MODULE_USAGE(
67         "name=<name for the card/sink/source, to be prefixed> "
68         "card_name=<name for the card> "
69         "sink_name=<name for the sink> "
70         "source_name=<name for the source> "
71         "address=<address of the device> "
72         "profile=<a2dp|hsp> "
73         "rate=<sample rate> "
74         "channels=<number of channels> "
75         "path=<device object path> "
76         "sco_sink=<SCO over PCM sink name> "
77         "sco_source=<SCO over PCM source name>");
78
79 static const char* const valid_modargs[] = {
80     "name",
81     "card_name",
82     "sink_name",
83     "source_name",
84     "address",
85     "profile",
86     "rate",
87     "channels",
88     "path",
89     "sco_sink",
90     "sco_source",
91     NULL
92 };
93
94 struct a2dp_info {
95     sbc_capabilities_t sbc_capabilities;
96     sbc_t sbc;                           /* Codec data */
97     pa_bool_t sbc_initialized;           /* Keep track if the encoder is initialized */
98     size_t codesize;                     /* SBC codesize */
99
100     void* buffer;                        /* Codec transfer buffer */
101     size_t buffer_size;                  /* Size of the buffer */
102
103     uint16_t seq_num;                    /* Cumulative packet sequence */
104 };
105
106 struct hsp_info {
107     pa_sink *sco_sink;
108     pa_source *sco_source;
109 };
110
111 enum profile {
112     PROFILE_A2DP,
113     PROFILE_HSP,
114     PROFILE_OFF
115 };
116
117 struct userdata {
118     pa_core *core;
119     pa_module *module;
120
121     pa_card *card;
122     pa_sink *sink;
123     pa_source *source;
124
125     pa_thread_mq thread_mq;
126     pa_rtpoll *rtpoll;
127     pa_rtpoll_item *rtpoll_item;
128     pa_thread *thread;
129
130     uint64_t read_index, write_index;
131     pa_usec_t started_at;
132     pa_smoother *read_smoother;
133
134     pa_memchunk write_memchunk;
135
136     pa_sample_spec sample_spec;
137
138     int service_fd;
139     int stream_fd;
140
141     size_t link_mtu;
142     size_t block_size;
143
144     struct a2dp_info a2dp;
145     struct hsp_info hsp;
146     pa_dbus_connection *connection;
147
148     enum profile profile;
149
150     pa_modargs *modargs;
151
152     pa_bluetooth_device *device;
153
154     int write_type, read_type;
155 };
156
157 static int service_send(int fd, const bt_audio_msg_header_t *msg) {
158     size_t length;
159     ssize_t r;
160
161     pa_assert(fd >= 0);
162     pa_assert(msg);
163
164     length = msg->length ? msg->length : BT_SUGGESTED_BUFFER_SIZE;
165
166     pa_log_debug("Sending %s -> %s",
167                  pa_strnull(bt_audio_strtype(msg->type)),
168                  pa_strnull(bt_audio_strname(msg->name)));
169
170     if ((r = send(fd, msg, length, 0)) == (ssize_t) length)
171         return 0;
172
173     if (r < 0)
174         pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
175     else
176         pa_log_error("Short send()");
177
178     return -1;
179 }
180
181 static int service_recv(int fd, bt_audio_msg_header_t *msg, size_t expected_length) {
182     size_t length;
183     ssize_t r;
184
185     pa_assert(fd >= 0);
186     pa_assert(msg);
187
188     length = expected_length ? expected_length : BT_SUGGESTED_BUFFER_SIZE;
189
190     pa_log_debug("Trying to receive message from audio service...");
191
192     r = recv(fd, msg, length, 0);
193
194     if (r > 0 && (r == (ssize_t) length || expected_length <= 0)) {
195
196         if ((size_t) r < sizeof(*msg)) {
197             pa_log_error("Packet read too small.");
198             return -1;
199         }
200
201         if (r != msg->length) {
202             pa_log_error("Size read doesn't match header size.");
203             return -1;
204         }
205
206         pa_log_debug("Received %s <- %s",
207                      pa_strnull(bt_audio_strtype(msg->type)),
208                      pa_strnull(bt_audio_strname(msg->name)));
209         return 0;
210     }
211
212     if (r < 0)
213         pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
214     else
215         pa_log_error("Short recv()");
216
217     return -1;
218 }
219
220 static int service_expect(int fd, bt_audio_msg_header_t *rsp, uint8_t expected_name, size_t expected_length) {
221     int r;
222
223     pa_assert(fd >= 0);
224     pa_assert(rsp);
225
226     if ((r = service_recv(fd, rsp, expected_length)) < 0)
227         return r;
228
229     if (rsp->name != expected_name) {
230         pa_log_error("Bogus message %s received while %s was expected",
231                      pa_strnull(bt_audio_strname(rsp->name)),
232                      pa_strnull(bt_audio_strname(expected_name)));
233         return -1;
234     }
235
236     if (rsp->type == BT_ERROR) {
237         bt_audio_error_t *error = (bt_audio_error_t *) rsp;
238         pa_log_error("%s failed: %s", pa_strnull(bt_audio_strname(rsp->name)), pa_cstrerror(error->posix_errno));
239         return -1;
240     }
241
242     return 0;
243 }
244
245 static int parse_caps(struct userdata *u, const struct bt_get_capabilities_rsp *rsp) {
246     uint16_t bytes_left;
247     const codec_capabilities_t *codec;
248
249     pa_assert(u);
250     pa_assert(rsp);
251
252     bytes_left = rsp->h.length - sizeof(*rsp);
253
254     if (bytes_left < sizeof(codec_capabilities_t)) {
255         pa_log_error("Packet too small to store codec information.");
256         return -1;
257     }
258
259     codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
260
261     pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
262
263     if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
264         (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
265         pa_log_error("Got capabilities for wrong codec.");
266         return -1;
267     }
268
269     if (u->profile != PROFILE_A2DP)
270         return 0;
271
272     while (bytes_left > 0) {
273         if (codec->type == BT_A2DP_CODEC_SBC)
274             break;
275
276         bytes_left -= codec->length;
277         codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
278     }
279
280     if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
281         return -1;
282
283     pa_assert(codec->type == BT_A2DP_CODEC_SBC);
284
285     memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
286     return 0;
287 }
288
289 static int get_caps(struct userdata *u) {
290     union {
291         struct bt_get_capabilities_req getcaps_req;
292         struct bt_get_capabilities_rsp getcaps_rsp;
293         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
294     } msg;
295
296     pa_assert(u);
297
298     memset(&msg, 0, sizeof(msg));
299     msg.getcaps_req.h.type = BT_REQUEST;
300     msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
301     msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
302
303     pa_strlcpy(msg.getcaps_req.device, u->device->address, sizeof(msg.getcaps_req.device));
304     if (u->profile == PROFILE_A2DP)
305         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
306     else {
307         pa_assert(u->profile == PROFILE_HSP);
308         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
309     }
310     msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
311
312     if (service_send(u->service_fd, &msg.getcaps_req.h) < 0)
313         return -1;
314
315     if (service_expect(u->service_fd, &msg.getcaps_rsp.h, BT_GET_CAPABILITIES, 0) < 0)
316         return -1;
317
318     return parse_caps(u, &msg.getcaps_rsp);
319 }
320
321 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
322
323     switch (freq) {
324         case BT_SBC_SAMPLING_FREQ_16000:
325         case BT_SBC_SAMPLING_FREQ_32000:
326             return 53;
327
328         case BT_SBC_SAMPLING_FREQ_44100:
329
330             switch (mode) {
331                 case BT_A2DP_CHANNEL_MODE_MONO:
332                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
333                     return 31;
334
335                 case BT_A2DP_CHANNEL_MODE_STEREO:
336                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
337                     return 53;
338
339                 default:
340                     pa_log_warn("Invalid channel mode %u", mode);
341                     return 53;
342             }
343
344         case BT_SBC_SAMPLING_FREQ_48000:
345
346             switch (mode) {
347                 case BT_A2DP_CHANNEL_MODE_MONO:
348                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
349                     return 29;
350
351                 case BT_A2DP_CHANNEL_MODE_STEREO:
352                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
353                     return 51;
354
355                 default:
356                     pa_log_warn("Invalid channel mode %u", mode);
357                     return 51;
358             }
359
360         default:
361             pa_log_warn("Invalid sampling freq %u", freq);
362             return 53;
363     }
364 }
365
366 static int setup_a2dp(struct userdata *u) {
367     sbc_capabilities_t *cap;
368     int i;
369
370     static const struct {
371         uint32_t rate;
372         uint8_t cap;
373     } freq_table[] = {
374         { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
375         { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
376         { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
377         { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
378     };
379
380     pa_assert(u);
381     pa_assert(u->profile == PROFILE_A2DP);
382
383     cap = &u->a2dp.sbc_capabilities;
384
385     /* Find the lowest freq that is at least as high as the requested
386      * sampling rate */
387     for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
388         if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
389             u->sample_spec.rate = freq_table[i].rate;
390             cap->frequency = freq_table[i].cap;
391             break;
392         }
393
394     if ((unsigned) i >= PA_ELEMENTSOF(freq_table)) {
395         for (; i >= 0; i--) {
396             if (cap->frequency & freq_table[i].cap) {
397                 u->sample_spec.rate = freq_table[i].rate;
398                 cap->frequency = freq_table[i].cap;
399                 break;
400             }
401         }
402
403         if (i < 0) {
404             pa_log("Not suitable sample rate");
405             return -1;
406         }
407     }
408
409     if (u->sample_spec.channels <= 1) {
410         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
411             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
412             u->sample_spec.channels = 1;
413         } else
414             u->sample_spec.channels = 2;
415     }
416
417     if (u->sample_spec.channels >= 2) {
418         u->sample_spec.channels = 2;
419
420         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
421             cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
422         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
423             cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
424         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
425             cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
426         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
427             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
428             u->sample_spec.channels = 1;
429         } else {
430             pa_log("No supported channel modes");
431             return -1;
432         }
433     }
434
435     if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
436         cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
437     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
438         cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
439     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
440         cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
441     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
442         cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
443     else {
444         pa_log_error("No supported block lengths");
445         return -1;
446     }
447
448     if (cap->subbands & BT_A2DP_SUBBANDS_8)
449         cap->subbands = BT_A2DP_SUBBANDS_8;
450     else if (cap->subbands & BT_A2DP_SUBBANDS_4)
451         cap->subbands = BT_A2DP_SUBBANDS_4;
452     else {
453         pa_log_error("No supported subbands");
454         return -1;
455     }
456
457     if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
458         cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
459     else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
460         cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
461
462     cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
463     cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
464
465     return 0;
466 }
467
468 static void setup_sbc(struct a2dp_info *a2dp) {
469     sbc_capabilities_t *active_capabilities;
470
471     pa_assert(a2dp);
472
473     active_capabilities = &a2dp->sbc_capabilities;
474
475     if (a2dp->sbc_initialized)
476         sbc_reinit(&a2dp->sbc, 0);
477     else
478         sbc_init(&a2dp->sbc, 0);
479     a2dp->sbc_initialized = TRUE;
480
481     switch (active_capabilities->frequency) {
482         case BT_SBC_SAMPLING_FREQ_16000:
483             a2dp->sbc.frequency = SBC_FREQ_16000;
484             break;
485         case BT_SBC_SAMPLING_FREQ_32000:
486             a2dp->sbc.frequency = SBC_FREQ_32000;
487             break;
488         case BT_SBC_SAMPLING_FREQ_44100:
489             a2dp->sbc.frequency = SBC_FREQ_44100;
490             break;
491         case BT_SBC_SAMPLING_FREQ_48000:
492             a2dp->sbc.frequency = SBC_FREQ_48000;
493             break;
494         default:
495             pa_assert_not_reached();
496     }
497
498     switch (active_capabilities->channel_mode) {
499         case BT_A2DP_CHANNEL_MODE_MONO:
500             a2dp->sbc.mode = SBC_MODE_MONO;
501             break;
502         case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
503             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
504             break;
505         case BT_A2DP_CHANNEL_MODE_STEREO:
506             a2dp->sbc.mode = SBC_MODE_STEREO;
507             break;
508         case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
509             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
510             break;
511         default:
512             pa_assert_not_reached();
513     }
514
515     switch (active_capabilities->allocation_method) {
516         case BT_A2DP_ALLOCATION_SNR:
517             a2dp->sbc.allocation = SBC_AM_SNR;
518             break;
519         case BT_A2DP_ALLOCATION_LOUDNESS:
520             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
521             break;
522         default:
523             pa_assert_not_reached();
524     }
525
526     switch (active_capabilities->subbands) {
527         case BT_A2DP_SUBBANDS_4:
528             a2dp->sbc.subbands = SBC_SB_4;
529             break;
530         case BT_A2DP_SUBBANDS_8:
531             a2dp->sbc.subbands = SBC_SB_8;
532             break;
533         default:
534             pa_assert_not_reached();
535     }
536
537     switch (active_capabilities->block_length) {
538         case BT_A2DP_BLOCK_LENGTH_4:
539             a2dp->sbc.blocks = SBC_BLK_4;
540             break;
541         case BT_A2DP_BLOCK_LENGTH_8:
542             a2dp->sbc.blocks = SBC_BLK_8;
543             break;
544         case BT_A2DP_BLOCK_LENGTH_12:
545             a2dp->sbc.blocks = SBC_BLK_12;
546             break;
547         case BT_A2DP_BLOCK_LENGTH_16:
548             a2dp->sbc.blocks = SBC_BLK_16;
549             break;
550         default:
551             pa_assert_not_reached();
552     }
553
554     a2dp->sbc.bitpool = active_capabilities->max_bitpool;
555     a2dp->codesize = (uint16_t) sbc_get_codesize(&a2dp->sbc);
556 }
557
558 static int set_conf(struct userdata *u) {
559     union {
560         struct bt_set_configuration_req setconf_req;
561         struct bt_set_configuration_rsp setconf_rsp;
562         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
563     } msg;
564
565     if (u->profile == PROFILE_A2DP ) {
566         u->sample_spec.format = PA_SAMPLE_S16LE;
567
568         if (setup_a2dp(u) < 0)
569             return -1;
570     } else {
571         pa_assert(u->profile == PROFILE_HSP);
572
573         u->sample_spec.format = PA_SAMPLE_S16LE;
574         u->sample_spec.channels = 1;
575         u->sample_spec.rate = 8000;
576     }
577
578     memset(&msg, 0, sizeof(msg));
579     msg.setconf_req.h.type = BT_REQUEST;
580     msg.setconf_req.h.name = BT_SET_CONFIGURATION;
581     msg.setconf_req.h.length = sizeof(msg.setconf_req);
582
583     pa_strlcpy(msg.setconf_req.device, u->device->address, sizeof(msg.setconf_req.device));
584     msg.setconf_req.access_mode = u->profile == PROFILE_A2DP ? BT_CAPABILITIES_ACCESS_MODE_WRITE : BT_CAPABILITIES_ACCESS_MODE_READWRITE;
585
586     msg.setconf_req.codec.transport = u->profile == PROFILE_A2DP ? BT_CAPABILITIES_TRANSPORT_A2DP : BT_CAPABILITIES_TRANSPORT_SCO;
587
588     if (u->profile == PROFILE_A2DP) {
589         memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
590         msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
591     }
592
593     if (service_send(u->service_fd, &msg.setconf_req.h) < 0)
594         return -1;
595
596     if (service_expect(u->service_fd, &msg.setconf_rsp.h, BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
597         return -1;
598
599     if ((u->profile == PROFILE_A2DP && msg.setconf_rsp.transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
600         (u->profile == PROFILE_HSP && msg.setconf_rsp.transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
601         pa_log("Transport doesn't match what we requested.");
602         return -1;
603     }
604
605     if ((u->profile == PROFILE_A2DP && msg.setconf_rsp.access_mode != BT_CAPABILITIES_ACCESS_MODE_WRITE) ||
606         (u->profile == PROFILE_HSP && msg.setconf_rsp.access_mode != BT_CAPABILITIES_ACCESS_MODE_READWRITE)) {
607         pa_log("Access mode doesn't match what we requested.");
608         return -1;
609     }
610
611     u->link_mtu = msg.setconf_rsp.link_mtu;
612
613     /* setup SBC encoder now we agree on parameters */
614     if (u->profile == PROFILE_A2DP) {
615         setup_sbc(&u->a2dp);
616         u->block_size = u->a2dp.codesize;
617         pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
618                     u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
619     } else
620         u->block_size = u->link_mtu;
621
622     return 0;
623 }
624
625 static int setup_stream_fd(struct userdata *u) {
626     union {
627         bt_audio_msg_header_t rsp;
628         struct bt_start_stream_req start_req;
629         struct bt_start_stream_rsp start_rsp;
630         struct bt_new_stream_ind streamfd_ind;
631         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
632     } msg;
633
634     pa_assert(u);
635     pa_assert(u->stream_fd < 0);
636
637     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
638     msg.start_req.h.type = BT_REQUEST;
639     msg.start_req.h.name = BT_START_STREAM;
640     msg.start_req.h.length = sizeof(msg.start_req);
641
642     if (service_send(u->service_fd, &msg.start_req.h) < 0)
643         return -1;
644
645     if (service_expect(u->service_fd, &msg.rsp, BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
646         return -1;
647
648     if (service_expect(u->service_fd, &msg.rsp, BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
649         return -1;
650
651     if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
652         pa_log("Failed to get stream fd from audio service.");
653         return -1;
654     }
655
656 /*     setsockopt(u->stream_fd, SOL_SCO, SCO_TXBUFS, &period_count, sizeof(period_count)); */
657 /*     setsockopt(u->stream_fd, SOL_SCO, SCO_SNDBUF, &period_count, sizeof(period_count)); */
658
659     pa_make_fd_nonblock(u->stream_fd);
660     pa_make_socket_low_delay(u->stream_fd);
661
662     return 0;
663 }
664
665 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
666     struct userdata *u = PA_SINK(o)->userdata;
667     pa_assert(u->sink == PA_SINK(o));
668
669     pa_log_debug("got message: %d", code);
670     switch (code) {
671
672         case PA_SINK_MESSAGE_SET_STATE:
673
674             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
675
676                 case PA_SINK_SUSPENDED:
677                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
678                     break;
679
680                 case PA_SINK_IDLE:
681                 case PA_SINK_RUNNING:
682                     if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
683                         u->started_at = pa_rtclock_usec();
684
685                     break;
686
687                 case PA_SINK_UNLINKED:
688                 case PA_SINK_INIT:
689                 case PA_SINK_INVALID_STATE:
690                     ;
691             }
692             break;
693
694         case PA_SINK_MESSAGE_GET_LATENCY: {
695             *((pa_usec_t*) data) = 0;
696             return 0;
697         }
698
699     }
700
701     return pa_sink_process_msg(o, code, data, offset, chunk);
702 }
703
704 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
705     struct userdata *u = PA_SOURCE(o)->userdata;
706
707     pa_assert(u->source == PA_SOURCE(o));
708
709     pa_log_debug("got message: %d", code);
710     switch (code) {
711
712         case PA_SOURCE_MESSAGE_SET_STATE:
713
714             switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
715
716                 case PA_SOURCE_SUSPENDED:
717                     pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
718                     break;
719
720                 case PA_SOURCE_IDLE:
721                 case PA_SOURCE_RUNNING:
722                     if (u->source->thread_info.state == PA_SOURCE_SUSPENDED)
723                         pa_smoother_resume(u->read_smoother, pa_rtclock_usec());
724                     break;
725
726                 case PA_SOURCE_UNLINKED:
727                 case PA_SOURCE_INIT:
728                 case PA_SOURCE_INVALID_STATE:
729                     ;
730             }
731             break;
732
733         case PA_SOURCE_MESSAGE_GET_LATENCY: {
734             *((pa_usec_t*) data) = 0;
735             return 0;
736         }
737
738     }
739
740     return pa_source_process_msg(o, code, data, offset, chunk);
741 }
742
743 static int hsp_process_render(struct userdata *u) {
744     int ret = 0;
745     pa_memchunk memchunk;
746
747     pa_assert(u);
748     pa_assert(u->profile == PROFILE_HSP);
749     pa_assert(u->sink);
750
751     pa_sink_render_full(u->sink, u->block_size, &memchunk);
752
753     for (;;) {
754         ssize_t l;
755         const void *p;
756
757         p = (const uint8_t*) pa_memblock_acquire(memchunk.memblock) + memchunk.index;
758         l = pa_write(u->stream_fd, p, memchunk.length, &u->write_type);
759         pa_memblock_release(memchunk.memblock);
760
761         pa_log_debug("Memblock written to socket: %lli bytes", (long long) l);
762
763         pa_assert(l != 0);
764
765         if (l < 0) {
766             if (errno == EINTR)
767                 continue;
768             else {
769                 pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
770                 ret = -1;
771                 break;
772             }
773         } else {
774             pa_assert((size_t) l <= memchunk.length);
775
776             memchunk.index += (size_t) l;
777             memchunk.length -= (size_t) l;
778
779             u->write_index += (uint64_t) l;
780
781             if (memchunk.length <= 0)
782                 break;
783         }
784     }
785
786     pa_memblock_unref(memchunk.memblock);
787
788     return ret;
789 }
790
791 static int hsp_process_push(struct userdata *u) {
792     int ret = 0;
793     pa_memchunk memchunk;
794
795     pa_assert(u);
796     pa_assert(u->profile == PROFILE_HSP);
797     pa_assert(u->source);
798
799     memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
800     memchunk.index = memchunk.length = 0;
801
802     for (;;) {
803         ssize_t l;
804         void *p;
805
806         p = pa_memblock_acquire(memchunk.memblock);
807         l = pa_read(u->stream_fd, p, pa_memblock_get_length(memchunk.memblock), &u->read_type);
808         pa_memblock_release(memchunk.memblock);
809
810         if (l <= 0) {
811             if (l < 0 && errno == EINTR)
812                 continue;
813             else {
814                 pa_log_error("Failed to read data from SCO socket: %s", ret < 0 ? pa_cstrerror(errno) : "EOF");
815                 ret = -1;
816                 break;
817             }
818         } else {
819             memchunk.length = (size_t) l;
820             u->read_index += (uint64_t) l;
821
822             pa_source_post(u->source, &memchunk);
823             break;
824         }
825     }
826
827     pa_memblock_unref(memchunk.memblock);
828
829     return ret;
830 }
831
832 static int a2dp_process_render(struct userdata *u) {
833     size_t frame_size;
834     struct a2dp_info *a2dp;
835     struct rtp_header *header;
836     struct rtp_payload *payload;
837     size_t left;
838     void *d;
839     const void *p;
840     unsigned frame_count;
841     int written;
842     uint64_t writing_at;
843
844     pa_assert(u);
845     pa_assert(u->profile == PROFILE_A2DP);
846     pa_assert(u->sink);
847
848     a2dp = &u->a2dp;
849
850     if (a2dp->buffer_size < u->link_mtu) {
851         a2dp->buffer_size = 2*u->link_mtu;
852         pa_xfree(a2dp->buffer);
853         a2dp->buffer = pa_xmalloc(a2dp->buffer_size);
854     }
855
856     header = (struct rtp_header*) a2dp->buffer;
857     payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
858     d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
859     left = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
860
861     frame_size = sbc_get_frame_length(&a2dp->sbc);
862     frame_count = 0;
863
864     writing_at = u->write_index;
865
866     do {
867         int encoded;
868
869         if (!u->write_memchunk.memblock)
870             pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
871
872         p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
873         encoded = sbc_encode(&a2dp->sbc,
874                              (void*) p, u->write_memchunk.length,
875                              d, left,
876                              &written);
877         pa_memblock_release(u->write_memchunk.memblock);
878
879         if (encoded <= 0) {
880             pa_log_error("SBC encoding error (%d)", encoded);
881             return -1;
882         }
883
884         pa_assert(written >= 0);
885
886         pa_assert((size_t) encoded <= u->write_memchunk.length);
887         pa_assert((size_t) written <= left);
888
889 /*         pa_log_debug("SBC: encoded: %d; written: %d", encoded, written); */
890
891         u->write_memchunk.index += encoded;
892         u->write_memchunk.length -= encoded;
893
894         if (u->write_memchunk.length <= 0) {
895             pa_memblock_unref(u->write_memchunk.memblock);
896             pa_memchunk_reset(&u->write_memchunk);
897         }
898
899         u->write_index += encoded;
900
901         d = (uint8_t*) d + written;
902         left -= written;
903
904         frame_count++;
905
906     } while ((uint8_t*) d - (uint8_t*) a2dp->buffer + written < (ptrdiff_t) u->link_mtu);
907
908     /* write it to the fifo */
909     memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
910     payload->frame_count = frame_count;
911     header->v = 2;
912     header->pt = 1;
913     header->sequence_number = htons(a2dp->seq_num++);
914     header->timestamp = htonl(writing_at / frame_size);
915     header->ssrc = htonl(1);
916
917     p = a2dp->buffer;
918     left = (uint8_t*) d - (uint8_t*) a2dp->buffer;
919
920     for (;;) {
921         ssize_t l;
922
923         l = pa_write(u->stream_fd, p, left, &u->write_type);
924 /*         pa_log_debug("write: requested %lu bytes; written %li bytes; mtu=%li", (unsigned long) left, (long) l, (unsigned long) u->link_mtu); */
925
926         pa_assert(l != 0);
927
928         if (l < 0) {
929             if (errno == EINTR)
930                 continue;
931             else {
932                 pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
933                 return -1;
934             }
935         } else {
936             pa_assert((size_t) l <= left);
937
938             d = (uint8_t*) d + l;
939             left -= l;
940
941             if (left <= 0)
942                 break;
943         }
944     }
945
946     return 0;
947 }
948
949 static void thread_func(void *userdata) {
950     struct userdata *u = userdata;
951     pa_bool_t do_write = FALSE, writable = FALSE;
952
953     pa_assert(u);
954
955     pa_log_debug("IO Thread starting up");
956
957     if (u->core->realtime_scheduling)
958         pa_make_realtime(u->core->realtime_priority);
959
960     pa_thread_mq_install(&u->thread_mq);
961     pa_rtpoll_install(u->rtpoll);
962
963     pa_smoother_set_time_offset(u->read_smoother, pa_rtclock_usec());
964
965     for (;;) {
966         struct pollfd *pollfd;
967         int ret;
968
969         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
970
971         if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
972
973             if (pollfd->revents & POLLIN) {
974
975                 if (hsp_process_push(u) < 0)
976                     goto fail;
977
978                 /* We just read something, so we are supposed to write something, too */
979                 do_write = TRUE;
980             }
981         }
982
983         if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
984
985             if (u->sink->thread_info.rewind_requested)
986                 pa_sink_process_rewind(u->sink, 0);
987
988             if (pollfd->revents & POLLOUT)
989                 writable = TRUE;
990
991             if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write && writable) {
992                 pa_usec_t time_passed;
993                 uint64_t should_have_written;
994
995                 /* Hmm, there is no input stream we could synchronize
996                  * to. So let's do things by time */
997
998                 time_passed = pa_rtclock_usec() - u->started_at;
999                 should_have_written = pa_usec_to_bytes(time_passed, &u->sink->sample_spec);
1000
1001                 do_write = u->write_index <= should_have_written ;
1002 /*                 pa_log_debug("Time has come: %s", pa_yes_no(do_write)); */
1003             }
1004
1005             if (writable && do_write) {
1006
1007                 if (u->profile == PROFILE_A2DP) {
1008                     if (a2dp_process_render(u) < 0)
1009                         goto fail;
1010                 } else {
1011                     if (hsp_process_render(u) < 0)
1012                         goto fail;
1013                 }
1014
1015                 do_write = FALSE;
1016                 writable = FALSE;
1017             }
1018
1019             if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write) {
1020                 pa_usec_t time_passed, next_write_at, sleep_for;
1021
1022                 /* Hmm, there is no input stream we could synchronize
1023                  * to. So let's estimate when we need to wake up the latest */
1024
1025                 time_passed = pa_rtclock_usec() - u->started_at;
1026                 next_write_at = pa_bytes_to_usec(u->write_index, &u->sink->sample_spec);
1027                 sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1028
1029 /*                 pa_log("Sleeping for %lu; time passed %lu, next write at %lu", (unsigned long) sleep_for, (unsigned long) time_passed, (unsigned long)next_write_at); */
1030
1031                 pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1032             }
1033         } else
1034             pa_rtpoll_set_timer_disabled(u->rtpoll);
1035
1036         /* Hmm, nothing to do. Let's sleep */
1037         pollfd->events = (short) (((u->sink && PA_SINK_IS_OPENED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1038                                   (u->source && PA_SOURCE_IS_OPENED(u->source->thread_info.state) ? POLLIN : 0));
1039
1040         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1041             goto fail;
1042
1043         if (ret == 0)
1044             goto finish;
1045
1046         pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
1047
1048         if (pollfd->revents & ~(POLLOUT|POLLIN)) {
1049             pa_log_error("FD error.");
1050             goto fail;
1051         }
1052     }
1053
1054 fail:
1055     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1056     pa_log_debug("IO thread failed");
1057     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1058     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1059
1060 finish:
1061     pa_log_debug("IO thread shutting down");
1062 }
1063
1064 /* static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *msg, void *userdata) { */
1065 /*     DBusMessageIter arg_i; */
1066 /*     DBusError err; */
1067 /*     const char *value; */
1068 /*     struct userdata *u; */
1069
1070 /*     pa_assert(bus); */
1071 /*     pa_assert(msg); */
1072 /*     pa_assert(userdata); */
1073 /*     u = userdata; */
1074
1075 /*     pa_log_debug("dbus: interface=%s, path=%s, member=%s\n", */
1076 /*                  dbus_message_get_interface(msg), */
1077 /*                  dbus_message_get_path(msg), */
1078 /*                  dbus_message_get_member(msg)); */
1079
1080 /*     dbus_error_init(&err); */
1081
1082 /*     if (dbus_message_is_signal(msg, "org.bluez.Headset", "PropertyChanged") || */
1083 /*         dbus_message_is_signal(msg, "org.bluez.AudioSink", "PropertyChanged")) { */
1084
1085 /*         struct device *d; */
1086 /*         const char *profile; */
1087 /*         DBusMessageIter variant_i; */
1088 /*         dbus_uint16_t gain; */
1089
1090 /*         if (!dbus_message_iter_init(msg, &arg_i)) { */
1091 /*             pa_log("dbus: message has no parameters"); */
1092 /*             goto done; */
1093 /*         } */
1094
1095 /*         if (dbus_message_iter_get_arg_type(&arg_i) != DBUS_TYPE_STRING) { */
1096 /*             pa_log("Property name not a string."); */
1097 /*             goto done; */
1098 /*         } */
1099
1100 /*         dbus_message_iter_get_basic(&arg_i, &value); */
1101
1102 /*         if (!dbus_message_iter_next(&arg_i)) { */
1103 /*             pa_log("Property value missing"); */
1104 /*             goto done; */
1105 /*         } */
1106
1107 /*         if (dbus_message_iter_get_arg_type(&arg_i) != DBUS_TYPE_VARIANT) { */
1108 /*             pa_log("Property value not a variant."); */
1109 /*             goto done; */
1110 /*         } */
1111
1112 /*         dbus_message_iter_recurse(&arg_i, &variant_i); */
1113
1114 /*         if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_UINT16) { */
1115 /*             dbus_message_iter_get_basic(&variant_i, &gain); */
1116
1117 /*             if (pa_streq(value, "SpeakerGain")) { */
1118 /*                 pa_log("spk gain: %d", gain); */
1119 /*                 pa_cvolume_set(&u->sink->virtual_volume, 1, (pa_volume_t) (gain * PA_VOLUME_NORM / 15)); */
1120 /*                 pa_subscription_post(u->sink->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, u->sink->index); */
1121 /*             } else { */
1122 /*                 pa_log("mic gain: %d", gain); */
1123 /*                 if (!u->source) */
1124 /*                     goto done; */
1125
1126 /*                 pa_cvolume_set(&u->source->virtual_volume, 1, (pa_volume_t) (gain * PA_VOLUME_NORM / 15)); */
1127 /*                 pa_subscription_post(u->source->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, u->source->index); */
1128 /*             } */
1129 /*         } */
1130 /*     } */
1131
1132 /* done: */
1133 /*     dbus_error_free(&err); */
1134 /*     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; */
1135 /* } */
1136
1137 /* static int sink_get_volume_cb(pa_sink *s) { */
1138 /*     struct userdata *u = s->userdata; */
1139 /*     pa_assert(u); */
1140
1141 /*     /\* refresh? *\/ */
1142
1143 /*     return 0; */
1144 /* } */
1145
1146 /* static int source_get_volume_cb(pa_source *s) { */
1147 /*     struct userdata *u = s->userdata; */
1148 /*     pa_assert(u); */
1149
1150 /*     /\* refresh? *\/ */
1151
1152 /*     return 0; */
1153 /* } */
1154
1155 /* static int sink_set_volume_cb(pa_sink *s) { */
1156 /*     DBusError e; */
1157 /*     DBusMessage *m, *r; */
1158 /*     DBusMessageIter it, itvar; */
1159 /*     dbus_uint16_t vol; */
1160 /*     const char *spkgain = "SpeakerGain"; */
1161 /*     struct userdata *u = s->userdata; */
1162 /*     pa_assert(u); */
1163
1164 /*     dbus_error_init(&e); */
1165
1166 /*     vol = ((float) pa_cvolume_max(&s->virtual_volume) / PA_VOLUME_NORM) * 15; */
1167 /*     pa_log_debug("set headset volume: %d", vol); */
1168
1169 /*     pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetProperty")); */
1170 /*     dbus_message_iter_init_append(m, &it); */
1171 /*     dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &spkgain); */
1172 /*     dbus_message_iter_open_container(&it, DBUS_TYPE_VARIANT, DBUS_TYPE_UINT16_AS_STRING, &itvar); */
1173 /*     dbus_message_iter_append_basic(&itvar, DBUS_TYPE_UINT16, &vol); */
1174 /*     dbus_message_iter_close_container(&it, &itvar); */
1175
1176 /*     r = dbus_connection_send_with_reply_and_block(pa_dbus_connection_get(u->conn), m, -1, &e); */
1177
1178 /* finish: */
1179 /*     if (m) */
1180 /*         dbus_message_unref(m); */
1181 /*     if (r) */
1182 /*         dbus_message_unref(r); */
1183
1184 /*     dbus_error_free(&e); */
1185
1186 /*     return 0; */
1187 /* } */
1188
1189 /* static int source_set_volume_cb(pa_source *s) { */
1190 /*     dbus_uint16_t vol; */
1191 /*     struct userdata *u = s->userdata; */
1192 /*     pa_assert(u); */
1193
1194 /*     vol = ((float)pa_cvolume_max(&s->virtual_volume) / PA_VOLUME_NORM) * 15; */
1195
1196 /*     pa_log_debug("set headset mic volume: %d (not implemented yet)", vol); */
1197
1198 /*     return 0; */
1199 /* } */
1200
1201 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1202     char *t;
1203     const char *n;
1204
1205     pa_assert(type);
1206     pa_assert(ma);
1207     pa_assert(device_id);
1208     pa_assert(namereg_fail);
1209
1210     t = pa_sprintf_malloc("%s_name", type);
1211     n = pa_modargs_get_value(ma, t, NULL);
1212     pa_xfree(t);
1213
1214     if (n) {
1215         *namereg_fail = TRUE;
1216         return pa_xstrdup(n);
1217     }
1218
1219     if ((n = pa_modargs_get_value(ma, "name", NULL)))
1220         *namereg_fail = TRUE;
1221     else {
1222         n = device_id;
1223         *namereg_fail = FALSE;
1224     }
1225
1226     return pa_sprintf_malloc("bluez_%s.%s", type, n);
1227 }
1228
1229 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
1230
1231 static int add_sink(struct userdata *u) {
1232
1233     if (USE_SCO_OVER_PCM(u)) {
1234         pa_proplist *p;
1235
1236         u->sink = u->hsp.sco_sink;
1237         u->sink->card = u->card; /* FIXME! */
1238         p = pa_proplist_new();
1239         pa_proplist_sets(p, "bluetooth.protocol", "sco");
1240         pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1241         pa_proplist_free(p);
1242
1243     } else {
1244         pa_sink_new_data data;
1245         pa_bool_t b;
1246
1247         pa_sink_new_data_init(&data);
1248         data.driver = __FILE__;
1249         data.module = u->module;
1250         pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1251         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1252         data.card = u->card;
1253         data.name = get_name("sink", u->modargs, u->device->address, &b);
1254         data.namereg_fail = b;
1255
1256         u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1257         pa_sink_new_data_done(&data);
1258
1259         if (!u->sink) {
1260             pa_log_error("Failed to create sink");
1261             return -1;
1262         }
1263
1264         u->sink->userdata = u;
1265         u->sink->parent.process_msg = sink_process_msg;
1266
1267         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1268         pa_sink_set_rtpoll(u->sink, u->rtpoll);
1269     }
1270
1271 /*     u->sink->get_volume = sink_get_volume_cb; */
1272 /*     u->sink->set_volume = sink_set_volume_cb; */
1273
1274     return 0;
1275 }
1276
1277 static int add_source(struct userdata *u) {
1278
1279     if (USE_SCO_OVER_PCM(u)) {
1280         pa_proplist *p;
1281
1282         u->source = u->hsp.sco_source;
1283         u->source->card = u->card; /* FIXME! */
1284         p = pa_proplist_new();
1285         pa_proplist_sets(p, "bluetooth.protocol", "sco");
1286         pa_proplist_update(u->source->proplist, PA_UPDATE_MERGE, p);
1287         pa_proplist_free(p);
1288
1289     } else {
1290         pa_source_new_data data;
1291         pa_bool_t b;
1292
1293         pa_source_new_data_init(&data);
1294         data.driver = __FILE__;
1295         data.module = u->module;
1296         pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1297         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1298         data.card = u->card;
1299         data.name = get_name("source", u->modargs, u->device->address, &b);
1300         data.namereg_fail = b;
1301
1302         u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1303         pa_source_new_data_done(&data);
1304
1305         if (!u->source) {
1306             pa_log_error("Failed to create source");
1307             return -1;
1308         }
1309
1310         u->source->userdata = u;
1311         u->source->parent.process_msg = source_process_msg;
1312
1313         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1314         pa_source_set_rtpoll(u->source, u->rtpoll);
1315     }
1316
1317 /*     u->source->get_volume = source_get_volume_cb; */
1318 /*     u->source->set_volume = source_set_volume_cb; */
1319
1320     return 0;
1321 }
1322
1323 static int init_bt(struct userdata *u) {
1324     pa_assert(u);
1325
1326     /* shutdown bt */
1327     if (u->stream_fd >= 0) {
1328         pa_close(u->stream_fd);
1329         u->stream_fd = -1;
1330     }
1331
1332     if (u->service_fd >= 0) {
1333         pa_close(u->service_fd);
1334         u->service_fd = -1;
1335     }
1336
1337     u->write_type = u->read_type = 0;
1338
1339     /* connect to the bluez audio service */
1340     if ((u->service_fd = bt_audio_service_open()) < 0) {
1341         pa_log_error("Couldn't connect to bluetooth audio service");
1342         return -1;
1343     }
1344     pa_log_debug("Connected to the bluetooth audio service");
1345
1346     return 0;
1347 }
1348
1349 static int setup_bt(struct userdata *u) {
1350     pa_assert(u);
1351
1352     if (get_caps(u) < 0)
1353         return -1;
1354
1355     pa_log_debug("Got device capabilities");
1356
1357     if (set_conf(u) < 0)
1358         return -1;
1359
1360     pa_log_debug("Connection to the device configured");
1361
1362     if (USE_SCO_OVER_PCM(u)) {
1363         pa_log_debug("Configured to use SCO over PCM");
1364         return 0;
1365     }
1366
1367     if (setup_stream_fd(u) < 0)
1368         return -1;
1369
1370     pa_log_debug("Got the stream socket");
1371
1372     return 0;
1373 }
1374
1375 static int init_profile(struct userdata *u) {
1376     int r = 0;
1377     pa_assert(u);
1378
1379     if (setup_bt(u) < 0)
1380         return -1;
1381
1382     if (u->profile == PROFILE_A2DP ||
1383         u->profile == PROFILE_HSP)
1384         if (add_sink(u) < 0)
1385             r = -1;
1386
1387     if (u->profile == PROFILE_HSP)
1388         if (add_source(u) < 0)
1389             r = -1;
1390
1391     return r;
1392 }
1393
1394 static void stop_thread(struct userdata *u) {
1395     pa_assert(u);
1396
1397     if (u->thread) {
1398         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1399         pa_thread_free(u->thread);
1400         u->thread = NULL;
1401     }
1402
1403     if (u->rtpoll_item) {
1404         pa_rtpoll_item_free(u->rtpoll_item);
1405         u->rtpoll_item = NULL;
1406     }
1407
1408     if (u->sink) {
1409         pa_sink_unref(u->sink);
1410         u->sink = NULL;
1411     }
1412
1413     if (u->source) {
1414         pa_source_unref(u->source);
1415         u->source = NULL;
1416     }
1417 }
1418
1419 static int start_thread(struct userdata *u) {
1420     struct pollfd *pollfd;
1421
1422     pa_assert(u);
1423     pa_assert(!u->thread);
1424     pa_assert(!u->rtpoll_item);
1425
1426     if (USE_SCO_OVER_PCM(u)) {
1427         pa_sink_ref(u->sink);
1428         pa_source_ref(u->source);
1429         return 0;
1430     }
1431
1432     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
1433     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
1434     pollfd->fd = u->stream_fd;
1435     pollfd->events = pollfd->revents = 0;
1436
1437     if (!(u->thread = pa_thread_new(thread_func, u))) {
1438         pa_log_error("Failed to create IO thread");
1439         stop_thread(u);
1440         return -1;
1441     }
1442
1443     if (u->sink)
1444         pa_sink_put(u->sink);
1445
1446     if (u->source)
1447         pa_source_put(u->source);
1448
1449     return 0;
1450 }
1451
1452 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1453     struct userdata *u;
1454     enum profile *d;
1455     pa_queue *inputs = NULL, *outputs = NULL;
1456
1457     pa_assert(c);
1458     pa_assert(new_profile);
1459     pa_assert_se(u = c->userdata);
1460
1461     d = PA_CARD_PROFILE_DATA(new_profile);
1462
1463     if (u->sink) {
1464         inputs = pa_sink_move_all_start(u->sink);
1465         if (!USE_SCO_OVER_PCM(u))
1466             pa_sink_unlink(u->sink);
1467     }
1468
1469     if (u->source) {
1470         outputs = pa_source_move_all_start(u->source);
1471         if (!USE_SCO_OVER_PCM(u))
1472             pa_source_unlink(u->source);
1473     }
1474
1475     stop_thread(u);
1476     init_bt(u);
1477
1478     if (u->write_memchunk.memblock) {
1479         pa_memblock_unref(u->write_memchunk.memblock);
1480         pa_memchunk_reset(&u->write_memchunk);
1481     }
1482
1483     u->profile = *d;
1484     init_profile(u);
1485
1486     if (u->sink || u->source)
1487         start_thread(u);
1488
1489     if (inputs) {
1490         if (u->sink)
1491             pa_sink_move_all_finish(u->sink, inputs, FALSE);
1492         else
1493             pa_sink_move_all_fail(inputs);
1494     }
1495
1496     if (outputs) {
1497         if (u->source)
1498             pa_source_move_all_finish(u->source, outputs, FALSE);
1499         else
1500             pa_source_move_all_fail(outputs);
1501     }
1502
1503     return 0;
1504 }
1505
1506 static int add_card(struct userdata *u, const char * default_profile) {
1507     pa_card_new_data data;
1508     pa_bool_t b;
1509     pa_card_profile *p;
1510     enum profile *d;
1511     const char *ff;
1512     char *n;
1513
1514     pa_card_new_data_init(&data);
1515     data.driver = __FILE__;
1516     data.module = u->module;
1517
1518     n = pa_bluetooth_cleanup_name(u->device->name);
1519     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1520     pa_xfree(n);
1521     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device->address);
1522     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1523     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1524     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CONNECTOR, "bluetooth");
1525     if ((ff = pa_bluetooth_get_form_factor(u->device->class)))
1526         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1527     pa_proplist_sets(data.proplist, "bluez.path", u->device->path);
1528     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) u->device->class);
1529     pa_proplist_sets(data.proplist, "bluez.name", u->device->name);
1530     data.name = get_name("card", u->modargs, u->device->address, &b);
1531     data.namereg_fail = b;
1532
1533     data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1534
1535     if (u->device->audio_sink_info_valid > 0) {
1536         p = pa_card_profile_new("a2dp", "A2DP Advanced Audio Distribution Profile", sizeof(enum profile));
1537         p->priority = 10;
1538         p->n_sinks = 1;
1539         p->n_sources = 0;
1540         p->max_sink_channels = 2;
1541         p->max_source_channels = 0;
1542
1543         d = PA_CARD_PROFILE_DATA(p);
1544         *d = PROFILE_A2DP;
1545
1546         pa_hashmap_put(data.profiles, p->name, p);
1547     }
1548
1549     if (u->device->headset_info_valid > 0) {
1550         p = pa_card_profile_new("hsp", "HSP/HFP Headset/Hands-Free Profile", sizeof(enum profile));
1551         p->priority = 20;
1552         p->n_sinks = 1;
1553         p->n_sources = 1;
1554         p->max_sink_channels = 1;
1555         p->max_source_channels = 1;
1556
1557         d = PA_CARD_PROFILE_DATA(p);
1558         *d = PROFILE_HSP;
1559
1560         pa_hashmap_put(data.profiles, p->name, p);
1561     }
1562
1563     pa_assert(!pa_hashmap_isempty(data.profiles));
1564
1565     p = pa_card_profile_new("off", "Off", sizeof(enum profile));
1566     d = PA_CARD_PROFILE_DATA(p);
1567     *d = PROFILE_OFF;
1568     pa_hashmap_put(data.profiles, p->name, p);
1569
1570     if (default_profile) {
1571         if (pa_hashmap_get(data.profiles, default_profile))
1572             pa_card_new_data_set_profile(&data, default_profile);
1573         else
1574             pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
1575     }
1576
1577     u->card = pa_card_new(u->core, &data);
1578     pa_card_new_data_done(&data);
1579
1580     if (!u->card) {
1581         pa_log("Failed to allocate card.");
1582         return -1;
1583     }
1584
1585     u->card->userdata = u;
1586     u->card->set_profile = card_set_profile;
1587
1588     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
1589     u->profile = *d;
1590
1591     return 0;
1592 }
1593
1594 static int setup_dbus(struct userdata *u) {
1595     DBusError error;
1596
1597     dbus_error_init(&error);
1598
1599     u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &error);
1600     if (dbus_error_is_set(&error) || (!u->connection)) {
1601         pa_log("Failed to get D-Bus connection: %s", error.message);
1602         dbus_error_free(&error);
1603         return -1;
1604     }
1605
1606     return 0;
1607 }
1608
1609 static int find_device(struct userdata *u, const char *address, const char *path) {
1610     pa_assert(u);
1611
1612     if (!address && !path) {
1613         pa_log_error("Failed to get device address/path from module arguments.");
1614         return -1;
1615     }
1616
1617     if (path) {
1618         if (!(u->device = pa_bluetooth_get_device(pa_dbus_connection_get(u->connection), path))) {
1619             pa_log_error("%s is not a valid BlueZ audio device.", path);
1620             return -1;
1621         }
1622
1623         if (address && !(pa_streq(u->device->address, address))) {
1624             pa_log_error("Passed path %s and address %s don't match.", path, address);
1625             return -1;
1626         }
1627     } else {
1628         if (!(u->device = pa_bluetooth_find_device(pa_dbus_connection_get(u->connection), address))) {
1629             pa_log_error("%s is not known.", address);
1630             return -1;
1631         }
1632     }
1633
1634     return 0;
1635 }
1636
1637 int pa__init(pa_module* m) {
1638     pa_modargs *ma;
1639     uint32_t channels;
1640     struct userdata *u;
1641     const char *address, *path;
1642
1643     pa_assert(m);
1644
1645     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1646         pa_log_error("Failed to parse module arguments");
1647         goto fail;
1648     }
1649
1650     m->userdata = u = pa_xnew0(struct userdata, 1);
1651     u->module = m;
1652     u->core = m->core;
1653     u->service_fd = -1;
1654     u->stream_fd = -1;
1655     u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
1656     u->rtpoll = pa_rtpoll_new();
1657     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1658     u->sample_spec = m->core->default_sample_spec;
1659     u->modargs = ma;
1660
1661     if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
1662         !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
1663         pa_log("SCO sink not found");
1664         goto fail;
1665     }
1666
1667     if (pa_modargs_get_value(ma, "sco_source", NULL) &&
1668         !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
1669         pa_log("SCO source not found");
1670         goto fail;
1671     }
1672
1673     if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
1674         u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
1675         pa_log_error("Failed to get rate from module arguments");
1676         goto fail;
1677     }
1678
1679     channels = u->sample_spec.channels;
1680     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
1681         channels <= 0 || channels > PA_CHANNELS_MAX) {
1682         pa_log_error("Failed to get channels from module arguments");
1683         goto fail;
1684     }
1685     u->sample_spec.channels = (uint8_t) channels;
1686
1687     if (setup_dbus(u) < 0)
1688         goto fail;
1689
1690     address = pa_modargs_get_value(ma, "address", NULL);
1691     path = pa_modargs_get_value(ma, "path", NULL);
1692
1693     if (find_device(u, address, path) < 0)
1694         goto fail;
1695
1696     pa_assert(u->device);
1697
1698     /* Add the card structure. This will also initialize the default profile */
1699     if (add_card(u, pa_modargs_get_value(ma, "profile", NULL)) < 0)
1700         goto fail;
1701
1702     /* Connect to the BT service and query capabilities */
1703     if (init_bt(u) < 0)
1704         goto fail;
1705
1706     if (init_profile(u) < 0)
1707         goto fail;
1708
1709 /*     if (u->path) { */
1710 /*         DBusError err; */
1711 /*         dbus_error_init(&err); */
1712 /*         char *t; */
1713
1714
1715 /*         if (!dbus_connection_add_filter(pa_dbus_connection_get(u->conn), filter_cb, u, NULL)) { */
1716 /*             pa_log_error("Failed to add filter function"); */
1717 /*             goto fail; */
1718 /*         } */
1719
1720 /*         if (u->transport == BT_CAPABILITIES_TRANSPORT_SCO || */
1721 /*             u->transport == BT_CAPABILITIES_TRANSPORT_ANY) { */
1722 /*             t = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged',path='%s'", u->path); */
1723 /*             dbus_bus_add_match(pa_dbus_connection_get(u->conn), t, &err); */
1724 /*             pa_xfree(t); */
1725
1726 /*             if (dbus_error_is_set(&err)) { */
1727 /*                 pa_log_error("Unable to subscribe to org.bluez.Headset signals: %s: %s", err.name, err.message); */
1728 /*                 goto fail; */
1729 /*             } */
1730 /*         } */
1731
1732 /*         if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP || */
1733 /*             u->transport == BT_CAPABILITIES_TRANSPORT_ANY) { */
1734 /*             t = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged',path='%s'", u->path); */
1735 /*             dbus_bus_add_match(pa_dbus_connection_get(u->conn), t, &err); */
1736 /*             pa_xfree(t); */
1737
1738 /*             if (dbus_error_is_set(&err)) { */
1739 /*                 pa_log_error("Unable to subscribe to org.bluez.AudioSink signals: %s: %s", err.name, err.message); */
1740 /*                 goto fail; */
1741 /*             } */
1742 /*         } */
1743 /*     } */
1744
1745     if (start_thread(u) < 0)
1746         goto fail;
1747
1748     return 0;
1749
1750 fail:
1751     pa__done(m);
1752     return -1;
1753 }
1754
1755 int pa__get_n_used(pa_module *m) {
1756     struct userdata *u;
1757
1758     pa_assert(m);
1759     pa_assert_se(u = m->userdata);
1760
1761     return
1762         (u->sink ? pa_sink_linked_by(u->sink) : 0) +
1763         (u->source ? pa_source_linked_by(u->source) : 0);
1764 }
1765
1766 void pa__done(pa_module *m) {
1767     struct userdata *u;
1768     pa_assert(m);
1769
1770     if (!(u = m->userdata))
1771         return;
1772
1773     if (u->sink && !USE_SCO_OVER_PCM(u))
1774         pa_sink_unlink(u->sink);
1775
1776     if (u->source && !USE_SCO_OVER_PCM(u))
1777         pa_source_unlink(u->source);
1778
1779     stop_thread(u);
1780
1781     if (u->connection) {
1782 /*         DBusError error; */
1783 /*         char *t; */
1784
1785 /*         if (u->transport == BT_CAPABILITIES_TRANSPORT_SCO || */
1786 /*             u->transport == BT_CAPABILITIES_TRANSPORT_ANY) { */
1787
1788 /*             t = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='PropertyChanged',path='%s'", u->path); */
1789 /*             dbus_error_init(&error); */
1790 /*             dbus_bus_remove_match(pa_dbus_connection_get(u->conn), t, &error); */
1791 /*             dbus_error_free(&error); */
1792 /*             pa_xfree(t); */
1793 /*         } */
1794
1795 /*         if (u->transport == BT_CAPABILITIES_TRANSPORT_A2DP || */
1796 /*             u->transport == BT_CAPABILITIES_TRANSPORT_ANY) { */
1797
1798 /*             t = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.AudioSink',member='PropertyChanged',path='%s'", u->path); */
1799 /*             dbus_error_init(&error); */
1800 /*             dbus_bus_remove_match(pa_dbus_connection_get(u->conn), t, &error); */
1801 /*             dbus_error_free(&error); */
1802 /*             pa_xfree(t); */
1803 /*         } */
1804
1805 /*         dbus_connection_remove_filter(pa_dbus_connection_get(u->conn), filter_cb, u); */
1806         pa_dbus_connection_unref(u->connection);
1807     }
1808
1809     if (u->card)
1810         pa_card_free(u->card);
1811
1812     pa_thread_mq_done(&u->thread_mq);
1813
1814     if (u->rtpoll)
1815         pa_rtpoll_free(u->rtpoll);
1816
1817     if (u->read_smoother)
1818         pa_smoother_free(u->read_smoother);
1819
1820     if (u->stream_fd >= 0)
1821         pa_close(u->stream_fd);
1822
1823     if (u->service_fd >= 0)
1824         pa_close(u->service_fd);
1825
1826     if (u->device)
1827         pa_bluetooth_device_free(u->device);
1828
1829     if (u->write_memchunk.memblock)
1830         pa_memblock_unref(u->write_memchunk.memblock);
1831
1832     if (u->a2dp.buffer)
1833         pa_xfree(u->a2dp.buffer);
1834
1835     sbc_finish(&u->a2dp.sbc);
1836
1837     if (u->modargs)
1838         pa_modargs_free(u->modargs);
1839
1840     pa_xfree(u);
1841 }