bluetooth: drop data every 500ms on oor condition
[profile/ivi/pulseaudio-panda.git] / src / modules / bluetooth / module-bluetooth-device.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2008-2009 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.1 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 <linux/sockios.h>
29 #include <arpa/inet.h>
30
31 #include <pulse/i18n.h>
32 #include <pulse/rtclock.h>
33 #include <pulse/sample.h>
34 #include <pulse/timeval.h>
35 #include <pulse/xmalloc.h>
36
37 #include <pulsecore/module.h>
38 #include <pulsecore/modargs.h>
39 #include <pulsecore/core-rtclock.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/core-error.h>
42 #include <pulsecore/shared.h>
43 #include <pulsecore/socket-util.h>
44 #include <pulsecore/thread.h>
45 #include <pulsecore/thread-mq.h>
46 #include <pulsecore/poll.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/time-smoother.h>
49 #include <pulsecore/namereg.h>
50 #include <pulsecore/dbus-shared.h>
51 #include <pulsecore/llist.h>
52
53 #include "module-bluetooth-device-symdef.h"
54 #include "ipc.h"
55 #include "sbc.h"
56 #include "a2dp-codecs.h"
57 #include "rtp.h"
58 #include "bluetooth-util.h"
59
60 #define BITPOOL_DEC_LIMIT 32
61 #define BITPOOL_DEC_STEP 5
62
63 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
64 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
65 PA_MODULE_VERSION(PACKAGE_VERSION);
66 PA_MODULE_LOAD_ONCE(FALSE);
67 PA_MODULE_USAGE(
68         "name=<name for the card/sink/source, to be prefixed> "
69         "card_name=<name for the card> "
70         "card_properties=<properties for the card> "
71         "sink_name=<name for the sink> "
72         "sink_properties=<properties for the sink> "
73         "source_name=<name for the source> "
74         "source_properties=<properties for the source> "
75         "address=<address of the device> "
76         "profile=<a2dp|hsp|hfgw> "
77         "rate=<sample rate> "
78         "channels=<number of channels> "
79         "path=<device object path> "
80         "auto_connect=<automatically connect?> "
81         "sco_sink=<SCO over PCM sink name> "
82         "sco_source=<SCO over PCM source name>");
83
84 /* TODO: not close fd when entering suspend mode in a2dp */
85
86 static const char* const valid_modargs[] = {
87     "name",
88     "card_name",
89     "card_properties",
90     "sink_name",
91     "sink_properties",
92     "source_name",
93     "source_properties",
94     "address",
95     "profile",
96     "rate",
97     "channels",
98     "path",
99     "auto_connect",
100     "sco_sink",
101     "sco_source",
102     NULL
103 };
104
105 struct a2dp_info {
106     sbc_capabilities_t sbc_capabilities;
107     sbc_t sbc;                           /* Codec data */
108     pa_bool_t sbc_initialized;           /* Keep track if the encoder is initialized */
109     size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
110
111     void* buffer;                        /* Codec transfer buffer */
112     size_t buffer_size;                  /* Size of the buffer */
113
114     uint16_t seq_num;                    /* Cumulative packet sequence */
115     uint8_t min_bitpool;
116     uint8_t max_bitpool;
117 };
118
119 struct hsp_info {
120     pcm_capabilities_t pcm_capabilities;
121     pa_sink *sco_sink;
122     void (*sco_sink_set_volume)(pa_sink *s);
123     pa_source *sco_source;
124     void (*sco_source_set_volume)(pa_source *s);
125     pa_hook_slot *sink_state_changed_slot;
126     pa_hook_slot *source_state_changed_slot;
127 };
128
129 struct userdata {
130     pa_core *core;
131     pa_module *module;
132
133     char *address;
134     char *path;
135     char *transport;
136     char *accesstype;
137
138     pa_bluetooth_discovery *discovery;
139     pa_bool_t auto_connect;
140
141     pa_dbus_connection *connection;
142
143     pa_card *card;
144     pa_sink *sink;
145     pa_source *source;
146
147     pa_thread_mq thread_mq;
148     pa_rtpoll *rtpoll;
149     pa_rtpoll_item *rtpoll_item;
150     pa_thread *thread;
151
152     uint64_t read_index, write_index;
153     pa_usec_t started_at;
154     pa_smoother *read_smoother;
155
156     pa_memchunk write_memchunk;
157
158     pa_sample_spec sample_spec, requested_sample_spec;
159
160     int service_fd;
161     int stream_fd;
162
163     size_t link_mtu;
164     size_t block_size;
165
166     struct a2dp_info a2dp;
167     struct hsp_info hsp;
168
169     enum profile profile;
170
171     pa_modargs *modargs;
172
173     int stream_write_type;
174     int service_write_type, service_read_type;
175
176     pa_bool_t filter_added;
177 };
178
179 #define FIXED_LATENCY_PLAYBACK_A2DP (25*PA_USEC_PER_MSEC)
180 #define FIXED_LATENCY_RECORD_A2DP (25*PA_USEC_PER_MSEC)
181 #define FIXED_LATENCY_PLAYBACK_HSP (125*PA_USEC_PER_MSEC)
182 #define FIXED_LATENCY_RECORD_HSP (25*PA_USEC_PER_MSEC)
183
184 #define MAX_PLAYBACK_CATCH_UP_USEC (100*PA_USEC_PER_MSEC)
185
186 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
187
188 static int init_bt(struct userdata *u);
189 static int init_profile(struct userdata *u);
190
191 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
192     ssize_t r;
193
194     pa_assert(u);
195     pa_assert(msg);
196     pa_assert(msg->length > 0);
197
198     if (u->service_fd < 0) {
199         pa_log_warn("Service not connected");
200         return -1;
201     }
202
203     pa_log_debug("Sending %s -> %s",
204                  pa_strnull(bt_audio_strtype(msg->type)),
205                  pa_strnull(bt_audio_strname(msg->name)));
206
207     if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
208         return 0;
209
210     if (r < 0)
211         pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
212     else
213         pa_log_error("Short write()");
214
215     return -1;
216 }
217
218 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
219     ssize_t r;
220
221     pa_assert(u);
222     pa_assert(u->service_fd >= 0);
223     pa_assert(msg);
224     pa_assert(room >= sizeof(*msg));
225
226     pa_log_debug("Trying to receive message from audio service...");
227
228     /* First, read the header */
229     if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
230         goto read_fail;
231
232     if (msg->length < sizeof(*msg)) {
233         pa_log_error("Invalid message size.");
234         return -1;
235     }
236
237     if (msg->length > room) {
238         pa_log_error("Not enough room.");
239         return -1;
240     }
241
242     /* Secondly, read the payload */
243     if (msg->length > sizeof(*msg)) {
244
245         size_t remains = msg->length - sizeof(*msg);
246
247         if ((r = pa_loop_read(u->service_fd,
248                               (uint8_t*) msg + sizeof(*msg),
249                               remains,
250                               &u->service_read_type)) != (ssize_t) remains)
251             goto read_fail;
252     }
253
254     pa_log_debug("Received %s <- %s",
255                  pa_strnull(bt_audio_strtype(msg->type)),
256                  pa_strnull(bt_audio_strname(msg->name)));
257
258     return 0;
259
260 read_fail:
261
262     if (r < 0)
263         pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
264     else
265         pa_log_error("Short read()");
266
267     return -1;
268 }
269
270 static ssize_t service_expect(struct userdata*u, bt_audio_msg_header_t *rsp, size_t room, uint8_t expected_name, size_t expected_size) {
271     int r;
272
273     pa_assert(u);
274     pa_assert(u->service_fd >= 0);
275     pa_assert(rsp);
276
277     if ((r = service_recv(u, rsp, room)) < 0)
278         return r;
279
280     if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
281         rsp->name != expected_name ||
282         (expected_size > 0 && rsp->length != expected_size)) {
283
284         if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
285             pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
286         else
287             pa_log_error("Bogus message %s received while %s was expected",
288                          pa_strnull(bt_audio_strname(rsp->name)),
289                          pa_strnull(bt_audio_strname(expected_name)));
290         return -1;
291     }
292
293     return 0;
294 }
295
296 /* Run from main thread */
297 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
298     uint16_t bytes_left;
299     const codec_capabilities_t *codec;
300
301     pa_assert(u);
302     pa_assert(rsp);
303
304     bytes_left = rsp->h.length - sizeof(*rsp);
305
306     if (bytes_left < sizeof(codec_capabilities_t)) {
307         pa_log_error("Packet too small to store codec information.");
308         return -1;
309     }
310
311     codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
312
313     pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
314
315     if (((u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
316         ((u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
317         pa_log_error("Got capabilities for wrong codec.");
318         return -1;
319     }
320
321     if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
322
323         if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
324             return -1;
325
326         pa_assert(codec->type == BT_HFP_CODEC_PCM);
327
328         if (codec->configured && seid == 0)
329             return codec->seid;
330
331         memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
332
333     } else if (u->profile == PROFILE_A2DP) {
334
335         while (bytes_left > 0) {
336             if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
337                 break;
338
339             bytes_left -= codec->length;
340             codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
341         }
342
343         if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
344             return -1;
345
346         pa_assert(codec->type == BT_A2DP_SBC_SINK);
347
348         if (codec->configured && seid == 0)
349             return codec->seid;
350
351         memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
352
353     } else if (u->profile == PROFILE_A2DP_SOURCE) {
354
355         while (bytes_left > 0) {
356             if ((codec->type == BT_A2DP_SBC_SOURCE) && !codec->lock)
357                 break;
358
359             bytes_left -= codec->length;
360             codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
361         }
362
363         if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
364             return -1;
365
366         pa_assert(codec->type == BT_A2DP_SBC_SOURCE);
367
368         if (codec->configured && seid == 0)
369             return codec->seid;
370
371         memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
372     }
373
374     return 0;
375 }
376
377 /* Run from main thread */
378 static int get_caps(struct userdata *u, uint8_t seid) {
379     union {
380         struct bt_get_capabilities_req getcaps_req;
381         struct bt_get_capabilities_rsp getcaps_rsp;
382         bt_audio_error_t error;
383         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
384     } msg;
385     int ret;
386
387     pa_assert(u);
388
389     memset(&msg, 0, sizeof(msg));
390     msg.getcaps_req.h.type = BT_REQUEST;
391     msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
392     msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
393     msg.getcaps_req.seid = seid;
394
395     pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
396     if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE)
397         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
398     else {
399         pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
400         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
401     }
402     msg.getcaps_req.flags = u->auto_connect ? BT_FLAG_AUTOCONNECT : 0;
403
404     if (service_send(u, &msg.getcaps_req.h) < 0)
405         return -1;
406
407     if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
408         return -1;
409
410     ret = parse_caps(u, seid, &msg.getcaps_rsp);
411     if (ret <= 0)
412         return ret;
413
414     return get_caps(u, ret);
415 }
416
417 /* Run from main thread */
418 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
419
420     switch (freq) {
421         case BT_SBC_SAMPLING_FREQ_16000:
422         case BT_SBC_SAMPLING_FREQ_32000:
423             return 53;
424
425         case BT_SBC_SAMPLING_FREQ_44100:
426
427             switch (mode) {
428                 case BT_A2DP_CHANNEL_MODE_MONO:
429                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
430                     return 31;
431
432                 case BT_A2DP_CHANNEL_MODE_STEREO:
433                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
434                     return 53;
435
436                 default:
437                     pa_log_warn("Invalid channel mode %u", mode);
438                     return 53;
439             }
440
441         case BT_SBC_SAMPLING_FREQ_48000:
442
443             switch (mode) {
444                 case BT_A2DP_CHANNEL_MODE_MONO:
445                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
446                     return 29;
447
448                 case BT_A2DP_CHANNEL_MODE_STEREO:
449                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
450                     return 51;
451
452                 default:
453                     pa_log_warn("Invalid channel mode %u", mode);
454                     return 51;
455             }
456
457         default:
458             pa_log_warn("Invalid sampling freq %u", freq);
459             return 53;
460     }
461 }
462
463 /* Run from main thread */
464 static int setup_a2dp(struct userdata *u) {
465     sbc_capabilities_t *cap;
466     int i;
467
468     static const struct {
469         uint32_t rate;
470         uint8_t cap;
471     } freq_table[] = {
472         { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
473         { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
474         { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
475         { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
476     };
477
478     pa_assert(u);
479     pa_assert(u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE);
480
481     cap = &u->a2dp.sbc_capabilities;
482
483     /* Find the lowest freq that is at least as high as the requested
484      * sampling rate */
485     for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
486         if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
487             u->sample_spec.rate = freq_table[i].rate;
488             cap->frequency = freq_table[i].cap;
489             break;
490         }
491
492     if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
493         for (--i; i >= 0; i--) {
494             if (cap->frequency & freq_table[i].cap) {
495                 u->sample_spec.rate = freq_table[i].rate;
496                 cap->frequency = freq_table[i].cap;
497                 break;
498             }
499         }
500
501         if (i < 0) {
502             pa_log("Not suitable sample rate");
503             return -1;
504         }
505     }
506
507     pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
508
509     if (cap->capability.configured)
510         return 0;
511
512     if (u->sample_spec.channels <= 1) {
513         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
514             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
515             u->sample_spec.channels = 1;
516         } else
517             u->sample_spec.channels = 2;
518     }
519
520     if (u->sample_spec.channels >= 2) {
521         u->sample_spec.channels = 2;
522
523         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
524             cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
525         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
526             cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
527         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
528             cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
529         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
530             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
531             u->sample_spec.channels = 1;
532         } else {
533             pa_log("No supported channel modes");
534             return -1;
535         }
536     }
537
538     if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
539         cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
540     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
541         cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
542     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
543         cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
544     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
545         cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
546     else {
547         pa_log_error("No supported block lengths");
548         return -1;
549     }
550
551     if (cap->subbands & BT_A2DP_SUBBANDS_8)
552         cap->subbands = BT_A2DP_SUBBANDS_8;
553     else if (cap->subbands & BT_A2DP_SUBBANDS_4)
554         cap->subbands = BT_A2DP_SUBBANDS_4;
555     else {
556         pa_log_error("No supported subbands");
557         return -1;
558     }
559
560     if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
561         cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
562     else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
563         cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
564
565     cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
566     cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
567
568     return 0;
569 }
570
571 /* Run from main thread */
572 static void setup_sbc(struct a2dp_info *a2dp, enum profile p) {
573     sbc_capabilities_t *active_capabilities;
574
575     pa_assert(a2dp);
576
577     active_capabilities = &a2dp->sbc_capabilities;
578
579     if (a2dp->sbc_initialized)
580         sbc_reinit(&a2dp->sbc, 0);
581     else
582         sbc_init(&a2dp->sbc, 0);
583     a2dp->sbc_initialized = TRUE;
584
585     switch (active_capabilities->frequency) {
586         case BT_SBC_SAMPLING_FREQ_16000:
587             a2dp->sbc.frequency = SBC_FREQ_16000;
588             break;
589         case BT_SBC_SAMPLING_FREQ_32000:
590             a2dp->sbc.frequency = SBC_FREQ_32000;
591             break;
592         case BT_SBC_SAMPLING_FREQ_44100:
593             a2dp->sbc.frequency = SBC_FREQ_44100;
594             break;
595         case BT_SBC_SAMPLING_FREQ_48000:
596             a2dp->sbc.frequency = SBC_FREQ_48000;
597             break;
598         default:
599             pa_assert_not_reached();
600     }
601
602     switch (active_capabilities->channel_mode) {
603         case BT_A2DP_CHANNEL_MODE_MONO:
604             a2dp->sbc.mode = SBC_MODE_MONO;
605             break;
606         case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
607             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
608             break;
609         case BT_A2DP_CHANNEL_MODE_STEREO:
610             a2dp->sbc.mode = SBC_MODE_STEREO;
611             break;
612         case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
613             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
614             break;
615         default:
616             pa_assert_not_reached();
617     }
618
619     switch (active_capabilities->allocation_method) {
620         case BT_A2DP_ALLOCATION_SNR:
621             a2dp->sbc.allocation = SBC_AM_SNR;
622             break;
623         case BT_A2DP_ALLOCATION_LOUDNESS:
624             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
625             break;
626         default:
627             pa_assert_not_reached();
628     }
629
630     switch (active_capabilities->subbands) {
631         case BT_A2DP_SUBBANDS_4:
632             a2dp->sbc.subbands = SBC_SB_4;
633             break;
634         case BT_A2DP_SUBBANDS_8:
635             a2dp->sbc.subbands = SBC_SB_8;
636             break;
637         default:
638             pa_assert_not_reached();
639     }
640
641     switch (active_capabilities->block_length) {
642         case BT_A2DP_BLOCK_LENGTH_4:
643             a2dp->sbc.blocks = SBC_BLK_4;
644             break;
645         case BT_A2DP_BLOCK_LENGTH_8:
646             a2dp->sbc.blocks = SBC_BLK_8;
647             break;
648         case BT_A2DP_BLOCK_LENGTH_12:
649             a2dp->sbc.blocks = SBC_BLK_12;
650             break;
651         case BT_A2DP_BLOCK_LENGTH_16:
652             a2dp->sbc.blocks = SBC_BLK_16;
653             break;
654         default:
655             pa_assert_not_reached();
656     }
657
658     a2dp->min_bitpool = active_capabilities->min_bitpool;
659     a2dp->max_bitpool = active_capabilities->max_bitpool;
660
661     /* Set minimum bitpool for source to get the maximum possible block_size */
662     a2dp->sbc.bitpool = p == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
663     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
664     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
665 }
666
667 /* Run from main thread */
668 static int set_conf(struct userdata *u) {
669     union {
670         struct bt_open_req open_req;
671         struct bt_open_rsp open_rsp;
672         struct bt_set_configuration_req setconf_req;
673         struct bt_set_configuration_rsp setconf_rsp;
674         bt_audio_error_t error;
675         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
676     } msg;
677
678     memset(&msg, 0, sizeof(msg));
679     msg.open_req.h.type = BT_REQUEST;
680     msg.open_req.h.name = BT_OPEN;
681     msg.open_req.h.length = sizeof(msg.open_req);
682
683     pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
684     msg.open_req.seid = (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
685     msg.open_req.lock = (u->profile == PROFILE_A2DP) ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
686
687     if (service_send(u, &msg.open_req.h) < 0)
688         return -1;
689
690     if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
691         return -1;
692
693     if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
694         u->sample_spec.format = PA_SAMPLE_S16LE;
695
696         if (setup_a2dp(u) < 0)
697             return -1;
698     } else {
699         pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
700
701         u->sample_spec.format = PA_SAMPLE_S16LE;
702         u->sample_spec.channels = 1;
703         u->sample_spec.rate = 8000;
704     }
705
706     memset(&msg, 0, sizeof(msg));
707     msg.setconf_req.h.type = BT_REQUEST;
708     msg.setconf_req.h.name = BT_SET_CONFIGURATION;
709     msg.setconf_req.h.length = sizeof(msg.setconf_req);
710
711     if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
712         memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
713     } else {
714         msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
715         msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
716         msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
717     }
718     msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
719
720     if (service_send(u, &msg.setconf_req.h) < 0)
721         return -1;
722
723     if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
724         return -1;
725
726     u->link_mtu = msg.setconf_rsp.link_mtu;
727
728     /* setup SBC encoder now we agree on parameters */
729     if (u->profile == PROFILE_A2DP || u->profile == PROFILE_A2DP_SOURCE) {
730         setup_sbc(&u->a2dp, u->profile);
731
732         u->block_size =
733             ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
734             / u->a2dp.frame_length
735             * u->a2dp.codesize);
736
737         pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
738                     u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
739     } else
740         u->block_size = u->link_mtu;
741
742     return 0;
743 }
744
745 /* from IO thread */
746 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool)
747 {
748     struct a2dp_info *a2dp;
749
750     pa_assert(u);
751
752     a2dp = &u->a2dp;
753
754     if (a2dp->sbc.bitpool == bitpool)
755         return;
756
757     if (bitpool > a2dp->max_bitpool)
758         bitpool = a2dp->max_bitpool;
759     else if (bitpool < a2dp->min_bitpool)
760         bitpool = a2dp->min_bitpool;
761
762     a2dp->sbc.bitpool = bitpool;
763
764     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
765     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
766
767     pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
768
769     u->block_size =
770             (u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
771             / a2dp->frame_length * a2dp->codesize;
772
773     pa_sink_set_max_request_within_thread(u->sink, u->block_size);
774     pa_sink_set_fixed_latency_within_thread(u->sink,
775             FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->block_size, &u->sample_spec));
776 }
777
778 /* from IO thread, except in SCO over PCM */
779
780 static int setup_stream(struct userdata *u) {
781     struct pollfd *pollfd;
782     int one;
783
784     pa_make_fd_nonblock(u->stream_fd);
785     pa_make_socket_low_delay(u->stream_fd);
786
787     one = 1;
788     if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
789         pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
790
791     pa_log_debug("Stream properly set up, we're ready to roll!");
792
793     if (u->profile == PROFILE_A2DP)
794         a2dp_set_bitpool(u, u->a2dp.max_bitpool);
795
796     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
797     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
798     pollfd->fd = u->stream_fd;
799     pollfd->events = pollfd->revents = 0;
800
801     u->read_index = u->write_index = 0;
802     u->started_at = 0;
803
804     if (u->source)
805         u->read_smoother = pa_smoother_new(
806                 PA_USEC_PER_SEC,
807                 PA_USEC_PER_SEC*2,
808                 TRUE,
809                 TRUE,
810                 10,
811                 pa_rtclock_now(),
812                 TRUE);
813
814     return 0;
815 }
816
817 static int start_stream_fd(struct userdata *u) {
818     union {
819         bt_audio_msg_header_t rsp;
820         struct bt_start_stream_req start_req;
821         struct bt_start_stream_rsp start_rsp;
822         struct bt_new_stream_ind streamfd_ind;
823         bt_audio_error_t error;
824         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
825     } msg;
826
827     pa_assert(u);
828     pa_assert(u->rtpoll);
829     pa_assert(!u->rtpoll_item);
830     pa_assert(u->stream_fd < 0);
831
832     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
833     msg.start_req.h.type = BT_REQUEST;
834     msg.start_req.h.name = BT_START_STREAM;
835     msg.start_req.h.length = sizeof(msg.start_req);
836
837     if (service_send(u, &msg.start_req.h) < 0)
838         return -1;
839
840     if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
841         return -1;
842
843     if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
844         return -1;
845
846     if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
847         pa_log("Failed to get stream fd from audio service.");
848         return -1;
849     }
850
851     return setup_stream(u);
852 }
853
854 /* from IO thread */
855 static int stop_stream_fd(struct userdata *u) {
856     union {
857         bt_audio_msg_header_t rsp;
858         struct bt_stop_stream_req start_req;
859         struct bt_stop_stream_rsp start_rsp;
860         bt_audio_error_t error;
861         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
862     } msg;
863     int r = 0;
864
865     pa_assert(u);
866     pa_assert(u->rtpoll);
867
868     if (u->rtpoll_item) {
869         pa_rtpoll_item_free(u->rtpoll_item);
870         u->rtpoll_item = NULL;
871     }
872
873     if (u->stream_fd >= 0) {
874         memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
875         msg.start_req.h.type = BT_REQUEST;
876         msg.start_req.h.name = BT_STOP_STREAM;
877         msg.start_req.h.length = sizeof(msg.start_req);
878
879         if (service_send(u, &msg.start_req.h) < 0 ||
880             service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
881             r = -1;
882
883         pa_close(u->stream_fd);
884         u->stream_fd = -1;
885     }
886
887     if (u->read_smoother) {
888         pa_smoother_free(u->read_smoother);
889         u->read_smoother = NULL;
890     }
891
892     return r;
893 }
894
895 static void bt_transport_release(struct userdata *u) {
896     const char *accesstype = "rw";
897     const pa_bluetooth_transport *t;
898
899     /* Ignore if already released */
900     if (!u->accesstype)
901         return;
902
903     pa_log_debug("Releasing transport %s", u->transport);
904
905     t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
906     if (t)
907         pa_bluetooth_transport_release(t, accesstype);
908
909     pa_xfree(u->accesstype);
910     u->accesstype = NULL;
911
912     if (u->rtpoll_item) {
913         pa_rtpoll_item_free(u->rtpoll_item);
914         u->rtpoll_item = NULL;
915     }
916
917     if (u->stream_fd >= 0) {
918         pa_close(u->stream_fd);
919         u->stream_fd = -1;
920     }
921
922     if (u->read_smoother) {
923         pa_smoother_free(u->read_smoother);
924         u->read_smoother = NULL;
925     }
926 }
927
928 static int bt_transport_acquire(struct userdata *u, pa_bool_t start) {
929     const char *accesstype = "rw";
930     const pa_bluetooth_transport *t;
931
932     if (u->accesstype) {
933         if (start)
934             goto done;
935         return 0;
936     }
937
938     pa_log_debug("Acquiring transport %s", u->transport);
939
940     t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
941     if (!t) {
942         pa_log("Transport %s no longer available", u->transport);
943         pa_xfree(u->transport);
944         u->transport = NULL;
945         return -1;
946     }
947
948     /* FIXME: Handle in/out MTU properly when unix socket is not longer supported */
949     u->stream_fd = pa_bluetooth_transport_acquire(t, accesstype, NULL, &u->link_mtu);
950     if (u->stream_fd < 0)
951         return -1;
952
953     u->accesstype = pa_xstrdup(accesstype);
954     pa_log_info("Transport %s acquired: fd %d", u->transport, u->stream_fd);
955
956     if (!start)
957         return 0;
958
959 done:
960     pa_log_info("Transport %s resuming", u->transport);
961     return setup_stream(u);
962 }
963
964 /* Run from IO thread */
965 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
966     struct userdata *u = PA_SINK(o)->userdata;
967     pa_bool_t failed = FALSE;
968     int r;
969
970     pa_assert(u->sink == PA_SINK(o));
971
972     switch (code) {
973
974         case PA_SINK_MESSAGE_SET_STATE:
975
976             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
977
978                 case PA_SINK_SUSPENDED:
979                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
980
981                     /* Stop the device if the source is suspended as well */
982                     if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
983                         /* We deliberately ignore whether stopping
984                          * actually worked. Since the stream_fd is
985                          * closed it doesn't really matter */
986                         if (u->transport)
987                             bt_transport_release(u);
988                         else
989                             stop_stream_fd(u);
990                     }
991
992                     break;
993
994                 case PA_SINK_IDLE:
995                 case PA_SINK_RUNNING:
996                     if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
997                         break;
998
999                     /* Resume the device if the source was suspended as well */
1000                     if (!u->source || u->source->state == PA_SOURCE_SUSPENDED) {
1001                         if (u->transport) {
1002                             if (bt_transport_acquire(u, TRUE) < 0)
1003                                 failed = TRUE;
1004                         } else if (start_stream_fd(u) < 0)
1005                             failed = TRUE;
1006                     }
1007                     break;
1008
1009                 case PA_SINK_UNLINKED:
1010                 case PA_SINK_INIT:
1011                 case PA_SINK_INVALID_STATE:
1012                     ;
1013             }
1014             break;
1015
1016         case PA_SINK_MESSAGE_GET_LATENCY: {
1017
1018             if (u->read_smoother) {
1019                 pa_usec_t wi, ri;
1020
1021                 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1022                 wi = pa_bytes_to_usec(u->write_index + u->block_size, &u->sample_spec);
1023
1024                 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1025             } else {
1026                 pa_usec_t ri, wi;
1027
1028                 ri = pa_rtclock_now() - u->started_at;
1029                 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1030
1031                 *((pa_usec_t*) data) = wi > ri ? wi - ri : 0;
1032             }
1033
1034             *((pa_usec_t*) data) += u->sink->thread_info.fixed_latency;
1035             return 0;
1036         }
1037     }
1038
1039     r = pa_sink_process_msg(o, code, data, offset, chunk);
1040
1041     return (r < 0 || !failed) ? r : -1;
1042 }
1043
1044 /* Run from IO thread */
1045 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1046     struct userdata *u = PA_SOURCE(o)->userdata;
1047     pa_bool_t failed = FALSE;
1048     int r;
1049
1050     pa_assert(u->source == PA_SOURCE(o));
1051
1052     switch (code) {
1053
1054         case PA_SOURCE_MESSAGE_SET_STATE:
1055
1056             switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
1057
1058                 case PA_SOURCE_SUSPENDED:
1059                     pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
1060
1061                     /* Stop the device if the sink is suspended as well */
1062                     if (!u->sink || u->sink->state == PA_SINK_SUSPENDED) {
1063                         if (u->transport)
1064                             bt_transport_release(u);
1065                         else
1066                             stop_stream_fd(u);
1067                     }
1068
1069                     if (u->read_smoother)
1070                         pa_smoother_pause(u->read_smoother, pa_rtclock_now());
1071                     break;
1072
1073                 case PA_SOURCE_IDLE:
1074                 case PA_SOURCE_RUNNING:
1075                     if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
1076                         break;
1077
1078                     /* Resume the device if the sink was suspended as well */
1079                     if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED) {
1080                         if (u->transport) {
1081                             if (bt_transport_acquire(u, TRUE) < 0)
1082                             failed = TRUE;
1083                         } else if (start_stream_fd(u) < 0)
1084                             failed = TRUE;
1085                     }
1086                     /* We don't resume the smoother here. Instead we
1087                      * wait until the first packet arrives */
1088                     break;
1089
1090                 case PA_SOURCE_UNLINKED:
1091                 case PA_SOURCE_INIT:
1092                 case PA_SOURCE_INVALID_STATE:
1093                     ;
1094             }
1095             break;
1096
1097         case PA_SOURCE_MESSAGE_GET_LATENCY: {
1098             pa_usec_t wi, ri;
1099
1100             if (u->read_smoother) {
1101                 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1102                 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
1103
1104                 *((pa_usec_t*) data) = (wi > ri ? wi - ri : 0) + u->source->thread_info.fixed_latency;
1105             } else
1106                 *((pa_usec_t*) data) = 0;
1107
1108             return 0;
1109         }
1110
1111     }
1112
1113     r = pa_source_process_msg(o, code, data, offset, chunk);
1114
1115     return (r < 0 || !failed) ? r : -1;
1116 }
1117
1118 /* Run from IO thread */
1119 static int hsp_process_render(struct userdata *u) {
1120     int ret = 0;
1121
1122     pa_assert(u);
1123     pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1124     pa_assert(u->sink);
1125
1126     /* First, render some data */
1127     if (!u->write_memchunk.memblock)
1128         pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1129
1130     pa_assert(u->write_memchunk.length == u->block_size);
1131
1132     for (;;) {
1133         ssize_t l;
1134         const void *p;
1135
1136         /* Now write that data to the socket. The socket is of type
1137          * SEQPACKET, and we generated the data of the MTU size, so this
1138          * should just work. */
1139
1140         p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1141         l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
1142         pa_memblock_release(u->write_memchunk.memblock);
1143
1144         pa_assert(l != 0);
1145
1146         if (l < 0) {
1147
1148             if (errno == EINTR)
1149                 /* Retry right away if we got interrupted */
1150                 continue;
1151
1152             else if (errno == EAGAIN)
1153                 /* Hmm, apparently the socket was not writable, give up for now */
1154                 break;
1155
1156             pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
1157             ret = -1;
1158             break;
1159         }
1160
1161         pa_assert((size_t) l <= u->write_memchunk.length);
1162
1163         if ((size_t) l != u->write_memchunk.length) {
1164             pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1165                         (unsigned long long) l,
1166                         (unsigned long long) u->write_memchunk.length);
1167             ret = -1;
1168             break;
1169         }
1170
1171         u->write_index += (uint64_t) u->write_memchunk.length;
1172         pa_memblock_unref(u->write_memchunk.memblock);
1173         pa_memchunk_reset(&u->write_memchunk);
1174
1175         ret = 1;
1176         break;
1177     }
1178
1179     return ret;
1180 }
1181
1182 /* Run from IO thread */
1183 static int hsp_process_push(struct userdata *u) {
1184     int ret = 0;
1185     pa_memchunk memchunk;
1186
1187     pa_assert(u);
1188     pa_assert(u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW);
1189     pa_assert(u->source);
1190     pa_assert(u->read_smoother);
1191
1192     memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1193     memchunk.index = memchunk.length = 0;
1194
1195     for (;;) {
1196         ssize_t l;
1197         void *p;
1198         struct msghdr m;
1199         struct cmsghdr *cm;
1200         uint8_t aux[1024];
1201         struct iovec iov;
1202         pa_bool_t found_tstamp = FALSE;
1203         pa_usec_t tstamp;
1204
1205         memset(&m, 0, sizeof(m));
1206         memset(&aux, 0, sizeof(aux));
1207         memset(&iov, 0, sizeof(iov));
1208
1209         m.msg_iov = &iov;
1210         m.msg_iovlen = 1;
1211         m.msg_control = aux;
1212         m.msg_controllen = sizeof(aux);
1213
1214         p = pa_memblock_acquire(memchunk.memblock);
1215         iov.iov_base = p;
1216         iov.iov_len = pa_memblock_get_length(memchunk.memblock);
1217         l = recvmsg(u->stream_fd, &m, 0);
1218         pa_memblock_release(memchunk.memblock);
1219
1220         if (l <= 0) {
1221
1222             if (l < 0 && errno == EINTR)
1223                 /* Retry right away if we got interrupted */
1224                 continue;
1225
1226             else if (l < 0 && errno == EAGAIN)
1227                 /* Hmm, apparently the socket was not readable, give up for now. */
1228                 break;
1229
1230             pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1231             ret = -1;
1232             break;
1233         }
1234
1235         pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
1236
1237         memchunk.length = (size_t) l;
1238         u->read_index += (uint64_t) l;
1239
1240         for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
1241             if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
1242                 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
1243                 pa_rtclock_from_wallclock(tv);
1244                 tstamp = pa_timeval_load(tv);
1245                 found_tstamp = TRUE;
1246                 break;
1247             }
1248
1249         if (!found_tstamp) {
1250             pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
1251             tstamp = pa_rtclock_now();
1252         }
1253
1254         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1255         pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1256
1257         pa_source_post(u->source, &memchunk);
1258
1259         ret = 1;
1260         break;
1261     }
1262
1263     pa_memblock_unref(memchunk.memblock);
1264
1265     return ret;
1266 }
1267
1268 /* Run from IO thread */
1269 static void a2dp_prepare_buffer(struct userdata *u) {
1270     pa_assert(u);
1271
1272     if (u->a2dp.buffer_size >= u->link_mtu)
1273         return;
1274
1275     u->a2dp.buffer_size = 2 * u->link_mtu;
1276     pa_xfree(u->a2dp.buffer);
1277     u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1278 }
1279
1280 /* Run from IO thread */
1281 static int a2dp_process_render(struct userdata *u) {
1282     struct a2dp_info *a2dp;
1283     struct rtp_header *header;
1284     struct rtp_payload *payload;
1285     size_t nbytes;
1286     void *d;
1287     const void *p;
1288     size_t to_write, to_encode;
1289     unsigned frame_count;
1290     int ret = 0;
1291
1292     pa_assert(u);
1293     pa_assert(u->profile == PROFILE_A2DP);
1294     pa_assert(u->sink);
1295
1296     /* First, render some data */
1297     if (!u->write_memchunk.memblock)
1298         pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1299
1300     pa_assert(u->write_memchunk.length == u->block_size);
1301
1302     a2dp_prepare_buffer(u);
1303
1304     a2dp = &u->a2dp;
1305     header = a2dp->buffer;
1306     payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1307
1308     frame_count = 0;
1309
1310     /* Try to create a packet of the full MTU */
1311
1312     p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1313     to_encode = u->write_memchunk.length;
1314
1315     d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1316     to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1317
1318     while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1319         ssize_t written;
1320         ssize_t encoded;
1321
1322         encoded = sbc_encode(&a2dp->sbc,
1323                              p, to_encode,
1324                              d, to_write,
1325                              &written);
1326
1327         if (PA_UNLIKELY(encoded <= 0)) {
1328             pa_log_error("SBC encoding error (%li)", (long) encoded);
1329             pa_memblock_release(u->write_memchunk.memblock);
1330             return -1;
1331         }
1332
1333 /*         pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1334 /*         pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1335
1336         pa_assert_fp((size_t) encoded <= to_encode);
1337         pa_assert_fp((size_t) encoded == a2dp->codesize);
1338
1339         pa_assert_fp((size_t) written <= to_write);
1340         pa_assert_fp((size_t) written == a2dp->frame_length);
1341
1342         p = (const uint8_t*) p + encoded;
1343         to_encode -= encoded;
1344
1345         d = (uint8_t*) d + written;
1346         to_write -= written;
1347
1348         frame_count++;
1349     }
1350
1351     pa_memblock_release(u->write_memchunk.memblock);
1352
1353     pa_assert(to_encode == 0);
1354
1355     PA_ONCE_BEGIN {
1356         pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1357     } PA_ONCE_END;
1358
1359     /* write it to the fifo */
1360     memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1361     header->v = 2;
1362     header->pt = 1;
1363     header->sequence_number = htons(a2dp->seq_num++);
1364     header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
1365     header->ssrc = htonl(1);
1366     payload->frame_count = frame_count;
1367
1368     nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1369
1370     for (;;) {
1371         ssize_t l;
1372
1373         l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1374
1375         pa_assert(l != 0);
1376
1377         if (l < 0) {
1378
1379             if (errno == EINTR)
1380                 /* Retry right away if we got interrupted */
1381                 continue;
1382
1383             else if (errno == EAGAIN)
1384                 /* Hmm, apparently the socket was not writable, give up for now */
1385                 break;
1386
1387             pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1388             ret = -1;
1389             break;
1390         }
1391
1392         pa_assert((size_t) l <= nbytes);
1393
1394         if ((size_t) l != nbytes) {
1395             pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1396                         (unsigned long long) l,
1397                         (unsigned long long) nbytes);
1398             ret = -1;
1399             break;
1400         }
1401
1402         u->write_index += (uint64_t) u->write_memchunk.length;
1403         pa_memblock_unref(u->write_memchunk.memblock);
1404         pa_memchunk_reset(&u->write_memchunk);
1405
1406         ret = 1;
1407
1408         break;
1409     }
1410
1411     return ret;
1412 }
1413
1414 static int a2dp_process_push(struct userdata *u) {
1415     int ret = 0;
1416     pa_memchunk memchunk;
1417
1418     pa_assert(u);
1419     pa_assert(u->profile == PROFILE_A2DP_SOURCE);
1420     pa_assert(u->source);
1421     pa_assert(u->read_smoother);
1422
1423     memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
1424     memchunk.index = memchunk.length = 0;
1425
1426     for (;;) {
1427         pa_bool_t found_tstamp = FALSE;
1428         pa_usec_t tstamp;
1429         struct a2dp_info *a2dp;
1430         struct rtp_header *header;
1431         struct rtp_payload *payload;
1432         const void *p;
1433         void *d;
1434         ssize_t l;
1435         size_t to_write, to_decode;
1436         unsigned frame_count;
1437
1438         a2dp_prepare_buffer(u);
1439
1440         a2dp = &u->a2dp;
1441         header = a2dp->buffer;
1442         payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1443
1444         l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
1445
1446         if (l <= 0) {
1447
1448             if (l < 0 && errno == EINTR)
1449                 /* Retry right away if we got interrupted */
1450                 continue;
1451
1452             else if (l < 0 && errno == EAGAIN)
1453                 /* Hmm, apparently the socket was not readable, give up for now. */
1454                 break;
1455
1456             pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
1457             ret = -1;
1458             break;
1459         }
1460
1461         pa_assert((size_t) l <= a2dp->buffer_size);
1462
1463         u->read_index += (uint64_t) l;
1464
1465         /* TODO: get timestamp from rtp */
1466         if (!found_tstamp) {
1467             /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
1468             tstamp = pa_rtclock_now();
1469         }
1470
1471         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
1472         pa_smoother_resume(u->read_smoother, tstamp, TRUE);
1473
1474         p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1475         to_decode = l - sizeof(*header) - sizeof(*payload);
1476
1477         d = pa_memblock_acquire(memchunk.memblock);
1478         to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
1479
1480         while (PA_LIKELY(to_decode > 0)) {
1481             size_t written;
1482             ssize_t decoded;
1483
1484             decoded = sbc_decode(&a2dp->sbc,
1485                                  p, to_decode,
1486                                  d, to_write,
1487                                  &written);
1488
1489             if (PA_UNLIKELY(decoded <= 0)) {
1490                 pa_log_error("SBC decoding error (%li)", (long) decoded);
1491                 pa_memblock_release(memchunk.memblock);
1492                 pa_memblock_unref(memchunk.memblock);
1493                 return -1;
1494             }
1495
1496 /*             pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
1497 /*             pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
1498
1499             /* Reset frame length, it can be changed due to bitpool change */
1500             a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1501
1502             pa_assert_fp((size_t) decoded <= to_decode);
1503             pa_assert_fp((size_t) decoded == a2dp->frame_length);
1504
1505             pa_assert_fp((size_t) written == a2dp->codesize);
1506
1507             p = (const uint8_t*) p + decoded;
1508             to_decode -= decoded;
1509
1510             d = (uint8_t*) d + written;
1511             to_write -= written;
1512
1513             frame_count++;
1514         }
1515
1516         memchunk.length -= to_write;
1517
1518         pa_memblock_release(memchunk.memblock);
1519
1520         pa_source_post(u->source, &memchunk);
1521
1522         ret = 1;
1523         break;
1524     }
1525
1526     pa_memblock_unref(memchunk.memblock);
1527
1528     return ret;
1529 }
1530
1531 static void a2dp_reduce_bitpool(struct userdata *u)
1532 {
1533     struct a2dp_info *a2dp;
1534     uint8_t bitpool;
1535
1536     pa_assert(u);
1537
1538     a2dp = &u->a2dp;
1539
1540     /* Check if bitpool is already at its limit */
1541     if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
1542         return;
1543
1544     bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
1545
1546     if (bitpool < BITPOOL_DEC_LIMIT)
1547         bitpool = BITPOOL_DEC_LIMIT;
1548
1549     a2dp_set_bitpool(u, bitpool);
1550 }
1551
1552 static void thread_func(void *userdata) {
1553     struct userdata *u = userdata;
1554     unsigned do_write = 0;
1555     pa_bool_t writable = FALSE;
1556
1557     pa_assert(u);
1558
1559     pa_log_debug("IO Thread starting up");
1560
1561     if (u->core->realtime_scheduling)
1562         pa_make_realtime(u->core->realtime_priority);
1563
1564     pa_thread_mq_install(&u->thread_mq);
1565
1566     if (u->transport) {
1567         if (bt_transport_acquire(u, TRUE) < 0)
1568             goto fail;
1569     } else if (start_stream_fd(u) < 0)
1570         goto fail;
1571
1572     for (;;) {
1573         struct pollfd *pollfd;
1574         int ret;
1575         pa_bool_t disable_timer = TRUE;
1576
1577         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1578
1579         if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1580
1581             /* We should send two blocks to the device before we expect
1582              * a response. */
1583
1584             if (u->write_index == 0 && u->read_index <= 0)
1585                 do_write = 2;
1586
1587             if (pollfd && (pollfd->revents & POLLIN)) {
1588                 int n_read;
1589
1590                 if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)
1591                     n_read = hsp_process_push(u);
1592                 else
1593                     n_read = a2dp_process_push(u);
1594
1595                 if (n_read < 0)
1596                     goto fail;
1597
1598                 /* We just read something, so we are supposed to write something, too */
1599                 do_write += n_read;
1600             }
1601         }
1602
1603         if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1604
1605             if (u->sink->thread_info.rewind_requested)
1606                 pa_sink_process_rewind(u->sink, 0);
1607
1608             if (pollfd) {
1609                 if (pollfd->revents & POLLOUT)
1610                     writable = TRUE;
1611
1612                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1613                     pa_usec_t time_passed;
1614                     pa_usec_t audio_sent;
1615
1616                     /* Hmm, there is no input stream we could synchronize
1617                      * to. So let's do things by time */
1618
1619                     time_passed = pa_rtclock_now() - u->started_at;
1620                     audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1621
1622                     if (audio_sent <= time_passed) {
1623                         pa_usec_t audio_to_send = time_passed - audio_sent;
1624
1625                         /* Never try to catch up for more than 100ms */
1626                         if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1627                             pa_usec_t skip_usec;
1628                             uint64_t skip_bytes;
1629
1630                             skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1631                             skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1632
1633                             if (skip_bytes > 0) {
1634                                 pa_memchunk tmp;
1635
1636                                 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1637                                             (unsigned long long) skip_usec,
1638                                             (unsigned long long) skip_bytes);
1639
1640                                 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1641                                 pa_memblock_unref(tmp.memblock);
1642                                 u->write_index += skip_bytes;
1643
1644                                 if (u->profile == PROFILE_A2DP)
1645                                     a2dp_reduce_bitpool(u);
1646                             }
1647                         }
1648
1649                         do_write = 1;
1650                     }
1651                 }
1652
1653                 if (writable && do_write > 0) {
1654                     int n_written;
1655
1656                     if (u->write_index <= 0)
1657                         u->started_at = pa_rtclock_now();
1658
1659                     if (u->profile == PROFILE_A2DP) {
1660                         if ((n_written = a2dp_process_render(u)) < 0)
1661                             goto fail;
1662                     } else {
1663                         if ((n_written = hsp_process_render(u)) < 0)
1664                             goto fail;
1665                     }
1666
1667                     if (n_written == 0)
1668                         pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1669
1670                     do_write -= n_written;
1671                     writable = FALSE;
1672                 }
1673
1674                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1675                     pa_usec_t sleep_for;
1676                     pa_usec_t time_passed, next_write_at;
1677
1678                     if (writable) {
1679                         /* Hmm, there is no input stream we could synchronize
1680                          * to. So let's estimate when we need to wake up the latest */
1681                         time_passed = pa_rtclock_now() - u->started_at;
1682                         next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1683                         sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1684                         /* 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); */
1685                     } else
1686                         /* drop stream every 500 ms */
1687                         sleep_for = PA_USEC_PER_MSEC * 500;
1688
1689                     pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1690                     disable_timer = FALSE;
1691                 }
1692             }
1693         }
1694
1695         if (disable_timer)
1696             pa_rtpoll_set_timer_disabled(u->rtpoll);
1697
1698         /* Hmm, nothing to do. Let's sleep */
1699         if (pollfd)
1700             pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1701                                       (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1702
1703         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1704             goto fail;
1705
1706         if (ret == 0)
1707             goto finish;
1708
1709         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1710
1711         if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1712             pa_log_info("FD error: %s%s%s%s",
1713                         pollfd->revents & POLLERR ? "POLLERR " :"",
1714                         pollfd->revents & POLLHUP ? "POLLHUP " :"",
1715                         pollfd->revents & POLLPRI ? "POLLPRI " :"",
1716                         pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1717             goto fail;
1718         }
1719     }
1720
1721 fail:
1722     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1723     pa_log_debug("IO thread failed");
1724     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1725     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1726
1727 finish:
1728     pa_log_debug("IO thread shutting down");
1729 }
1730
1731 /* Run from main thread */
1732 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1733     DBusError err;
1734     struct userdata *u;
1735
1736     pa_assert(bus);
1737     pa_assert(m);
1738     pa_assert_se(u = userdata);
1739
1740     dbus_error_init(&err);
1741
1742     pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1743                  dbus_message_get_interface(m),
1744                  dbus_message_get_path(m),
1745                  dbus_message_get_member(m));
1746
1747     if (!dbus_message_has_path(m, u->path) && !dbus_message_has_path(m, u->transport))
1748         goto fail;
1749
1750     if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1751         dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1752
1753         dbus_uint16_t gain;
1754         pa_cvolume v;
1755
1756         if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1757             pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1758             goto fail;
1759         }
1760
1761         if (u->profile == PROFILE_HSP) {
1762             if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1763
1764                 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1765                 pa_sink_volume_changed(u->sink, &v);
1766
1767             } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1768
1769                 pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1770                 pa_source_volume_changed(u->source, &v);
1771             }
1772         }
1773     } else if (dbus_message_is_signal(m, "org.bluez.MediaTransport", "PropertyChanged")) {
1774         DBusMessageIter arg_i;
1775         pa_bluetooth_transport *t;
1776         pa_bool_t nrec;
1777
1778         t = (pa_bluetooth_transport *) pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
1779         pa_assert(t);
1780
1781         if (!dbus_message_iter_init(m, &arg_i)) {
1782             pa_log("Failed to parse PropertyChanged: %s", err.message);
1783             goto fail;
1784         }
1785
1786         nrec = t->nrec;
1787
1788         if (pa_bluetooth_transport_parse_property(t, &arg_i) < 0)
1789             goto fail;
1790
1791         if (nrec != t->nrec) {
1792             pa_log_debug("dbus: property 'NREC' changed to value '%s'", t->nrec ? "True" : "False");
1793             pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1794         }
1795     }
1796
1797 fail:
1798     dbus_error_free(&err);
1799
1800     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1801 }
1802
1803 /* Run from main thread */
1804 static void sink_set_volume_cb(pa_sink *s) {
1805     DBusMessage *m;
1806     dbus_uint16_t gain;
1807     struct userdata *u;
1808     char *k;
1809
1810     pa_assert(s);
1811     pa_assert(s->core);
1812
1813     k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1814     u = pa_shared_get(s->core, k);
1815     pa_xfree(k);
1816
1817     pa_assert(u);
1818     pa_assert(u->sink == s);
1819     pa_assert(u->profile == PROFILE_HSP);
1820
1821     gain = (pa_cvolume_max(&s->real_volume) * 15) / PA_VOLUME_NORM;
1822
1823     if (gain > 15)
1824         gain = 15;
1825
1826     pa_cvolume_set(&s->real_volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1827
1828     pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1829     pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1830     pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1831     dbus_message_unref(m);
1832 }
1833
1834 /* Run from main thread */
1835 static void source_set_volume_cb(pa_source *s) {
1836     DBusMessage *m;
1837     dbus_uint16_t gain;
1838     struct userdata *u;
1839     char *k;
1840
1841     pa_assert(s);
1842     pa_assert(s->core);
1843
1844     k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1845     u = pa_shared_get(s->core, k);
1846     pa_xfree(k);
1847
1848     pa_assert(u);
1849     pa_assert(u->source == s);
1850     pa_assert(u->profile == PROFILE_HSP);
1851
1852     gain = (pa_cvolume_max(&s->volume) * 15) / PA_VOLUME_NORM;
1853
1854     if (gain > 15)
1855         gain = 15;
1856
1857     pa_cvolume_set(&s->volume, u->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1858
1859     pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1860     pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1861     pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1862     dbus_message_unref(m);
1863 }
1864
1865 /* Run from main thread */
1866 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1867     char *t;
1868     const char *n;
1869
1870     pa_assert(type);
1871     pa_assert(ma);
1872     pa_assert(device_id);
1873     pa_assert(namereg_fail);
1874
1875     t = pa_sprintf_malloc("%s_name", type);
1876     n = pa_modargs_get_value(ma, t, NULL);
1877     pa_xfree(t);
1878
1879     if (n) {
1880         *namereg_fail = TRUE;
1881         return pa_xstrdup(n);
1882     }
1883
1884     if ((n = pa_modargs_get_value(ma, "name", NULL)))
1885         *namereg_fail = TRUE;
1886     else {
1887         n = device_id;
1888         *namereg_fail = FALSE;
1889     }
1890
1891     return pa_sprintf_malloc("bluez_%s.%s", type, n);
1892 }
1893
1894 static int sco_over_pcm_state_update(struct userdata *u) {
1895     pa_assert(u);
1896     pa_assert(USE_SCO_OVER_PCM(u));
1897
1898     if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1899         PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1900
1901         if (u->service_fd >= 0 && u->stream_fd >= 0)
1902             return 0;
1903
1904         init_bt(u);
1905
1906         pa_log_debug("Resuming SCO over PCM");
1907         if (init_profile(u) < 0) {
1908             pa_log("Can't resume SCO over PCM");
1909             return -1;
1910         }
1911
1912         if (u->transport)
1913             return bt_transport_acquire(u, TRUE);
1914         else
1915             return start_stream_fd(u);
1916
1917     } else {
1918         if (u->service_fd < 0 && u->stream_fd < 0)
1919             return 0;
1920
1921         pa_log_debug("Closing SCO over PCM");
1922
1923         if (u->transport)
1924             bt_transport_release(u);
1925         else if (u->stream_fd >= 0)
1926             stop_stream_fd(u);
1927
1928         if (u->service_fd >= 0) {
1929             pa_close(u->service_fd);
1930             u->service_fd = -1;
1931         }
1932
1933         return 0;
1934     }
1935 }
1936
1937 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1938     pa_assert(c);
1939     pa_sink_assert_ref(s);
1940     pa_assert(u);
1941
1942     if (s != u->hsp.sco_sink)
1943         return PA_HOOK_OK;
1944
1945     sco_over_pcm_state_update(u);
1946
1947     return PA_HOOK_OK;
1948 }
1949
1950 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1951     pa_assert(c);
1952     pa_source_assert_ref(s);
1953     pa_assert(u);
1954
1955     if (s != u->hsp.sco_source)
1956         return PA_HOOK_OK;
1957
1958     sco_over_pcm_state_update(u);
1959
1960     return PA_HOOK_OK;
1961 }
1962
1963 /* Run from main thread */
1964 static int add_sink(struct userdata *u) {
1965     char *k;
1966
1967     if (USE_SCO_OVER_PCM(u)) {
1968         pa_proplist *p;
1969
1970         u->sink = u->hsp.sco_sink;
1971         p = pa_proplist_new();
1972         pa_proplist_sets(p, "bluetooth.protocol", "sco");
1973         pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1974         pa_proplist_free(p);
1975
1976         if (!u->hsp.sink_state_changed_slot)
1977             u->hsp.sink_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
1978
1979     } else {
1980         pa_sink_new_data data;
1981         pa_bool_t b;
1982
1983         pa_sink_new_data_init(&data);
1984         data.driver = __FILE__;
1985         data.module = u->module;
1986         pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1987         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1988         if (u->profile == PROFILE_HSP)
1989             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1990         data.card = u->card;
1991         data.name = get_name("sink", u->modargs, u->address, &b);
1992         data.namereg_fail = b;
1993
1994         if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1995             pa_log("Invalid properties");
1996             pa_sink_new_data_done(&data);
1997             return -1;
1998         }
1999
2000         u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
2001         pa_sink_new_data_done(&data);
2002
2003         if (!u->sink) {
2004             pa_log_error("Failed to create sink");
2005             return -1;
2006         }
2007
2008         u->sink->userdata = u;
2009         u->sink->parent.process_msg = sink_process_msg;
2010
2011         pa_sink_set_max_request(u->sink, u->block_size);
2012         pa_sink_set_fixed_latency(u->sink,
2013                                   (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
2014                                   pa_bytes_to_usec(u->block_size, &u->sample_spec));
2015     }
2016
2017     if (u->profile == PROFILE_HSP) {
2018         u->sink->set_volume = sink_set_volume_cb;
2019         u->sink->n_volume_steps = 16;
2020
2021         k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2022         pa_shared_set(u->core, k, u);
2023         pa_xfree(k);
2024     }
2025
2026     return 0;
2027 }
2028
2029 /* Run from main thread */
2030 static int add_source(struct userdata *u) {
2031     char *k;
2032
2033     if (USE_SCO_OVER_PCM(u)) {
2034         u->source = u->hsp.sco_source;
2035         pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2036
2037         if (!u->hsp.source_state_changed_slot)
2038             u->hsp.source_state_changed_slot = pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2039
2040     } else {
2041         pa_source_new_data data;
2042         pa_bool_t b;
2043
2044         pa_source_new_data_init(&data);
2045         data.driver = __FILE__;
2046         data.module = u->module;
2047         pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2048         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2049         if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2050             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2051
2052         data.card = u->card;
2053         data.name = get_name("source", u->modargs, u->address, &b);
2054         data.namereg_fail = b;
2055
2056         if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2057             pa_log("Invalid properties");
2058             pa_source_new_data_done(&data);
2059             return -1;
2060         }
2061
2062         u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2063         pa_source_new_data_done(&data);
2064
2065         if (!u->source) {
2066             pa_log_error("Failed to create source");
2067             return -1;
2068         }
2069
2070         u->source->userdata = u;
2071         u->source->parent.process_msg = source_process_msg;
2072
2073         pa_source_set_fixed_latency(u->source,
2074                                     (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2075                                     pa_bytes_to_usec(u->block_size, &u->sample_spec));
2076     }
2077
2078     if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2079         if (u->transport) {
2080             const pa_bluetooth_transport *t;
2081             t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2082             pa_assert(t);
2083             pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2084         } else
2085             pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2086     }
2087
2088     if (u->profile == PROFILE_HSP) {
2089         u->source->set_volume = source_set_volume_cb;
2090         u->source->n_volume_steps = 16;
2091
2092         k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2093         pa_shared_set(u->core, k, u);
2094         pa_xfree(k);
2095     }
2096
2097     return 0;
2098 }
2099
2100 /* Run from main thread */
2101 static void shutdown_bt(struct userdata *u) {
2102     pa_assert(u);
2103
2104     if (u->stream_fd >= 0) {
2105         pa_close(u->stream_fd);
2106         u->stream_fd = -1;
2107
2108         u->stream_write_type = 0;
2109     }
2110
2111     if (u->service_fd >= 0) {
2112         pa_close(u->service_fd);
2113         u->service_fd = -1;
2114         u->service_write_type = 0;
2115         u->service_read_type = 0;
2116     }
2117
2118     if (u->write_memchunk.memblock) {
2119         pa_memblock_unref(u->write_memchunk.memblock);
2120         pa_memchunk_reset(&u->write_memchunk);
2121     }
2122 }
2123
2124 static int bt_transport_config_a2dp(struct userdata *u) {
2125     const pa_bluetooth_transport *t;
2126     struct a2dp_info *a2dp = &u->a2dp;
2127     a2dp_sbc_t *config;
2128
2129     t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2130     pa_assert(t);
2131
2132     config = (a2dp_sbc_t *) t->config;
2133
2134     if (a2dp->sbc_initialized)
2135         sbc_reinit(&a2dp->sbc, 0);
2136     else
2137         sbc_init(&a2dp->sbc, 0);
2138     a2dp->sbc_initialized = TRUE;
2139
2140     switch (config->frequency) {
2141         case BT_SBC_SAMPLING_FREQ_16000:
2142             a2dp->sbc.frequency = SBC_FREQ_16000;
2143             break;
2144         case BT_SBC_SAMPLING_FREQ_32000:
2145             a2dp->sbc.frequency = SBC_FREQ_32000;
2146             break;
2147         case BT_SBC_SAMPLING_FREQ_44100:
2148             a2dp->sbc.frequency = SBC_FREQ_44100;
2149             break;
2150         case BT_SBC_SAMPLING_FREQ_48000:
2151             a2dp->sbc.frequency = SBC_FREQ_48000;
2152             break;
2153         default:
2154             pa_assert_not_reached();
2155     }
2156
2157     switch (config->channel_mode) {
2158         case BT_A2DP_CHANNEL_MODE_MONO:
2159             a2dp->sbc.mode = SBC_MODE_MONO;
2160             break;
2161         case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2162             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2163             break;
2164         case BT_A2DP_CHANNEL_MODE_STEREO:
2165             a2dp->sbc.mode = SBC_MODE_STEREO;
2166             break;
2167         case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2168             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2169             break;
2170         default:
2171             pa_assert_not_reached();
2172     }
2173
2174     switch (config->allocation_method) {
2175         case BT_A2DP_ALLOCATION_SNR:
2176             a2dp->sbc.allocation = SBC_AM_SNR;
2177             break;
2178         case BT_A2DP_ALLOCATION_LOUDNESS:
2179             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2180             break;
2181         default:
2182             pa_assert_not_reached();
2183     }
2184
2185     switch (config->subbands) {
2186         case BT_A2DP_SUBBANDS_4:
2187             a2dp->sbc.subbands = SBC_SB_4;
2188             break;
2189         case BT_A2DP_SUBBANDS_8:
2190             a2dp->sbc.subbands = SBC_SB_8;
2191             break;
2192         default:
2193             pa_assert_not_reached();
2194     }
2195
2196     switch (config->block_length) {
2197         case BT_A2DP_BLOCK_LENGTH_4:
2198             a2dp->sbc.blocks = SBC_BLK_4;
2199             break;
2200         case BT_A2DP_BLOCK_LENGTH_8:
2201             a2dp->sbc.blocks = SBC_BLK_8;
2202             break;
2203         case BT_A2DP_BLOCK_LENGTH_12:
2204             a2dp->sbc.blocks = SBC_BLK_12;
2205             break;
2206         case BT_A2DP_BLOCK_LENGTH_16:
2207             a2dp->sbc.blocks = SBC_BLK_16;
2208             break;
2209         default:
2210             pa_assert_not_reached();
2211     }
2212
2213     a2dp->min_bitpool = config->min_bitpool;
2214     a2dp->max_bitpool = config->max_bitpool;
2215
2216     /* Set minimum bitpool for source to get the maximum possible block_size */
2217     a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2218     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2219     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2220
2221     u->block_size =
2222         ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2223         / a2dp->frame_length
2224         * a2dp->codesize);
2225
2226     pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2227                 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2228
2229     return 0;
2230 }
2231
2232 static int bt_transport_config(struct userdata *u) {
2233     if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2234         u->block_size = u->link_mtu;
2235         return 0;
2236     }
2237
2238     return bt_transport_config_a2dp(u);
2239 }
2240
2241 /* Run from main thread */
2242 static int bt_transport_open(struct userdata *u) {
2243     if (bt_transport_acquire(u, FALSE) < 0)
2244         return -1;
2245
2246     return bt_transport_config(u);
2247 }
2248
2249 /* Run from main thread */
2250 static int init_bt(struct userdata *u) {
2251     pa_assert(u);
2252
2253     shutdown_bt(u);
2254
2255     u->stream_write_type = 0;
2256     u->service_write_type = 0;
2257     u->service_read_type = 0;
2258
2259     if ((u->service_fd = bt_audio_service_open()) < 0) {
2260         pa_log_warn("Bluetooth audio service not available");
2261         return -1;
2262     }
2263
2264     pa_log_debug("Connected to the bluetooth audio service");
2265
2266     return 0;
2267 }
2268
2269 /* Run from main thread */
2270 static int setup_bt(struct userdata *u) {
2271     const pa_bluetooth_device *d;
2272     const pa_bluetooth_transport *t;
2273
2274     pa_assert(u);
2275
2276     if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2277         pa_log_error("Failed to get device object.");
2278         return -1;
2279     }
2280
2281     /* release transport if exist */
2282     if (u->transport) {
2283         bt_transport_release(u);
2284         pa_xfree(u->transport);
2285         u->transport = NULL;
2286     }
2287
2288     /* check if profile has a transport */
2289     t = pa_bluetooth_device_get_transport(d, u->profile);
2290     if (t) {
2291         u->transport = pa_xstrdup(t->path);
2292         return bt_transport_open(u);
2293     }
2294
2295     if (get_caps(u, 0) < 0)
2296         return -1;
2297
2298     pa_log_debug("Got device capabilities");
2299
2300     if (set_conf(u) < 0)
2301         return -1;
2302
2303     pa_log_debug("Connection to the device configured");
2304
2305     if (USE_SCO_OVER_PCM(u)) {
2306         pa_log_debug("Configured to use SCO over PCM");
2307         return 0;
2308     }
2309
2310     pa_log_debug("Got the stream socket");
2311
2312     return 0;
2313 }
2314
2315 /* Run from main thread */
2316 static int init_profile(struct userdata *u) {
2317     int r = 0;
2318     pa_assert(u);
2319     pa_assert(u->profile != PROFILE_OFF);
2320
2321     if (setup_bt(u) < 0)
2322         return -1;
2323
2324     if (u->profile == PROFILE_A2DP ||
2325         u->profile == PROFILE_HSP ||
2326         u->profile == PROFILE_HFGW)
2327         if (add_sink(u) < 0)
2328             r = -1;
2329
2330     if (u->profile == PROFILE_HSP ||
2331         u->profile == PROFILE_A2DP_SOURCE ||
2332         u->profile == PROFILE_HFGW)
2333         if (add_source(u) < 0)
2334             r = -1;
2335
2336     return r;
2337 }
2338
2339 /* Run from main thread */
2340 static void stop_thread(struct userdata *u) {
2341     char *k;
2342
2343     pa_assert(u);
2344
2345     if (u->thread) {
2346         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2347         pa_thread_free(u->thread);
2348         u->thread = NULL;
2349     }
2350
2351     if (u->rtpoll_item) {
2352         pa_rtpoll_item_free(u->rtpoll_item);
2353         u->rtpoll_item = NULL;
2354     }
2355
2356     if (u->hsp.sink_state_changed_slot) {
2357         pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2358         u->hsp.sink_state_changed_slot = NULL;
2359     }
2360
2361     if (u->hsp.source_state_changed_slot) {
2362         pa_hook_slot_free(u->hsp.source_state_changed_slot);
2363         u->hsp.source_state_changed_slot = NULL;
2364     }
2365
2366     if (u->sink) {
2367         if (u->profile == PROFILE_HSP) {
2368             k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2369             pa_shared_remove(u->core, k);
2370             pa_xfree(k);
2371         }
2372
2373         pa_sink_unref(u->sink);
2374         u->sink = NULL;
2375     }
2376
2377     if (u->source) {
2378         if (u->profile == PROFILE_HSP) {
2379             k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2380             pa_shared_remove(u->core, k);
2381             pa_xfree(k);
2382         }
2383
2384         pa_source_unref(u->source);
2385         u->source = NULL;
2386     }
2387
2388     if (u->rtpoll) {
2389         pa_thread_mq_done(&u->thread_mq);
2390
2391         pa_rtpoll_free(u->rtpoll);
2392         u->rtpoll = NULL;
2393     }
2394
2395     if (u->read_smoother) {
2396         pa_smoother_free(u->read_smoother);
2397         u->read_smoother = NULL;
2398     }
2399 }
2400
2401 /* Run from main thread */
2402 static int start_thread(struct userdata *u) {
2403     pa_assert(u);
2404     pa_assert(!u->thread);
2405     pa_assert(!u->rtpoll);
2406     pa_assert(!u->rtpoll_item);
2407
2408     u->rtpoll = pa_rtpoll_new();
2409     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2410
2411     if (USE_SCO_OVER_PCM(u)) {
2412         if (sco_over_pcm_state_update(u) < 0) {
2413             char *k;
2414
2415             if (u->sink) {
2416                 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
2417                 pa_shared_remove(u->core, k);
2418                 pa_xfree(k);
2419                 u->sink = NULL;
2420             }
2421             if (u->source) {
2422                 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
2423                 pa_shared_remove(u->core, k);
2424                 pa_xfree(k);
2425                 u->source = NULL;
2426             }
2427             return -1;
2428         }
2429
2430         pa_sink_ref(u->sink);
2431         pa_source_ref(u->source);
2432         /* FIXME: monitor stream_fd error */
2433         return 0;
2434     }
2435
2436     if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2437         pa_log_error("Failed to create IO thread");
2438         stop_thread(u);
2439         return -1;
2440     }
2441
2442     if (u->sink) {
2443         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2444         pa_sink_set_rtpoll(u->sink, u->rtpoll);
2445         pa_sink_put(u->sink);
2446
2447         if (u->sink->set_volume)
2448             u->sink->set_volume(u->sink);
2449     }
2450
2451     if (u->source) {
2452         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2453         pa_source_set_rtpoll(u->source, u->rtpoll);
2454         pa_source_put(u->source);
2455
2456         if (u->source->set_volume)
2457             u->source->set_volume(u->source);
2458     }
2459
2460     return 0;
2461 }
2462
2463 static void save_sco_volume_callbacks(struct userdata *u) {
2464     pa_assert(u);
2465     pa_assert(USE_SCO_OVER_PCM(u));
2466
2467     u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2468     u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2469 }
2470
2471 static void restore_sco_volume_callbacks(struct userdata *u) {
2472     pa_assert(u);
2473     pa_assert(USE_SCO_OVER_PCM(u));
2474
2475     u->hsp.sco_sink->set_volume = u->hsp.sco_sink_set_volume;
2476     u->hsp.sco_source->set_volume = u->hsp.sco_source_set_volume;
2477 }
2478
2479 /* Run from main thread */
2480 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2481     struct userdata *u;
2482     enum profile *d;
2483     pa_queue *inputs = NULL, *outputs = NULL;
2484     const pa_bluetooth_device *device;
2485
2486     pa_assert(c);
2487     pa_assert(new_profile);
2488     pa_assert_se(u = c->userdata);
2489
2490     d = PA_CARD_PROFILE_DATA(new_profile);
2491
2492     if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2493         pa_log_error("Failed to get device object.");
2494         return -PA_ERR_IO;
2495     }
2496
2497     /* The state signal is sent by bluez, so it is racy to check
2498        strictly for CONNECTED, we should also accept STREAMING state
2499        as being good enough. However, if the profile is used
2500        concurrently (which is unlikely), ipc will fail later on, and
2501        module will be unloaded. */
2502     if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2503         pa_log_warn("HSP is not connected, refused to switch profile");
2504         return -PA_ERR_IO;
2505     }
2506     else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2507         pa_log_warn("A2DP is not connected, refused to switch profile");
2508         return -PA_ERR_IO;
2509     }
2510     else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2511         pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2512         return -PA_ERR_IO;
2513     }
2514
2515     if (u->sink) {
2516         inputs = pa_sink_move_all_start(u->sink, NULL);
2517
2518         if (!USE_SCO_OVER_PCM(u))
2519             pa_sink_unlink(u->sink);
2520     }
2521
2522     if (u->source) {
2523         outputs = pa_source_move_all_start(u->source, NULL);
2524
2525         if (!USE_SCO_OVER_PCM(u))
2526             pa_source_unlink(u->source);
2527     }
2528
2529     stop_thread(u);
2530     shutdown_bt(u);
2531
2532     if (USE_SCO_OVER_PCM(u))
2533         restore_sco_volume_callbacks(u);
2534
2535     u->profile = *d;
2536     u->sample_spec = u->requested_sample_spec;
2537
2538     if (USE_SCO_OVER_PCM(u))
2539         save_sco_volume_callbacks(u);
2540
2541     init_bt(u);
2542
2543     if (u->profile != PROFILE_OFF)
2544         init_profile(u);
2545
2546     if (u->sink || u->source)
2547         start_thread(u);
2548
2549     if (inputs) {
2550         if (u->sink)
2551             pa_sink_move_all_finish(u->sink, inputs, FALSE);
2552         else
2553             pa_sink_move_all_fail(inputs);
2554     }
2555
2556     if (outputs) {
2557         if (u->source)
2558             pa_source_move_all_finish(u->source, outputs, FALSE);
2559         else
2560             pa_source_move_all_fail(outputs);
2561     }
2562
2563     return 0;
2564 }
2565
2566 /* Run from main thread */
2567 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2568     pa_card_new_data data;
2569     pa_bool_t b;
2570     pa_card_profile *p;
2571     enum profile *d;
2572     const char *ff;
2573     char *n;
2574     const char *default_profile;
2575
2576     pa_assert(u);
2577     pa_assert(device);
2578
2579     pa_card_new_data_init(&data);
2580     data.driver = __FILE__;
2581     data.module = u->module;
2582
2583     n = pa_bluetooth_cleanup_name(device->name);
2584     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2585     pa_xfree(n);
2586     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2587     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2588     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2589     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2590     if ((ff = pa_bluetooth_get_form_factor(device->class)))
2591         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2592     pa_proplist_sets(data.proplist, "bluez.path", device->path);
2593     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2594     pa_proplist_sets(data.proplist, "bluez.name", device->name);
2595     data.name = get_name("card", u->modargs, device->address, &b);
2596     data.namereg_fail = b;
2597
2598     if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2599         pa_log("Invalid properties");
2600         pa_card_new_data_done(&data);
2601         return -1;
2602     }
2603
2604     data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2605
2606     /* we base hsp/a2dp availability on UUIDs.
2607        Ideally, it would be based on "Connected" state, but
2608        we can't afford to wait for this information when
2609        we are loaded with profile="hsp", for instance */
2610     if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2611         p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2612         p->priority = 10;
2613         p->n_sinks = 1;
2614         p->n_sources = 0;
2615         p->max_sink_channels = 2;
2616         p->max_source_channels = 0;
2617
2618         d = PA_CARD_PROFILE_DATA(p);
2619         *d = PROFILE_A2DP;
2620
2621         pa_hashmap_put(data.profiles, p->name, p);
2622     }
2623
2624     if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2625         p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2626         p->priority = 10;
2627         p->n_sinks = 0;
2628         p->n_sources = 1;
2629         p->max_sink_channels = 0;
2630         p->max_source_channels = 2;
2631
2632         d = PA_CARD_PROFILE_DATA(p);
2633         *d = PROFILE_A2DP_SOURCE;
2634
2635         pa_hashmap_put(data.profiles, p->name, p);
2636     }
2637
2638     if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2639         pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2640         p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2641         p->priority = 20;
2642         p->n_sinks = 1;
2643         p->n_sources = 1;
2644         p->max_sink_channels = 1;
2645         p->max_source_channels = 1;
2646
2647         d = PA_CARD_PROFILE_DATA(p);
2648         *d = PROFILE_HSP;
2649
2650         pa_hashmap_put(data.profiles, p->name, p);
2651     }
2652
2653     if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2654         p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2655         p->priority = 20;
2656         p->n_sinks = 1;
2657         p->n_sources = 1;
2658         p->max_sink_channels = 1;
2659         p->max_source_channels = 1;
2660
2661         d = PA_CARD_PROFILE_DATA(p);
2662         *d = PROFILE_HFGW;
2663
2664         pa_hashmap_put(data.profiles, p->name, p);
2665     }
2666
2667     pa_assert(!pa_hashmap_isempty(data.profiles));
2668
2669     p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2670     d = PA_CARD_PROFILE_DATA(p);
2671     *d = PROFILE_OFF;
2672     pa_hashmap_put(data.profiles, p->name, p);
2673
2674     if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2675         if (pa_hashmap_get(data.profiles, default_profile))
2676             pa_card_new_data_set_profile(&data, default_profile);
2677         else
2678             pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2679     }
2680
2681     u->card = pa_card_new(u->core, &data);
2682     pa_card_new_data_done(&data);
2683
2684     if (!u->card) {
2685         pa_log("Failed to allocate card.");
2686         return -1;
2687     }
2688
2689     u->card->userdata = u;
2690     u->card->set_profile = card_set_profile;
2691
2692     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2693
2694     if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2695         (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2696         (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2697         pa_log_warn("Default profile not connected, selecting off profile");
2698         u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2699         u->card->save_profile = FALSE;
2700     }
2701
2702     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2703     u->profile = *d;
2704
2705     if (USE_SCO_OVER_PCM(u))
2706         save_sco_volume_callbacks(u);
2707
2708     return 0;
2709 }
2710
2711 /* Run from main thread */
2712 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2713     const pa_bluetooth_device *d = NULL;
2714
2715     pa_assert(u);
2716
2717     if (!address && !path) {
2718         pa_log_error("Failed to get device address/path from module arguments.");
2719         return NULL;
2720     }
2721
2722     if (path) {
2723         if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2724             pa_log_error("%s is not a valid BlueZ audio device.", path);
2725             return NULL;
2726         }
2727
2728         if (address && !(pa_streq(d->address, address))) {
2729             pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2730             return NULL;
2731         }
2732
2733     } else {
2734         if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2735             pa_log_error("%s is not known.", address);
2736             return NULL;
2737         }
2738     }
2739
2740     if (d) {
2741         u->address = pa_xstrdup(d->address);
2742         u->path = pa_xstrdup(d->path);
2743     }
2744
2745     return d;
2746 }
2747
2748 /* Run from main thread */
2749 static int setup_dbus(struct userdata *u) {
2750     DBusError err;
2751
2752     dbus_error_init(&err);
2753
2754     u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2755
2756     if (dbus_error_is_set(&err) || !u->connection) {
2757         pa_log("Failed to get D-Bus connection: %s", err.message);
2758         dbus_error_free(&err);
2759         return -1;
2760     }
2761
2762     return 0;
2763 }
2764
2765 int pa__init(pa_module* m) {
2766     pa_modargs *ma;
2767     uint32_t channels;
2768     struct userdata *u;
2769     const char *address, *path;
2770     DBusError err;
2771     char *mike, *speaker, *transport;
2772     const pa_bluetooth_device *device;
2773
2774     pa_assert(m);
2775
2776     dbus_error_init(&err);
2777
2778     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2779         pa_log_error("Failed to parse module arguments");
2780         goto fail;
2781     }
2782
2783     m->userdata = u = pa_xnew0(struct userdata, 1);
2784     u->module = m;
2785     u->core = m->core;
2786     u->service_fd = -1;
2787     u->stream_fd = -1;
2788     u->sample_spec = m->core->default_sample_spec;
2789     u->modargs = ma;
2790
2791     if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2792         !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2793         pa_log("SCO sink not found");
2794         goto fail;
2795     }
2796
2797     if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2798         !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2799         pa_log("SCO source not found");
2800         goto fail;
2801     }
2802
2803     if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2804         u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2805         pa_log_error("Failed to get rate from module arguments");
2806         goto fail;
2807     }
2808
2809     u->auto_connect = TRUE;
2810     if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2811         pa_log("Failed to parse auto_connect= argument");
2812         goto fail;
2813     }
2814
2815     channels = u->sample_spec.channels;
2816     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2817         channels <= 0 || channels > PA_CHANNELS_MAX) {
2818         pa_log_error("Failed to get channels from module arguments");
2819         goto fail;
2820     }
2821     u->sample_spec.channels = (uint8_t) channels;
2822     u->requested_sample_spec = u->sample_spec;
2823
2824     address = pa_modargs_get_value(ma, "address", NULL);
2825     path = pa_modargs_get_value(ma, "path", NULL);
2826
2827     if (setup_dbus(u) < 0)
2828         goto fail;
2829
2830     if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2831         goto fail;
2832
2833     if (!(device = find_device(u, address, path)))
2834         goto fail;
2835
2836     /* Add the card structure. This will also initialize the default profile */
2837     if (add_card(u, device) < 0)
2838         goto fail;
2839
2840     if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2841         pa_log_error("Failed to add filter function");
2842         goto fail;
2843     }
2844     u->filter_added = TRUE;
2845
2846     speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2847     mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2848     transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2849
2850     if (pa_dbus_add_matches(
2851                 pa_dbus_connection_get(u->connection), &err,
2852                 speaker,
2853                 mike,
2854                 transport,
2855                 NULL) < 0) {
2856
2857         pa_xfree(speaker);
2858         pa_xfree(mike);
2859         pa_xfree(transport);
2860
2861         pa_log("Failed to add D-Bus matches: %s", err.message);
2862         goto fail;
2863     }
2864
2865     pa_xfree(speaker);
2866     pa_xfree(mike);
2867     pa_xfree(transport);
2868
2869     /* Connect to the BT service */
2870     init_bt(u);
2871
2872     if (u->profile != PROFILE_OFF)
2873         if (init_profile(u) < 0)
2874             goto fail;
2875
2876     if (u->sink || u->source)
2877         if (start_thread(u) < 0)
2878             goto fail;
2879
2880     return 0;
2881
2882 fail:
2883
2884     pa__done(m);
2885
2886     dbus_error_free(&err);
2887
2888     return -1;
2889 }
2890
2891 int pa__get_n_used(pa_module *m) {
2892     struct userdata *u;
2893
2894     pa_assert(m);
2895     pa_assert_se(u = m->userdata);
2896
2897     return
2898         (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2899         (u->source ? pa_source_linked_by(u->source) : 0);
2900 }
2901
2902 void pa__done(pa_module *m) {
2903     struct userdata *u;
2904
2905     pa_assert(m);
2906
2907     if (!(u = m->userdata))
2908         return;
2909
2910     if (u->sink && !USE_SCO_OVER_PCM(u))
2911         pa_sink_unlink(u->sink);
2912
2913     if (u->source && !USE_SCO_OVER_PCM(u))
2914         pa_source_unlink(u->source);
2915
2916     stop_thread(u);
2917
2918     if (USE_SCO_OVER_PCM(u))
2919         restore_sco_volume_callbacks(u);
2920
2921     if (u->connection) {
2922
2923         if (u->path) {
2924             char *speaker, *mike;
2925             speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2926             mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2927
2928             pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2929
2930             pa_xfree(speaker);
2931             pa_xfree(mike);
2932         }
2933
2934         if (u->filter_added)
2935             dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2936
2937         pa_dbus_connection_unref(u->connection);
2938     }
2939
2940     if (u->card)
2941         pa_card_free(u->card);
2942
2943     if (u->read_smoother)
2944         pa_smoother_free(u->read_smoother);
2945
2946     shutdown_bt(u);
2947
2948     if (u->a2dp.buffer)
2949         pa_xfree(u->a2dp.buffer);
2950
2951     sbc_finish(&u->a2dp.sbc);
2952
2953     if (u->modargs)
2954         pa_modargs_free(u->modargs);
2955
2956     pa_xfree(u->address);
2957     pa_xfree(u->path);
2958
2959     if (u->transport) {
2960         bt_transport_release(u);
2961         pa_xfree(u->transport);
2962     }
2963
2964     if (u->discovery)
2965         pa_bluetooth_discovery_unref(u->discovery);
2966
2967     pa_xfree(u);
2968 }