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