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