bluetooth: Drop all "#ifdef NOKIA" directives.
[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 void 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)
1882             return;
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
1890         if (u->transport)
1891             bt_transport_acquire(u, TRUE);
1892         else
1893             start_stream_fd(u);
1894     } else {
1895
1896         if (u->service_fd < 0)
1897             return;
1898
1899         if (u->transport)
1900             bt_transport_release(u);
1901         else
1902             stop_stream_fd(u);
1903
1904         pa_log_debug("Closing SCO over PCM");
1905         pa_close(u->service_fd);
1906         u->service_fd = -1;
1907     }
1908 }
1909
1910 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1911     pa_assert(c);
1912     pa_sink_assert_ref(s);
1913     pa_assert(u);
1914
1915     if (s != u->hsp.sco_sink)
1916         return PA_HOOK_OK;
1917
1918     sco_over_pcm_state_update(u);
1919
1920     return PA_HOOK_OK;
1921 }
1922
1923 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1924     pa_assert(c);
1925     pa_source_assert_ref(s);
1926     pa_assert(u);
1927
1928     if (s != u->hsp.sco_source)
1929         return PA_HOOK_OK;
1930
1931     sco_over_pcm_state_update(u);
1932
1933     return PA_HOOK_OK;
1934 }
1935
1936 /* Run from main thread */
1937 static int add_sink(struct userdata *u) {
1938     if (USE_SCO_OVER_PCM(u)) {
1939         pa_proplist *p;
1940
1941         u->sink = u->hsp.sco_sink;
1942         p = pa_proplist_new();
1943         pa_proplist_sets(p, "bluetooth.protocol", "sco");
1944         pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1945         pa_proplist_free(p);
1946
1947         if (!u->hsp.sink_state_changed_slot)
1948             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);
1949
1950     } else {
1951         pa_sink_new_data data;
1952         pa_bool_t b;
1953
1954         pa_sink_new_data_init(&data);
1955         data.driver = __FILE__;
1956         data.module = u->module;
1957         pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1958         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1959         if (u->profile == PROFILE_HSP)
1960             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1961         data.card = u->card;
1962         data.name = get_name("sink", u->modargs, u->address, &b);
1963         data.namereg_fail = b;
1964
1965         if (pa_modargs_get_proplist(u->modargs, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1966             pa_log("Invalid properties");
1967             pa_sink_new_data_done(&data);
1968             return -1;
1969         }
1970
1971         u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1972         pa_sink_new_data_done(&data);
1973
1974         if (!u->sink) {
1975             pa_log_error("Failed to create sink");
1976             return -1;
1977         }
1978
1979         u->sink->userdata = u;
1980         u->sink->parent.process_msg = sink_process_msg;
1981
1982         pa_sink_set_max_request(u->sink, u->block_size);
1983         pa_sink_set_fixed_latency(u->sink,
1984                                   (u->profile == PROFILE_A2DP ? FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_HSP) +
1985                                   pa_bytes_to_usec(u->block_size, &u->sample_spec));
1986     }
1987
1988     if (u->profile == PROFILE_HSP) {
1989         u->sink->set_volume = sink_set_volume_cb;
1990         u->sink->n_volume_steps = 16;
1991     }
1992
1993     return 0;
1994 }
1995
1996 /* Run from main thread */
1997 static int add_source(struct userdata *u) {
1998     if (USE_SCO_OVER_PCM(u)) {
1999         u->source = u->hsp.sco_source;
2000         pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "hsp");
2001
2002         if (!u->hsp.source_state_changed_slot)
2003             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);
2004
2005     } else {
2006         pa_source_new_data data;
2007         pa_bool_t b;
2008
2009         pa_source_new_data_init(&data);
2010         data.driver = __FILE__;
2011         data.module = u->module;
2012         pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
2013         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP_SOURCE ? "a2dp_source" : "hsp");
2014         if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW))
2015             pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
2016
2017         data.card = u->card;
2018         data.name = get_name("source", u->modargs, u->address, &b);
2019         data.namereg_fail = b;
2020
2021         if (pa_modargs_get_proplist(u->modargs, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2022             pa_log("Invalid properties");
2023             pa_source_new_data_done(&data);
2024             return -1;
2025         }
2026
2027         u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
2028         pa_source_new_data_done(&data);
2029
2030         if (!u->source) {
2031             pa_log_error("Failed to create source");
2032             return -1;
2033         }
2034
2035         u->source->userdata = u;
2036         u->source->parent.process_msg = source_process_msg;
2037
2038         pa_source_set_fixed_latency(u->source,
2039                                     (u->profile == PROFILE_A2DP_SOURCE ? FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_HSP) +
2040                                     pa_bytes_to_usec(u->block_size, &u->sample_spec));
2041     }
2042
2043     if ((u->profile == PROFILE_HSP) || (u->profile == PROFILE_HFGW)) {
2044         if (u->transport) {
2045             const pa_bluetooth_transport *t;
2046             t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2047             pa_assert(t);
2048             pa_proplist_sets(u->source->proplist, "bluetooth.nrec", t->nrec ? "1" : "0");
2049         } else
2050             pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
2051     }
2052
2053     if (u->profile == PROFILE_HSP) {
2054         u->source->set_volume = source_set_volume_cb;
2055         u->source->n_volume_steps = 16;
2056     }
2057
2058     return 0;
2059 }
2060
2061 /* Run from main thread */
2062 static void shutdown_bt(struct userdata *u) {
2063     pa_assert(u);
2064
2065     if (u->stream_fd >= 0) {
2066         pa_close(u->stream_fd);
2067         u->stream_fd = -1;
2068
2069         u->stream_write_type = 0;
2070     }
2071
2072     if (u->service_fd >= 0) {
2073         pa_close(u->service_fd);
2074         u->service_fd = -1;
2075         u->service_write_type = 0;
2076         u->service_read_type = 0;
2077     }
2078
2079     if (u->write_memchunk.memblock) {
2080         pa_memblock_unref(u->write_memchunk.memblock);
2081         pa_memchunk_reset(&u->write_memchunk);
2082     }
2083 }
2084
2085 static int bt_transport_config_a2dp(struct userdata *u) {
2086     const pa_bluetooth_transport *t;
2087     struct a2dp_info *a2dp = &u->a2dp;
2088     a2dp_sbc_t *config;
2089
2090     t = pa_bluetooth_discovery_get_transport(u->discovery, u->transport);
2091     pa_assert(t);
2092
2093     config = (a2dp_sbc_t *) t->config;
2094
2095     if (a2dp->sbc_initialized)
2096         sbc_reinit(&a2dp->sbc, 0);
2097     else
2098         sbc_init(&a2dp->sbc, 0);
2099     a2dp->sbc_initialized = TRUE;
2100
2101     switch (config->frequency) {
2102         case BT_SBC_SAMPLING_FREQ_16000:
2103             a2dp->sbc.frequency = SBC_FREQ_16000;
2104             break;
2105         case BT_SBC_SAMPLING_FREQ_32000:
2106             a2dp->sbc.frequency = SBC_FREQ_32000;
2107             break;
2108         case BT_SBC_SAMPLING_FREQ_44100:
2109             a2dp->sbc.frequency = SBC_FREQ_44100;
2110             break;
2111         case BT_SBC_SAMPLING_FREQ_48000:
2112             a2dp->sbc.frequency = SBC_FREQ_48000;
2113             break;
2114         default:
2115             pa_assert_not_reached();
2116     }
2117
2118     switch (config->channel_mode) {
2119         case BT_A2DP_CHANNEL_MODE_MONO:
2120             a2dp->sbc.mode = SBC_MODE_MONO;
2121             break;
2122         case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
2123             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
2124             break;
2125         case BT_A2DP_CHANNEL_MODE_STEREO:
2126             a2dp->sbc.mode = SBC_MODE_STEREO;
2127             break;
2128         case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
2129             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
2130             break;
2131         default:
2132             pa_assert_not_reached();
2133     }
2134
2135     switch (config->allocation_method) {
2136         case BT_A2DP_ALLOCATION_SNR:
2137             a2dp->sbc.allocation = SBC_AM_SNR;
2138             break;
2139         case BT_A2DP_ALLOCATION_LOUDNESS:
2140             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
2141             break;
2142         default:
2143             pa_assert_not_reached();
2144     }
2145
2146     switch (config->subbands) {
2147         case BT_A2DP_SUBBANDS_4:
2148             a2dp->sbc.subbands = SBC_SB_4;
2149             break;
2150         case BT_A2DP_SUBBANDS_8:
2151             a2dp->sbc.subbands = SBC_SB_8;
2152             break;
2153         default:
2154             pa_assert_not_reached();
2155     }
2156
2157     switch (config->block_length) {
2158         case BT_A2DP_BLOCK_LENGTH_4:
2159             a2dp->sbc.blocks = SBC_BLK_4;
2160             break;
2161         case BT_A2DP_BLOCK_LENGTH_8:
2162             a2dp->sbc.blocks = SBC_BLK_8;
2163             break;
2164         case BT_A2DP_BLOCK_LENGTH_12:
2165             a2dp->sbc.blocks = SBC_BLK_12;
2166             break;
2167         case BT_A2DP_BLOCK_LENGTH_16:
2168             a2dp->sbc.blocks = SBC_BLK_16;
2169             break;
2170         default:
2171             pa_assert_not_reached();
2172     }
2173
2174     a2dp->min_bitpool = config->min_bitpool;
2175     a2dp->max_bitpool = config->max_bitpool;
2176
2177     /* Set minimum bitpool for source to get the maximum possible block_size */
2178     a2dp->sbc.bitpool = u->profile == PROFILE_A2DP ? a2dp->max_bitpool : a2dp->min_bitpool;
2179     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
2180     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
2181
2182     u->block_size =
2183         ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
2184         / a2dp->frame_length
2185         * a2dp->codesize);
2186
2187     pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
2188                 a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks, a2dp->sbc.bitpool);
2189
2190     return 0;
2191 }
2192
2193 static int bt_transport_config(struct userdata *u) {
2194     if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW) {
2195         u->block_size = u->link_mtu;
2196         return 0;
2197     }
2198
2199     return bt_transport_config_a2dp(u);
2200 }
2201
2202 /* Run from main thread */
2203 static int bt_transport_open(struct userdata *u) {
2204     if (bt_transport_acquire(u, FALSE) < 0)
2205         return -1;
2206
2207     return bt_transport_config(u);
2208 }
2209
2210 /* Run from main thread */
2211 static int init_bt(struct userdata *u) {
2212     pa_assert(u);
2213
2214     shutdown_bt(u);
2215
2216     u->stream_write_type = 0;
2217     u->service_write_type = 0;
2218     u->service_read_type = 0;
2219
2220     if ((u->service_fd = bt_audio_service_open()) < 0) {
2221         pa_log_warn("Bluetooth audio service not available");
2222         return -1;
2223     }
2224
2225     pa_log_debug("Connected to the bluetooth audio service");
2226
2227     return 0;
2228 }
2229
2230 /* Run from main thread */
2231 static int setup_bt(struct userdata *u) {
2232     const pa_bluetooth_device *d;
2233     const pa_bluetooth_transport *t;
2234
2235     pa_assert(u);
2236
2237     if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2238         pa_log_error("Failed to get device object.");
2239         return -1;
2240     }
2241
2242     /* release transport if exist */
2243     if (u->transport) {
2244         bt_transport_release(u);
2245         pa_xfree(u->transport);
2246         u->transport = NULL;
2247     }
2248
2249     /* check if profile has a transport */
2250     t = pa_bluetooth_device_get_transport(d, u->profile);
2251     if (t) {
2252         u->transport = pa_xstrdup(t->path);
2253         return bt_transport_open(u);
2254     }
2255
2256     if (get_caps(u, 0) < 0)
2257         return -1;
2258
2259     pa_log_debug("Got device capabilities");
2260
2261     if (set_conf(u) < 0)
2262         return -1;
2263
2264     pa_log_debug("Connection to the device configured");
2265
2266     if (USE_SCO_OVER_PCM(u)) {
2267         pa_log_debug("Configured to use SCO over PCM");
2268         return 0;
2269     }
2270
2271     pa_log_debug("Got the stream socket");
2272
2273     return 0;
2274 }
2275
2276 /* Run from main thread */
2277 static int init_profile(struct userdata *u) {
2278     int r = 0;
2279     pa_assert(u);
2280     pa_assert(u->profile != PROFILE_OFF);
2281
2282     if (setup_bt(u) < 0)
2283         return -1;
2284
2285     if (u->profile == PROFILE_A2DP ||
2286         u->profile == PROFILE_HSP ||
2287         u->profile == PROFILE_HFGW)
2288         if (add_sink(u) < 0)
2289             r = -1;
2290
2291     if (u->profile == PROFILE_HSP ||
2292         u->profile == PROFILE_A2DP_SOURCE ||
2293         u->profile == PROFILE_HFGW)
2294         if (add_source(u) < 0)
2295             r = -1;
2296
2297     return r;
2298 }
2299
2300 /* Run from main thread */
2301 static void stop_thread(struct userdata *u) {
2302     pa_assert(u);
2303
2304     if (u->thread) {
2305         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
2306         pa_thread_free(u->thread);
2307         u->thread = NULL;
2308     }
2309
2310     if (u->rtpoll_item) {
2311         pa_rtpoll_item_free(u->rtpoll_item);
2312         u->rtpoll_item = NULL;
2313     }
2314
2315     if (u->hsp.sink_state_changed_slot) {
2316         pa_hook_slot_free(u->hsp.sink_state_changed_slot);
2317         u->hsp.sink_state_changed_slot = NULL;
2318     }
2319
2320     if (u->hsp.source_state_changed_slot) {
2321         pa_hook_slot_free(u->hsp.source_state_changed_slot);
2322         u->hsp.source_state_changed_slot = NULL;
2323     }
2324
2325     if (u->sink) {
2326         pa_sink_unref(u->sink);
2327         u->sink = NULL;
2328     }
2329
2330     if (u->source) {
2331         pa_source_unref(u->source);
2332         u->source = NULL;
2333     }
2334
2335     if (u->rtpoll) {
2336         pa_thread_mq_done(&u->thread_mq);
2337
2338         pa_rtpoll_free(u->rtpoll);
2339         u->rtpoll = NULL;
2340     }
2341
2342     if (u->read_smoother) {
2343         pa_smoother_free(u->read_smoother);
2344         u->read_smoother = NULL;
2345     }
2346 }
2347
2348 /* Run from main thread */
2349 static int start_thread(struct userdata *u) {
2350     pa_assert(u);
2351     pa_assert(!u->thread);
2352     pa_assert(!u->rtpoll);
2353     pa_assert(!u->rtpoll_item);
2354
2355     u->rtpoll = pa_rtpoll_new();
2356     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
2357
2358     if (USE_SCO_OVER_PCM(u)) {
2359         if (u->transport) {
2360             if (bt_transport_acquire(u, TRUE) < 0)
2361                 return -1;
2362         } else if (start_stream_fd(u) < 0)
2363             return -1;
2364
2365         pa_sink_ref(u->sink);
2366         pa_source_ref(u->source);
2367         /* FIXME: monitor stream_fd error */
2368         return 0;
2369     }
2370
2371     if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
2372         pa_log_error("Failed to create IO thread");
2373         stop_thread(u);
2374         return -1;
2375     }
2376
2377     if (u->sink) {
2378         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
2379         pa_sink_set_rtpoll(u->sink, u->rtpoll);
2380         pa_sink_put(u->sink);
2381
2382         if (u->sink->set_volume)
2383             u->sink->set_volume(u->sink);
2384     }
2385
2386     if (u->source) {
2387         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
2388         pa_source_set_rtpoll(u->source, u->rtpoll);
2389         pa_source_put(u->source);
2390
2391         if (u->source->set_volume)
2392             u->source->set_volume(u->source);
2393     }
2394
2395     return 0;
2396 }
2397
2398 /* Run from main thread */
2399 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
2400     struct userdata *u;
2401     enum profile *d;
2402     pa_queue *inputs = NULL, *outputs = NULL;
2403     const pa_bluetooth_device *device;
2404
2405     pa_assert(c);
2406     pa_assert(new_profile);
2407     pa_assert_se(u = c->userdata);
2408
2409     d = PA_CARD_PROFILE_DATA(new_profile);
2410
2411     if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
2412         pa_log_error("Failed to get device object.");
2413         return -PA_ERR_IO;
2414     }
2415
2416     /* The state signal is sent by bluez, so it is racy to check
2417        strictly for CONNECTED, we should also accept STREAMING state
2418        as being good enough. However, if the profile is used
2419        concurrently (which is unlikely), ipc will fail later on, and
2420        module will be unloaded. */
2421     if (device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
2422         pa_log_warn("HSP is not connected, refused to switch profile");
2423         return -PA_ERR_IO;
2424     }
2425     else if (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
2426         pa_log_warn("A2DP is not connected, refused to switch profile");
2427         return -PA_ERR_IO;
2428     }
2429     else if (device->hfgw_state <= PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW) {
2430         pa_log_warn("HandsfreeGateway is not connected, refused to switch profile");
2431         return -PA_ERR_IO;
2432     }
2433
2434     if (u->sink) {
2435         inputs = pa_sink_move_all_start(u->sink, NULL);
2436
2437         if (!USE_SCO_OVER_PCM(u))
2438             pa_sink_unlink(u->sink);
2439     }
2440
2441     if (u->source) {
2442         outputs = pa_source_move_all_start(u->source, NULL);
2443
2444         if (!USE_SCO_OVER_PCM(u))
2445             pa_source_unlink(u->source);
2446     }
2447
2448     stop_thread(u);
2449     shutdown_bt(u);
2450
2451     u->profile = *d;
2452     u->sample_spec = u->requested_sample_spec;
2453
2454     init_bt(u);
2455
2456     if (u->profile != PROFILE_OFF)
2457         init_profile(u);
2458
2459     if (u->sink || u->source)
2460         start_thread(u);
2461
2462     if (inputs) {
2463         if (u->sink)
2464             pa_sink_move_all_finish(u->sink, inputs, FALSE);
2465         else
2466             pa_sink_move_all_fail(inputs);
2467     }
2468
2469     if (outputs) {
2470         if (u->source)
2471             pa_source_move_all_finish(u->source, outputs, FALSE);
2472         else
2473             pa_source_move_all_fail(outputs);
2474     }
2475
2476     return 0;
2477 }
2478
2479 /* Run from main thread */
2480 static int add_card(struct userdata *u, const pa_bluetooth_device *device) {
2481     pa_card_new_data data;
2482     pa_bool_t b;
2483     pa_card_profile *p;
2484     enum profile *d;
2485     const char *ff;
2486     char *n;
2487     const char *default_profile;
2488
2489     pa_assert(u);
2490     pa_assert(device);
2491
2492     pa_card_new_data_init(&data);
2493     data.driver = __FILE__;
2494     data.module = u->module;
2495
2496     n = pa_bluetooth_cleanup_name(device->name);
2497     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
2498     pa_xfree(n);
2499     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
2500     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2501     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2502     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2503     if ((ff = pa_bluetooth_get_form_factor(device->class)))
2504         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
2505     pa_proplist_sets(data.proplist, "bluez.path", device->path);
2506     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
2507     pa_proplist_sets(data.proplist, "bluez.name", device->name);
2508     data.name = get_name("card", u->modargs, device->address, &b);
2509     data.namereg_fail = b;
2510
2511     if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
2512         pa_log("Invalid properties");
2513         pa_card_new_data_done(&data);
2514         return -1;
2515     }
2516
2517     data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
2518
2519     /* we base hsp/a2dp availability on UUIDs.
2520        Ideally, it would be based on "Connected" state, but
2521        we can't afford to wait for this information when
2522        we are loaded with profile="hsp", for instance */
2523     if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
2524         p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
2525         p->priority = 10;
2526         p->n_sinks = 1;
2527         p->n_sources = 0;
2528         p->max_sink_channels = 2;
2529         p->max_source_channels = 0;
2530
2531         d = PA_CARD_PROFILE_DATA(p);
2532         *d = PROFILE_A2DP;
2533
2534         pa_hashmap_put(data.profiles, p->name, p);
2535     }
2536
2537     if (pa_bluetooth_uuid_has(device->uuids, A2DP_SOURCE_UUID)) {
2538         p = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP)"), sizeof(enum profile));
2539         p->priority = 10;
2540         p->n_sinks = 0;
2541         p->n_sources = 1;
2542         p->max_sink_channels = 0;
2543         p->max_source_channels = 2;
2544
2545         d = PA_CARD_PROFILE_DATA(p);
2546         *d = PROFILE_A2DP_SOURCE;
2547
2548         pa_hashmap_put(data.profiles, p->name, p);
2549     }
2550
2551     if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
2552         pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
2553         p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
2554         p->priority = 20;
2555         p->n_sinks = 1;
2556         p->n_sources = 1;
2557         p->max_sink_channels = 1;
2558         p->max_source_channels = 1;
2559
2560         d = PA_CARD_PROFILE_DATA(p);
2561         *d = PROFILE_HSP;
2562
2563         pa_hashmap_put(data.profiles, p->name, p);
2564     }
2565
2566     if (pa_bluetooth_uuid_has(device->uuids, HFP_AG_UUID)) {
2567         p = pa_card_profile_new("hfgw", _("Handsfree Gateway"), sizeof(enum profile));
2568         p->priority = 20;
2569         p->n_sinks = 1;
2570         p->n_sources = 1;
2571         p->max_sink_channels = 1;
2572         p->max_source_channels = 1;
2573
2574         d = PA_CARD_PROFILE_DATA(p);
2575         *d = PROFILE_HFGW;
2576
2577         pa_hashmap_put(data.profiles, p->name, p);
2578     }
2579
2580     pa_assert(!pa_hashmap_isempty(data.profiles));
2581
2582     p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
2583     d = PA_CARD_PROFILE_DATA(p);
2584     *d = PROFILE_OFF;
2585     pa_hashmap_put(data.profiles, p->name, p);
2586
2587     if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
2588         if (pa_hashmap_get(data.profiles, default_profile))
2589             pa_card_new_data_set_profile(&data, default_profile);
2590         else
2591             pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
2592     }
2593
2594     u->card = pa_card_new(u->core, &data);
2595     pa_card_new_data_done(&data);
2596
2597     if (!u->card) {
2598         pa_log("Failed to allocate card.");
2599         return -1;
2600     }
2601
2602     u->card->userdata = u;
2603     u->card->set_profile = card_set_profile;
2604
2605     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2606
2607     if ((device->headset_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) ||
2608         (device->audio_sink_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) ||
2609         (device->hfgw_state < PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HFGW)) {
2610         pa_log_warn("Default profile not connected, selecting off profile");
2611         u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
2612         u->card->save_profile = FALSE;
2613     }
2614
2615     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
2616     u->profile = *d;
2617
2618     return 0;
2619 }
2620
2621 /* Run from main thread */
2622 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
2623     const pa_bluetooth_device *d = NULL;
2624
2625     pa_assert(u);
2626
2627     if (!address && !path) {
2628         pa_log_error("Failed to get device address/path from module arguments.");
2629         return NULL;
2630     }
2631
2632     if (path) {
2633         if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
2634             pa_log_error("%s is not a valid BlueZ audio device.", path);
2635             return NULL;
2636         }
2637
2638         if (address && !(pa_streq(d->address, address))) {
2639             pa_log_error("Passed path %s address %s != %s don't match.", path, d->address, address);
2640             return NULL;
2641         }
2642
2643     } else {
2644         if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
2645             pa_log_error("%s is not known.", address);
2646             return NULL;
2647         }
2648     }
2649
2650     if (d) {
2651         u->address = pa_xstrdup(d->address);
2652         u->path = pa_xstrdup(d->path);
2653     }
2654
2655     return d;
2656 }
2657
2658 /* Run from main thread */
2659 static int setup_dbus(struct userdata *u) {
2660     DBusError err;
2661
2662     dbus_error_init(&err);
2663
2664     u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
2665
2666     if (dbus_error_is_set(&err) || !u->connection) {
2667         pa_log("Failed to get D-Bus connection: %s", err.message);
2668         dbus_error_free(&err);
2669         return -1;
2670     }
2671
2672     return 0;
2673 }
2674
2675 int pa__init(pa_module* m) {
2676     pa_modargs *ma;
2677     uint32_t channels;
2678     struct userdata *u;
2679     const char *address, *path;
2680     DBusError err;
2681     char *mike, *speaker, *transport;
2682     const pa_bluetooth_device *device;
2683
2684     pa_assert(m);
2685
2686     dbus_error_init(&err);
2687
2688     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2689         pa_log_error("Failed to parse module arguments");
2690         goto fail;
2691     }
2692
2693     m->userdata = u = pa_xnew0(struct userdata, 1);
2694     u->module = m;
2695     u->core = m->core;
2696     u->service_fd = -1;
2697     u->stream_fd = -1;
2698     u->sample_spec = m->core->default_sample_spec;
2699     u->modargs = ma;
2700
2701     if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
2702         !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
2703         pa_log("SCO sink not found");
2704         goto fail;
2705     }
2706
2707     if (pa_modargs_get_value(ma, "sco_source", NULL) &&
2708         !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
2709         pa_log("SCO source not found");
2710         goto fail;
2711     }
2712
2713     if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
2714         u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
2715         pa_log_error("Failed to get rate from module arguments");
2716         goto fail;
2717     }
2718
2719     u->auto_connect = TRUE;
2720     if (pa_modargs_get_value_boolean(ma, "auto_connect", &u->auto_connect)) {
2721         pa_log("Failed to parse auto_connect= argument");
2722         goto fail;
2723     }
2724
2725     channels = u->sample_spec.channels;
2726     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
2727         channels <= 0 || channels > PA_CHANNELS_MAX) {
2728         pa_log_error("Failed to get channels from module arguments");
2729         goto fail;
2730     }
2731     u->sample_spec.channels = (uint8_t) channels;
2732     u->requested_sample_spec = u->sample_spec;
2733
2734     address = pa_modargs_get_value(ma, "address", NULL);
2735     path = pa_modargs_get_value(ma, "path", NULL);
2736
2737     if (setup_dbus(u) < 0)
2738         goto fail;
2739
2740     if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2741         goto fail;
2742
2743     if (!(device = find_device(u, address, path)))
2744         goto fail;
2745
2746     /* Add the card structure. This will also initialize the default profile */
2747     if (add_card(u, device) < 0)
2748         goto fail;
2749
2750     if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2751         pa_log_error("Failed to add filter function");
2752         goto fail;
2753     }
2754     u->filter_added = TRUE;
2755
2756     speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2757     mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2758     transport = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.MediaTransport',member='PropertyChanged'");
2759
2760     if (pa_dbus_add_matches(
2761                 pa_dbus_connection_get(u->connection), &err,
2762                 speaker,
2763                 mike,
2764                 transport,
2765                 NULL) < 0) {
2766
2767         pa_xfree(speaker);
2768         pa_xfree(mike);
2769         pa_xfree(transport);
2770
2771         pa_log("Failed to add D-Bus matches: %s", err.message);
2772         goto fail;
2773     }
2774
2775     pa_xfree(speaker);
2776     pa_xfree(mike);
2777     pa_xfree(transport);
2778
2779     /* Connect to the BT service */
2780     init_bt(u);
2781
2782     if (u->profile != PROFILE_OFF)
2783         if (init_profile(u) < 0)
2784             goto fail;
2785
2786     if (u->sink || u->source)
2787         if (start_thread(u) < 0)
2788             goto fail;
2789
2790     return 0;
2791
2792 fail:
2793
2794     pa__done(m);
2795
2796     dbus_error_free(&err);
2797
2798     return -1;
2799 }
2800
2801 int pa__get_n_used(pa_module *m) {
2802     struct userdata *u;
2803
2804     pa_assert(m);
2805     pa_assert_se(u = m->userdata);
2806
2807     return
2808         (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2809         (u->source ? pa_source_linked_by(u->source) : 0);
2810 }
2811
2812 void pa__done(pa_module *m) {
2813     struct userdata *u;
2814     pa_assert(m);
2815
2816     if (!(u = m->userdata))
2817         return;
2818
2819     if (u->sink && !USE_SCO_OVER_PCM(u))
2820         pa_sink_unlink(u->sink);
2821
2822     if (u->source && !USE_SCO_OVER_PCM(u))
2823         pa_source_unlink(u->source);
2824
2825     stop_thread(u);
2826
2827     if (u->connection) {
2828
2829         if (u->path) {
2830             char *speaker, *mike;
2831             speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2832             mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2833
2834             pa_dbus_remove_matches(pa_dbus_connection_get(u->connection), speaker, mike, NULL);
2835
2836             pa_xfree(speaker);
2837             pa_xfree(mike);
2838         }
2839
2840         if (u->filter_added)
2841             dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2842
2843         pa_dbus_connection_unref(u->connection);
2844     }
2845
2846     if (u->card)
2847         pa_card_free(u->card);
2848
2849     if (u->read_smoother)
2850         pa_smoother_free(u->read_smoother);
2851
2852     shutdown_bt(u);
2853
2854     if (u->a2dp.buffer)
2855         pa_xfree(u->a2dp.buffer);
2856
2857     sbc_finish(&u->a2dp.sbc);
2858
2859     if (u->modargs)
2860         pa_modargs_free(u->modargs);
2861
2862     pa_xfree(u->address);
2863     pa_xfree(u->path);
2864
2865     if (u->transport) {
2866         bt_transport_release(u);
2867         pa_xfree(u->transport);
2868     }
2869
2870     if (u->discovery)
2871         pa_bluetooth_discovery_unref(u->discovery);
2872
2873     pa_xfree(u);
2874 }