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