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