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