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