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