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