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