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