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