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