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