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