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