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