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