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