Sending translation for Finnish
[profile/ivi/pulseaudio.git] / src / modules / bluetooth / module-bluetooth-device.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2008 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 <poll.h>
29 #include <sys/ioctl.h>
30 #include <linux/sockios.h>
31 #include <arpa/inet.h>
32
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/sample.h>
36 #include <pulse/i18n.h>
37
38 #include <pulsecore/module.h>
39 #include <pulsecore/modargs.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/rtpoll.h>
46 #include <pulsecore/time-smoother.h>
47 #include <pulsecore/rtclock.h>
48 #include <pulsecore/namereg.h>
49 #include <pulsecore/dbus-shared.h>
50
51 #include "module-bluetooth-device-symdef.h"
52 #include "ipc.h"
53 #include "sbc.h"
54 #include "rtp.h"
55 #include "bluetooth-util.h"
56
57 #define MAX_BITPOOL 64
58 #define MIN_BITPOOL 2U
59
60 PA_MODULE_AUTHOR("Joao Paulo Rechi Vita");
61 PA_MODULE_DESCRIPTION("Bluetooth audio sink and source");
62 PA_MODULE_VERSION(PACKAGE_VERSION);
63 PA_MODULE_LOAD_ONCE(FALSE);
64 PA_MODULE_USAGE(
65         "name=<name for the card/sink/source, to be prefixed> "
66         "card_name=<name for the card> "
67         "sink_name=<name for the sink> "
68         "source_name=<name for the source> "
69         "address=<address of the device> "
70         "profile=<a2dp|hsp> "
71         "rate=<sample rate> "
72         "channels=<number of channels> "
73         "path=<device object path>");
74
75 /*
76 #ifdef NOKIA
77         "sco_sink=<SCO over PCM sink name> "
78         "sco_source=<SCO over PCM source name>"
79 #endif
80 */
81
82 /* TODO: not close fd when entering suspend mode in a2dp */
83
84 static const char* const valid_modargs[] = {
85     "name",
86     "card_name",
87     "sink_name",
88     "source_name",
89     "address",
90     "profile",
91     "rate",
92     "channels",
93     "path",
94 #ifdef NOKIA
95     "sco_sink",
96     "sco_source",
97 #endif
98     NULL
99 };
100
101 struct a2dp_info {
102     sbc_capabilities_t sbc_capabilities;
103     sbc_t sbc;                           /* Codec data */
104     pa_bool_t sbc_initialized;           /* Keep track if the encoder is initialized */
105     size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
106
107     void* buffer;                        /* Codec transfer buffer */
108     size_t buffer_size;                  /* Size of the buffer */
109
110     uint16_t seq_num;                    /* Cumulative packet sequence */
111 };
112
113 struct hsp_info {
114     pcm_capabilities_t pcm_capabilities;
115 #ifdef NOKIA
116     pa_sink *sco_sink;
117     pa_source *sco_source;
118 #endif
119     pa_hook_slot *sink_state_changed_slot;
120     pa_hook_slot *source_state_changed_slot;
121 };
122
123 enum profile {
124     PROFILE_A2DP,
125     PROFILE_HSP,
126     PROFILE_OFF
127 };
128
129 struct userdata {
130     pa_core *core;
131     pa_module *module;
132
133     char *address;
134     char *path;
135     pa_bluetooth_discovery *discovery;
136
137     pa_dbus_connection *connection;
138
139     pa_card *card;
140     pa_sink *sink;
141     pa_source *source;
142
143     pa_thread_mq thread_mq;
144     pa_rtpoll *rtpoll;
145     pa_rtpoll_item *rtpoll_item;
146     pa_thread *thread;
147
148     uint64_t read_index, write_index;
149     pa_usec_t started_at;
150     pa_smoother *read_smoother;
151
152     pa_memchunk write_memchunk;
153
154     pa_sample_spec sample_spec, requested_sample_spec;
155
156     int service_fd;
157     int stream_fd;
158
159     size_t link_mtu;
160     size_t block_size;
161
162     struct a2dp_info a2dp;
163     struct hsp_info hsp;
164
165     enum profile profile;
166
167     pa_modargs *modargs;
168
169     int stream_write_type, stream_read_type;
170     int service_write_type, service_read_type;
171 };
172
173 #ifdef NOKIA
174 #define USE_SCO_OVER_PCM(u) (u->profile == PROFILE_HSP && (u->hsp.sco_sink && u->hsp.sco_source))
175 #endif
176
177 static int init_bt(struct userdata *u);
178 static int init_profile(struct userdata *u);
179
180 static int service_send(struct userdata *u, const bt_audio_msg_header_t *msg) {
181     ssize_t r;
182
183     pa_assert(u);
184     pa_assert(u->service_fd >= 0);
185     pa_assert(msg);
186     pa_assert(msg->length > 0);
187
188     pa_log_debug("Sending %s -> %s",
189                  pa_strnull(bt_audio_strtype(msg->type)),
190                  pa_strnull(bt_audio_strname(msg->name)));
191
192     if ((r = pa_loop_write(u->service_fd, msg, msg->length, &u->service_write_type)) == (ssize_t) msg->length)
193         return 0;
194
195     if (r < 0)
196         pa_log_error("Error sending data to audio service: %s", pa_cstrerror(errno));
197     else
198         pa_log_error("Short write()");
199
200     return -1;
201 }
202
203 static int service_recv(struct userdata *u, bt_audio_msg_header_t *msg, size_t room) {
204     ssize_t r;
205
206     pa_assert(u);
207     pa_assert(u->service_fd >= 0);
208     pa_assert(msg);
209
210     if (room <= 0)
211         room = BT_SUGGESTED_BUFFER_SIZE;
212
213     pa_log_debug("Trying to receive message from audio service...");
214
215     /* First, read the header */
216     if ((r = pa_loop_read(u->service_fd, msg, sizeof(*msg), &u->service_read_type)) != sizeof(*msg))
217         goto read_fail;
218
219     if (msg->length < sizeof(*msg)) {
220         pa_log_error("Invalid message size.");
221         return -1;
222     }
223
224     /* Secondly, read the payload */
225     if (msg->length > sizeof(*msg)) {
226
227         size_t remains = msg->length - sizeof(*msg);
228
229         if ((r = pa_loop_read(u->service_fd,
230                               (uint8_t*) msg + sizeof(*msg),
231                               remains,
232                               &u->service_read_type)) != (ssize_t) remains)
233             goto read_fail;
234     }
235
236     pa_log_debug("Received %s <- %s",
237                  pa_strnull(bt_audio_strtype(msg->type)),
238                  pa_strnull(bt_audio_strname(msg->name)));
239
240     return 0;
241
242 read_fail:
243
244     if (r < 0)
245         pa_log_error("Error receiving data from audio service: %s", pa_cstrerror(errno));
246     else
247         pa_log_error("Short read()");
248
249     return -1;
250 }
251
252 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) {
253     int r;
254
255     pa_assert(u);
256     pa_assert(u->service_fd >= 0);
257     pa_assert(rsp);
258
259     if ((r = service_recv(u, rsp, room)) < 0)
260         return r;
261
262     if ((rsp->type != BT_INDICATION && rsp->type != BT_RESPONSE) ||
263         rsp->name != expected_name ||
264         (expected_size > 0 && rsp->length != expected_size)) {
265
266         if (rsp->type == BT_ERROR && rsp->length == sizeof(bt_audio_error_t))
267             pa_log_error("Received error condition: %s", pa_cstrerror(((bt_audio_error_t*) rsp)->posix_errno));
268         else
269             pa_log_error("Bogus message %s received while %s was expected",
270                          pa_strnull(bt_audio_strname(rsp->name)),
271                          pa_strnull(bt_audio_strname(expected_name)));
272         return -1;
273     }
274
275     return 0;
276 }
277
278 static int parse_caps(struct userdata *u, uint8_t seid, const struct bt_get_capabilities_rsp *rsp) {
279     uint16_t bytes_left;
280     const codec_capabilities_t *codec;
281
282     pa_assert(u);
283     pa_assert(rsp);
284
285     bytes_left = rsp->h.length - sizeof(*rsp);
286
287     if (bytes_left < sizeof(codec_capabilities_t)) {
288         pa_log_error("Packet too small to store codec information.");
289         return -1;
290     }
291
292     codec = (codec_capabilities_t *) rsp->data; /** ALIGNMENT? **/
293
294     pa_log_debug("Payload size is %lu %lu", (unsigned long) bytes_left, (unsigned long) sizeof(*codec));
295
296     if ((u->profile == PROFILE_A2DP && codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP) ||
297         (u->profile == PROFILE_HSP && codec->transport != BT_CAPABILITIES_TRANSPORT_SCO)) {
298         pa_log_error("Got capabilities for wrong codec.");
299         return -1;
300     }
301
302     if (u->profile == PROFILE_HSP) {
303
304         if (bytes_left <= 0 || codec->length != sizeof(u->hsp.pcm_capabilities))
305             return -1;
306
307         pa_assert(codec->type == BT_HFP_CODEC_PCM);
308
309         if (codec->configured && seid == 0)
310             return codec->seid;
311
312         memcpy(&u->hsp.pcm_capabilities, codec, sizeof(u->hsp.pcm_capabilities));
313
314     } else if (u->profile == PROFILE_A2DP) {
315
316         while (bytes_left > 0) {
317             if ((codec->type == BT_A2DP_SBC_SINK) && !codec->lock)
318                 break;
319
320             bytes_left -= codec->length;
321             codec = (const codec_capabilities_t*) ((const uint8_t*) codec + codec->length);
322         }
323
324         if (bytes_left <= 0 || codec->length != sizeof(u->a2dp.sbc_capabilities))
325             return -1;
326
327         pa_assert(codec->type == BT_A2DP_SBC_SINK);
328
329         if (codec->configured && seid == 0)
330             return codec->seid;
331
332         memcpy(&u->a2dp.sbc_capabilities, codec, sizeof(u->a2dp.sbc_capabilities));
333     }
334
335     return 0;
336 }
337
338 static int get_caps(struct userdata *u, uint8_t seid) {
339     union {
340         struct bt_get_capabilities_req getcaps_req;
341         struct bt_get_capabilities_rsp getcaps_rsp;
342         bt_audio_error_t error;
343         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
344     } msg;
345     int ret;
346
347     pa_assert(u);
348
349     memset(&msg, 0, sizeof(msg));
350     msg.getcaps_req.h.type = BT_REQUEST;
351     msg.getcaps_req.h.name = BT_GET_CAPABILITIES;
352     msg.getcaps_req.h.length = sizeof(msg.getcaps_req);
353     msg.getcaps_req.seid = seid;
354
355     pa_strlcpy(msg.getcaps_req.object, u->path, sizeof(msg.getcaps_req.object));
356     if (u->profile == PROFILE_A2DP)
357         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
358     else {
359         pa_assert(u->profile == PROFILE_HSP);
360         msg.getcaps_req.transport = BT_CAPABILITIES_TRANSPORT_SCO;
361     }
362     msg.getcaps_req.flags = BT_FLAG_AUTOCONNECT;
363
364     if (service_send(u, &msg.getcaps_req.h) < 0)
365         return -1;
366
367     if (service_expect(u, &msg.getcaps_rsp.h, sizeof(msg), BT_GET_CAPABILITIES, 0) < 0)
368         return -1;
369
370     ret = parse_caps(u, seid, &msg.getcaps_rsp);
371     if (ret <= 0)
372         return ret;
373
374     return get_caps(u, ret);
375 }
376
377 static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
378
379     switch (freq) {
380         case BT_SBC_SAMPLING_FREQ_16000:
381         case BT_SBC_SAMPLING_FREQ_32000:
382             return 53;
383
384         case BT_SBC_SAMPLING_FREQ_44100:
385
386             switch (mode) {
387                 case BT_A2DP_CHANNEL_MODE_MONO:
388                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
389                     return 31;
390
391                 case BT_A2DP_CHANNEL_MODE_STEREO:
392                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
393                     return 53;
394
395                 default:
396                     pa_log_warn("Invalid channel mode %u", mode);
397                     return 53;
398             }
399
400         case BT_SBC_SAMPLING_FREQ_48000:
401
402             switch (mode) {
403                 case BT_A2DP_CHANNEL_MODE_MONO:
404                 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
405                     return 29;
406
407                 case BT_A2DP_CHANNEL_MODE_STEREO:
408                 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
409                     return 51;
410
411                 default:
412                     pa_log_warn("Invalid channel mode %u", mode);
413                     return 51;
414             }
415
416         default:
417             pa_log_warn("Invalid sampling freq %u", freq);
418             return 53;
419     }
420 }
421
422 static int setup_a2dp(struct userdata *u) {
423     sbc_capabilities_t *cap;
424     int i;
425
426     static const struct {
427         uint32_t rate;
428         uint8_t cap;
429     } freq_table[] = {
430         { 16000U, BT_SBC_SAMPLING_FREQ_16000 },
431         { 32000U, BT_SBC_SAMPLING_FREQ_32000 },
432         { 44100U, BT_SBC_SAMPLING_FREQ_44100 },
433         { 48000U, BT_SBC_SAMPLING_FREQ_48000 }
434     };
435
436     pa_assert(u);
437     pa_assert(u->profile == PROFILE_A2DP);
438
439     cap = &u->a2dp.sbc_capabilities;
440
441     /* Find the lowest freq that is at least as high as the requested
442      * sampling rate */
443     for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
444         if (freq_table[i].rate >= u->sample_spec.rate && (cap->frequency & freq_table[i].cap)) {
445             u->sample_spec.rate = freq_table[i].rate;
446             cap->frequency = freq_table[i].cap;
447             break;
448         }
449
450     if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
451         for (--i; i >= 0; i--) {
452             if (cap->frequency & freq_table[i].cap) {
453                 u->sample_spec.rate = freq_table[i].rate;
454                 cap->frequency = freq_table[i].cap;
455                 break;
456             }
457         }
458
459         if (i < 0) {
460             pa_log("Not suitable sample rate");
461             return -1;
462         }
463     }
464
465     pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
466
467     if (cap->capability.configured)
468         return 0;
469
470     if (u->sample_spec.channels <= 1) {
471         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
472             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
473             u->sample_spec.channels = 1;
474         } else
475             u->sample_spec.channels = 2;
476     }
477
478     if (u->sample_spec.channels >= 2) {
479         u->sample_spec.channels = 2;
480
481         if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
482             cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
483         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
484             cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
485         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
486             cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
487         else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
488             cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
489             u->sample_spec.channels = 1;
490         } else {
491             pa_log("No supported channel modes");
492             return -1;
493         }
494     }
495
496     if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
497         cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
498     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
499         cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
500     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
501         cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
502     else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
503         cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
504     else {
505         pa_log_error("No supported block lengths");
506         return -1;
507     }
508
509     if (cap->subbands & BT_A2DP_SUBBANDS_8)
510         cap->subbands = BT_A2DP_SUBBANDS_8;
511     else if (cap->subbands & BT_A2DP_SUBBANDS_4)
512         cap->subbands = BT_A2DP_SUBBANDS_4;
513     else {
514         pa_log_error("No supported subbands");
515         return -1;
516     }
517
518     if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
519         cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
520     else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
521         cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
522
523     cap->min_bitpool = (uint8_t) PA_MAX(MIN_BITPOOL, cap->min_bitpool);
524     cap->max_bitpool = (uint8_t) PA_MIN(a2dp_default_bitpool(cap->frequency, cap->channel_mode), cap->max_bitpool);
525
526     return 0;
527 }
528
529 static void setup_sbc(struct a2dp_info *a2dp) {
530     sbc_capabilities_t *active_capabilities;
531
532     pa_assert(a2dp);
533
534     active_capabilities = &a2dp->sbc_capabilities;
535
536     if (a2dp->sbc_initialized)
537         sbc_reinit(&a2dp->sbc, 0);
538     else
539         sbc_init(&a2dp->sbc, 0);
540     a2dp->sbc_initialized = TRUE;
541
542     switch (active_capabilities->frequency) {
543         case BT_SBC_SAMPLING_FREQ_16000:
544             a2dp->sbc.frequency = SBC_FREQ_16000;
545             break;
546         case BT_SBC_SAMPLING_FREQ_32000:
547             a2dp->sbc.frequency = SBC_FREQ_32000;
548             break;
549         case BT_SBC_SAMPLING_FREQ_44100:
550             a2dp->sbc.frequency = SBC_FREQ_44100;
551             break;
552         case BT_SBC_SAMPLING_FREQ_48000:
553             a2dp->sbc.frequency = SBC_FREQ_48000;
554             break;
555         default:
556             pa_assert_not_reached();
557     }
558
559     switch (active_capabilities->channel_mode) {
560         case BT_A2DP_CHANNEL_MODE_MONO:
561             a2dp->sbc.mode = SBC_MODE_MONO;
562             break;
563         case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
564             a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
565             break;
566         case BT_A2DP_CHANNEL_MODE_STEREO:
567             a2dp->sbc.mode = SBC_MODE_STEREO;
568             break;
569         case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
570             a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
571             break;
572         default:
573             pa_assert_not_reached();
574     }
575
576     switch (active_capabilities->allocation_method) {
577         case BT_A2DP_ALLOCATION_SNR:
578             a2dp->sbc.allocation = SBC_AM_SNR;
579             break;
580         case BT_A2DP_ALLOCATION_LOUDNESS:
581             a2dp->sbc.allocation = SBC_AM_LOUDNESS;
582             break;
583         default:
584             pa_assert_not_reached();
585     }
586
587     switch (active_capabilities->subbands) {
588         case BT_A2DP_SUBBANDS_4:
589             a2dp->sbc.subbands = SBC_SB_4;
590             break;
591         case BT_A2DP_SUBBANDS_8:
592             a2dp->sbc.subbands = SBC_SB_8;
593             break;
594         default:
595             pa_assert_not_reached();
596     }
597
598     switch (active_capabilities->block_length) {
599         case BT_A2DP_BLOCK_LENGTH_4:
600             a2dp->sbc.blocks = SBC_BLK_4;
601             break;
602         case BT_A2DP_BLOCK_LENGTH_8:
603             a2dp->sbc.blocks = SBC_BLK_8;
604             break;
605         case BT_A2DP_BLOCK_LENGTH_12:
606             a2dp->sbc.blocks = SBC_BLK_12;
607             break;
608         case BT_A2DP_BLOCK_LENGTH_16:
609             a2dp->sbc.blocks = SBC_BLK_16;
610             break;
611         default:
612             pa_assert_not_reached();
613     }
614
615     a2dp->sbc.bitpool = active_capabilities->max_bitpool;
616     a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
617     a2dp->frame_length = sbc_get_frame_length(&a2dp->sbc);
618 }
619
620 static int set_conf(struct userdata *u) {
621     union {
622         struct bt_open_req open_req;
623         struct bt_open_rsp open_rsp;
624         struct bt_set_configuration_req setconf_req;
625         struct bt_set_configuration_rsp setconf_rsp;
626         bt_audio_error_t error;
627         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
628     } msg;
629
630     memset(&msg, 0, sizeof(msg));
631     msg.open_req.h.type = BT_REQUEST;
632     msg.open_req.h.name = BT_OPEN;
633     msg.open_req.h.length = sizeof(msg.open_req);
634
635     pa_strlcpy(msg.open_req.object, u->path, sizeof(msg.open_req.object));
636     msg.open_req.seid = u->profile == PROFILE_A2DP ? u->a2dp.sbc_capabilities.capability.seid : BT_A2DP_SEID_RANGE + 1;
637     msg.open_req.lock = u->profile == PROFILE_A2DP ? BT_WRITE_LOCK : BT_READ_LOCK | BT_WRITE_LOCK;
638
639     if (service_send(u, &msg.open_req.h) < 0)
640         return -1;
641
642     if (service_expect(u, &msg.open_rsp.h, sizeof(msg), BT_OPEN, sizeof(msg.open_rsp)) < 0)
643         return -1;
644
645     if (u->profile == PROFILE_A2DP ) {
646         u->sample_spec.format = PA_SAMPLE_S16LE;
647
648         if (setup_a2dp(u) < 0)
649             return -1;
650     } else {
651         pa_assert(u->profile == PROFILE_HSP);
652
653         u->sample_spec.format = PA_SAMPLE_S16LE;
654         u->sample_spec.channels = 1;
655         u->sample_spec.rate = 8000;
656     }
657
658     memset(&msg, 0, sizeof(msg));
659     msg.setconf_req.h.type = BT_REQUEST;
660     msg.setconf_req.h.name = BT_SET_CONFIGURATION;
661     msg.setconf_req.h.length = sizeof(msg.setconf_req);
662
663     if (u->profile == PROFILE_A2DP) {
664         memcpy(&msg.setconf_req.codec, &u->a2dp.sbc_capabilities, sizeof(u->a2dp.sbc_capabilities));
665     } else {
666         msg.setconf_req.codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
667         msg.setconf_req.codec.seid = BT_A2DP_SEID_RANGE + 1;
668         msg.setconf_req.codec.length = sizeof(pcm_capabilities_t);
669     }
670     msg.setconf_req.h.length += msg.setconf_req.codec.length - sizeof(msg.setconf_req.codec);
671
672     if (service_send(u, &msg.setconf_req.h) < 0)
673         return -1;
674
675     if (service_expect(u, &msg.setconf_rsp.h, sizeof(msg), BT_SET_CONFIGURATION, sizeof(msg.setconf_rsp)) < 0)
676         return -1;
677
678     u->link_mtu = msg.setconf_rsp.link_mtu;
679
680     /* setup SBC encoder now we agree on parameters */
681     if (u->profile == PROFILE_A2DP) {
682         setup_sbc(&u->a2dp);
683
684         u->block_size =
685             ((u->link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
686             / u->a2dp.frame_length
687             * u->a2dp.codesize);
688
689         pa_log_info("SBC parameters:\n\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
690                     u->a2dp.sbc.allocation, u->a2dp.sbc.subbands, u->a2dp.sbc.blocks, u->a2dp.sbc.bitpool);
691     } else
692         u->block_size = u->link_mtu;
693
694     return 0;
695 }
696
697 /* from IO thread, except in SCO over PCM */
698 static int start_stream_fd(struct userdata *u) {
699     union {
700         bt_audio_msg_header_t rsp;
701         struct bt_start_stream_req start_req;
702         struct bt_start_stream_rsp start_rsp;
703         struct bt_new_stream_ind streamfd_ind;
704         bt_audio_error_t error;
705         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
706     } msg;
707     struct pollfd *pollfd;
708
709     pa_assert(u);
710     pa_assert(u->rtpoll);
711     pa_assert(!u->rtpoll_item);
712     pa_assert(u->stream_fd < 0);
713
714     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
715     msg.start_req.h.type = BT_REQUEST;
716     msg.start_req.h.name = BT_START_STREAM;
717     msg.start_req.h.length = sizeof(msg.start_req);
718
719     if (service_send(u, &msg.start_req.h) < 0)
720         return -1;
721
722     if (service_expect(u, &msg.rsp, sizeof(msg), BT_START_STREAM, sizeof(msg.start_rsp)) < 0)
723         return -1;
724
725     if (service_expect(u, &msg.rsp, sizeof(msg), BT_NEW_STREAM, sizeof(msg.streamfd_ind)) < 0)
726         return -1;
727
728     if ((u->stream_fd = bt_audio_service_get_data_fd(u->service_fd)) < 0) {
729         pa_log("Failed to get stream fd from audio service.");
730         return -1;
731     }
732
733     pa_make_fd_nonblock(u->stream_fd);
734     pa_make_socket_low_delay(u->stream_fd);
735
736     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
737     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
738     pollfd->fd = u->stream_fd;
739     pollfd->events = pollfd->revents = 0;
740
741     u->read_index = 0;
742     u->write_index = 0;
743
744     return 0;
745 }
746
747 /* from IO thread */
748 static int stop_stream_fd(struct userdata *u) {
749     union {
750         bt_audio_msg_header_t rsp;
751         struct bt_stop_stream_req start_req;
752         struct bt_stop_stream_rsp start_rsp;
753         bt_audio_error_t error;
754         uint8_t buf[BT_SUGGESTED_BUFFER_SIZE];
755     } msg;
756     int r = 0;
757
758     pa_assert(u);
759     pa_assert(u->rtpoll);
760     pa_assert(u->rtpoll_item);
761     pa_assert(u->stream_fd >= 0);
762
763     pa_rtpoll_item_free(u->rtpoll_item);
764     u->rtpoll_item = NULL;
765
766     memset(msg.buf, 0, BT_SUGGESTED_BUFFER_SIZE);
767     msg.start_req.h.type = BT_REQUEST;
768     msg.start_req.h.name = BT_STOP_STREAM;
769     msg.start_req.h.length = sizeof(msg.start_req);
770
771     if (service_send(u, &msg.start_req.h) < 0 ||
772         service_expect(u, &msg.rsp, sizeof(msg), BT_STOP_STREAM, sizeof(msg.start_rsp)) < 0)
773         r = -1;
774
775     pa_close(u->stream_fd);
776     u->stream_fd = -1;
777
778     return r;
779 }
780
781 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
782     struct userdata *u = PA_SINK(o)->userdata;
783     pa_bool_t failed = FALSE;
784     int r;
785
786     pa_assert(u->sink == PA_SINK(o));
787
788     pa_log_debug("got message: %d", code);
789     switch (code) {
790
791         case PA_SINK_MESSAGE_SET_STATE:
792
793             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
794
795                 case PA_SINK_SUSPENDED:
796                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
797
798                     /* Stop the device if the source is suspended as well */
799                     if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
800                         /* We deliberately ignore whether stopping
801                          * actually worked. Since the stream_fd is
802                          * closed it doesn't really matter */
803                         stop_stream_fd(u);
804
805                     break;
806
807                 case PA_SINK_IDLE:
808                 case PA_SINK_RUNNING:
809                     if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
810                         break;
811
812                     /* Resume the device if the source was suspended as well */
813                     if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
814                         if (start_stream_fd(u) < 0)
815                             failed = TRUE;
816
817                     u->started_at = pa_rtclock_usec();
818                     break;
819
820                 case PA_SINK_UNLINKED:
821                 case PA_SINK_INIT:
822                 case PA_SINK_INVALID_STATE:
823                     ;
824             }
825             break;
826
827         case PA_SINK_MESSAGE_GET_LATENCY: {
828             *((pa_usec_t*) data) = 0;
829             return 0;
830         }
831     }
832
833     r = pa_sink_process_msg(o, code, data, offset, chunk);
834
835     return (r < 0 || !failed) ? r : -1;
836 }
837
838 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
839     struct userdata *u = PA_SOURCE(o)->userdata;
840     pa_bool_t failed = FALSE;
841     int r;
842
843     pa_assert(u->source == PA_SOURCE(o));
844
845     pa_log_debug("got message: %d", code);
846     switch (code) {
847
848         case PA_SOURCE_MESSAGE_SET_STATE:
849
850             switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
851
852                 case PA_SOURCE_SUSPENDED:
853                     pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
854
855                     /* Stop the device if the sink is suspended as well */
856                     if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
857                         stop_stream_fd(u);
858
859                     pa_smoother_pause(u->read_smoother, pa_rtclock_usec());
860                     break;
861
862                 case PA_SOURCE_IDLE:
863                 case PA_SOURCE_RUNNING:
864                     if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
865                         break;
866
867                     /* Resume the device if the sink was suspended as well */
868                     if (!u->sink || u->sink->thread_info.state == PA_SINK_SUSPENDED)
869                         if (start_stream_fd(u) < 0)
870                             failed = TRUE;
871
872                     pa_smoother_resume(u->read_smoother, pa_rtclock_usec());
873                     break;
874
875                 case PA_SOURCE_UNLINKED:
876                 case PA_SOURCE_INIT:
877                 case PA_SOURCE_INVALID_STATE:
878                     ;
879             }
880             break;
881
882         case PA_SOURCE_MESSAGE_GET_LATENCY: {
883             *((pa_usec_t*) data) = 0;
884             return 0;
885         }
886
887     }
888
889     r = pa_source_process_msg(o, code, data, offset, chunk);
890
891     return (r < 0 || !failed) ? r : -1;
892 }
893
894 static int hsp_process_render(struct userdata *u) {
895     int ret = 0;
896
897     pa_assert(u);
898     pa_assert(u->profile == PROFILE_HSP);
899     pa_assert(u->sink);
900
901     /* First, render some data */
902     if (!u->write_memchunk.memblock)
903         pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
904
905     pa_assert(u->write_memchunk.length == u->block_size);
906
907     for (;;) {
908         ssize_t l;
909         const void *p;
910
911         /* Now write that data to the socket. The socket is of type
912          * SEQPACKET, and we generated the data of the MTU size, so this
913          * should just work. */
914
915         p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
916         l = pa_write(u->stream_fd, p, u->write_memchunk.length, &u->stream_write_type);
917         pa_memblock_release(u->write_memchunk.memblock);
918
919         pa_assert(l != 0);
920
921         if (l < 0) {
922
923             if (errno == EINTR)
924                 /* Retry right away if we got interrupted */
925                 continue;
926
927             else if (errno == EAGAIN)
928                 /* Hmm, apparently the socket was not writable, give up for now */
929                 break;
930
931             pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
932             ret = -1;
933             break;
934         }
935
936         pa_assert((size_t) l <= u->write_memchunk.length);
937
938         if ((size_t) l != u->write_memchunk.length) {
939             pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
940                         (unsigned long long) l,
941                         (unsigned long long) u->write_memchunk.length);
942             ret = -1;
943             break;
944         }
945
946         u->write_index += (uint64_t) u->write_memchunk.length;
947         pa_memblock_unref(u->write_memchunk.memblock);
948         pa_memchunk_reset(&u->write_memchunk);
949
950         break;
951     }
952
953     return ret;
954 }
955
956 static int hsp_process_push(struct userdata *u) {
957     int ret = 0;
958     pa_memchunk memchunk;
959
960     pa_assert(u);
961     pa_assert(u->profile == PROFILE_HSP);
962     pa_assert(u->source);
963
964     memchunk.memblock = pa_memblock_new(u->core->mempool, u->block_size);
965     memchunk.index = memchunk.length = 0;
966
967     for (;;) {
968         ssize_t l;
969         void *p;
970
971         p = pa_memblock_acquire(memchunk.memblock);
972         l = pa_read(u->stream_fd, p, pa_memblock_get_length(memchunk.memblock), &u->stream_read_type);
973         pa_memblock_release(memchunk.memblock);
974
975         if (l <= 0) {
976
977             if (l < 0 && errno == EINTR)
978                 /* Retry right away if we got interrupted */
979                 continue;
980
981             else if (l < 0 && errno == EAGAIN)
982                 /* Hmm, apparently the socket was not readable, give up for now. */
983                 break;
984
985             pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
986             ret = -1;
987             break;
988         }
989
990         pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
991
992         memchunk.length = (size_t) l;
993         u->read_index += (uint64_t) l;
994
995         pa_source_post(u->source, &memchunk);
996         break;
997     }
998
999     pa_memblock_unref(memchunk.memblock);
1000
1001     return ret;
1002 }
1003
1004 static void a2dp_prepare_buffer(struct userdata *u) {
1005     pa_assert(u);
1006
1007     if (u->a2dp.buffer_size >= u->link_mtu)
1008         return;
1009
1010     u->a2dp.buffer_size = 2 * u->link_mtu;
1011     pa_xfree(u->a2dp.buffer);
1012     u->a2dp.buffer = pa_xmalloc(u->a2dp.buffer_size);
1013 }
1014
1015 static int a2dp_process_render(struct userdata *u) {
1016     struct a2dp_info *a2dp;
1017     struct rtp_header *header;
1018     struct rtp_payload *payload;
1019     size_t nbytes;
1020     void *d;
1021     const void *p;
1022     size_t to_write, to_encode;
1023     unsigned frame_count;
1024     int ret = 0;
1025
1026     pa_assert(u);
1027     pa_assert(u->profile == PROFILE_A2DP);
1028     pa_assert(u->sink);
1029
1030     /* First, render some data */
1031     if (!u->write_memchunk.memblock)
1032         pa_sink_render_full(u->sink, u->block_size, &u->write_memchunk);
1033
1034     pa_assert(u->write_memchunk.length == u->block_size);
1035
1036     a2dp_prepare_buffer(u);
1037
1038     a2dp = &u->a2dp;
1039     header = a2dp->buffer;
1040     payload = (struct rtp_payload*) ((uint8_t*) a2dp->buffer + sizeof(*header));
1041
1042     frame_count = 0;
1043
1044     /* Try to create a packet of the full MTU */
1045
1046     p = (const uint8_t*) pa_memblock_acquire(u->write_memchunk.memblock) + u->write_memchunk.index;
1047     to_encode = u->write_memchunk.length;
1048
1049     d = (uint8_t*) a2dp->buffer + sizeof(*header) + sizeof(*payload);
1050     to_write = a2dp->buffer_size - sizeof(*header) - sizeof(*payload);
1051
1052     while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
1053         size_t written;
1054         ssize_t encoded;
1055
1056         encoded = sbc_encode(&a2dp->sbc,
1057                              p, to_encode,
1058                              d, to_write,
1059                              &written);
1060
1061         if (PA_UNLIKELY(encoded <= 0)) {
1062             pa_log_error("SBC encoding error (%li)", (long) encoded);
1063             pa_memblock_release(u->write_memchunk.memblock);
1064             return -1;
1065         }
1066
1067 /*         pa_log_debug("SBC: encoded: %lu; written: %lu", (unsigned long) encoded, (unsigned long) written); */
1068 /*         pa_log_debug("SBC: codesize: %lu; frame_length: %lu", (unsigned long) a2dp->codesize, (unsigned long) a2dp->frame_length); */
1069
1070         pa_assert_fp((size_t) encoded <= to_encode);
1071         pa_assert_fp((size_t) encoded == a2dp->codesize);
1072
1073         pa_assert_fp((size_t) written <= to_write);
1074         pa_assert_fp((size_t) written == a2dp->frame_length);
1075
1076         p = (const uint8_t*) p + encoded;
1077         to_encode -= encoded;
1078
1079         d = (uint8_t*) d + written;
1080         to_write -= written;
1081
1082         frame_count++;
1083     }
1084
1085     pa_memblock_release(u->write_memchunk.memblock);
1086
1087     pa_assert(to_encode == 0);
1088
1089     PA_ONCE_BEGIN {
1090         pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&a2dp->sbc)));
1091     } PA_ONCE_END;
1092
1093     /* write it to the fifo */
1094     memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
1095     header->v = 2;
1096     header->pt = 1;
1097     header->sequence_number = htons(a2dp->seq_num++);
1098     header->timestamp = htonl(u->write_index / pa_frame_size(&u->sink->sample_spec));
1099     header->ssrc = htonl(1);
1100     payload->frame_count = frame_count;
1101
1102     nbytes = (uint8_t*) d - (uint8_t*) a2dp->buffer;
1103
1104     for (;;) {
1105         ssize_t l;
1106
1107         l = pa_write(u->stream_fd, a2dp->buffer, nbytes, &u->stream_write_type);
1108
1109         pa_assert(l != 0);
1110
1111         if (l < 0) {
1112
1113             if (errno == EINTR)
1114                 /* Retry right away if we got interrupted */
1115                 continue;
1116
1117             else if (errno == EAGAIN)
1118                 /* Hmm, apparently the socket was not writable, give up for now */
1119                 break;
1120
1121             pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
1122             ret  = -1;
1123             break;
1124         }
1125
1126         pa_assert((size_t) l <= nbytes);
1127
1128         if ((size_t) l != nbytes) {
1129             pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
1130                         (unsigned long long) l,
1131                         (unsigned long long) nbytes);
1132             ret = -1;
1133             break;
1134         }
1135
1136         u->write_index += (uint64_t) u->write_memchunk.length;
1137         pa_memblock_unref(u->write_memchunk.memblock);
1138         pa_memchunk_reset(&u->write_memchunk);
1139
1140         break;
1141     }
1142
1143     return ret;
1144 }
1145
1146 static void thread_func(void *userdata) {
1147     struct userdata *u = userdata;
1148     pa_bool_t do_write = FALSE, writable = FALSE;
1149
1150     pa_assert(u);
1151
1152     pa_log_debug("IO Thread starting up");
1153
1154     if (u->core->realtime_scheduling)
1155         pa_make_realtime(u->core->realtime_priority);
1156
1157     if (start_stream_fd(u) < 0)
1158         goto fail;
1159
1160     pa_thread_mq_install(&u->thread_mq);
1161     pa_rtpoll_install(u->rtpoll);
1162
1163     pa_smoother_set_time_offset(u->read_smoother, pa_rtclock_usec());
1164
1165     for (;;) {
1166         struct pollfd *pollfd;
1167         int ret;
1168         pa_bool_t disable_timer = TRUE;
1169
1170         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1171
1172         if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
1173
1174             if (pollfd && (pollfd->revents & POLLIN)) {
1175
1176                 if (hsp_process_push(u) < 0)
1177                     goto fail;
1178
1179                 /* We just read something, so we are supposed to write something, too */
1180                 do_write = TRUE;
1181             }
1182         }
1183
1184         if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
1185
1186             if (u->sink->thread_info.rewind_requested)
1187                 pa_sink_process_rewind(u->sink, 0);
1188
1189             if (pollfd) {
1190                 if (pollfd->revents & POLLOUT)
1191                     writable = TRUE;
1192
1193                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write && writable) {
1194                     pa_usec_t time_passed;
1195                     uint64_t should_have_written;
1196
1197                     /* Hmm, there is no input stream we could synchronize
1198                      * to. So let's do things by time */
1199
1200                     time_passed = pa_rtclock_usec() - u->started_at;
1201                     should_have_written = pa_usec_to_bytes(time_passed, &u->sink->sample_spec);
1202
1203                     do_write = u->write_index <= should_have_written ;
1204 /*                 pa_log_debug("Time has come: %s", pa_yes_no(do_write)); */
1205                 }
1206
1207                 if (writable && do_write) {
1208                     if (u->write_index == 0)
1209                         u->started_at = pa_rtclock_usec();
1210
1211                     if (u->profile == PROFILE_A2DP) {
1212                         if (a2dp_process_render(u) < 0)
1213                             goto fail;
1214                     } else {
1215                         if (hsp_process_render(u) < 0)
1216                             goto fail;
1217                     }
1218
1219                     do_write = FALSE;
1220                     writable = FALSE;
1221                 }
1222
1223                 if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && !do_write) {
1224                     pa_usec_t time_passed, next_write_at, sleep_for;
1225
1226                     /* Hmm, there is no input stream we could synchronize
1227                      * to. So let's estimate when we need to wake up the latest */
1228
1229                     time_passed = pa_rtclock_usec() - u->started_at;
1230                     next_write_at = pa_bytes_to_usec(u->write_index, &u->sink->sample_spec);
1231                     sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1232
1233 /*                 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); */
1234
1235                     pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1236                     disable_timer = FALSE;
1237                 }
1238             }
1239         }
1240
1241         if (disable_timer)
1242             pa_rtpoll_set_timer_disabled(u->rtpoll);
1243
1244         /* Hmm, nothing to do. Let's sleep */
1245         if (pollfd)
1246             pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
1247                                       (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
1248
1249         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
1250             goto fail;
1251
1252         if (ret == 0)
1253             goto finish;
1254
1255         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1256
1257         if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1258             pa_log_error("FD error.");
1259             goto fail;
1260         }
1261     }
1262
1263 fail:
1264     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1265     pa_log_debug("IO thread failed");
1266     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
1267     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1268
1269 finish:
1270     pa_log_debug("IO thread shutting down");
1271 }
1272
1273 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
1274     DBusError err;
1275     struct userdata *u;
1276
1277     pa_assert(bus);
1278     pa_assert(m);
1279     pa_assert_se(u = userdata);
1280
1281     dbus_error_init(&err);
1282
1283     pa_log_debug("dbus: interface=%s, path=%s, member=%s\n",
1284                  dbus_message_get_interface(m),
1285                  dbus_message_get_path(m),
1286                  dbus_message_get_member(m));
1287
1288    if (!dbus_message_has_path(m, u->path))
1289        goto fail;
1290
1291     if (dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged") ||
1292         dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1293
1294         dbus_uint16_t gain;
1295         pa_cvolume v;
1296
1297         if (!dbus_message_get_args(m, &err, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID) || gain > 15) {
1298             pa_log("Failed to parse org.bluez.Headset.{Speaker|Microphone}GainChanged: %s", err.message);
1299             goto fail;
1300         }
1301
1302         if (u->profile == PROFILE_HSP) {
1303             if (u->sink && dbus_message_is_signal(m, "org.bluez.Headset", "SpeakerGainChanged")) {
1304
1305                 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1306                 pa_sink_volume_changed(u->sink, &v);
1307
1308             } else if (u->source && dbus_message_is_signal(m, "org.bluez.Headset", "MicrophoneGainChanged")) {
1309
1310                 pa_cvolume_set(&v, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1311                 pa_source_volume_changed(u->source, &v);
1312             }
1313         }
1314     }
1315
1316 fail:
1317     dbus_error_free(&err);
1318
1319     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1320 }
1321
1322 static void sink_set_volume_cb(pa_sink *s) {
1323     struct userdata *u = s->userdata;
1324     DBusMessage *m;
1325     dbus_uint16_t gain;
1326
1327     pa_assert(u);
1328
1329     if (u->profile != PROFILE_HSP)
1330         return;
1331
1332     gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1333
1334     if (gain > 15)
1335         gain = 15;
1336
1337     pa_cvolume_set(&s->virtual_volume, u->sink->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1338
1339     pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetSpeakerGain"));
1340     pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1341     pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1342     dbus_message_unref(m);
1343 }
1344
1345 static void source_set_volume_cb(pa_source *s) {
1346     struct userdata *u = s->userdata;
1347     DBusMessage *m;
1348     dbus_uint16_t gain;
1349
1350     pa_assert(u);
1351
1352     if (u->profile != PROFILE_HSP)
1353         return;
1354
1355     gain = (pa_cvolume_max(&s->virtual_volume) * 15) / PA_VOLUME_NORM;
1356
1357     if (gain > 15)
1358         gain = 15;
1359
1360     pa_cvolume_set(&s->virtual_volume, u->source->sample_spec.channels, (pa_volume_t) (gain * PA_VOLUME_NORM / 15));
1361
1362     pa_assert_se(m = dbus_message_new_method_call("org.bluez", u->path, "org.bluez.Headset", "SetMicrophoneGain"));
1363     pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_UINT16, &gain, DBUS_TYPE_INVALID));
1364     pa_assert_se(dbus_connection_send(pa_dbus_connection_get(u->connection), m, NULL));
1365     dbus_message_unref(m);
1366 }
1367
1368 static char *get_name(const char *type, pa_modargs *ma, const char *device_id, pa_bool_t *namereg_fail) {
1369     char *t;
1370     const char *n;
1371
1372     pa_assert(type);
1373     pa_assert(ma);
1374     pa_assert(device_id);
1375     pa_assert(namereg_fail);
1376
1377     t = pa_sprintf_malloc("%s_name", type);
1378     n = pa_modargs_get_value(ma, t, NULL);
1379     pa_xfree(t);
1380
1381     if (n) {
1382         *namereg_fail = TRUE;
1383         return pa_xstrdup(n);
1384     }
1385
1386     if ((n = pa_modargs_get_value(ma, "name", NULL)))
1387         *namereg_fail = TRUE;
1388     else {
1389         n = device_id;
1390         *namereg_fail = FALSE;
1391     }
1392
1393     return pa_sprintf_malloc("bluez_%s.%s", type, n);
1394 }
1395
1396 #ifdef NOKIA
1397
1398 static void sco_over_pcm_state_update(struct userdata *u) {
1399     pa_assert(u);
1400     pa_assert(USE_SCO_OVER_PCM(u));
1401
1402     if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
1403         PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
1404
1405         if (u->service_fd >= 0)
1406             return;
1407
1408         pa_log_debug("Resuming SCO over PCM");
1409         if ((init_bt(u) < 0) || (init_profile(u) < 0))
1410             pa_log("Can't resume SCO over PCM");
1411
1412         start_stream_fd(u);
1413     } else {
1414
1415         if (u->service_fd < 0)
1416             return;
1417
1418         stop_stream_fd(u);
1419
1420         pa_log_debug("Closing SCO over PCM");
1421         pa_close(u->service_fd);
1422         u->service_fd = -1;
1423     }
1424 }
1425
1426 static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
1427     pa_assert(c);
1428     pa_sink_assert_ref(s);
1429     pa_assert(u);
1430
1431     if (s != u->hsp.sco_sink)
1432         return PA_HOOK_OK;
1433
1434     sco_over_pcm_state_update(u);
1435
1436     return PA_HOOK_OK;
1437 }
1438
1439 static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
1440     pa_assert(c);
1441     pa_source_assert_ref(s);
1442     pa_assert(u);
1443
1444     if (s != u->hsp.sco_source)
1445         return PA_HOOK_OK;
1446
1447     sco_over_pcm_state_update(u);
1448
1449     return PA_HOOK_OK;
1450 }
1451
1452 #endif
1453
1454 static int add_sink(struct userdata *u) {
1455
1456 #ifdef NOKIA
1457     if (USE_SCO_OVER_PCM(u)) {
1458         pa_proplist *p;
1459
1460         u->sink = u->hsp.sco_sink;
1461         p = pa_proplist_new();
1462         pa_proplist_sets(p, "bluetooth.protocol", "sco");
1463         pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
1464         pa_proplist_free(p);
1465
1466         if (!u->hsp.sink_state_changed_slot)
1467             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);
1468
1469     } else
1470 #endif
1471
1472     {
1473         pa_sink_new_data data;
1474         pa_bool_t b;
1475
1476         pa_sink_new_data_init(&data);
1477         data.driver = __FILE__;
1478         data.module = u->module;
1479         pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
1480         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1481         data.card = u->card;
1482         data.name = get_name("sink", u->modargs, u->address, &b);
1483         data.namereg_fail = b;
1484
1485         u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY | (u->profile == PROFILE_HSP ? PA_SINK_HW_VOLUME_CTRL : 0));
1486         pa_sink_new_data_done(&data);
1487
1488         if (!u->sink) {
1489             pa_log_error("Failed to create sink");
1490             return -1;
1491         }
1492
1493         u->sink->userdata = u;
1494         u->sink->parent.process_msg = sink_process_msg;
1495     }
1496
1497     if (u->profile == PROFILE_HSP) {
1498         u->sink->set_volume = sink_set_volume_cb;
1499         u->sink->n_volume_steps = 16;
1500     }
1501
1502     return 0;
1503 }
1504
1505 static int add_source(struct userdata *u) {
1506
1507 #ifdef NOKIA
1508     if (USE_SCO_OVER_PCM(u)) {
1509         u->source = u->hsp.sco_source;
1510         pa_proplist_sets(u->source->proplist, "bluetooth.protocol", "sco");
1511
1512         if (!u->hsp.source_state_changed_slot)
1513             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);
1514
1515     } else
1516 #endif
1517
1518     {
1519         pa_source_new_data data;
1520         pa_bool_t b;
1521
1522         pa_source_new_data_init(&data);
1523         data.driver = __FILE__;
1524         data.module = u->module;
1525         pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
1526         pa_proplist_sets(data.proplist, "bluetooth.protocol", u->profile == PROFILE_A2DP ? "a2dp" : "sco");
1527         data.card = u->card;
1528         data.name = get_name("source", u->modargs, u->address, &b);
1529         data.namereg_fail = b;
1530
1531         u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY | (u->profile == PROFILE_HSP ? PA_SOURCE_HW_VOLUME_CTRL : 0));
1532         pa_source_new_data_done(&data);
1533
1534         if (!u->source) {
1535             pa_log_error("Failed to create source");
1536             return -1;
1537         }
1538
1539         u->source->userdata = u;
1540         u->source->parent.process_msg = source_process_msg;
1541     }
1542
1543     if (u->profile == PROFILE_HSP) {
1544         pa_proplist_sets(u->source->proplist, "bluetooth.nrec", (u->hsp.pcm_capabilities.flags & BT_PCM_FLAG_NREC) ? "1" : "0");
1545         u->source->set_volume = source_set_volume_cb;
1546         u->source->n_volume_steps = 16;
1547     }
1548
1549     return 0;
1550 }
1551
1552 static void shutdown_bt(struct userdata *u) {
1553     pa_assert(u);
1554
1555     if (u->stream_fd >= 0) {
1556         pa_close(u->stream_fd);
1557         u->stream_fd = -1;
1558
1559         u->stream_write_type = 0;
1560         u->stream_read_type = 0;
1561     }
1562
1563     if (u->service_fd >= 0) {
1564         pa_close(u->service_fd);
1565         u->service_fd = -1;
1566     }
1567
1568     if (u->write_memchunk.memblock) {
1569         pa_memblock_unref(u->write_memchunk.memblock);
1570         pa_memchunk_reset(&u->write_memchunk);
1571     }
1572 }
1573
1574 static int init_bt(struct userdata *u) {
1575     pa_assert(u);
1576
1577     shutdown_bt(u);
1578
1579     u->stream_write_type = u->stream_read_type = 0;
1580     u->service_write_type = u->service_write_type = 0;
1581
1582     if ((u->service_fd = bt_audio_service_open()) < 0) {
1583         pa_log_error("Couldn't connect to bluetooth audio service");
1584         return -1;
1585     }
1586
1587     pa_log_debug("Connected to the bluetooth audio service");
1588
1589     return 0;
1590 }
1591
1592 static int setup_bt(struct userdata *u) {
1593     pa_assert(u);
1594
1595     if (get_caps(u, 0) < 0)
1596         return -1;
1597
1598     pa_log_debug("Got device capabilities");
1599
1600     if (set_conf(u) < 0)
1601         return -1;
1602
1603     pa_log_debug("Connection to the device configured");
1604
1605 #ifdef NOKIA
1606     if (USE_SCO_OVER_PCM(u)) {
1607         pa_log_debug("Configured to use SCO over PCM");
1608         return 0;
1609     }
1610 #endif
1611
1612     pa_log_debug("Got the stream socket");
1613
1614     return 0;
1615 }
1616
1617 static int init_profile(struct userdata *u) {
1618     int r = 0;
1619     pa_assert(u);
1620     pa_assert(u->profile != PROFILE_OFF);
1621
1622     if (setup_bt(u) < 0)
1623         return -1;
1624
1625     if (u->profile == PROFILE_A2DP ||
1626         u->profile == PROFILE_HSP)
1627         if (add_sink(u) < 0)
1628             r = -1;
1629
1630     if (u->profile == PROFILE_HSP)
1631         if (add_source(u) < 0)
1632             r = -1;
1633
1634     return r;
1635 }
1636
1637 static void stop_thread(struct userdata *u) {
1638     pa_assert(u);
1639
1640     if (u->thread) {
1641         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1642         pa_thread_free(u->thread);
1643         u->thread = NULL;
1644     }
1645
1646     if (u->rtpoll_item) {
1647         pa_rtpoll_item_free(u->rtpoll_item);
1648         u->rtpoll_item = NULL;
1649     }
1650
1651     if (u->hsp.sink_state_changed_slot) {
1652         pa_hook_slot_free(u->hsp.sink_state_changed_slot);
1653         u->hsp.sink_state_changed_slot = NULL;
1654     }
1655
1656     if (u->hsp.source_state_changed_slot) {
1657         pa_hook_slot_free(u->hsp.source_state_changed_slot);
1658         u->hsp.source_state_changed_slot = NULL;
1659     }
1660
1661     if (u->sink) {
1662         pa_sink_unref(u->sink);
1663         u->sink = NULL;
1664     }
1665
1666     if (u->source) {
1667         pa_source_unref(u->source);
1668         u->source = NULL;
1669     }
1670
1671     if (u->rtpoll) {
1672         pa_thread_mq_done(&u->thread_mq);
1673
1674         pa_rtpoll_free(u->rtpoll);
1675         u->rtpoll = NULL;
1676     }
1677 }
1678
1679 static int start_thread(struct userdata *u) {
1680     pa_assert(u);
1681     pa_assert(!u->thread);
1682     pa_assert(!u->rtpoll);
1683     pa_assert(!u->rtpoll_item);
1684
1685     u->rtpoll = pa_rtpoll_new();
1686     pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
1687
1688 #ifdef NOKIA
1689     if (USE_SCO_OVER_PCM(u)) {
1690         if (start_stream_fd(u) < 0)
1691             return -1;
1692
1693         pa_sink_ref(u->sink);
1694         pa_source_ref(u->source);
1695         /* FIXME: monitor stream_fd error */
1696         return 0;
1697     }
1698 #endif
1699
1700     if (!(u->thread = pa_thread_new(thread_func, u))) {
1701         pa_log_error("Failed to create IO thread");
1702         stop_thread(u);
1703         return -1;
1704     }
1705
1706     if (u->sink) {
1707         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1708         pa_sink_set_rtpoll(u->sink, u->rtpoll);
1709         pa_sink_put(u->sink);
1710
1711         if (u->sink->set_volume)
1712             u->sink->set_volume(u->sink);
1713     }
1714
1715     if (u->source) {
1716         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1717         pa_source_set_rtpoll(u->source, u->rtpoll);
1718         pa_source_put(u->source);
1719
1720         if (u->source->set_volume)
1721             u->source->set_volume(u->source);
1722     }
1723
1724     return 0;
1725 }
1726
1727 static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
1728     struct userdata *u;
1729     enum profile *d;
1730     pa_queue *inputs = NULL, *outputs = NULL;
1731     const pa_bluetooth_device *device;
1732
1733     pa_assert(c);
1734     pa_assert(new_profile);
1735     pa_assert_se(u = c->userdata);
1736
1737     d = PA_CARD_PROFILE_DATA(new_profile);
1738
1739     if (!(device = pa_bluetooth_discovery_get_by_path(u->discovery, u->path))) {
1740         pa_log_error("Failed to get device object.");
1741         return -1;
1742     }
1743
1744     if (device->headset_state != PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_HSP) {
1745         pa_log_warn("HSP is not connected, refused to switch profile");
1746         return -1;
1747     }
1748     else if (device->audio_sink_state != PA_BT_AUDIO_STATE_CONNECTED && *d == PROFILE_A2DP) {
1749         pa_log_warn("A2DP is not connected, refused to switch profile");
1750         return -1;
1751     }
1752
1753     if (u->sink) {
1754         inputs = pa_sink_move_all_start(u->sink);
1755 #ifdef NOKIA
1756         if (!USE_SCO_OVER_PCM(u))
1757 #endif
1758             pa_sink_unlink(u->sink);
1759     }
1760
1761     if (u->source) {
1762         outputs = pa_source_move_all_start(u->source);
1763 #ifdef NOKIA
1764         if (!USE_SCO_OVER_PCM(u))
1765 #endif
1766             pa_source_unlink(u->source);
1767     }
1768
1769     stop_thread(u);
1770     shutdown_bt(u);
1771
1772     u->profile = *d;
1773     u->sample_spec = u->requested_sample_spec;
1774
1775     init_bt(u);
1776
1777     if (u->profile != PROFILE_OFF)
1778         init_profile(u);
1779
1780     if (u->sink || u->source)
1781         start_thread(u);
1782
1783     if (inputs) {
1784         if (u->sink)
1785             pa_sink_move_all_finish(u->sink, inputs, FALSE);
1786         else
1787             pa_sink_move_all_fail(inputs);
1788     }
1789
1790     if (outputs) {
1791         if (u->source)
1792             pa_source_move_all_finish(u->source, outputs, FALSE);
1793         else
1794             pa_source_move_all_fail(outputs);
1795     }
1796
1797     return 0;
1798 }
1799
1800 static int add_card(struct userdata *u, const char *default_profile, const pa_bluetooth_device *device) {
1801     pa_card_new_data data;
1802     pa_bool_t b;
1803     pa_card_profile *p;
1804     enum profile *d;
1805     const char *ff;
1806     char *n;
1807
1808     pa_card_new_data_init(&data);
1809     data.driver = __FILE__;
1810     data.module = u->module;
1811
1812     n = pa_bluetooth_cleanup_name(device->name);
1813     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, n);
1814     pa_xfree(n);
1815     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, device->address);
1816     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
1817     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
1818     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
1819     if ((ff = pa_bluetooth_get_form_factor(device->class)))
1820         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, ff);
1821     pa_proplist_sets(data.proplist, "bluez.path", device->path);
1822     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", (unsigned) device->class);
1823     pa_proplist_sets(data.proplist, "bluez.name", device->name);
1824     data.name = get_name("card", u->modargs, device->address, &b);
1825     data.namereg_fail = b;
1826
1827     data.profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
1828
1829     /* we base hsp/a2dp availability on UUIDs.
1830        Ideally, it would be based on "Connected" state, but
1831        we can't afford to wait for this information when
1832        we are loaded with profile="hsp", for instance */
1833     if (pa_bluetooth_uuid_has(device->uuids, A2DP_SINK_UUID)) {
1834         p = pa_card_profile_new("a2dp", _("High Fidelity Playback (A2DP)"), sizeof(enum profile));
1835         p->priority = 10;
1836         p->n_sinks = 1;
1837         p->n_sources = 0;
1838         p->max_sink_channels = 2;
1839         p->max_source_channels = 0;
1840
1841         d = PA_CARD_PROFILE_DATA(p);
1842         *d = PROFILE_A2DP;
1843
1844         pa_hashmap_put(data.profiles, p->name, p);
1845     }
1846
1847     if (pa_bluetooth_uuid_has(device->uuids, HSP_HS_UUID) ||
1848         pa_bluetooth_uuid_has(device->uuids, HFP_HS_UUID)) {
1849         p = pa_card_profile_new("hsp", _("Telephony Duplex (HSP/HFP)"), sizeof(enum profile));
1850         p->priority = 20;
1851         p->n_sinks = 1;
1852         p->n_sources = 1;
1853         p->max_sink_channels = 1;
1854         p->max_source_channels = 1;
1855
1856         d = PA_CARD_PROFILE_DATA(p);
1857         *d = PROFILE_HSP;
1858
1859         pa_hashmap_put(data.profiles, p->name, p);
1860     }
1861
1862     pa_assert(!pa_hashmap_isempty(data.profiles));
1863
1864     p = pa_card_profile_new("off", _("Off"), sizeof(enum profile));
1865     d = PA_CARD_PROFILE_DATA(p);
1866     *d = PROFILE_OFF;
1867     pa_hashmap_put(data.profiles, p->name, p);
1868
1869     if (default_profile) {
1870         if (pa_hashmap_get(data.profiles, default_profile))
1871             pa_card_new_data_set_profile(&data, default_profile);
1872         else
1873             pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
1874     }
1875
1876     u->card = pa_card_new(u->core, &data);
1877     pa_card_new_data_done(&data);
1878
1879     if (!u->card) {
1880         pa_log("Failed to allocate card.");
1881         return -1;
1882     }
1883
1884     u->card->userdata = u;
1885     u->card->set_profile = card_set_profile;
1886
1887     d = PA_CARD_PROFILE_DATA(u->card->active_profile);
1888     u->profile = *d;
1889
1890     return 0;
1891 }
1892
1893 static const pa_bluetooth_device* find_device(struct userdata *u, const char *address, const char *path) {
1894     const pa_bluetooth_device *d = NULL;
1895
1896     pa_assert(u);
1897
1898     if (!address && !path) {
1899         pa_log_error("Failed to get device address/path from module arguments.");
1900         return NULL;
1901     }
1902
1903     if (path) {
1904         if (!(d = pa_bluetooth_discovery_get_by_path(u->discovery, path))) {
1905             pa_log_error("%s is not a valid BlueZ audio device.", path);
1906             return NULL;
1907         }
1908
1909         if (address && !(pa_streq(d->address, address))) {
1910             pa_log_error("Passed path %s and address %s don't match.", path, address);
1911             return NULL;
1912         }
1913
1914     } else {
1915         if (!(d = pa_bluetooth_discovery_get_by_address(u->discovery, address))) {
1916             pa_log_error("%s is not known.", address);
1917             return NULL;
1918         }
1919     }
1920
1921     if (d) {
1922         u->address = pa_xstrdup(d->address);
1923         u->path = pa_xstrdup(d->path);
1924     }
1925
1926     return d;
1927 }
1928
1929 static int setup_dbus(struct userdata *u) {
1930     DBusError err;
1931
1932     dbus_error_init(&err);
1933
1934     u->connection = pa_dbus_bus_get(u->core, DBUS_BUS_SYSTEM, &err);
1935
1936     if (dbus_error_is_set(&err) || !u->connection) {
1937         pa_log("Failed to get D-Bus connection: %s", err.message);
1938         dbus_error_free(&err);
1939         return -1;
1940     }
1941
1942     return 0;
1943 }
1944
1945 int pa__init(pa_module* m) {
1946     pa_modargs *ma;
1947     uint32_t channels;
1948     struct userdata *u;
1949     const char *address, *path;
1950     DBusError err;
1951     char *mike, *speaker;
1952     const pa_bluetooth_device *device;
1953
1954     pa_assert(m);
1955
1956     dbus_error_init(&err);
1957
1958     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1959         pa_log_error("Failed to parse module arguments");
1960         goto fail;
1961     }
1962
1963     m->userdata = u = pa_xnew0(struct userdata, 1);
1964     u->module = m;
1965     u->core = m->core;
1966     u->service_fd = -1;
1967     u->stream_fd = -1;
1968     u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE, 10);
1969     u->sample_spec = m->core->default_sample_spec;
1970     u->modargs = ma;
1971
1972 #ifdef NOKIA
1973     if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
1974         !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
1975         pa_log("SCO sink not found");
1976         goto fail;
1977     }
1978
1979     if (pa_modargs_get_value(ma, "sco_source", NULL) &&
1980         !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
1981         pa_log("SCO source not found");
1982         goto fail;
1983     }
1984 #endif
1985
1986     if (pa_modargs_get_value_u32(ma, "rate", &u->sample_spec.rate) < 0 ||
1987         u->sample_spec.rate <= 0 || u->sample_spec.rate > PA_RATE_MAX) {
1988         pa_log_error("Failed to get rate from module arguments");
1989         goto fail;
1990     }
1991
1992     channels = u->sample_spec.channels;
1993     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
1994         channels <= 0 || channels > PA_CHANNELS_MAX) {
1995         pa_log_error("Failed to get channels from module arguments");
1996         goto fail;
1997     }
1998     u->sample_spec.channels = (uint8_t) channels;
1999     u->requested_sample_spec = u->sample_spec;
2000
2001     address = pa_modargs_get_value(ma, "address", NULL);
2002     path = pa_modargs_get_value(ma, "path", NULL);
2003
2004     if (setup_dbus(u) < 0)
2005         goto fail;
2006
2007     if (!(u->discovery = pa_bluetooth_discovery_get(m->core)))
2008         goto fail;
2009
2010     if (!(device = find_device(u, address, path)))
2011         goto fail;
2012
2013     /* Add the card structure. This will also initialize the default profile */
2014     if (add_card(u, pa_modargs_get_value(ma, "profile", NULL), device) < 0)
2015         goto fail;
2016
2017     /* Connect to the BT service and query capabilities */
2018     if (init_bt(u) < 0)
2019         goto fail;
2020
2021     if (!dbus_connection_add_filter(pa_dbus_connection_get(u->connection), filter_cb, u, NULL)) {
2022         pa_log_error("Failed to add filter function");
2023         goto fail;
2024     }
2025
2026     speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2027     mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2028
2029     if (pa_dbus_add_matches(
2030                 pa_dbus_connection_get(u->connection), &err,
2031                 speaker,
2032                 mike,
2033                 NULL) < 0) {
2034
2035         pa_xfree(speaker);
2036         pa_xfree(mike);
2037
2038         pa_log("Failed to add D-Bus matches: %s", err.message);
2039         goto fail;
2040     }
2041
2042     pa_xfree(speaker);
2043     pa_xfree(mike);
2044
2045     if (u->profile != PROFILE_OFF)
2046         if (init_profile(u) < 0)
2047             goto fail;
2048
2049     if (u->sink || u->source)
2050         if (start_thread(u) < 0)
2051             goto fail;
2052
2053     return 0;
2054
2055 fail:
2056
2057     pa__done(m);
2058
2059     dbus_error_free(&err);
2060
2061     return -1;
2062 }
2063
2064 int pa__get_n_used(pa_module *m) {
2065     struct userdata *u;
2066
2067     pa_assert(m);
2068     pa_assert_se(u = m->userdata);
2069
2070     return
2071         (u->sink ? pa_sink_linked_by(u->sink) : 0) +
2072         (u->source ? pa_source_linked_by(u->source) : 0);
2073 }
2074
2075 void pa__done(pa_module *m) {
2076     struct userdata *u;
2077     pa_assert(m);
2078
2079     if (!(u = m->userdata))
2080         return;
2081
2082     if (u->sink
2083 #ifdef NOKIA
2084         && !USE_SCO_OVER_PCM(u)
2085 #endif
2086     )
2087         pa_sink_unlink(u->sink);
2088
2089     if (u->source
2090 #ifdef NOKIA
2091         && !USE_SCO_OVER_PCM(u)
2092 #endif
2093     )
2094         pa_source_unlink(u->source);
2095
2096     stop_thread(u);
2097
2098     if (u->connection) {
2099
2100         if (u->path) {
2101             char *speaker, *mike;
2102             speaker = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='SpeakerGainChanged',path='%s'", u->path);
2103             mike = pa_sprintf_malloc("type='signal',sender='org.bluez',interface='org.bluez.Headset',member='MicrophoneGainChanged',path='%s'", u->path);
2104
2105             pa_dbus_remove_matches(pa_dbus_connection_get(u->connection),
2106                                    speaker,
2107                                    mike,
2108                                    NULL);
2109
2110             pa_xfree(speaker);
2111             pa_xfree(mike);
2112         }
2113
2114         dbus_connection_remove_filter(pa_dbus_connection_get(u->connection), filter_cb, u);
2115         pa_dbus_connection_unref(u->connection);
2116     }
2117
2118     if (u->card)
2119         pa_card_free(u->card);
2120
2121     if (u->read_smoother)
2122         pa_smoother_free(u->read_smoother);
2123
2124     shutdown_bt(u);
2125
2126     if (u->a2dp.buffer)
2127         pa_xfree(u->a2dp.buffer);
2128
2129     sbc_finish(&u->a2dp.sbc);
2130
2131     if (u->modargs)
2132         pa_modargs_free(u->modargs);
2133
2134     pa_xfree(u->address);
2135     pa_xfree(u->path);
2136
2137     if (u->discovery)
2138         pa_bluetooth_discovery_unref(u->discovery);
2139
2140     pa_xfree(u);
2141 }