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