87592834e135de3beebba1babe0da022b14c4cf0
[platform/upstream/pulseaudio.git] / src / modules / bluetooth / module-bluez4-device.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2008-2013 João Paulo Rechi Vita
5   Copyright 2011-2013 BMW Car IT GmbH.
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as
9   published by the Free Software Foundation; either version 2.1 of the
10   License, or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public
18   License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <string.h>
26 #include <errno.h>
27 #include <math.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/utf8.h>
35 #include <pulse/xmalloc.h>
36
37 #include <pulsecore/i18n.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.h>
40 #include <pulsecore/core-rtclock.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/core-error.h>
43 #include <pulsecore/shared.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/poll.h>
48 #include <pulsecore/rtpoll.h>
49 #include <pulsecore/time-smoother.h>
50 #include <pulsecore/namereg.h>
51
52 #include <sbc/sbc.h>
53
54 #include "a2dp-codecs.h"
55 #include "rtp.h"
56 #include "bluez4-util.h"
57
58 #define BITPOOL_DEC_LIMIT 32
59 #define BITPOOL_DEC_STEP 5
60
61 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
62 PA_MODULE_DESCRIPTION("BlueZ 4 Bluetooth audio sink and source");
63 PA_MODULE_VERSION(PACKAGE_VERSION);
64 PA_MODULE_LOAD_ONCE(false);
65 PA_MODULE_USAGE(
66         "name=<name for the card/sink/source, to be prefixed> "
67         "card_name=<name for the card> "
68         "card_properties=<properties for the card> "
69         "sink_name=<name for the sink> "
70         "sink_properties=<properties for the sink> "
71         "source_name=<name for the source> "
72         "source_properties=<properties for the source> "
73         "address=<address of the device> "
74         "profile=<a2dp|hsp|hfgw> "
75         "rate=<sample rate> "
76         "channels=<number of channels> "
77         "path=<device object path> "
78         "sco_sink=<SCO over PCM sink name> "
79         "sco_source=<SCO over PCM source name>");
80
81 /* TODO: not close fd when entering suspend mode in a2dp */
82
83 static const char* const valid_modargs[] = {
84     "name",
85     "card_name",
86     "card_properties",
87     "sink_name",
88     "sink_properties",
89     "source_name",
90     "source_properties",
91     "address",
92     "profile",
93     "rate",
94     "channels",
95     "path",
96     "sco_sink",
97     "sco_source",
98     NULL
99 };
100
101 struct a2dp_info {
102     sbc_t sbc;                           /* Codec data */
103     bool sbc_initialized;                /* Keep track if the encoder is initialized */
104     size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
105
106     void* buffer;                        /* Codec transfer buffer */
107     size_t buffer_size;                  /* Size of the buffer */
108
109     uint16_t seq_num;                    /* Cumulative packet sequence */
110     uint8_t min_bitpool;
111     uint8_t max_bitpool;
112 };
113
114 struct hsp_info {
115     pa_sink *sco_sink;
116     void (*sco_sink_set_volume)(pa_sink *s);
117     pa_source *sco_source;
118     void (*sco_source_set_volume)(pa_source *s);
119 };
120
121 struct bluetooth_msg {
122     pa_msgobject parent;
123     pa_card *card;
124 };
125
126 typedef struct bluetooth_msg bluetooth_msg;
127 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
128 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
129
130 struct userdata {
131     pa_core *core;
132     pa_module *module;
133
134     pa_bluez4_device *device;
135     pa_hook_slot *uuid_added_slot;
136     char *address;
137     char *path;
138     pa_bluez4_transport *transport;
139     bool transport_acquired;
140     pa_hook_slot *discovery_slot;
141     pa_hook_slot *sink_state_changed_slot;
142     pa_hook_slot *source_state_changed_slot;
143     pa_hook_slot *transport_state_changed_slot;
144     pa_hook_slot *transport_nrec_changed_slot;
145     pa_hook_slot *transport_microphone_changed_slot;
146     pa_hook_slot *transport_speaker_changed_slot;
147
148     pa_bluez4_discovery *discovery;
149
150     char *output_port_name;
151     char *input_port_name;
152
153     pa_card *card;
154     pa_sink *sink;
155     pa_source *source;
156
157     pa_thread_mq thread_mq;
158     pa_rtpoll *rtpoll;
159     pa_rtpoll_item *rtpoll_item;
160     pa_thread *thread;
161     bluetooth_msg *msg;
162
163     uint64_t read_index, write_index;
164     pa_usec_t started_at;
165     pa_smoother *read_smoother;
166
167     pa_memchunk write_memchunk;
168
169     pa_sample_spec sample_spec, requested_sample_spec;
170
171     int stream_fd;
172
173     size_t read_link_mtu;
174     size_t read_block_size;
175
176     size_t write_link_mtu;
177     size_t write_block_size;
178
179     struct a2dp_info a2dp;
180     struct hsp_info hsp;
181
182     pa_bluez4_profile_t profile;
183
184     pa_modargs *modargs;
185
186     int stream_write_type;
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 == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT && (u->hsp.sco_sink && u->hsp.sco_source))
202
203 static int init_profile(struct userdata *u);
204
205 /* from IO thread */
206 static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
207     struct a2dp_info *a2dp;
208
209     pa_assert(u);
210
211     a2dp = &u->a2dp;
212
213     if (a2dp->sbc.bitpool == bitpool)
214         return;
215
216     if (bitpool > a2dp->max_bitpool)
217         bitpool = a2dp->max_bitpool;
218     else if (bitpool < a2dp->min_bitpool)
219         bitpool = a2dp->min_bitpool;
220
221     a2dp->sbc.bitpool = bitpool;
222
223     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
224     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
225
226     pa_log_debug("Bitpool has changed to %u", a2dp->sbc.bitpool);
227
228     u->read_block_size =
229         (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
230         / a2dp->frame_length * a2dp->codesize;
231
232     u->write_block_size =
233         (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
234         / a2dp->frame_length * a2dp->codesize;
235
236     pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
237     pa_sink_set_fixed_latency_within_thread(u->sink,
238             FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
239 }
240
241 /* from IO thread, except in SCO over PCM */
242 static void bt_transport_config_mtu(struct userdata *u) {
243     /* Calculate block sizes */
244     if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY) {
245         u->read_block_size = u->read_link_mtu;
246         u->write_block_size = u->write_link_mtu;
247     } else {
248         u->read_block_size =
249             (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
250             / u->a2dp.frame_length * u->a2dp.codesize;
251
252         u->write_block_size =
253             (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
254             / u->a2dp.frame_length * u->a2dp.codesize;
255     }
256
257     if (USE_SCO_OVER_PCM(u))
258         return;
259
260     if (u->sink) {
261         pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
262         pa_sink_set_fixed_latency_within_thread(u->sink,
263                                                 (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ?
264                                                  FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
265                                                 pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
266     }
267
268     if (u->source)
269         pa_source_set_fixed_latency_within_thread(u->source,
270                                                   (u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE ?
271                                                    FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
272                                                   pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
273 }
274
275 /* from IO thread, except in SCO over PCM */
276
277 static void setup_stream(struct userdata *u) {
278     struct pollfd *pollfd;
279     int one;
280
281     pa_log_info("Transport %s resuming", u->transport->path);
282
283     bt_transport_config_mtu(u);
284
285     pa_make_fd_nonblock(u->stream_fd);
286     pa_make_socket_low_delay(u->stream_fd);
287
288     one = 1;
289     if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
290         pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
291
292     pa_log_debug("Stream properly set up, we're ready to roll!");
293
294     if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK)
295         a2dp_set_bitpool(u, u->a2dp.max_bitpool);
296
297     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
298     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
299     pollfd->fd = u->stream_fd;
300     pollfd->events = pollfd->revents = 0;
301
302     u->read_index = u->write_index = 0;
303     u->started_at = 0;
304
305     if (u->source)
306         u->read_smoother = pa_smoother_new(
307                 PA_USEC_PER_SEC,
308                 PA_USEC_PER_SEC*2,
309                 true,
310                 true,
311                 10,
312                 pa_rtclock_now(),
313                 true);
314 }
315
316 static void teardown_stream(struct userdata *u) {
317     if (u->rtpoll_item) {
318         pa_rtpoll_item_free(u->rtpoll_item);
319         u->rtpoll_item = NULL;
320     }
321
322     if (u->stream_fd >= 0) {
323         pa_close(u->stream_fd);
324         u->stream_fd = -1;
325     }
326
327     if (u->read_smoother) {
328         pa_smoother_free(u->read_smoother);
329         u->read_smoother = NULL;
330     }
331
332     if (u->write_memchunk.memblock) {
333         pa_memblock_unref(u->write_memchunk.memblock);
334         pa_memchunk_reset(&u->write_memchunk);
335     }
336
337     pa_log_debug("Audio stream torn down");
338 }
339
340 static void bt_transport_release(struct userdata *u) {
341     pa_assert(u->transport);
342
343     /* Ignore if already released */
344     if (!u->transport_acquired)
345         return;
346
347     pa_log_debug("Releasing transport %s", u->transport->path);
348
349     pa_bluez4_transport_release(u->transport);
350
351     u->transport_acquired = false;
352
353     teardown_stream(u);
354 }
355
356 static int bt_transport_acquire(struct userdata *u, bool optional) {
357     pa_assert(u->transport);
358
359     if (u->transport_acquired)
360         return 0;
361
362     pa_log_debug("Acquiring transport %s", u->transport->path);
363
364     u->stream_fd = pa_bluez4_transport_acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
365     if (u->stream_fd < 0) {
366         if (!optional)
367             pa_log("Failed to acquire transport %s", u->transport->path);
368         else
369             pa_log_info("Failed optional acquire of transport %s", u->transport->path);
370
371         return -1;
372     }
373
374     u->transport_acquired = true;
375     pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
376
377     return 0;
378 }
379
380 /* Run from IO thread */
381 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
382     struct userdata *u = PA_SINK(o)->userdata;
383
384     pa_assert(u->sink == PA_SINK(o));
385     pa_assert(u->transport);
386
387     switch (code) {
388
389         case PA_SINK_MESSAGE_GET_LATENCY: {
390
391             if (u->read_smoother) {
392                 int64_t wi, ri;
393
394                 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
395                 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
396
397                 *((int64_t*) data) = wi - ri;
398             } else {
399                 int64_t ri, wi;
400
401                 ri = pa_rtclock_now() - u->started_at;
402                 wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
403
404                 *((int64_t*) data) = wi - ri;
405             }
406
407             *((int64_t*) data) += u->sink->thread_info.fixed_latency;
408             return 0;
409         }
410     }
411
412     return pa_sink_process_msg(o, code, data, offset, chunk);
413 }
414
415 /* Called from the IO thread. */
416 static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
417     struct userdata *u;
418
419     pa_assert(s);
420     pa_assert_se(u = s->userdata);
421
422     switch (new_state) {
423
424         case PA_SINK_SUSPENDED:
425             /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
426             if (!PA_SINK_IS_OPENED(s->thread_info.state))
427                 break;
428
429             /* Stop the device if the source is suspended as well */
430             if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
431                 /* We deliberately ignore whether stopping
432                  * actually worked. Since the stream_fd is
433                  * closed it doesn't really matter */
434                 bt_transport_release(u);
435
436             break;
437
438         case PA_SINK_IDLE:
439         case PA_SINK_RUNNING:
440             if (s->thread_info.state != PA_SINK_SUSPENDED)
441                 break;
442
443             /* Resume the device if the source was suspended as well */
444             if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
445                 if (bt_transport_acquire(u, false) < 0)
446                     return -1;
447                 else
448                     setup_stream(u);
449             }
450             break;
451
452         case PA_SINK_UNLINKED:
453         case PA_SINK_INIT:
454         case PA_SINK_INVALID_STATE:
455             break;
456     }
457
458     return 0;
459 }
460
461 /* Run from IO thread */
462 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
463     struct userdata *u = PA_SOURCE(o)->userdata;
464
465     pa_assert(u->source == PA_SOURCE(o));
466     pa_assert(u->transport);
467
468     switch (code) {
469
470         case PA_SOURCE_MESSAGE_GET_LATENCY: {
471             int64_t wi, ri;
472
473             if (u->read_smoother) {
474                 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
475                 ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
476
477                 *((int64_t*) data) = wi - ri + u->source->thread_info.fixed_latency;
478             } else
479                 *((int64_t*) data) = 0;
480
481             return 0;
482         }
483
484     }
485
486     return pa_source_process_msg(o, code, data, offset, chunk);
487 }
488
489 /* Called from the IO thread. */
490 static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
491     struct userdata *u;
492
493     pa_assert(s);
494     pa_assert_se(u = s->userdata);
495
496     switch (new_state) {
497
498         case PA_SOURCE_SUSPENDED:
499             /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
500             if (!PA_SOURCE_IS_OPENED(s->thread_info.state))
501                 break;
502
503             /* Stop the device if the sink is suspended as well */
504             if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
505                 bt_transport_release(u);
506
507             if (u->read_smoother)
508                 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
509             break;
510
511         case PA_SOURCE_IDLE:
512         case PA_SOURCE_RUNNING:
513             if (s->thread_info.state != PA_SOURCE_SUSPENDED)
514                 break;
515
516             /* Resume the device if the sink was suspended as well */
517             if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
518                 if (bt_transport_acquire(u, false) < 0)
519                     return -1;
520                 else
521                     setup_stream(u);
522             }
523             /* We don't resume the smoother here. Instead we
524              * wait until the first packet arrives */
525             break;
526
527         case PA_SOURCE_UNLINKED:
528         case PA_SOURCE_INIT:
529         case PA_SOURCE_INVALID_STATE:
530             break;
531     }
532
533     return 0;
534 }
535
536 /* Called from main thread context */
537 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
538     struct bluetooth_msg *u = BLUETOOTH_MSG(obj);
539
540     switch (code) {
541         case BLUETOOTH_MESSAGE_IO_THREAD_FAILED: {
542             if (u->card->module->unload_requested)
543                 break;
544
545             pa_log_debug("Switching the profile to off due to IO thread failure.");
546
547             pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
548             break;
549         }
550     }
551     return 0;
552 }
553
554 /* Run from IO thread */
555 static int hsp_process_render(struct userdata *u) {
556     int ret = 0;
557
558     pa_assert(u);
559     pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY);
560     pa_assert(u->sink);
561
562     /* First, render some data */
563     if (!u->write_memchunk.memblock)
564         pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
565
566     pa_assert(u->write_memchunk.length == u->write_block_size);
567
568     for (;;) {
569         ssize_t l;
570         const void *p;
571
572         /* Now write that data to the socket. The socket is of type
573          * SEQPACKET, and we generated the data of the MTU size, so this
574          * should just work. */
575
576         p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
577         l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
578         pa_memblock_release(u->write_memchunk.memblock);
579
580         pa_assert(l != 0);
581
582         if (l < 0) {
583
584             if (errno == EINTR)
585                 /* Retry right away if we got interrupted */
586                 continue;
587
588             else if (errno == EAGAIN)
589                 /* Hmm, apparently the socket was not writable, give up for now */
590                 break;
591
592             pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
593             ret = -1;
594             break;
595         }
596
597         pa_assert((size_t) l <= u->write_memchunk.length);
598
599         if ((size_t) l != u->write_memchunk.length) {
600             pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
601                         (unsigned long long) l,
602                         (unsigned long long) u->write_memchunk.length);
603             ret = -1;
604             break;
605         }
606
607         u->write_index += (uint64_t) u->write_memchunk.length;
608         pa_memblock_unref(u->write_memchunk.memblock);
609         pa_memchunk_reset(&u->write_memchunk);
610
611         ret = 1;
612         break;
613     }
614
615     return ret;
616 }
617
618 /* Run from IO thread */
619 static int hsp_process_push(struct userdata *u) {
620     int ret = 0;
621     pa_memchunk memchunk;
622
623     pa_assert(u);
624     pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY);
625     pa_assert(u->source);
626     pa_assert(u->read_smoother);
627
628     memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
629     memchunk.index = memchunk.length = 0;
630
631     for (;;) {
632         ssize_t l;
633         void *p;
634         struct msghdr m;
635         struct cmsghdr *cm;
636         uint8_t aux[1024];
637         struct iovec iov;
638         bool found_tstamp = false;
639         pa_usec_t tstamp;
640
641         memset(&m, 0, sizeof(m));
642         memset(&aux, 0, sizeof(aux));
643         memset(&iov, 0, sizeof(iov));
644
645         m.msg_iov = &iov;
646         m.msg_iovlen = 1;
647         m.msg_control = aux;
648         m.msg_controllen = sizeof(aux);
649
650         p = pa_memblock_acquire(memchunk.memblock);
651         iov.iov_base = p;
652         iov.iov_len = pa_memblock_get_length(memchunk.memblock);
653         l = recvmsg(u->stream_fd, &m, 0);
654         pa_memblock_release(memchunk.memblock);
655
656         if (l <= 0) {
657
658             if (l < 0 && errno == EINTR)
659                 /* Retry right away if we got interrupted */
660                 continue;
661
662             else if (l < 0 && errno == EAGAIN)
663                 /* Hmm, apparently the socket was not readable, give up for now. */
664                 break;
665
666             pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
667             ret = -1;
668             break;
669         }
670
671         pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
672
673         /* In some rare occasions, we might receive packets of a very strange
674          * size. This could potentially be possible if the SCO packet was
675          * received partially over-the-air, or more probably due to hardware
676          * issues in our Bluetooth adapter. In these cases, in order to avoid
677          * an assertion failure due to unaligned data, just discard the whole
678          * packet */
679         if (!pa_frame_aligned(l, &u->sample_spec)) {
680             pa_log_warn("SCO packet received of unaligned size: %zu", l);
681             break;
682         }
683
684         memchunk.length = (size_t) l;
685         u->read_index += (uint64_t) l;
686
687         for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
688             if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
689                 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
690                 pa_rtclock_from_wallclock(tv);
691                 tstamp = pa_timeval_load(tv);
692                 found_tstamp = true;
693                 break;
694             }
695
696         if (!found_tstamp) {
697             pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
698             tstamp = pa_rtclock_now();
699         }
700
701         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
702         pa_smoother_resume(u->read_smoother, tstamp, true);
703
704         pa_source_post(u->source, &memchunk);
705
706         ret = l;
707         break;
708     }
709
710     pa_memblock_unref(memchunk.memblock);
711
712     return ret;
713 }
714
715 /* Run from IO thread */
716 static void a2dp_prepare_buffer(struct userdata *u) {
717     size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
718
719     pa_assert(u);
720
721     if (u->a2dp.buffer_size >= min_buffer_size)
722         return;
723
724     u->a2dp.buffer_size = 2 * min_buffer_size;
725     pa_xfree(u->a2dp.buffer);
726     u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
727 }
728
729 /* Run from IO thread */
730 static int a2dp_process_render(struct userdata *u) {
731     struct a2dp_info *a2dp;
732     struct rtp_header *header;
733     struct rtp_payload *payload;
734     size_t nbytes;
735     void *d;
736     const void *p;
737     size_t to_write, to_encode;
738     unsigned frame_count;
739     int ret = 0;
740
741     pa_assert(u);
742     pa_assert(u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK);
743     pa_assert(u->sink);
744
745     /* First, render some data */
746     if (!u->write_memchunk.memblock)
747         pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
748
749     pa_assert(u->write_memchunk.length == u->write_block_size);
750
751     a2dp_prepare_buffer(u);
752
753     a2dp = &u->a2dp;
754     header = a2dp->buffer;
755     payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
756
757     frame_count = 0;
758
759     /* Try to create a packet of the full MTU */
760
761     p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
762     to_encode = u->write_memchunk.length;
763
764     d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
765     to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
766
767     while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
768         ssize_t written;
769         ssize_t encoded;
770
771         encoded = sbc_encode(&a2dp->sbc,
772                              p, to_encode,
773                              d, to_write,
774                              &written);
775
776         if (PA_UNLIKELY(encoded <= 0)) {
777             pa_log_error("SBC encoding error (%li)", (long) encoded);
778             pa_memblock_release(u->write_memchunk.memblock);
779             return -1;
780         }
781
782 /*         pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
783 /*         pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
784
785         pa_assert_fp((size_t) encoded <= to_encode);
786         pa_assert_fp((size_t) encoded == a2dp->codesize);
787
788         pa_assert_fp((size_t) written <= to_write);
789         pa_assert_fp((size_t) written == a2dp->frame_length);
790
791         p = (const uint8_t*) p + encoded;
792         to_encode -= encoded;
793
794         d = (uint8_t*) d + written;
795         to_write -= written;
796
797         frame_count++;
798     }
799
800     pa_memblock_release(u->write_memchunk.memblock);
801
802     pa_assert(to_encode == 0);
803
804     PA_ONCE_BEGIN {
805         pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
806     } PA_ONCE_END;
807
808     /* write it to the fifo */
809     memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
810     header->v = 2;
811     header->pt = 1;
812     header->sequence_number = htons(a2dp->seq_num++);
813     header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
814     header->ssrc = htonl(1);
815     payload->frame_count = frame_count;
816
817     nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
818
819     for (;;) {
820         ssize_t l;
821
822         l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
823
824         pa_assert(l != 0);
825
826         if (l < 0) {
827
828             if (errno == EINTR)
829                 /* Retry right away if we got interrupted */
830                 continue;
831
832             else if (errno == EAGAIN)
833                 /* Hmm, apparently the socket was not writable, give up for now */
834                 break;
835
836             pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
837             ret = -1;
838             break;
839         }
840
841         pa_assert((size_t) l <= nbytes);
842
843         if ((size_t) l != nbytes) {
844             pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
845                         (unsigned long long) l,
846                         (unsigned long long) nbytes);
847             ret = -1;
848             break;
849         }
850
851         u->write_index += (uint64_t) u->write_memchunk.length;
852         pa_memblock_unref(u->write_memchunk.memblock);
853         pa_memchunk_reset(&u->write_memchunk);
854
855         ret = 1;
856
857         break;
858     }
859
860     return ret;
861 }
862
863 static int a2dp_process_push(struct userdata *u) {
864     int ret = 0;
865     pa_memchunk memchunk;
866
867     pa_assert(u);
868     pa_assert(u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE);
869     pa_assert(u->source);
870     pa_assert(u->read_smoother);
871
872     memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
873     memchunk.index = memchunk.length = 0;
874
875     for (;;) {
876         bool found_tstamp = false;
877         pa_usec_t tstamp;
878         struct a2dp_info *a2dp;
879         struct rtp_header *header;
880         struct rtp_payload *payload;
881         const void *p;
882         void *d;
883         ssize_t l;
884         size_t to_write, to_decode;
885         size_t total_written = 0;
886
887         a2dp_prepare_buffer(u);
888
889         a2dp = &u->a2dp;
890         header = a2dp->buffer;
891         payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
892
893         l = pa_read(u->stream_fd, a2dp->buffer, a2dp->buffer_size, &u->stream_write_type);
894
895         if (l <= 0) {
896
897             if (l < 0 && errno == EINTR)
898                 /* Retry right away if we got interrupted */
899                 continue;
900
901             else if (l < 0 && errno == EAGAIN)
902                 /* Hmm, apparently the socket was not readable, give up for now. */
903                 break;
904
905             pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
906             ret = -1;
907             break;
908         }
909
910         pa_assert((size_t) l <= a2dp->buffer_size);
911
912         /* TODO: get timestamp from rtp */
913         if (!found_tstamp) {
914             /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
915             tstamp = pa_rtclock_now();
916         }
917
918         p = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
919         to_decode = l - sizeof(*header) - sizeof(*payload);
920
921         d = pa_memblock_acquire(memchunk.memblock);
922         to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
923
924         while (PA_LIKELY(to_decode > 0)) {
925             size_t written;
926             ssize_t decoded;
927
928             decoded = sbc_decode(&a2dp->sbc,
929                                  p, to_decode,
930                                  d, to_write,
931                                  &written);
932
933             if (PA_UNLIKELY(decoded <= 0)) {
934                 pa_log_error("SBC decoding error (%li)", (long) decoded);
935                 pa_memblock_release(memchunk.memblock);
936                 pa_memblock_unref(memchunk.memblock);
937                 return 0;
938             }
939
940 /*             pa_log_debug("SBC: decoded: %lu; written: %lu", (unsigned long) decoded, (unsigned long) written); */
941 /*             pa_log_debug("SBC: frame_length: %lu; codesize: %lu", (unsigned long) a2dp->frame_length, (unsigned long) a2dp->codesize); */
942
943             total_written += written;
944
945             /* Reset frame length, it can be changed due to bitpool change */
946             a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
947
948             pa_assert_fp((size_t) decoded <= to_decode);
949             pa_assert_fp((size_t) decoded == a2dp->frame_length);
950
951             pa_assert_fp((size_t) written == a2dp->codesize);
952
953             p = (const uint8_t*) p + decoded;
954             to_decode -= decoded;
955
956             d = (uint8_t*) d + written;
957             to_write -= written;
958         }
959
960         u->read_index += (uint64_t) total_written;
961         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
962         pa_smoother_resume(u->read_smoother, tstamp, true);
963
964         memchunk.length -= to_write;
965
966         pa_memblock_release(memchunk.memblock);
967
968         pa_source_post(u->source, &memchunk);
969
970         ret = l;
971         break;
972     }
973
974     pa_memblock_unref(memchunk.memblock);
975
976     return ret;
977 }
978
979 static void a2dp_reduce_bitpool(struct userdata *u) {
980     struct a2dp_info *a2dp;
981     uint8_t bitpool;
982
983     pa_assert(u);
984
985     a2dp = &u->a2dp;
986
987     /* Check if bitpool is already at its limit */
988     if (a2dp->sbc.bitpool <= BITPOOL_DEC_LIMIT)
989         return;
990
991     bitpool = a2dp->sbc.bitpool - BITPOOL_DEC_STEP;
992
993     if (bitpool < BITPOOL_DEC_LIMIT)
994         bitpool = BITPOOL_DEC_LIMIT;
995
996     a2dp_set_bitpool(u, bitpool);
997 }
998
999 static void thread_func(void *userdata) {
1000     struct userdata *u = userdata;
1001     unsigned do_write = 0;
1002     unsigned pending_read_bytes = 0;
1003     bool writable = false;
1004
1005     pa_assert(u);
1006     pa_assert(u->transport);
1007
1008     pa_log_debug("IO Thread starting up");
1009
1010     if (u->core->realtime_scheduling)
1011         pa_make_realtime(u->core->realtime_priority);
1012
1013     pa_thread_mq_install(&u->thread_mq);
1014
1015     /* Setup the stream only if the transport was already acquired */
1016     if (u->transport_acquired)
1017         setup_stream(u);
1018
1019     for (;;) {
1020         struct pollfd *pollfd;
1021         int ret;
1022         bool disable_timer = true;
1023
1024         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1025
1026         if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1027
1028             /* We should send two blocks to the device before we expect
1029              * a response. */
1030
1031             if (u->write_index == 0 && u->read_index <= 0)
1032                 do_write = 2;
1033
1034             if (pollfd && (pollfd->revents & POLLIN)) {
1035                 int n_read;
1036
1037                 if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1038                     n_read = hsp_process_push(u);
1039                 else
1040                     n_read = a2dp_process_push(u);
1041
1042                 if (n_read < 0)
1043                     goto io_fail;
1044
1045                 if (n_read > 0) {
1046                     /* We just read something, so we are supposed to write something, too */
1047                     pending_read_bytes += n_read;
1048                     do_write += pending_read_bytes / u->write_block_size;
1049                     pending_read_bytes = pending_read_bytes % u->write_block_size;
1050                 }
1051             }
1052         }
1053
1054         if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1055
1056             if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1057                 pa_sink_process_rewind(u->sink, 0);
1058
1059             if (pollfd) {
1060                 if (pollfd->revents & POLLOUT)
1061                     writable = true;
1062
1063                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
1064                     pa_usec_t time_passed;
1065                     pa_usec_t audio_sent;
1066
1067                     /* Hmm, there is no input stream we could synchronize
1068                      * to. So let's do things by time */
1069
1070                     time_passed = pa_rtclock_now() - u->started_at;
1071                     audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1072
1073                     if (audio_sent <= time_passed) {
1074                         pa_usec_t audio_to_send = time_passed - audio_sent;
1075
1076                         /* Never try to catch up for more than 100ms */
1077                         if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
1078                             pa_usec_t skip_usec;
1079                             uint64_t skip_bytes;
1080
1081                             skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
1082                             skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
1083
1084                             if (skip_bytes > 0) {
1085                                 pa_memchunk tmp;
1086
1087                                 pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
1088                                             (unsigned long long) skip_usec,
1089                                             (unsigned long long) skip_bytes);
1090
1091                                 pa_sink_render_full(u->sink, skip_bytes, &tmp);
1092                                 pa_memblock_unref(tmp.memblock);
1093                                 u->write_index += skip_bytes;
1094
1095                                 if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK)
1096                                     a2dp_reduce_bitpool(u);
1097                             }
1098                         }
1099
1100                         do_write = 1;
1101                         pending_read_bytes = 0;
1102                     }
1103                 }
1104
1105                 if (writable && do_write > 0) {
1106                     int n_written;
1107
1108                     if (u->write_index <= 0)
1109                         u->started_at = pa_rtclock_now();
1110
1111                     if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK) {
1112                         if ((n_written = a2dp_process_render(u)) < 0)
1113                             goto io_fail;
1114                     } else {
1115                         if ((n_written = hsp_process_render(u)) < 0)
1116                             goto io_fail;
1117                     }
1118
1119                     if (n_written == 0)
1120                         pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
1121
1122                     do_write -= n_written;
1123                     writable = false;
1124                 }
1125
1126                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
1127                     pa_usec_t sleep_for;
1128                     pa_usec_t time_passed, next_write_at;
1129
1130                     if (writable) {
1131                         /* Hmm, there is no input stream we could synchronize
1132                          * to. So let's estimate when we need to wake up the latest */
1133                         time_passed = pa_rtclock_now() - u->started_at;
1134                         next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
1135                         sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1136                         /* 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); */
1137                     } else
1138                         /* drop stream every 500 ms */
1139                         sleep_for = PA_USEC_PER_MSEC * 500;
1140
1141                     pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1142                     disable_timer = false;
1143                 }
1144             }
1145         }
1146
1147         if (disable_timer)
1148             pa_rtpoll_set_timer_disabled(u->rtpoll);
1149
1150         /* Hmm, nothing to do. Let's sleep */
1151         if (pollfd)
1152             pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1153                                       (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1154
1155         if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1156             pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1157             goto fail;
1158         }
1159         if (ret == 0) {
1160             pa_log_debug("IO thread shutdown requested, stopping cleanly");
1161             bt_transport_release(u);
1162             goto finish;
1163         }
1164
1165         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1166
1167         if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1168             pa_log_info("FD error: %s%s%s%s",
1169                         pollfd->revents & POLLERR ? "POLLERR " :"",
1170                         pollfd->revents & POLLHUP ? "POLLHUP " :"",
1171                         pollfd->revents & POLLPRI ? "POLLPRI " :"",
1172                         pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1173             goto io_fail;
1174         }
1175
1176         continue;
1177
1178 io_fail:
1179         /* In case of HUP, just tear down the streams */
1180         if (!pollfd || (pollfd->revents & POLLHUP) == 0)
1181             goto fail;
1182
1183         do_write = 0;
1184         pending_read_bytes = 0;
1185         writable = false;
1186
1187         teardown_stream(u);
1188     }
1189
1190 fail:
1191     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1192     pa_log_debug("IO thread failed");
1193     pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1194     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1195
1196 finish:
1197     pa_log_debug("IO thread shutting down");
1198 }
1199
1200 static pa_available_t transport_state_to_availability(pa_bluez4_transport_state_t state) {
1201     if (state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)
1202         return PA_AVAILABLE_NO;
1203     else if (state >= PA_BLUEZ4_TRANSPORT_STATE_PLAYING)
1204         return PA_AVAILABLE_YES;
1205     else
1206         return PA_AVAILABLE_UNKNOWN;
1207 }
1208
1209 static pa_direction_t get_profile_direction(pa_bluez4_profile_t p) {
1210     static const pa_direction_t profile_direction[] = {
1211         [PA_BLUEZ4_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1212         [PA_BLUEZ4_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1213         [PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1214         [PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1215         [PA_BLUEZ4_PROFILE_OFF] = 0
1216     };
1217
1218     return profile_direction[p];
1219 }
1220
1221 /* Run from main thread */
1222 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1223     pa_available_t result = PA_AVAILABLE_NO;
1224     unsigned i;
1225
1226     pa_assert(u);
1227     pa_assert(u->device);
1228
1229     for (i = 0; i < PA_BLUEZ4_PROFILE_COUNT; i++) {
1230         pa_bluez4_transport *transport;
1231
1232         if (!(get_profile_direction(i) & direction))
1233             continue;
1234
1235         if (!(transport = u->device->transports[i]))
1236             continue;
1237
1238         switch(transport->state) {
1239             case PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED:
1240                 continue;
1241
1242             case PA_BLUEZ4_TRANSPORT_STATE_IDLE:
1243                 if (result == PA_AVAILABLE_NO)
1244                     result = PA_AVAILABLE_UNKNOWN;
1245
1246                 break;
1247
1248             case PA_BLUEZ4_TRANSPORT_STATE_PLAYING:
1249                 return PA_AVAILABLE_YES;
1250         }
1251     }
1252
1253     return result;
1254 }
1255
1256 /* Run from main thread */
1257 static void handle_transport_state_change(struct userdata *u, struct pa_bluez4_transport *transport) {
1258     bool acquire = false;
1259     bool release = false;
1260     pa_bluez4_profile_t profile;
1261     pa_card_profile *cp;
1262     pa_bluez4_transport_state_t state;
1263     pa_device_port *port;
1264
1265     pa_assert(u);
1266     pa_assert(transport);
1267
1268     profile = transport->profile;
1269     state = transport->state;
1270
1271     /* Update profile availability */
1272     if (!(cp = pa_hashmap_get(u->card->profiles, pa_bluez4_profile_to_string(profile))))
1273         return;
1274
1275     pa_card_profile_set_available(cp, transport_state_to_availability(state));
1276
1277     /* Update port availability */
1278     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
1279     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
1280
1281     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
1282     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
1283
1284     /* Acquire or release transport as needed */
1285     acquire = (state == PA_BLUEZ4_TRANSPORT_STATE_PLAYING && u->profile == profile);
1286     release = (state != PA_BLUEZ4_TRANSPORT_STATE_PLAYING && u->profile == profile);
1287
1288     if (acquire)
1289         if (bt_transport_acquire(u, true) >= 0) {
1290             if (u->source) {
1291                 pa_log_debug("Resuming source %s, because the bluetooth audio state changed to 'playing'.", u->source->name);
1292                 pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1293             }
1294
1295             if (u->sink) {
1296                 pa_log_debug("Resuming sink %s, because the bluetooth audio state changed to 'playing'.", u->sink->name);
1297                 pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
1298             }
1299         }
1300
1301     if (release && u->transport_acquired) {
1302         /* FIXME: this release is racy, since the audio stream might have
1303            been set up again in the meantime (but not processed yet by PA).
1304            BlueZ should probably release the transport automatically, and
1305            in that case we would just mark the transport as released */
1306
1307         /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
1308         if (u->source) {
1309             pa_log_debug("Suspending source %s, because the remote end closed the stream.", u->source->name);
1310             pa_source_suspend(u->source, true, PA_SUSPEND_USER);
1311         }
1312
1313         if (u->sink) {
1314             pa_log_debug("Suspending sink %s, because the remote end closed the stream.", u->sink->name);
1315             pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
1316         }
1317     }
1318 }
1319
1320 /* Run from main thread */
1321 static void sink_set_volume_cb(pa_sink *s) {
1322     uint16_t gain;
1323     pa_volume_t volume;
1324     struct userdata *u;
1325     char *k;
1326
1327     pa_assert(s);
1328     pa_assert(s->core);
1329
1330     k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1331     u = pa_shared_get(s->core, k);
1332     pa_xfree(k);
1333
1334     pa_assert(u);
1335     pa_assert(u->sink == s);
1336     pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT);
1337     pa_assert(u->transport);
1338
1339     gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1340     volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1341
1342     pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1343
1344     pa_bluez4_transport_set_speaker_gain(u->transport, gain);
1345 }
1346
1347 /* Run from main thread */
1348 static void source_set_volume_cb(pa_source *s) {
1349     uint16_t gain;
1350     pa_volume_t volume;
1351     struct userdata *u;
1352     char *k;
1353
1354     pa_assert(s);
1355     pa_assert(s->core);
1356
1357     k = pa_sprintf_malloc("bluetooth-device@%p", (void*) s);
1358     u = pa_shared_get(s->core, k);
1359     pa_xfree(k);
1360
1361     pa_assert(u);
1362     pa_assert(u->source == s);
1363     pa_assert(u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT);
1364     pa_assert(u->transport);
1365
1366     gain = (dbus_uint16_t) round((double) pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN / PA_VOLUME_NORM);
1367     volume = (pa_volume_t) round((double) gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1368
1369     pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
1370
1371     pa_bluez4_transport_set_microphone_gain(u->transport, gain);
1372 }
1373
1374 /* Run from main thread */
1375 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, const char *profile, bool *namereg_fail) {
1376     char *t;
1377     const char *n;
1378
1379     pa_assert(type);
1380     pa_assert(ma);
1381     pa_assert(device_id);
1382     pa_assert(namereg_fail);
1383
1384     t = pa_sprintf_malloc("%s_name", type);
1385     n = pa_modargs_get_value(ma, t, NULL);
1386     pa_xfree(t);
1387
1388     if (n) {
1389         *namereg_fail = true;
1390         return pa_xstrdup(n);
1391     }
1392
1393     if ((n = pa_modargs_get_value(ma, "name", NULL)))
1394         *namereg_fail = true;
1395     else {
1396         n = device_id;
1397         *namereg_fail = false;
1398     }
1399
1400     if (profile)
1401         return pa_sprintf_malloc("bluez_%s.%s.%s", type, n, profile);
1402     else
1403         return pa_sprintf_malloc("bluez_%s.%s", type, n);
1404 }
1405
1406 static int sco_over_pcm_state_update(struct userdata *u, bool changed) {
1407     pa_assert(u);
1408     pa_assert(USE_SCO_OVER_PCM(u));
1409
1410     if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1411         PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1412
1413         if (u->stream_fd >= 0)
1414             return 0;
1415
1416         pa_log_debug("Resuming SCO over PCM");
1417         if (init_profile(u) < 0) {
1418             pa_log("Can't resume SCO over PCM");
1419             return -1;
1420         }
1421
1422         if (bt_transport_acquire(u, false) < 0)
1423             return -1;
1424
1425         setup_stream(u);
1426
1427         return 0;
1428     }
1429
1430     if (changed) {
1431         if (u->stream_fd < 0)
1432             return 0;
1433
1434         pa_log_debug("Closing SCO over PCM");
1435
1436         bt_transport_release(u);
1437     }
1438
1439     return 0;
1440 }
1441
1442 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1443     pa_assert(c);
1444     pa_sink_assert_ref(s);
1445     pa_assert(u);
1446
1447     if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_sink)
1448         return PA_HOOK_OK;
1449
1450     sco_over_pcm_state_update(u, true);
1451
1452     return PA_HOOK_OK;
1453 }
1454
1455 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1456     pa_assert(c);
1457     pa_source_assert_ref(s);
1458     pa_assert(u);
1459
1460     if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_source)
1461         return PA_HOOK_OK;
1462
1463     sco_over_pcm_state_update(u, true);
1464
1465     return PA_HOOK_OK;
1466 }
1467
1468 static pa_hook_result_t transport_nrec_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t, struct userdata *u) {
1469     pa_proplist *p;
1470
1471     pa_assert(t);
1472     pa_assert(u);
1473
1474     if (t != u->transport)
1475         return PA_HOOK_OK;
1476
1477     p = pa_proplist_new();
1478     pa_proplist_sets(p, "bluetooth.nrec", t->nrec ? "1" : "0");
1479     pa_source_update_proplist(u->source, PA_UPDATE_REPLACE, p);
1480     pa_proplist_free(p);
1481
1482     return PA_HOOK_OK;
1483 }
1484
1485 static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t,
1486                                                              struct userdata *u) {
1487     pa_cvolume v;
1488
1489     pa_assert(t);
1490     pa_assert(u);
1491
1492     if (t != u->transport)
1493         return PA_HOOK_OK;
1494
1495     pa_assert(u->source);
1496
1497     pa_cvolume_set(&v, u->sample_spec.channels,
1498                    (pa_volume_t) round((double) t->microphone_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1499     pa_source_volume_changed(u->source, &v);
1500
1501     return PA_HOOK_OK;
1502 }
1503
1504 static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t,
1505                                                           struct userdata *u) {
1506     pa_cvolume v;
1507
1508     pa_assert(t);
1509     pa_assert(u);
1510
1511     if (t != u->transport)
1512         return PA_HOOK_OK;
1513
1514     pa_assert(u->sink);
1515
1516     pa_cvolume_set(&v, u->sample_spec.channels, (pa_volume_t) round((double) t->speaker_gain * PA_VOLUME_NORM / HSP_MAX_GAIN));
1517     pa_sink_volume_changed(u->sink, &v);
1518
1519     return PA_HOOK_OK;
1520 }
1521
1522 static void connect_ports(struct userdata *u, void *sink_or_source_new_data, pa_direction_t direction) {
1523     pa_device_port *port;
1524
1525     if (direction == PA_DIRECTION_OUTPUT) {
1526         pa_sink_new_data *sink_new_data = sink_or_source_new_data;
1527
1528         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
1529         pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
1530         pa_device_port_ref(port);
1531     } else {
1532         pa_source_new_data *source_new_data = sink_or_source_new_data;
1533
1534         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
1535         pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
1536         pa_device_port_ref(port);
1537     }
1538 }
1539
1540 static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
1541     return 0;
1542 }
1543
1544 static int source_set_port_cb(pa_source *s, pa_device_port *p) {
1545     return 0;
1546 }
1547
1548 /* Run from main thread */
1549 static int add_sink(struct userdata *u) {
1550     char *k;
1551
1552     pa_assert(u->transport);
1553
1554     if (USE_SCO_OVER_PCM(u)) {
1555         pa_proplist *p;
1556
1557         u->sink = u->hsp.sco_sink;
1558         p = pa_proplist_new();
1559         pa_proplist_sets(p, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1560         pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1561         pa_proplist_free(p);
1562     } else {
1563         pa_sink_new_data data;
1564         bool b;
1565
1566         pa_sink_new_data_init(&data);
1567         data.driver = __FILE__;
1568         data.module = u->module;
1569         pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1570         pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1571         if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT)
1572             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1573         data.card = u->card;
1574         data.name = get_name("sink", u->modargs, u->address, pa_bluez4_profile_to_string(u->profile), &b);
1575         data.namereg_fail = b;
1576
1577         if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1578             pa_log("Invalid properties");
1579             pa_sink_new_data_done(&data);
1580             return -1;
1581         }
1582         connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1583
1584         if (!u->transport_acquired)
1585             switch (u->profile) {
1586                 case PA_BLUEZ4_PROFILE_A2DP_SINK:
1587                 case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
1588                     pa_assert_not_reached(); /* Profile switch should have failed */
1589                     break;
1590                 case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
1591                     data.suspend_cause = PA_SUSPEND_USER;
1592                     break;
1593                 case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
1594                 case PA_BLUEZ4_PROFILE_OFF:
1595                     pa_assert_not_reached();
1596             }
1597
1598         u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1599         pa_sink_new_data_done(&data);
1600
1601         if (!u->sink) {
1602             pa_log_error("Failed to create sink");
1603             return -1;
1604         }
1605
1606         u->sink->userdata = u;
1607         u->sink->parent.process_msg = sink_process_msg;
1608         u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1609         u->sink->set_port = sink_set_port_cb;
1610     }
1611
1612     if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1613         pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1614         u->sink->n_volume_steps = 16;
1615
1616         k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1617         pa_shared_set(u->core, k, u);
1618         pa_xfree(k);
1619     }
1620
1621     return 0;
1622 }
1623
1624 /* Run from main thread */
1625 static int add_source(struct userdata *u) {
1626     char *k;
1627
1628     pa_assert(u->transport);
1629
1630     if (USE_SCO_OVER_PCM(u)) {
1631         u->source = u->hsp.sco_source;
1632         pa_proplist_sets(u->source->proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1633     } else {
1634         pa_source_new_data data;
1635         bool b;
1636
1637         pa_source_new_data_init(&data);
1638         data.driver = __FILE__;
1639         data.module = u->module;
1640         pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1641         pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluez4_profile_to_string(u->profile));
1642         if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT)
1643             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1644
1645         data.card = u->card;
1646         data.name = get_name("source", u->modargs, u->address, pa_bluez4_profile_to_string(u->profile), &b);
1647         data.namereg_fail = b;
1648
1649         if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1650             pa_log("Invalid properties");
1651             pa_source_new_data_done(&data);
1652             return -1;
1653         }
1654
1655         connect_ports(u, &data, PA_DIRECTION_INPUT);
1656
1657         if (!u->transport_acquired)
1658             switch (u->profile) {
1659                 case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
1660                     pa_assert_not_reached(); /* Profile switch should have failed */
1661                     break;
1662                 case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
1663                 case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
1664                     data.suspend_cause = PA_SUSPEND_USER;
1665                     break;
1666                 case PA_BLUEZ4_PROFILE_A2DP_SINK:
1667                 case PA_BLUEZ4_PROFILE_OFF:
1668                     pa_assert_not_reached();
1669             }
1670
1671         u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1672         pa_source_new_data_done(&data);
1673
1674         if (!u->source) {
1675             pa_log_error("Failed to create source");
1676             return -1;
1677         }
1678
1679         u->source->userdata = u;
1680         u->source->parent.process_msg = source_process_msg;
1681         u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
1682         u->source->set_port = source_set_port_cb;
1683     }
1684
1685     if ((u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) || (u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)) {
1686         pa_bluez4_transport *t = u->transport;
1687         pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
1688     }
1689
1690     if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1691         pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1692         u->source->n_volume_steps = 16;
1693
1694         k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1695         pa_shared_set(u->core, k, u);
1696         pa_xfree(k);
1697     }
1698
1699     return 0;
1700 }
1701
1702 static void bt_transport_config_a2dp(struct userdata *u) {
1703     const pa_bluez4_transport *t;
1704     struct a2dp_info *a2dp = &u->a2dp;
1705     a2dp_sbc_t *config;
1706
1707     t = u->transport;
1708     pa_assert(t);
1709
1710     config = (a2dp_sbc_t *) t->config;
1711
1712     u->sample_spec.format = PA_SAMPLE_S16LE;
1713
1714     if (a2dp->sbc_initialized)
1715         sbc_reinit(&a2dp->sbc, 0);
1716     else
1717         sbc_init(&a2dp->sbc, 0);
1718     a2dp->sbc_initialized = true;
1719
1720     switch (config->frequency) {
1721         case SBC_SAMPLING_FREQ_16000:
1722             a2dp->sbc.frequency = SBC_FREQ_16000;
1723             u->sample_spec.rate = 16000U;
1724             break;
1725         case SBC_SAMPLING_FREQ_32000:
1726             a2dp->sbc.frequency = SBC_FREQ_32000;
1727             u->sample_spec.rate = 32000U;
1728             break;
1729         case SBC_SAMPLING_FREQ_44100:
1730             a2dp->sbc.frequency = SBC_FREQ_44100;
1731             u->sample_spec.rate = 44100U;
1732             break;
1733         case SBC_SAMPLING_FREQ_48000:
1734             a2dp->sbc.frequency = SBC_FREQ_48000;
1735             u->sample_spec.rate = 48000U;
1736             break;
1737         default:
1738             pa_assert_not_reached();
1739     }
1740
1741     switch (config->channel_mode) {
1742         case SBC_CHANNEL_MODE_MONO:
1743             a2dp->sbc.mode = SBC_MODE_MONO;
1744             u->sample_spec.channels = 1;
1745             break;
1746         case SBC_CHANNEL_MODE_DUAL_CHANNEL:
1747             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
1748             u->sample_spec.channels = 2;
1749             break;
1750         case SBC_CHANNEL_MODE_STEREO:
1751             a2dp->sbc.mode = SBC_MODE_STEREO;
1752             u->sample_spec.channels = 2;
1753             break;
1754         case SBC_CHANNEL_MODE_JOINT_STEREO:
1755             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
1756             u->sample_spec.channels = 2;
1757             break;
1758         default:
1759             pa_assert_not_reached();
1760     }
1761
1762     switch (config->allocation_method) {
1763         case SBC_ALLOCATION_SNR:
1764             a2dp->sbc.allocation = SBC_AM_SNR;
1765             break;
1766         case SBC_ALLOCATION_LOUDNESS:
1767             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
1768             break;
1769         default:
1770             pa_assert_not_reached();
1771     }
1772
1773     switch (config->subbands) {
1774         case SBC_SUBBANDS_4:
1775             a2dp->sbc.subbands = SBC_SB_4;
1776             break;
1777         case SBC_SUBBANDS_8:
1778             a2dp->sbc.subbands = SBC_SB_8;
1779             break;
1780         default:
1781             pa_assert_not_reached();
1782     }
1783
1784     switch (config->block_length) {
1785         case SBC_BLOCK_LENGTH_4:
1786             a2dp->sbc.blocks = SBC_BLK_4;
1787             break;
1788         case SBC_BLOCK_LENGTH_8:
1789             a2dp->sbc.blocks = SBC_BLK_8;
1790             break;
1791         case SBC_BLOCK_LENGTH_12:
1792             a2dp->sbc.blocks = SBC_BLK_12;
1793             break;
1794         case SBC_BLOCK_LENGTH_16:
1795             a2dp->sbc.blocks = SBC_BLK_16;
1796             break;
1797         default:
1798             pa_assert_not_reached();
1799     }
1800
1801     a2dp->min_bitpool = config->min_bitpool;
1802     a2dp->max_bitpool = config->max_bitpool;
1803
1804     /* Set minimum bitpool for source to get the maximum possible block_size */
1805     a2dp->sbc.bitpool = u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ? a2dp->max_bitpool : a2dp->min_bitpool;
1806     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
1807     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
1808
1809     pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u",
1810                 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
1811 }
1812
1813 static void bt_transport_config(struct userdata *u) {
1814     if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY) {
1815         u->sample_spec.format = PA_SAMPLE_S16LE;
1816         u->sample_spec.channels = 1;
1817         u->sample_spec.rate = 8000;
1818     } else
1819         bt_transport_config_a2dp(u);
1820 }
1821
1822 /* Run from main thread */
1823 static pa_hook_result_t transport_state_changed_cb(pa_bluez4_discovery *y, pa_bluez4_transport *t, struct userdata *u) {
1824     pa_assert(t);
1825     pa_assert(u);
1826
1827     if (t == u->transport && t->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)
1828         pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
1829
1830     if (t->device == u->device)
1831         handle_transport_state_change(u, t);
1832
1833     return PA_HOOK_OK;
1834 }
1835
1836 /* Run from main thread */
1837 static int setup_transport(struct userdata *u) {
1838     pa_bluez4_transport *t;
1839
1840     pa_assert(u);
1841     pa_assert(!u->transport);
1842     pa_assert(u->profile != PA_BLUEZ4_PROFILE_OFF);
1843
1844     /* check if profile has a transport */
1845     t = u->device->transports[u->profile];
1846     if (!t || t->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED) {
1847         pa_log_warn("Profile has no transport");
1848         return -1;
1849     }
1850
1851     u->transport = t;
1852
1853     if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE || u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1854         bt_transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1855     else if (bt_transport_acquire(u, false) < 0)
1856         return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1857
1858     bt_transport_config(u);
1859
1860     return 0;
1861 }
1862
1863 /* Run from main thread */
1864 static int init_profile(struct userdata *u) {
1865     int r = 0;
1866     pa_assert(u);
1867     pa_assert(u->profile != PA_BLUEZ4_PROFILE_OFF);
1868
1869     if (setup_transport(u) < 0)
1870         return -1;
1871
1872     pa_assert(u->transport);
1873
1874     if (u->profile == PA_BLUEZ4_PROFILE_A2DP_SINK ||
1875         u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT ||
1876         u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1877         if (add_sink(u) < 0)
1878             r = -1;
1879
1880     if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT ||
1881         u->profile == PA_BLUEZ4_PROFILE_A2DP_SOURCE ||
1882         u->profile == PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY)
1883         if (add_source(u) < 0)
1884             r = -1;
1885
1886     return r;
1887 }
1888
1889 /* Run from main thread */
1890 static void stop_thread(struct userdata *u) {
1891     char *k;
1892
1893     pa_assert(u);
1894
1895     if (u->sink && !USE_SCO_OVER_PCM(u))
1896         pa_sink_unlink(u->sink);
1897
1898     if (u->source && !USE_SCO_OVER_PCM(u))
1899         pa_source_unlink(u->source);
1900
1901     if (u->thread) {
1902         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1903         pa_thread_free(u->thread);
1904         u->thread = NULL;
1905     }
1906
1907     if (u->rtpoll_item) {
1908         pa_rtpoll_item_free(u->rtpoll_item);
1909         u->rtpoll_item = NULL;
1910     }
1911
1912     if (u->rtpoll) {
1913         pa_thread_mq_done(&u->thread_mq);
1914
1915         pa_rtpoll_free(u->rtpoll);
1916         u->rtpoll = NULL;
1917     }
1918
1919     if (u->transport) {
1920         bt_transport_release(u);
1921         u->transport = NULL;
1922     }
1923
1924     if (u->sink) {
1925         if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1926             k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1927             pa_shared_remove(u->core, k);
1928             pa_xfree(k);
1929         }
1930
1931         pa_sink_unref(u->sink);
1932         u->sink = NULL;
1933     }
1934
1935     if (u->source) {
1936         if (u->profile == PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT) {
1937             k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1938             pa_shared_remove(u->core, k);
1939             pa_xfree(k);
1940         }
1941
1942         pa_source_unref(u->source);
1943         u->source = NULL;
1944     }
1945
1946     if (u->read_smoother) {
1947         pa_smoother_free(u->read_smoother);
1948         u->read_smoother = NULL;
1949     }
1950 }
1951
1952 /* Run from main thread */
1953 static int start_thread(struct userdata *u) {
1954     pa_assert(u);
1955     pa_assert(!u->thread);
1956     pa_assert(!u->rtpoll);
1957     pa_assert(!u->rtpoll_item);
1958
1959     u->rtpoll = pa_rtpoll_new();
1960
1961     if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1962         pa_log("pa_thread_mq_init() failed.");
1963         return -1;
1964     }
1965
1966     if (USE_SCO_OVER_PCM(u)) {
1967         if (sco_over_pcm_state_update(u, false) < 0) {
1968             char *k;
1969
1970             if (u->sink) {
1971                 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->sink);
1972                 pa_shared_remove(u->core, k);
1973                 pa_xfree(k);
1974                 u->sink = NULL;
1975             }
1976             if (u->source) {
1977                 k = pa_sprintf_malloc("bluetooth-device@%p", (void*) u->source);
1978                 pa_shared_remove(u->core, k);
1979                 pa_xfree(k);
1980                 u->source = NULL;
1981             }
1982             return -1;
1983         }
1984
1985         pa_sink_ref(u->sink);
1986         pa_source_ref(u->source);
1987         /* FIXME: monitor stream_fd error */
1988         return 0;
1989     }
1990
1991     if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1992         pa_log_error("Failed to create IO thread");
1993         return -1;
1994     }
1995
1996     if (u->sink) {
1997         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1998         pa_sink_set_rtpoll(u->sink, u->rtpoll);
1999         pa_sink_put(u->sink);
2000
2001         if (u->sink->set_volume)
2002             u->sink->set_volume(u->sink);
2003     }
2004
2005     if (u->source) {
2006         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2007         pa_source_set_rtpoll(u->source, u->rtpoll);
2008         pa_source_put(u->source);
2009
2010         if (u->source->set_volume)
2011             u->source->set_volume(u->source);
2012     }
2013
2014     return 0;
2015 }
2016
2017 static void save_sco_volume_callbacks(struct userdata *u) {
2018     pa_assert(u);
2019     pa_assert(USE_SCO_OVER_PCM(u));
2020
2021     u->hsp.sco_sink_set_volume = u->hsp.sco_sink->set_volume;
2022     u->hsp.sco_source_set_volume = u->hsp.sco_source->set_volume;
2023 }
2024
2025 static void restore_sco_volume_callbacks(struct userdata *u) {
2026     pa_assert(u);
2027     pa_assert(USE_SCO_OVER_PCM(u));
2028
2029     pa_sink_set_set_volume_callback(u->hsp.sco_sink, u->hsp.sco_sink_set_volume);
2030     pa_source_set_set_volume_callback(u->hsp.sco_source, u->hsp.sco_source_set_volume);
2031 }
2032
2033 /* Run from main thread */
2034 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2035     struct userdata *u;
2036     pa_bluez4_profile_t *d;
2037
2038     pa_assert(c);
2039     pa_assert(new_profile);
2040     pa_assert_se(u = c->userdata);
2041
2042     d = PA_CARD_PROFILE_DATA(new_profile);
2043
2044     if (*d != PA_BLUEZ4_PROFILE_OFF) {
2045         const pa_bluez4_device *device = u->device;
2046
2047         if (!device->transports[*d] || device->transports[*d]->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED) {
2048             pa_log_warn("Profile not connected, refused to switch profile to %s", new_profile->name);
2049             return -PA_ERR_IO;
2050         }
2051     }
2052
2053     stop_thread(u);
2054
2055     if (USE_SCO_OVER_PCM(u))
2056         restore_sco_volume_callbacks(u);
2057
2058     u->profile = *d;
2059     u->sample_spec = u->requested_sample_spec;
2060
2061     if (USE_SCO_OVER_PCM(u))
2062         save_sco_volume_callbacks(u);
2063
2064     if (u->profile != PA_BLUEZ4_PROFILE_OFF)
2065         if (init_profile(u) < 0)
2066             goto off;
2067
2068     if (u->sink || u->source)
2069         if (start_thread(u) < 0)
2070             goto off;
2071
2072     return 0;
2073
2074 off:
2075     stop_thread(u);
2076
2077     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2078
2079     return -PA_ERR_IO;
2080 }
2081
2082 /* Run from main thread */
2083 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
2084     pa_device_port *port;
2085     pa_device_port_new_data port_data;
2086
2087     const char *name_prefix = NULL;
2088     const char *input_description = NULL;
2089     const char *output_description = NULL;
2090
2091     pa_assert(u);
2092     pa_assert(ports);
2093     pa_assert(u->device);
2094
2095     switch (pa_bluez4_get_form_factor(u->device->class)) {
2096         case PA_BLUEZ4_FORM_FACTOR_UNKNOWN:
2097             break;
2098
2099         case PA_BLUEZ4_FORM_FACTOR_HEADSET:
2100             name_prefix = "headset";
2101             input_description = output_description = _("Headset");
2102             break;
2103
2104         case PA_BLUEZ4_FORM_FACTOR_HANDSFREE:
2105             name_prefix = "handsfree";
2106             input_description = output_description = _("Handsfree");
2107             break;
2108
2109         case PA_BLUEZ4_FORM_FACTOR_MICROPHONE:
2110             name_prefix = "microphone";
2111             input_description = _("Microphone");
2112             break;
2113
2114         case PA_BLUEZ4_FORM_FACTOR_SPEAKER:
2115             name_prefix = "speaker";
2116             output_description = _("Speaker");
2117             break;
2118
2119         case PA_BLUEZ4_FORM_FACTOR_HEADPHONE:
2120             name_prefix = "headphone";
2121             output_description = _("Headphone");
2122             break;
2123
2124         case PA_BLUEZ4_FORM_FACTOR_PORTABLE:
2125             name_prefix = "portable";
2126             input_description = output_description = _("Portable");
2127             break;
2128
2129         case PA_BLUEZ4_FORM_FACTOR_CAR:
2130             name_prefix = "car";
2131             input_description = output_description = _("Car");
2132             break;
2133
2134         case PA_BLUEZ4_FORM_FACTOR_HIFI:
2135             name_prefix = "hifi";
2136             input_description = output_description = _("HiFi");
2137             break;
2138
2139         case PA_BLUEZ4_FORM_FACTOR_PHONE:
2140             name_prefix = "phone";
2141             input_description = output_description = _("Phone");
2142             break;
2143     }
2144
2145     if (!name_prefix)
2146         name_prefix = "unknown";
2147
2148     if (!output_description)
2149         output_description = _("Bluetooth Output");
2150
2151     if (!input_description)
2152         input_description = _("Bluetooth Input");
2153
2154     u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
2155     u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
2156
2157     pa_device_port_new_data_init(&port_data);
2158     pa_device_port_new_data_set_name(&port_data, u->output_port_name);
2159     pa_device_port_new_data_set_description(&port_data, output_description);
2160     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
2161     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
2162     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2163     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2164     pa_device_port_new_data_done(&port_data);
2165
2166     pa_device_port_new_data_init(&port_data);
2167     pa_device_port_new_data_set_name(&port_data, u->input_port_name);
2168     pa_device_port_new_data_set_description(&port_data, input_description);
2169     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
2170     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
2171     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2172     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2173     pa_device_port_new_data_done(&port_data);
2174 }
2175
2176 /* Run from main thread */
2177 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluez4_profile_t profile, pa_hashmap *ports) {
2178     pa_device_port *input_port, *output_port;
2179     const char *name;
2180     pa_card_profile *p = NULL;
2181     pa_bluez4_profile_t *d = NULL;
2182     pa_bluez4_transport *t;
2183
2184     pa_assert(u->input_port_name);
2185     pa_assert(u->output_port_name);
2186     pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2187     pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2188
2189     name = pa_bluez4_profile_to_string(profile);
2190
2191     switch (profile) {
2192     case PA_BLUEZ4_PROFILE_A2DP_SINK:
2193         p = pa_card_profile_new(name, _("High Fidelity Playback (A2DP)"), sizeof(pa_bluez4_profile_t));
2194         p->priority = 10;
2195         p->n_sinks = 1;
2196         p->n_sources = 0;
2197         p->max_sink_channels = 2;
2198         p->max_source_channels = 0;
2199         pa_hashmap_put(output_port->profiles, p->name, p);
2200
2201         d = PA_CARD_PROFILE_DATA(p);
2202         break;
2203
2204     case PA_BLUEZ4_PROFILE_A2DP_SOURCE:
2205         p = pa_card_profile_new(name, _("High Fidelity Capture (A2DP)"), sizeof(pa_bluez4_profile_t));
2206         p->priority = 10;
2207         p->n_sinks = 0;
2208         p->n_sources = 1;
2209         p->max_sink_channels = 0;
2210         p->max_source_channels = 2;
2211         pa_hashmap_put(input_port->profiles, p->name, p);
2212
2213         d = PA_CARD_PROFILE_DATA(p);
2214         break;
2215
2216     case PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT:
2217         p = pa_card_profile_new(name, _("Telephony Duplex (HSP/HFP)"), sizeof(pa_bluez4_profile_t));
2218         p->priority = 20;
2219         p->n_sinks = 1;
2220         p->n_sources = 1;
2221         p->max_sink_channels = 1;
2222         p->max_source_channels = 1;
2223         pa_hashmap_put(input_port->profiles, p->name, p);
2224         pa_hashmap_put(output_port->profiles, p->name, p);
2225
2226         d = PA_CARD_PROFILE_DATA(p);
2227         break;
2228
2229     case PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY:
2230         p = pa_card_profile_new(name, _("Handsfree Gateway"), sizeof(pa_bluez4_profile_t));
2231         p->priority = 20;
2232         p->n_sinks = 1;
2233         p->n_sources = 1;
2234         p->max_sink_channels = 1;
2235         p->max_source_channels = 1;
2236         pa_hashmap_put(input_port->profiles, p->name, p);
2237         pa_hashmap_put(output_port->profiles, p->name, p);
2238
2239         d = PA_CARD_PROFILE_DATA(p);
2240         break;
2241
2242     case PA_BLUEZ4_PROFILE_OFF:
2243         pa_assert_not_reached();
2244     }
2245
2246     *d = profile;
2247
2248     if ((t = u->device->transports[*d]))
2249         p->available = transport_state_to_availability(t->state);
2250
2251     return p;
2252 }
2253
2254 static int uuid_to_profile(const char *uuid, pa_bluez4_profile_t *_r) {
2255     if (pa_streq(uuid, PA_BLUEZ4_UUID_A2DP_SINK))
2256         *_r = PA_BLUEZ4_PROFILE_A2DP_SINK;
2257     else if (pa_streq(uuid, PA_BLUEZ4_UUID_A2DP_SOURCE))
2258         *_r = PA_BLUEZ4_PROFILE_A2DP_SOURCE;
2259     else if (pa_streq(uuid, PA_BLUEZ4_UUID_HSP_HS) || pa_streq(uuid, PA_BLUEZ4_UUID_HFP_HF))
2260         *_r = PA_BLUEZ4_PROFILE_HEADSET_HEAD_UNIT;
2261     else if (pa_streq(uuid, PA_BLUEZ4_UUID_HSP_AG) || pa_streq(uuid, PA_BLUEZ4_UUID_HFP_AG))
2262         *_r = PA_BLUEZ4_PROFILE_HEADSET_AUDIO_GATEWAY;
2263     else
2264         return -PA_ERR_INVALID;
2265
2266     return 0;
2267 }
2268
2269 /* Run from main thread */
2270 static int add_card(struct userdata *u) {
2271     pa_card_new_data data;
2272     bool b;
2273     pa_card_profile *p;
2274     pa_bluez4_profile_t *d;
2275     pa_bluez4_form_factor_t ff;
2276     char *n;
2277     const char *profile_str;
2278     const pa_bluez4_device *device;
2279     const char *uuid;
2280     void *state;
2281
2282     pa_assert(u);
2283     pa_assert(u->device);
2284
2285     device = u->device;
2286
2287     pa_card_new_data_init(&data);
2288     data.driver = __FILE__;
2289     data.module = u->module;
2290
2291     n = pa_utf8_filter(device->alias);
2292     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2293     pa_xfree(n);
2294     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2295     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2296     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2297     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2298
2299     if ((ff = pa_bluez4_get_form_factor(device->class)) != PA_BLUEZ4_FORM_FACTOR_UNKNOWN)
2300         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, pa_bluez4_form_factor_to_string(ff));
2301
2302     pa_proplist_sets(data.proplist, "bluez.path", device->path);
2303     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2304     pa_proplist_sets(data.proplist, "bluez.alias", device->alias);
2305     data.name = get_name("card", u->modargs, device->address, NULL, &b);
2306     data.namereg_fail = b;
2307
2308     if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2309         pa_log("Invalid properties");
2310         pa_card_new_data_done(&data);
2311         return -1;
2312     }
2313
2314     create_card_ports(u, data.ports);
2315
2316     PA_HASHMAP_FOREACH(uuid, device->uuids, state) {
2317         pa_bluez4_profile_t profile;
2318
2319         if (uuid_to_profile(uuid, &profile) < 0)
2320             continue;
2321
2322         if (pa_hashmap_get(data.profiles, pa_bluez4_profile_to_string(profile)))
2323             continue;
2324
2325         p = create_card_profile(u, profile, data.ports);
2326         pa_hashmap_put(data.profiles, p->name, p);
2327     }
2328
2329     pa_assert(!pa_hashmap_isempty(data.profiles));
2330
2331     p = pa_card_profile_new("off", _("Off"), sizeof(pa_bluez4_profile_t));
2332     p->available = PA_AVAILABLE_YES;
2333     d = PA_CARD_PROFILE_DATA(p);
2334     *d = PA_BLUEZ4_PROFILE_OFF;
2335     pa_hashmap_put(data.profiles, p->name, p);
2336
2337     u->card = pa_card_new(u->core, &data);
2338     pa_card_new_data_done(&data);
2339
2340     if (!u->card) {
2341         pa_log("Failed to allocate card.");
2342         return -1;
2343     }
2344
2345     u->card->userdata = u;
2346     u->card->set_profile = card_set_profile;
2347
2348     pa_card_choose_initial_profile(u->card);
2349
2350     /* If the "profile" modarg is given, we have to override whatever the usual
2351      * policy chose in pa_card_choose_initial_profile(). */
2352     profile_str = pa_modargs_get_value(u->modargs, "profile", NULL);
2353     if (profile_str) {
2354         pa_card_profile *profile;
2355
2356         profile = pa_hashmap_get(u->card->profiles, profile_str);
2357         if (!profile) {
2358             pa_log("No such profile: %s", profile_str);
2359             return -1;
2360         }
2361
2362         pa_card_set_profile(u->card, profile, false);
2363     }
2364
2365     pa_card_put(u->card);
2366
2367     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2368
2369     if (*d != PA_BLUEZ4_PROFILE_OFF && (!device->transports[*d] ||
2370                               device->transports[*d]->state == PA_BLUEZ4_TRANSPORT_STATE_DISCONNECTED)) {
2371         pa_log_warn("Default profile not connected, selecting off profile");
2372         u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2373         u->card->save_profile = false;
2374     }
2375
2376     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2377     u->profile = *d;
2378
2379     if (USE_SCO_OVER_PCM(u))
2380         save_sco_volume_callbacks(u);
2381
2382     return 0;
2383 }
2384
2385 /* Run from main thread */
2386 static pa_bluez4_device* find_device(struct userdata *u, const char *address, const char *path) {
2387     pa_bluez4_device *d = NULL;
2388
2389     pa_assert(u);
2390
2391     if (!address && !path) {
2392         pa_log_error("Failed to get device address/path from module arguments.");
2393         return NULL;
2394     }
2395
2396     if (path) {
2397         if (!(d = pa_bluez4_discovery_get_by_path(u->discovery, path))) {
2398             pa_log_error("%s is not a valid BlueZ audio device.", path);
2399             return NULL;
2400         }
2401
2402         if (address && !(pa_streq(d->address, address))) {
2403             pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2404             return NULL;
2405         }
2406
2407     } else {
2408         if (!(d = pa_bluez4_discovery_get_by_address(u->discovery, address))) {
2409             pa_log_error("%s is not known.", address);
2410             return NULL;
2411         }
2412     }
2413
2414     if (d) {
2415         u->address = pa_xstrdup(d->address);
2416         u->path = pa_xstrdup(d->path);
2417     }
2418
2419     return d;
2420 }
2421
2422 /* Run from main thread */
2423 static pa_hook_result_t uuid_added_cb(pa_bluez4_discovery *y, const struct pa_bluez4_hook_uuid_data *data,
2424                                       struct userdata *u) {
2425     pa_bluez4_profile_t profile;
2426     pa_card_profile *p;
2427
2428     pa_assert(data);
2429     pa_assert(data->device);
2430     pa_assert(data->uuid);
2431     pa_assert(u);
2432
2433     if (data->device != u->device)
2434         return PA_HOOK_OK;
2435
2436     if (uuid_to_profile(data->uuid, &profile) < 0)
2437         return PA_HOOK_OK;
2438
2439     if (pa_hashmap_get(u->card->profiles, pa_bluez4_profile_to_string(profile)))
2440         return PA_HOOK_OK;
2441
2442     p = create_card_profile(u, profile, u->card->ports);
2443     pa_card_add_profile(u->card, p);
2444
2445     return PA_HOOK_OK;
2446 }
2447
2448 /* Run from main thread */
2449 static pa_hook_result_t discovery_hook_cb(pa_bluez4_discovery *y, const pa_bluez4_device *d, struct userdata *u) {
2450     pa_assert(u);
2451     pa_assert(d);
2452
2453     if (d != u->device)
2454         return PA_HOOK_OK;
2455
2456     if (d->dead)
2457         pa_log_debug("Device %s removed: unloading module", d->path);
2458     else if (!pa_bluez4_device_any_audio_connected(d))
2459         pa_log_debug("Unloading module, because device %s doesn't have any audio profiles connected anymore.", d->path);
2460     else
2461         return PA_HOOK_OK;
2462
2463     pa_module_unload(u->module, true);
2464
2465     return PA_HOOK_OK;
2466 }
2467
2468 int pa__init(pa_module *m) {
2469     pa_modargs *ma;
2470     uint32_t channels;
2471     struct userdata *u;
2472     const char *address, *path;
2473     pa_bluez4_device *device;
2474
2475     pa_assert(m);
2476
2477     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2478         pa_log_error("Failed to parse module arguments");
2479         goto fail;
2480     }
2481
2482     m->userdata = u = pa_xnew0(struct userdata, 1);
2483     u->module = m;
2484     u->core = m->core;
2485     u->stream_fd = -1;
2486     u->sample_spec = m->core->default_sample_spec;
2487     u->modargs = ma;
2488
2489     if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2490         !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2491         pa_log("SCO sink not found");
2492         goto fail;
2493     }
2494
2495     if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2496         !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2497         pa_log("SCO source not found");
2498         goto fail;
2499     }
2500
2501     if (pa_modargs_get_sample_rate(ma, &u->sample_spec.rate) < 0) {
2502         pa_log_error("Failed to get rate from module arguments");
2503         goto fail;
2504     }
2505
2506     channels = u->sample_spec.channels;
2507     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2508         !pa_channels_valid(channels)) {
2509         pa_log_error("Failed to get channels from module arguments");
2510         goto fail;
2511     }
2512     u->sample_spec.channels = (uint8_t) channels;
2513     u->requested_sample_spec = u->sample_spec;
2514
2515     address = pa_modargs_get_value(ma, "address", NULL);
2516     path = pa_modargs_get_value(ma, "path", NULL);
2517
2518     if (!(u->discovery = pa_bluez4_discovery_get(m->core)))
2519         goto fail;
2520
2521     if (!(device = find_device(u, address, path)))
2522         goto fail;
2523
2524     u->device = device;
2525
2526     u->discovery_slot =
2527         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_DEVICE_CONNECTION_CHANGED),
2528                         PA_HOOK_NORMAL, (pa_hook_cb_t) discovery_hook_cb, u);
2529
2530     u->uuid_added_slot =
2531         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_DEVICE_UUID_ADDED),
2532                         PA_HOOK_NORMAL, (pa_hook_cb_t) uuid_added_cb, u);
2533
2534     u->sink_state_changed_slot =
2535         pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED],
2536                         PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
2537
2538     u->source_state_changed_slot =
2539         pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED],
2540                         PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
2541
2542     u->transport_state_changed_slot =
2543         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_STATE_CHANGED),
2544                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2545
2546     u->transport_nrec_changed_slot =
2547         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_NREC_CHANGED),
2548                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_nrec_changed_cb, u);
2549
2550     u->transport_microphone_changed_slot =
2551         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED),
2552                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2553
2554     u->transport_speaker_changed_slot =
2555         pa_hook_connect(pa_bluez4_discovery_hook(u->discovery, PA_BLUEZ4_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED),
2556                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2557
2558     /* Add the card structure. This will also initialize the default profile */
2559     if (add_card(u) < 0)
2560         goto fail;
2561
2562     if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2563         goto fail;
2564
2565     u->msg->parent.process_msg = device_process_msg;
2566     u->msg->card = u->card;
2567
2568     if (u->profile != PA_BLUEZ4_PROFILE_OFF)
2569         if (init_profile(u) < 0)
2570             goto off;
2571
2572     if (u->sink || u->source)
2573         if (start_thread(u) < 0)
2574             goto off;
2575
2576     return 0;
2577
2578 off:
2579     stop_thread(u);
2580
2581     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2582
2583     return 0;
2584
2585 fail:
2586
2587     pa__done(m);
2588
2589     return -1;
2590 }
2591
2592 int pa__get_n_used(pa_module *m) {
2593     struct userdata *u;
2594
2595     pa_assert(m);
2596     pa_assert_se(u = m->userdata);
2597
2598     return
2599         (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2600         (u->source ? pa_source_linked_by(u->source) : 0);
2601 }
2602
2603 void pa__done(pa_module *m) {
2604     struct userdata *u;
2605
2606     pa_assert(m);
2607
2608     if (!(u = m->userdata))
2609         return;
2610
2611     stop_thread(u);
2612
2613     if (u->discovery_slot)
2614         pa_hook_slot_free(u->discovery_slot);
2615
2616     if (u->uuid_added_slot)
2617         pa_hook_slot_free(u->uuid_added_slot);
2618
2619     if (u->sink_state_changed_slot)
2620         pa_hook_slot_free(u->sink_state_changed_slot);
2621
2622     if (u->source_state_changed_slot)
2623         pa_hook_slot_free(u->source_state_changed_slot);
2624
2625     if (u->transport_state_changed_slot)
2626         pa_hook_slot_free(u->transport_state_changed_slot);
2627
2628     if (u->transport_nrec_changed_slot)
2629         pa_hook_slot_free(u->transport_nrec_changed_slot);
2630
2631     if (u->transport_microphone_changed_slot)
2632         pa_hook_slot_free(u->transport_microphone_changed_slot);
2633
2634     if (u->transport_speaker_changed_slot)
2635         pa_hook_slot_free(u->transport_speaker_changed_slot);
2636
2637     if (USE_SCO_OVER_PCM(u))
2638         restore_sco_volume_callbacks(u);
2639
2640     if (u->msg)
2641         pa_xfree(u->msg);
2642
2643     if (u->card)
2644         pa_card_free(u->card);
2645
2646     if (u->a2dp.buffer)
2647         pa_xfree(u->a2dp.buffer);
2648
2649     sbc_finish(&u->a2dp.sbc);
2650
2651     if (u->modargs)
2652         pa_modargs_free(u->modargs);
2653
2654     pa_xfree(u->output_port_name);
2655     pa_xfree(u->input_port_name);
2656
2657     pa_xfree(u->address);
2658     pa_xfree(u->path);
2659
2660     if (u->discovery)
2661         pa_bluez4_discovery_unref(u->discovery);
2662
2663     pa_xfree(u);
2664 }