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