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