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