~binli/ubuntu/vivid/pulseaudio/load-extcon-module

« back to all changes in this revision

Viewing changes to src/modules/bluetooth/module-bluez5-device.c

  • Committer: Bin Li
  • Date: 2016-01-23 15:04:48 UTC
  • Revision ID: bin.li@canonical.com-20160123150448-5ockvw4p5xxntda4
init the 1:6.0-0ubuntu9.15 from silo 12

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/***
 
2
  This file is part of PulseAudio.
 
3
 
 
4
  Copyright 2008-2013 João Paulo Rechi Vita
 
5
  Copyright 2011-2013 BMW Car IT GmbH.
 
6
 
 
7
  PulseAudio is free software; you can redistribute it and/or modify
 
8
  it under the terms of the GNU Lesser General Public License as
 
9
  published by the Free Software Foundation; either version 2.1 of the
 
10
  License, or (at your option) any later version.
 
11
 
 
12
  PulseAudio is distributed in the hope that it will be useful, but
 
13
  WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 
15
  General Public License for more details.
 
16
 
 
17
  You should have received a copy of the GNU Lesser General Public
 
18
  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
 
19
***/
 
20
 
 
21
#ifdef HAVE_CONFIG_H
 
22
#include <config.h>
 
23
#endif
 
24
 
 
25
#include <errno.h>
 
26
 
 
27
#include <arpa/inet.h>
 
28
#include <sbc/sbc.h>
 
29
 
 
30
#include <pulse/rtclock.h>
 
31
#include <pulse/timeval.h>
 
32
 
 
33
#include <pulsecore/core.h>
 
34
#include <pulsecore/core-error.h>
 
35
#include <pulsecore/core-rtclock.h>
 
36
#include <pulsecore/core-util.h>
 
37
#include <pulsecore/i18n.h>
 
38
#include <pulsecore/module.h>
 
39
#include <pulsecore/modargs.h>
 
40
#include <pulsecore/poll.h>
 
41
#include <pulsecore/rtpoll.h>
 
42
#include <pulsecore/shared.h>
 
43
#include <pulsecore/socket-util.h>
 
44
#include <pulsecore/thread.h>
 
45
#include <pulsecore/thread-mq.h>
 
46
#include <pulsecore/time-smoother.h>
 
47
#include <pulsecore/namereg.h>
 
48
#include <pulse/mainloop-api.h>
 
49
 
 
50
#include "a2dp-codecs.h"
 
51
#include "bluez5-util.h"
 
52
#include "rtp.h"
 
53
 
 
54
#include "module-bluez5-device-symdef.h"
 
55
 
 
56
PA_MODULE_AUTHOR("João Paulo Rechi Vita");
 
57
PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
 
58
PA_MODULE_VERSION(PACKAGE_VERSION);
 
59
PA_MODULE_LOAD_ONCE(false);
 
60
PA_MODULE_USAGE("path=<device object path> "
 
61
                "profile=<a2dp|hsp|hfgw> "
 
62
                "sco_sink=<name of sink> "
 
63
                "sco_source=<name of source> ");
 
64
 
 
65
#define MAX_PLAYBACK_CATCH_UP_USEC (100 * PA_USEC_PER_MSEC)
 
66
#define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
 
67
#define FIXED_LATENCY_PLAYBACK_SCO (125 * PA_USEC_PER_MSEC)
 
68
#define FIXED_LATENCY_RECORD_A2DP   (25 * PA_USEC_PER_MSEC)
 
69
#define FIXED_LATENCY_RECORD_SCO    (25 * PA_USEC_PER_MSEC)
 
70
 
 
71
#define BITPOOL_DEC_LIMIT 32
 
72
#define BITPOOL_DEC_STEP 5
 
73
#define HSP_MAX_GAIN 15
 
74
 
 
75
#define USE_SCO_OVER_PCM(u) (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT && (u->hsp.sco_sink && u->hsp.sco_source))
 
76
 
 
77
static const char* const valid_modargs[] = {
 
78
    "path",
 
79
    "profile",
 
80
    "sco_sink",
 
81
    "sco_source",
 
82
    NULL
 
83
};
 
84
 
 
85
enum {
 
86
    BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
 
87
    BLUETOOTH_MESSAGE_STREAM_FD_HUP,
 
88
    BLUETOOTH_MESSAGE_MAX
 
89
};
 
90
 
 
91
typedef struct bluetooth_msg {
 
92
    pa_msgobject parent;
 
93
    pa_card *card;
 
94
} bluetooth_msg;
 
95
PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
 
96
#define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
 
97
 
 
98
typedef struct sbc_info {
 
99
    sbc_t sbc;                           /* Codec data */
 
100
    bool sbc_initialized;                /* Keep track if the encoder is initialized */
 
101
    size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
 
102
    uint16_t seq_num;                    /* Cumulative packet sequence */
 
103
    uint8_t min_bitpool;
 
104
    uint8_t max_bitpool;
 
105
 
 
106
    void* buffer;                        /* Codec transfer buffer */
 
107
    size_t buffer_size;                  /* Size of the buffer */
 
108
} sbc_info_t;
 
109
 
 
110
struct hsp_info {
 
111
    pa_sink *sco_sink;
 
112
    pa_source *sco_source;
 
113
};
 
114
 
 
115
struct userdata {
 
116
    pa_module *module;
 
117
    pa_core *core;
 
118
 
 
119
    pa_modargs *modargs;
 
120
 
 
121
    pa_hook_slot *device_connection_changed_slot;
 
122
    pa_hook_slot *transport_state_changed_slot;
 
123
    pa_hook_slot *transport_speaker_gain_changed_slot;
 
124
    pa_hook_slot *transport_microphone_gain_changed_slot;
 
125
 
 
126
    pa_hook_slot *sink_state_changed_slot;
 
127
    pa_hook_slot *source_state_changed_slot;
 
128
 
 
129
    pa_hook_slot *sco_sink_proplist_changed_slot;
 
130
    bool prevent_suspend_transport;
 
131
 
 
132
    pa_bluetooth_discovery *discovery;
 
133
    pa_bluetooth_device *device;
 
134
    pa_bluetooth_transport *transport;
 
135
    bool transport_acquired;
 
136
 
 
137
    pa_card *card;
 
138
    pa_sink *sink;
 
139
    pa_source *source;
 
140
    pa_bluetooth_profile_t profile;
 
141
    char *output_port_name;
 
142
    char *input_port_name;
 
143
 
 
144
    pa_thread *thread;
 
145
    pa_thread_mq thread_mq;
 
146
    pa_rtpoll *rtpoll;
 
147
    pa_rtpoll_item *rtpoll_item;
 
148
    bluetooth_msg *msg;
 
149
 
 
150
    int stream_fd;
 
151
    int stream_write_type;
 
152
    size_t read_link_mtu;
 
153
    size_t write_link_mtu;
 
154
    size_t read_block_size;
 
155
    size_t write_block_size;
 
156
    uint64_t read_index;
 
157
    uint64_t write_index;
 
158
    pa_usec_t started_at;
 
159
    pa_smoother *read_smoother;
 
160
    pa_memchunk write_memchunk;
 
161
    pa_sample_spec sample_spec;
 
162
    struct sbc_info sbc_info;
 
163
    struct hsp_info hsp;
 
164
 
 
165
    char *default_profile;
 
166
    bool transport_acquire_pending;
 
167
    pa_io_event *stream_event;
 
168
 
 
169
    pa_defer_event *set_default_profile_event;
 
170
};
 
171
 
 
172
typedef enum pa_bluetooth_form_factor {
 
173
    PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
 
174
    PA_BLUETOOTH_FORM_FACTOR_HEADSET,
 
175
    PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
 
176
    PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
 
177
    PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
 
178
    PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
 
179
    PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
 
180
    PA_BLUETOOTH_FORM_FACTOR_CAR,
 
181
    PA_BLUETOOTH_FORM_FACTOR_HIFI,
 
182
    PA_BLUETOOTH_FORM_FACTOR_PHONE,
 
183
} pa_bluetooth_form_factor_t;
 
184
 
 
185
/* Run from main thread */
 
186
static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
 
187
    unsigned major, minor;
 
188
    pa_bluetooth_form_factor_t r;
 
189
 
 
190
    static const pa_bluetooth_form_factor_t table[] = {
 
191
        [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
 
192
        [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
 
193
        [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
 
194
        [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
 
195
        [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
 
196
        [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
 
197
        [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
 
198
        [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
 
199
    };
 
200
 
 
201
    /*
 
202
     * See Bluetooth Assigned Numbers:
 
203
     * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
 
204
     */
 
205
    major = (class_of_device >> 8) & 0x1F;
 
206
    minor = (class_of_device >> 2) & 0x3F;
 
207
 
 
208
    switch (major) {
 
209
        case 2:
 
210
            return PA_BLUETOOTH_FORM_FACTOR_PHONE;
 
211
        case 4:
 
212
            break;
 
213
        default:
 
214
            pa_log_debug("Unknown Bluetooth major device class %u", major);
 
215
            return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
 
216
    }
 
217
 
 
218
    r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
 
219
 
 
220
    if (!r)
 
221
        pa_log_debug("Unknown Bluetooth minor device class %u", minor);
 
222
 
 
223
    return r;
 
224
}
 
225
 
 
226
/* Run from main thread */
 
227
static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
 
228
    switch (ff) {
 
229
        case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
 
230
            return "unknown";
 
231
        case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
 
232
            return "headset";
 
233
        case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
 
234
            return "hands-free";
 
235
        case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
 
236
            return "microphone";
 
237
        case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
 
238
            return "speaker";
 
239
        case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
 
240
            return "headphone";
 
241
        case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
 
242
            return "portable";
 
243
        case PA_BLUETOOTH_FORM_FACTOR_CAR:
 
244
            return "car";
 
245
        case PA_BLUETOOTH_FORM_FACTOR_HIFI:
 
246
            return "hifi";
 
247
        case PA_BLUETOOTH_FORM_FACTOR_PHONE:
 
248
            return "phone";
 
249
    }
 
250
 
 
251
    pa_assert_not_reached();
 
252
}
 
253
 
 
254
/* Run from main thread */
 
255
static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
 
256
    pa_device_port *port;
 
257
 
 
258
    if (direction == PA_DIRECTION_OUTPUT) {
 
259
        pa_sink_new_data *sink_new_data = new_data;
 
260
 
 
261
        pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
 
262
        pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
 
263
        pa_device_port_ref(port);
 
264
    } else {
 
265
        pa_source_new_data *source_new_data = new_data;
 
266
 
 
267
        pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
 
268
        pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
 
269
        pa_device_port_ref(port);
 
270
    }
 
271
}
 
272
 
 
273
/* Run from IO thread */
 
274
static int sco_process_render(struct userdata *u) {
 
275
    ssize_t l;
 
276
    pa_memchunk memchunk;
 
277
 
 
278
    pa_assert(u);
 
279
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
 
280
                u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
 
281
    pa_assert(u->sink);
 
282
 
 
283
    pa_sink_render_full(u->sink, u->write_block_size, &memchunk);
 
284
 
 
285
    pa_assert(memchunk.length == u->write_block_size);
 
286
 
 
287
    for (;;) {
 
288
        const void *p;
 
289
 
 
290
        /* Now write that data to the socket. The socket is of type
 
291
         * SEQPACKET, and we generated the data of the MTU size, so this
 
292
         * should just work. */
 
293
 
 
294
        p = (const uint8_t *) pa_memblock_acquire_chunk(&memchunk);
 
295
        l = pa_write(u->stream_fd, p, memchunk.length, &u->stream_write_type);
 
296
        pa_memblock_release(memchunk.memblock);
 
297
 
 
298
        pa_assert(l != 0);
 
299
 
 
300
        if (l > 0)
 
301
            break;
 
302
 
 
303
        if (errno == EINTR)
 
304
            /* Retry right away if we got interrupted */
 
305
            continue;
 
306
        else if (errno == EAGAIN)
 
307
            /* Hmm, apparently the socket was not writable, give up for now */
 
308
            return 0;
 
309
 
 
310
        pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(errno));
 
311
        return -1;
 
312
    }
 
313
 
 
314
    pa_assert((size_t) l <= memchunk.length);
 
315
 
 
316
    if ((size_t) l != memchunk.length) {
 
317
        pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
 
318
                    (unsigned long long) l,
 
319
                    (unsigned long long) memchunk.length);
 
320
        return -1;
 
321
    }
 
322
 
 
323
    u->write_index += (uint64_t) memchunk.length;
 
324
    pa_memblock_unref(memchunk.memblock);
 
325
 
 
326
    return 1;
 
327
}
 
328
 
 
329
/* Run from IO thread */
 
330
static int sco_process_push(struct userdata *u) {
 
331
    ssize_t l;
 
332
    pa_memchunk memchunk;
 
333
    struct cmsghdr *cm;
 
334
    struct msghdr m;
 
335
    bool found_tstamp = false;
 
336
    pa_usec_t tstamp = 0;
 
337
 
 
338
    pa_assert(u);
 
339
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
 
340
                u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
 
341
    pa_assert(u->source);
 
342
    pa_assert(u->read_smoother);
 
343
 
 
344
    memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
 
345
    memchunk.index = memchunk.length = 0;
 
346
 
 
347
    for (;;) {
 
348
        void *p;
 
349
        uint8_t aux[1024];
 
350
        struct iovec iov;
 
351
 
 
352
        pa_zero(m);
 
353
        pa_zero(aux);
 
354
        pa_zero(iov);
 
355
 
 
356
        m.msg_iov = &iov;
 
357
        m.msg_iovlen = 1;
 
358
        m.msg_control = aux;
 
359
        m.msg_controllen = sizeof(aux);
 
360
 
 
361
        p = pa_memblock_acquire(memchunk.memblock);
 
362
        iov.iov_base = p;
 
363
        iov.iov_len = pa_memblock_get_length(memchunk.memblock);
 
364
        l = recvmsg(u->stream_fd, &m, 0);
 
365
        pa_memblock_release(memchunk.memblock);
 
366
 
 
367
        if (l > 0)
 
368
            break;
 
369
 
 
370
        if (l < 0 && errno == EINTR)
 
371
            /* Retry right away if we got interrupted */
 
372
            continue;
 
373
 
 
374
        pa_memblock_unref(memchunk.memblock);
 
375
 
 
376
        if (l < 0 && errno == EAGAIN)
 
377
            /* Hmm, apparently the socket was not readable, give up for now. */
 
378
            return 0;
 
379
 
 
380
        pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
 
381
        return -1;
 
382
    }
 
383
 
 
384
    pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
 
385
 
 
386
    /* In some rare occasions, we might receive packets of a very strange
 
387
     * size. This could potentially be possible if the SCO packet was
 
388
     * received partially over-the-air, or more probably due to hardware
 
389
     * issues in our Bluetooth adapter. In these cases, in order to avoid
 
390
     * an assertion failure due to unaligned data, just discard the whole
 
391
     * packet */
 
392
    if (!pa_frame_aligned(l, &u->sample_spec)) {
 
393
        pa_log_warn("SCO packet received of unaligned size: %zu", l);
 
394
        pa_memblock_unref(memchunk.memblock);
 
395
        return -1;
 
396
    }
 
397
 
 
398
    memchunk.length = (size_t) l;
 
399
    u->read_index += (uint64_t) l;
 
400
 
 
401
    for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
 
402
        if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
 
403
            struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
 
404
            pa_rtclock_from_wallclock(tv);
 
405
            tstamp = pa_timeval_load(tv);
 
406
            found_tstamp = true;
 
407
            break;
 
408
        }
 
409
 
 
410
    if (!found_tstamp) {
 
411
        pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
 
412
        tstamp = pa_rtclock_now();
 
413
    }
 
414
 
 
415
    pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
 
416
    pa_smoother_resume(u->read_smoother, tstamp, true);
 
417
 
 
418
    pa_source_post(u->source, &memchunk);
 
419
    pa_memblock_unref(memchunk.memblock);
 
420
 
 
421
    return l;
 
422
}
 
423
 
 
424
/* Run from IO thread */
 
425
static void a2dp_prepare_buffer(struct userdata *u) {
 
426
    size_t min_buffer_size = PA_MAX(u->read_link_mtu, u->write_link_mtu);
 
427
 
 
428
    pa_assert(u);
 
429
 
 
430
    if (u->sbc_info.buffer_size >= min_buffer_size)
 
431
        return;
 
432
 
 
433
    u->sbc_info.buffer_size = 2 * min_buffer_size;
 
434
    pa_xfree(u->sbc_info.buffer);
 
435
    u->sbc_info.buffer = pa_xmalloc(u->sbc_info.buffer_size);
 
436
}
 
437
 
 
438
/* Run from IO thread */
 
439
static int a2dp_process_render(struct userdata *u) {
 
440
    struct sbc_info *sbc_info;
 
441
    struct rtp_header *header;
 
442
    struct rtp_payload *payload;
 
443
    size_t nbytes;
 
444
    void *d;
 
445
    const void *p;
 
446
    size_t to_write, to_encode;
 
447
    unsigned frame_count;
 
448
    int ret = 0;
 
449
 
 
450
    pa_assert(u);
 
451
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
 
452
    pa_assert(u->sink);
 
453
 
 
454
    /* First, render some data */
 
455
    if (!u->write_memchunk.memblock)
 
456
        pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
 
457
 
 
458
    pa_assert(u->write_memchunk.length == u->write_block_size);
 
459
 
 
460
    a2dp_prepare_buffer(u);
 
461
 
 
462
    sbc_info = &u->sbc_info;
 
463
    header = sbc_info->buffer;
 
464
    payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
 
465
 
 
466
    frame_count = 0;
 
467
 
 
468
    /* Try to create a packet of the full MTU */
 
469
 
 
470
    p = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
 
471
    to_encode = u->write_memchunk.length;
 
472
 
 
473
    d = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
 
474
    to_write = sbc_info->buffer_size - sizeof(*header) - sizeof(*payload);
 
475
 
 
476
    while (PA_LIKELY(to_encode > 0 && to_write > 0)) {
 
477
        ssize_t written;
 
478
        ssize_t encoded;
 
479
 
 
480
        encoded = sbc_encode(&sbc_info->sbc,
 
481
                             p, to_encode,
 
482
                             d, to_write,
 
483
                             &written);
 
484
 
 
485
        if (PA_UNLIKELY(encoded <= 0)) {
 
486
            pa_log_error("SBC encoding error (%li)", (long) encoded);
 
487
            pa_memblock_release(u->write_memchunk.memblock);
 
488
            return -1;
 
489
        }
 
490
 
 
491
        pa_assert_fp((size_t) encoded <= to_encode);
 
492
        pa_assert_fp((size_t) encoded == sbc_info->codesize);
 
493
 
 
494
        pa_assert_fp((size_t) written <= to_write);
 
495
        pa_assert_fp((size_t) written == sbc_info->frame_length);
 
496
 
 
497
        p = (const uint8_t*) p + encoded;
 
498
        to_encode -= encoded;
 
499
 
 
500
        d = (uint8_t*) d + written;
 
501
        to_write -= written;
 
502
 
 
503
        frame_count++;
 
504
    }
 
505
 
 
506
    pa_memblock_release(u->write_memchunk.memblock);
 
507
 
 
508
    pa_assert(to_encode == 0);
 
509
 
 
510
    PA_ONCE_BEGIN {
 
511
        pa_log_debug("Using SBC encoder implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
 
512
    } PA_ONCE_END;
 
513
 
 
514
    /* write it to the fifo */
 
515
    memset(sbc_info->buffer, 0, sizeof(*header) + sizeof(*payload));
 
516
    header->v = 2;
 
517
    header->pt = 1;
 
518
    header->sequence_number = htons(sbc_info->seq_num++);
 
519
    header->timestamp = htonl(u->write_index / pa_frame_size(&u->sample_spec));
 
520
    header->ssrc = htonl(1);
 
521
    payload->frame_count = frame_count;
 
522
 
 
523
    nbytes = (uint8_t*) d - (uint8_t*) sbc_info->buffer;
 
524
 
 
525
    for (;;) {
 
526
        ssize_t l;
 
527
 
 
528
        l = pa_write(u->stream_fd, sbc_info->buffer, nbytes, &u->stream_write_type);
 
529
 
 
530
        pa_assert(l != 0);
 
531
 
 
532
        if (l < 0) {
 
533
 
 
534
            if (errno == EINTR)
 
535
                /* Retry right away if we got interrupted */
 
536
                continue;
 
537
 
 
538
            else if (errno == EAGAIN)
 
539
                /* Hmm, apparently the socket was not writable, give up for now */
 
540
                break;
 
541
 
 
542
            pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
 
543
            ret = -1;
 
544
            break;
 
545
        }
 
546
 
 
547
        pa_assert((size_t) l <= nbytes);
 
548
 
 
549
        if ((size_t) l != nbytes) {
 
550
            pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
 
551
                        (unsigned long long) l,
 
552
                        (unsigned long long) nbytes);
 
553
            ret = -1;
 
554
            break;
 
555
        }
 
556
 
 
557
        u->write_index += (uint64_t) u->write_memchunk.length;
 
558
        pa_memblock_unref(u->write_memchunk.memblock);
 
559
        pa_memchunk_reset(&u->write_memchunk);
 
560
 
 
561
        ret = 1;
 
562
 
 
563
        break;
 
564
    }
 
565
 
 
566
    return ret;
 
567
}
 
568
 
 
569
/* Run from IO thread */
 
570
static int a2dp_process_push(struct userdata *u) {
 
571
    int ret = 0;
 
572
    pa_memchunk memchunk;
 
573
 
 
574
    pa_assert(u);
 
575
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
 
576
    pa_assert(u->source);
 
577
    pa_assert(u->read_smoother);
 
578
 
 
579
    memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
 
580
    memchunk.index = memchunk.length = 0;
 
581
 
 
582
    for (;;) {
 
583
        bool found_tstamp = false;
 
584
        pa_usec_t tstamp;
 
585
        struct sbc_info *sbc_info;
 
586
        struct rtp_header *header;
 
587
        struct rtp_payload *payload;
 
588
        const void *p;
 
589
        void *d;
 
590
        ssize_t l;
 
591
        size_t to_write, to_decode;
 
592
        size_t total_written = 0;
 
593
 
 
594
        a2dp_prepare_buffer(u);
 
595
 
 
596
        sbc_info = &u->sbc_info;
 
597
        header = sbc_info->buffer;
 
598
        payload = (struct rtp_payload*) ((uint8_t*) sbc_info->buffer + sizeof(*header));
 
599
 
 
600
        l = pa_read(u->stream_fd, sbc_info->buffer, sbc_info->buffer_size, &u->stream_write_type);
 
601
 
 
602
        if (l <= 0) {
 
603
 
 
604
            if (l < 0 && errno == EINTR)
 
605
                /* Retry right away if we got interrupted */
 
606
                continue;
 
607
 
 
608
            else if (l < 0 && errno == EAGAIN)
 
609
                /* Hmm, apparently the socket was not readable, give up for now. */
 
610
                break;
 
611
 
 
612
            pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
 
613
            ret = -1;
 
614
            break;
 
615
        }
 
616
 
 
617
        pa_assert((size_t) l <= sbc_info->buffer_size);
 
618
 
 
619
        /* TODO: get timestamp from rtp */
 
620
        if (!found_tstamp) {
 
621
            /* pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!"); */
 
622
            tstamp = pa_rtclock_now();
 
623
        }
 
624
 
 
625
        p = (uint8_t*) sbc_info->buffer + sizeof(*header) + sizeof(*payload);
 
626
        to_decode = l - sizeof(*header) - sizeof(*payload);
 
627
 
 
628
        d = pa_memblock_acquire(memchunk.memblock);
 
629
        to_write = memchunk.length = pa_memblock_get_length(memchunk.memblock);
 
630
 
 
631
        while (PA_LIKELY(to_decode > 0)) {
 
632
            size_t written;
 
633
            ssize_t decoded;
 
634
 
 
635
            decoded = sbc_decode(&sbc_info->sbc,
 
636
                                 p, to_decode,
 
637
                                 d, to_write,
 
638
                                 &written);
 
639
 
 
640
            if (PA_UNLIKELY(decoded <= 0)) {
 
641
                pa_log_error("SBC decoding error (%li)", (long) decoded);
 
642
                pa_memblock_release(memchunk.memblock);
 
643
                pa_memblock_unref(memchunk.memblock);
 
644
                return 0;
 
645
            }
 
646
 
 
647
            total_written += written;
 
648
 
 
649
            /* Reset frame length, it can be changed due to bitpool change */
 
650
            sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
 
651
 
 
652
            pa_assert_fp((size_t) decoded <= to_decode);
 
653
            pa_assert_fp((size_t) decoded == sbc_info->frame_length);
 
654
 
 
655
            pa_assert_fp((size_t) written == sbc_info->codesize);
 
656
 
 
657
            p = (const uint8_t*) p + decoded;
 
658
            to_decode -= decoded;
 
659
 
 
660
            d = (uint8_t*) d + written;
 
661
            to_write -= written;
 
662
        }
 
663
 
 
664
        u->read_index += (uint64_t) total_written;
 
665
        pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->sample_spec));
 
666
        pa_smoother_resume(u->read_smoother, tstamp, true);
 
667
 
 
668
        memchunk.length -= to_write;
 
669
 
 
670
        pa_memblock_release(memchunk.memblock);
 
671
 
 
672
        pa_source_post(u->source, &memchunk);
 
673
 
 
674
        ret = l;
 
675
        break;
 
676
    }
 
677
 
 
678
    pa_memblock_unref(memchunk.memblock);
 
679
 
 
680
    return ret;
 
681
}
 
682
 
 
683
/* Run from I/O thread */
 
684
static void a2dp_set_bitpool(struct userdata *u, uint8_t bitpool) {
 
685
    struct sbc_info *sbc_info;
 
686
 
 
687
    pa_assert(u);
 
688
 
 
689
    sbc_info = &u->sbc_info;
 
690
 
 
691
    if (sbc_info->sbc.bitpool == bitpool)
 
692
        return;
 
693
 
 
694
    if (bitpool > sbc_info->max_bitpool)
 
695
        bitpool = sbc_info->max_bitpool;
 
696
    else if (bitpool < sbc_info->min_bitpool)
 
697
        bitpool = sbc_info->min_bitpool;
 
698
 
 
699
    sbc_info->sbc.bitpool = bitpool;
 
700
 
 
701
    sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
 
702
    sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
 
703
 
 
704
    pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
 
705
 
 
706
    u->read_block_size =
 
707
        (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
 
708
        / sbc_info->frame_length * sbc_info->codesize;
 
709
 
 
710
    u->write_block_size =
 
711
        (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
 
712
        / sbc_info->frame_length * sbc_info->codesize;
 
713
 
 
714
    pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
 
715
    pa_sink_set_fixed_latency_within_thread(u->sink,
 
716
            FIXED_LATENCY_PLAYBACK_A2DP + pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
 
717
}
 
718
 
 
719
/* Run from I/O thread */
 
720
static void a2dp_reduce_bitpool(struct userdata *u) {
 
721
    struct sbc_info *sbc_info;
 
722
    uint8_t bitpool;
 
723
 
 
724
    pa_assert(u);
 
725
 
 
726
    sbc_info = &u->sbc_info;
 
727
 
 
728
    /* Check if bitpool is already at its limit */
 
729
    if (sbc_info->sbc.bitpool <= BITPOOL_DEC_LIMIT)
 
730
        return;
 
731
 
 
732
    bitpool = sbc_info->sbc.bitpool - BITPOOL_DEC_STEP;
 
733
 
 
734
    if (bitpool < BITPOOL_DEC_LIMIT)
 
735
        bitpool = BITPOOL_DEC_LIMIT;
 
736
 
 
737
    a2dp_set_bitpool(u, bitpool);
 
738
}
 
739
 
 
740
static void teardown_stream(struct userdata *u) {
 
741
    if (u->rtpoll_item) {
 
742
        pa_rtpoll_item_free(u->rtpoll_item);
 
743
        u->rtpoll_item = NULL;
 
744
    }
 
745
 
 
746
    if (u->stream_event) {
 
747
        u->core->mainloop->io_free(u->stream_event);
 
748
        u->stream_event = NULL;
 
749
    }
 
750
 
 
751
    if (u->stream_fd >= 0) {
 
752
        pa_close(u->stream_fd);
 
753
        u->stream_fd = -1;
 
754
    }
 
755
 
 
756
    if (u->read_smoother) {
 
757
        pa_smoother_free(u->read_smoother);
 
758
        u->read_smoother = NULL;
 
759
    }
 
760
 
 
761
    if (u->write_memchunk.memblock) {
 
762
        pa_memblock_unref(u->write_memchunk.memblock);
 
763
        pa_memchunk_reset(&u->write_memchunk);
 
764
    }
 
765
 
 
766
    pa_log_debug("Audio stream torn down");
 
767
}
 
768
 
 
769
static int transport_acquire(struct userdata *u, bool optional) {
 
770
    pa_assert(u->transport);
 
771
 
 
772
    if (u->transport_acquire_pending)
 
773
        return -1;
 
774
 
 
775
    if (u->transport_acquired) {
 
776
        pa_log_debug("Transport already acquired");
 
777
        return 0;
 
778
    }
 
779
 
 
780
    u->transport_acquire_pending = true;
 
781
 
 
782
    pa_log_debug("Acquiring transport %s", u->transport->path);
 
783
 
 
784
    u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
 
785
    if (u->stream_fd < 0) {
 
786
        u->transport_acquire_pending = false;
 
787
        return -1;
 
788
    }
 
789
 
 
790
    u->transport_acquired = true;
 
791
    pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
 
792
 
 
793
    u->transport_acquire_pending = false;
 
794
 
 
795
    return 0;
 
796
}
 
797
 
 
798
static void transport_release(struct userdata *u) {
 
799
    pa_assert(u->transport);
 
800
 
 
801
    /* Ignore if already released */
 
802
    if (!u->transport_acquired)
 
803
        return;
 
804
 
 
805
    pa_log_debug("Releasing transport %s", u->transport->path);
 
806
 
 
807
    u->transport->release(u->transport);
 
808
 
 
809
    u->transport_acquired = false;
 
810
 
 
811
    teardown_stream(u);
 
812
}
 
813
 
 
814
/* Run from I/O thread */
 
815
static void transport_config_mtu(struct userdata *u) {
 
816
 
 
817
    pa_log_debug("Configuring MTU for transport of profile %s",
 
818
                 pa_bluetooth_profile_to_string(u->profile));
 
819
 
 
820
    if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
 
821
        u->read_block_size = u->read_link_mtu;
 
822
        u->write_block_size = u->write_link_mtu;
 
823
    } else {
 
824
        u->read_block_size =
 
825
            (u->read_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
 
826
            / u->sbc_info.frame_length * u->sbc_info.codesize;
 
827
 
 
828
        u->write_block_size =
 
829
            (u->write_link_mtu - sizeof(struct rtp_header) - sizeof(struct rtp_payload))
 
830
            / u->sbc_info.frame_length * u->sbc_info.codesize;
 
831
    }
 
832
 
 
833
    if (USE_SCO_OVER_PCM(u))
 
834
        return;
 
835
 
 
836
    if (u->sink) {
 
837
        pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
 
838
        pa_sink_set_fixed_latency_within_thread(u->sink,
 
839
                                                (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
 
840
                                                 FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
 
841
                                                pa_bytes_to_usec(u->write_block_size, &u->sample_spec));
 
842
    }
 
843
 
 
844
    if (u->source)
 
845
        pa_source_set_fixed_latency_within_thread(u->source,
 
846
                                                  (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
 
847
                                                   FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
 
848
                                                  pa_bytes_to_usec(u->read_block_size, &u->sample_spec));
 
849
}
 
850
 
 
851
/* Run from I/O thread except in SCO over PCM */
 
852
static void setup_stream(struct userdata *u) {
 
853
    struct pollfd *pollfd;
 
854
    int one;
 
855
 
 
856
    pa_log_info("Transport %s resuming", u->transport->path);
 
857
 
 
858
    transport_config_mtu(u);
 
859
 
 
860
    pa_make_fd_nonblock(u->stream_fd);
 
861
    pa_make_socket_low_delay(u->stream_fd);
 
862
 
 
863
    one = 1;
 
864
    if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
 
865
        pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
 
866
 
 
867
    pa_log_debug("Stream properly set up, we're ready to roll!");
 
868
 
 
869
    if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
 
870
        a2dp_set_bitpool(u, u->sbc_info.max_bitpool);
 
871
 
 
872
    u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
 
873
    pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
 
874
    pollfd->fd = u->stream_fd;
 
875
    pollfd->events = pollfd->revents = 0;
 
876
 
 
877
    u->read_index = u->write_index = 0;
 
878
    u->started_at = 0;
 
879
 
 
880
    if (u->source)
 
881
        u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
 
882
}
 
883
 
 
884
/* Run from IO thread */
 
885
static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
 
886
    struct userdata *u = PA_SOURCE(o)->userdata;
 
887
    bool failed = false;
 
888
    int r;
 
889
 
 
890
    pa_assert(u->source == PA_SOURCE(o));
 
891
    pa_assert(u->transport);
 
892
 
 
893
    switch (code) {
 
894
 
 
895
        case PA_SOURCE_MESSAGE_SET_STATE:
 
896
 
 
897
            switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
 
898
 
 
899
                case PA_SOURCE_SUSPENDED:
 
900
                    /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
 
901
                    if (!PA_SOURCE_IS_OPENED(u->source->thread_info.state))
 
902
                        break;
 
903
 
 
904
                    /* Stop the device if the sink is suspended as well */
 
905
                    if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
 
906
                        transport_release(u);
 
907
 
 
908
                    if (u->read_smoother)
 
909
                        pa_smoother_pause(u->read_smoother, pa_rtclock_now());
 
910
 
 
911
                    break;
 
912
 
 
913
                case PA_SOURCE_IDLE:
 
914
                case PA_SOURCE_RUNNING:
 
915
                    if (u->source->thread_info.state != PA_SOURCE_SUSPENDED)
 
916
                        break;
 
917
 
 
918
                    /* Resume the device if the sink was suspended as well */
 
919
                    if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
 
920
                        if (transport_acquire(u, false) < 0)
 
921
                            failed = true;
 
922
                        else
 
923
                            setup_stream(u);
 
924
                    }
 
925
 
 
926
                    /* We don't resume the smoother here. Instead we
 
927
                     * wait until the first packet arrives */
 
928
 
 
929
                    break;
 
930
 
 
931
                case PA_SOURCE_UNLINKED:
 
932
                case PA_SOURCE_INIT:
 
933
                case PA_SOURCE_INVALID_STATE:
 
934
                    break;
 
935
            }
 
936
 
 
937
            break;
 
938
 
 
939
        case PA_SOURCE_MESSAGE_GET_LATENCY: {
 
940
            pa_usec_t wi, ri;
 
941
 
 
942
            if (u->read_smoother) {
 
943
                wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
 
944
                ri = pa_bytes_to_usec(u->read_index, &u->sample_spec);
 
945
 
 
946
                *((pa_usec_t*) data) = FIXED_LATENCY_RECORD_A2DP + wi > ri ? FIXED_LATENCY_RECORD_A2DP + wi - ri : 0;
 
947
            } else
 
948
                *((pa_usec_t*) data) = 0;
 
949
 
 
950
            return 0;
 
951
        }
 
952
 
 
953
    }
 
954
 
 
955
    r = pa_source_process_msg(o, code, data, offset, chunk);
 
956
 
 
957
    return (r < 0 || !failed) ? r : -1;
 
958
}
 
959
 
 
960
/* Run from main thread */
 
961
static void source_set_volume_cb(pa_source *s) {
 
962
    uint16_t gain;
 
963
    pa_volume_t volume;
 
964
    struct userdata *u;
 
965
 
 
966
    pa_assert(s);
 
967
    pa_assert(s->core);
 
968
 
 
969
    u = s->userdata;
 
970
 
 
971
    pa_assert(u);
 
972
    pa_assert(u->source == s);
 
973
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
 
974
 
 
975
    if (u->transport->set_microphone_gain == NULL)
 
976
      return;
 
977
 
 
978
    gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
 
979
 
 
980
    if (gain > HSP_MAX_GAIN)
 
981
        gain = HSP_MAX_GAIN;
 
982
 
 
983
    volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
 
984
 
 
985
    /* increment volume by one to correct rounding errors */
 
986
    if (volume < PA_VOLUME_NORM)
 
987
        volume++;
 
988
 
 
989
    pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
 
990
 
 
991
    u->transport->set_microphone_gain(u->transport, gain);
 
992
}
 
993
 
 
994
/* Run from main thread */
 
995
static int add_source(struct userdata *u) {
 
996
    pa_source_new_data data;
 
997
 
 
998
    pa_assert(u->transport);
 
999
 
 
1000
    if (USE_SCO_OVER_PCM(u)) {
 
1001
        u->source = u->hsp.sco_source;
 
1002
        pa_proplist_sets(u->source->proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
 
1003
    } else {
 
1004
        pa_source_new_data_init(&data);
 
1005
        data.module = u->module;
 
1006
        data.card = u->card;
 
1007
        data.driver = __FILE__;
 
1008
        data.name = pa_sprintf_malloc("bluez_source.%s", u->device->address);
 
1009
        data.namereg_fail = false;
 
1010
        pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
 
1011
        pa_source_new_data_set_sample_spec(&data, &u->sample_spec);
 
1012
        if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
 
1013
            pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
 
1014
 
 
1015
        connect_ports(u, &data, PA_DIRECTION_INPUT);
 
1016
 
 
1017
        if (!u->transport_acquired)
 
1018
            switch (u->profile) {
 
1019
                case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
 
1020
                case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
 
1021
                    data.suspend_cause = PA_SUSPEND_USER;
 
1022
                    break;
 
1023
                case PA_BLUETOOTH_PROFILE_A2DP_SINK:
 
1024
                case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
 
1025
                case PA_BLUETOOTH_PROFILE_OFF:
 
1026
                    pa_assert_not_reached();
 
1027
                    break;
 
1028
            }
 
1029
 
 
1030
        u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
 
1031
        pa_source_new_data_done(&data);
 
1032
        if (!u->source) {
 
1033
            pa_log_error("Failed to create source");
 
1034
            return -1;
 
1035
        }
 
1036
 
 
1037
        u->source->userdata = u;
 
1038
        u->source->parent.process_msg = source_process_msg;
 
1039
    }
 
1040
 
 
1041
    if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
 
1042
        pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
 
1043
        u->source->n_volume_steps = 16;
 
1044
    }
 
1045
 
 
1046
    return 0;
 
1047
}
 
1048
 
 
1049
#define HSP_PREVENT_SUSPEND_STR "bluetooth.hsp.prevent.suspend.transport"
 
1050
 
 
1051
/* Check and update prevent_suspend_transport value from sco sink proplist.
 
1052
 *
 
1053
 * Return < 0 if sink proplist doesn't contain HSP_PREVENT_SUSPEND_STR value,
 
1054
 * 1 if value is 'true'
 
1055
 * 0 if value is something else. */
 
1056
static int check_proplist(struct userdata *u) {
 
1057
    int ret;
 
1058
    const char *str;
 
1059
 
 
1060
    pa_assert(u);
 
1061
    pa_assert(u->hsp.sco_sink);
 
1062
 
 
1063
    if ((str = pa_proplist_gets(u->hsp.sco_sink->proplist, HSP_PREVENT_SUSPEND_STR))) {
 
1064
        if (pa_streq(str, "true"))
 
1065
            ret = 1;
 
1066
        else
 
1067
            ret = 0;
 
1068
    } else
 
1069
        ret = -1;
 
1070
 
 
1071
    u->prevent_suspend_transport = ret == 1;
 
1072
 
 
1073
    pa_log_debug("Set %s %s (ret %d)", HSP_PREVENT_SUSPEND_STR, u->prevent_suspend_transport ? "true" : "false", ret);
 
1074
 
 
1075
    return ret;
 
1076
}
 
1077
 
 
1078
/* There are cases where keeping the transport running even when sco sink and source are suspended
 
1079
 * is needed.
 
1080
 * To work with these cases, check sco.sink for bluetooth.hsp.prevent.suspend.transport value, and
 
1081
 * when set to true prevent closing the transport when sink suspends.
 
1082
 * Also, if the sink&source are suspended when sco-sink suspend.transport value changes to true,
 
1083
 * bring sco transport up. When suspend.transport value changes to false while sink&source are suspended,
 
1084
 * tear down the transport. */
 
1085
static pa_hook_result_t update_allow_release_cb(pa_core *c, pa_sink *s, struct userdata *u) {
 
1086
    pa_assert(u);
 
1087
    pa_assert(s);
 
1088
 
 
1089
    if (!u->hsp.sco_sink || u->hsp.sco_sink != s)
 
1090
        return PA_HOOK_OK;
 
1091
 
 
1092
    if (check_proplist(u) < 0)
 
1093
        return PA_HOOK_OK;
 
1094
 
 
1095
    if (!USE_SCO_OVER_PCM(u)) {
 
1096
        pa_log_debug("SCO sink not available.");
 
1097
        return PA_HOOK_OK;
 
1098
    }
 
1099
 
 
1100
    if (!PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) &&
 
1101
        !PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
 
1102
 
 
1103
        pa_log_debug("Resuming SCO sink");
 
1104
 
 
1105
        /* Clear all suspend bits, effectively resuming SCO sink for a while. */
 
1106
        pa_sink_suspend(s, false, PA_SUSPEND_ALL);
 
1107
    }
 
1108
 
 
1109
    return PA_HOOK_OK;
 
1110
}
 
1111
 
 
1112
/* Run from IO thread */
 
1113
static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
 
1114
    struct userdata *u = PA_SINK(o)->userdata;
 
1115
    bool failed = false;
 
1116
    int r;
 
1117
 
 
1118
    pa_assert(u->sink == PA_SINK(o));
 
1119
    pa_assert(u->transport);
 
1120
 
 
1121
    switch (code) {
 
1122
 
 
1123
        case PA_SINK_MESSAGE_SET_STATE:
 
1124
 
 
1125
            switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
 
1126
 
 
1127
                case PA_SINK_SUSPENDED:
 
1128
                    /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
 
1129
                    if (!PA_SINK_IS_OPENED(u->sink->thread_info.state))
 
1130
                        break;
 
1131
 
 
1132
                    /* Stop the device if the source is suspended as well */
 
1133
                    if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
 
1134
                        /* We deliberately ignore whether stopping
 
1135
                         * actually worked. Since the stream_fd is
 
1136
                         * closed it doesn't really matter */
 
1137
                        transport_release(u);
 
1138
 
 
1139
                    break;
 
1140
 
 
1141
                case PA_SINK_IDLE:
 
1142
                case PA_SINK_RUNNING:
 
1143
                    if (u->sink->thread_info.state != PA_SINK_SUSPENDED)
 
1144
                        break;
 
1145
 
 
1146
                    /* Resume the device if the source was suspended as well */
 
1147
                    if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
 
1148
                        if (transport_acquire(u, false) < 0)
 
1149
                            failed = true;
 
1150
                        else
 
1151
                            setup_stream(u);
 
1152
                    }
 
1153
 
 
1154
                    break;
 
1155
 
 
1156
                case PA_SINK_UNLINKED:
 
1157
                case PA_SINK_INIT:
 
1158
                case PA_SINK_INVALID_STATE:
 
1159
                    break;
 
1160
            }
 
1161
 
 
1162
            break;
 
1163
 
 
1164
        case PA_SINK_MESSAGE_GET_LATENCY: {
 
1165
            pa_usec_t wi, ri;
 
1166
 
 
1167
            if (u->read_smoother) {
 
1168
                ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
 
1169
                wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->sample_spec);
 
1170
            } else {
 
1171
                ri = pa_rtclock_now() - u->started_at;
 
1172
                wi = pa_bytes_to_usec(u->write_index, &u->sample_spec);
 
1173
            }
 
1174
 
 
1175
            *((pa_usec_t*) data) = FIXED_LATENCY_PLAYBACK_A2DP + wi > ri ? FIXED_LATENCY_PLAYBACK_A2DP + wi - ri : 0;
 
1176
 
 
1177
            return 0;
 
1178
        }
 
1179
    }
 
1180
 
 
1181
    r = pa_sink_process_msg(o, code, data, offset, chunk);
 
1182
 
 
1183
    return (r < 0 || !failed) ? r : -1;
 
1184
}
 
1185
 
 
1186
/* Run from main thread */
 
1187
static void sink_set_volume_cb(pa_sink *s) {
 
1188
    uint16_t gain;
 
1189
    pa_volume_t volume;
 
1190
    struct userdata *u;
 
1191
 
 
1192
    pa_assert(s);
 
1193
    pa_assert(s->core);
 
1194
 
 
1195
    u = s->userdata;
 
1196
 
 
1197
    pa_assert(u);
 
1198
    pa_assert(u->sink == s);
 
1199
    pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT);
 
1200
 
 
1201
    if (u->transport->set_speaker_gain == NULL)
 
1202
      return;
 
1203
 
 
1204
    gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
 
1205
 
 
1206
    if (gain > HSP_MAX_GAIN)
 
1207
        gain = HSP_MAX_GAIN;
 
1208
 
 
1209
    volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
 
1210
 
 
1211
    /* increment volume by one to correct rounding errors */
 
1212
    if (volume < PA_VOLUME_NORM)
 
1213
        volume++;
 
1214
 
 
1215
    pa_cvolume_set(&s->real_volume, u->sample_spec.channels, volume);
 
1216
 
 
1217
    u->transport->set_speaker_gain(u->transport, gain);
 
1218
}
 
1219
 
 
1220
/* Run from main thread */
 
1221
static int add_sink(struct userdata *u) {
 
1222
    pa_sink_new_data data;
 
1223
 
 
1224
    pa_assert(u->transport);
 
1225
 
 
1226
    if (USE_SCO_OVER_PCM(u)) {
 
1227
        pa_proplist *p;
 
1228
 
 
1229
        u->sink = u->hsp.sco_sink;
 
1230
        p = pa_proplist_new();
 
1231
        pa_proplist_sets(p, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
 
1232
        pa_proplist_update(u->sink->proplist, PA_UPDATE_MERGE, p);
 
1233
        pa_proplist_free(p);
 
1234
    } else {
 
1235
        pa_sink_new_data_init(&data);
 
1236
        data.module = u->module;
 
1237
        data.card = u->card;
 
1238
        data.driver = __FILE__;
 
1239
        data.name = pa_sprintf_malloc("bluez_sink.%s", u->device->address);
 
1240
        data.namereg_fail = false;
 
1241
        pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
 
1242
        pa_sink_new_data_set_sample_spec(&data, &u->sample_spec);
 
1243
        if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
 
1244
            pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
 
1245
 
 
1246
        connect_ports(u, &data, PA_DIRECTION_OUTPUT);
 
1247
 
 
1248
        if (!u->transport_acquired)
 
1249
            switch (u->profile) {
 
1250
                case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
 
1251
                    data.suspend_cause = PA_SUSPEND_USER;
 
1252
                    break;
 
1253
                case PA_BLUETOOTH_PROFILE_A2DP_SINK:
 
1254
                    /* Profile switch should have failed */
 
1255
                case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
 
1256
                case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
 
1257
                case PA_BLUETOOTH_PROFILE_OFF:
 
1258
                    pa_assert_not_reached();
 
1259
                    break;
 
1260
            }
 
1261
 
 
1262
        u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
 
1263
        pa_sink_new_data_done(&data);
 
1264
        if (!u->sink) {
 
1265
            pa_log_error("Failed to create sink");
 
1266
            return -1;
 
1267
        }
 
1268
 
 
1269
        u->sink->userdata = u;
 
1270
        u->sink->parent.process_msg = sink_process_msg;
 
1271
    }
 
1272
 
 
1273
    if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT) {
 
1274
        pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
 
1275
        u->sink->n_volume_steps = 16;
 
1276
    }
 
1277
 
 
1278
    return 0;
 
1279
}
 
1280
 
 
1281
/* Run from main thread */
 
1282
static void transport_config(struct userdata *u) {
 
1283
 
 
1284
    pa_log_debug("Configuring transport for profile %s",
 
1285
                 pa_bluetooth_profile_to_string(u->profile));
 
1286
 
 
1287
    if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
 
1288
        u->sample_spec.format = PA_SAMPLE_S16LE;
 
1289
        u->sample_spec.channels = 1;
 
1290
        u->sample_spec.rate = 8000;
 
1291
    } else {
 
1292
        sbc_info_t *sbc_info = &u->sbc_info;
 
1293
        a2dp_sbc_t *config;
 
1294
 
 
1295
        pa_assert(u->transport);
 
1296
 
 
1297
        u->sample_spec.format = PA_SAMPLE_S16LE;
 
1298
        config = (a2dp_sbc_t *) u->transport->config;
 
1299
 
 
1300
        if (sbc_info->sbc_initialized)
 
1301
            sbc_reinit(&sbc_info->sbc, 0);
 
1302
        else
 
1303
            sbc_init(&sbc_info->sbc, 0);
 
1304
        sbc_info->sbc_initialized = true;
 
1305
 
 
1306
        switch (config->frequency) {
 
1307
            case SBC_SAMPLING_FREQ_16000:
 
1308
                sbc_info->sbc.frequency = SBC_FREQ_16000;
 
1309
                u->sample_spec.rate = 16000U;
 
1310
                break;
 
1311
            case SBC_SAMPLING_FREQ_32000:
 
1312
                sbc_info->sbc.frequency = SBC_FREQ_32000;
 
1313
                u->sample_spec.rate = 32000U;
 
1314
                break;
 
1315
            case SBC_SAMPLING_FREQ_44100:
 
1316
                sbc_info->sbc.frequency = SBC_FREQ_44100;
 
1317
                u->sample_spec.rate = 44100U;
 
1318
                break;
 
1319
            case SBC_SAMPLING_FREQ_48000:
 
1320
                sbc_info->sbc.frequency = SBC_FREQ_48000;
 
1321
                u->sample_spec.rate = 48000U;
 
1322
                break;
 
1323
            default:
 
1324
                pa_assert_not_reached();
 
1325
        }
 
1326
 
 
1327
        switch (config->channel_mode) {
 
1328
            case SBC_CHANNEL_MODE_MONO:
 
1329
                sbc_info->sbc.mode = SBC_MODE_MONO;
 
1330
                u->sample_spec.channels = 1;
 
1331
                break;
 
1332
            case SBC_CHANNEL_MODE_DUAL_CHANNEL:
 
1333
                sbc_info->sbc.mode = SBC_MODE_DUAL_CHANNEL;
 
1334
                u->sample_spec.channels = 2;
 
1335
                break;
 
1336
            case SBC_CHANNEL_MODE_STEREO:
 
1337
                sbc_info->sbc.mode = SBC_MODE_STEREO;
 
1338
                u->sample_spec.channels = 2;
 
1339
                break;
 
1340
            case SBC_CHANNEL_MODE_JOINT_STEREO:
 
1341
                sbc_info->sbc.mode = SBC_MODE_JOINT_STEREO;
 
1342
                u->sample_spec.channels = 2;
 
1343
                break;
 
1344
            default:
 
1345
                pa_assert_not_reached();
 
1346
        }
 
1347
 
 
1348
        switch (config->allocation_method) {
 
1349
            case SBC_ALLOCATION_SNR:
 
1350
                sbc_info->sbc.allocation = SBC_AM_SNR;
 
1351
                break;
 
1352
            case SBC_ALLOCATION_LOUDNESS:
 
1353
                sbc_info->sbc.allocation = SBC_AM_LOUDNESS;
 
1354
                break;
 
1355
            default:
 
1356
                pa_assert_not_reached();
 
1357
        }
 
1358
 
 
1359
        switch (config->subbands) {
 
1360
            case SBC_SUBBANDS_4:
 
1361
                sbc_info->sbc.subbands = SBC_SB_4;
 
1362
                break;
 
1363
            case SBC_SUBBANDS_8:
 
1364
                sbc_info->sbc.subbands = SBC_SB_8;
 
1365
                break;
 
1366
            default:
 
1367
                pa_assert_not_reached();
 
1368
        }
 
1369
 
 
1370
        switch (config->block_length) {
 
1371
            case SBC_BLOCK_LENGTH_4:
 
1372
                sbc_info->sbc.blocks = SBC_BLK_4;
 
1373
                break;
 
1374
            case SBC_BLOCK_LENGTH_8:
 
1375
                sbc_info->sbc.blocks = SBC_BLK_8;
 
1376
                break;
 
1377
            case SBC_BLOCK_LENGTH_12:
 
1378
                sbc_info->sbc.blocks = SBC_BLK_12;
 
1379
                break;
 
1380
            case SBC_BLOCK_LENGTH_16:
 
1381
                sbc_info->sbc.blocks = SBC_BLK_16;
 
1382
                break;
 
1383
            default:
 
1384
                pa_assert_not_reached();
 
1385
        }
 
1386
 
 
1387
        sbc_info->min_bitpool = config->min_bitpool;
 
1388
        sbc_info->max_bitpool = config->max_bitpool;
 
1389
 
 
1390
        /* Set minimum bitpool for source to get the maximum possible block_size */
 
1391
        sbc_info->sbc.bitpool = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ? sbc_info->max_bitpool : sbc_info->min_bitpool;
 
1392
        sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
 
1393
        sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
 
1394
 
 
1395
        pa_log_info("SBC parameters: allocation=%u, subbands=%u, blocks=%u, bitpool=%u",
 
1396
                    sbc_info->sbc.allocation, sbc_info->sbc.subbands, sbc_info->sbc.blocks, sbc_info->sbc.bitpool);
 
1397
    }
 
1398
}
 
1399
 
 
1400
/* Run from main thread */
 
1401
static int setup_transport(struct userdata *u) {
 
1402
    pa_bluetooth_transport *t;
 
1403
 
 
1404
    pa_assert(u);
 
1405
    pa_assert(!u->transport_acquired);
 
1406
    pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
 
1407
 
 
1408
    pa_log_debug("profile %s", pa_bluetooth_profile_to_string(u->profile));
 
1409
 
 
1410
    /* check if profile has a transport */
 
1411
    t = u->device->transports[u->profile];
 
1412
 
 
1413
    pa_log_debug("profile %s transport %p transport state %s",
 
1414
                 pa_bluetooth_profile_to_string(u->profile),
 
1415
                 t, t ? pa_bluetooth_transport_state_to_string(t->state) : "unknown");
 
1416
 
 
1417
    if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
 
1418
        pa_log_warn("Profile has no transport");
 
1419
        return -1;
 
1420
    }
 
1421
 
 
1422
    u->transport = t;
 
1423
 
 
1424
    if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
 
1425
        transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
 
1426
    else if (transport_acquire(u, false) < 0)
 
1427
        return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
 
1428
 
 
1429
    transport_config(u);
 
1430
 
 
1431
    return 0;
 
1432
}
 
1433
 
 
1434
/* Run from main thread */
 
1435
static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
 
1436
    static const pa_direction_t profile_direction[] = {
 
1437
        [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
 
1438
        [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
 
1439
        [PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
 
1440
        [PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
 
1441
        [PA_BLUETOOTH_PROFILE_OFF] = 0
 
1442
    };
 
1443
 
 
1444
    return profile_direction[p];
 
1445
}
 
1446
 
 
1447
/* Run from main thread */
 
1448
static int init_profile(struct userdata *u) {
 
1449
    int r = 0;
 
1450
    pa_assert(u);
 
1451
    pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
 
1452
 
 
1453
    pa_log_debug("Initializing profile %s", pa_bluetooth_profile_to_string(u->profile));
 
1454
 
 
1455
    if (setup_transport(u) < 0)
 
1456
        return -1;
 
1457
 
 
1458
    pa_assert(u->transport);
 
1459
 
 
1460
    pa_log_debug("Transport for profile %s successfully setup",
 
1461
                 pa_bluetooth_profile_to_string(u->profile));
 
1462
 
 
1463
    if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
 
1464
        if (add_sink(u) < 0)
 
1465
            r = -1;
 
1466
 
 
1467
    if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
 
1468
        if (add_source(u) < 0)
 
1469
            r = -1;
 
1470
 
 
1471
    return r;
 
1472
}
 
1473
 
 
1474
/* I/O thread function */
 
1475
static void thread_func(void *userdata) {
 
1476
    struct userdata *u = userdata;
 
1477
    unsigned do_write = 0;
 
1478
    unsigned pending_read_bytes = 0;
 
1479
    bool writable = false;
 
1480
 
 
1481
    pa_assert(u);
 
1482
    pa_assert(u->transport);
 
1483
 
 
1484
    pa_log_debug("IO Thread starting up");
 
1485
 
 
1486
    if (u->core->realtime_scheduling)
 
1487
        pa_make_realtime(u->core->realtime_priority);
 
1488
 
 
1489
    pa_thread_mq_install(&u->thread_mq);
 
1490
 
 
1491
    /* Setup the stream only if the transport was already acquired */
 
1492
    if (u->transport_acquired)
 
1493
        setup_stream(u);
 
1494
 
 
1495
    for (;;) {
 
1496
        struct pollfd *pollfd;
 
1497
        int ret;
 
1498
        bool disable_timer = true;
 
1499
 
 
1500
        pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
 
1501
 
 
1502
        if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
 
1503
            pa_log_info("FD error: %s%s%s%s",
 
1504
                        pollfd->revents & POLLERR ? "POLLERR " :"",
 
1505
                        pollfd->revents & POLLHUP ? "POLLHUP " :"",
 
1506
                        pollfd->revents & POLLPRI ? "POLLPRI " :"",
 
1507
                        pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
 
1508
 
 
1509
            if (pollfd->revents & POLLHUP) {
 
1510
                pollfd = NULL;
 
1511
                teardown_stream(u);
 
1512
                do_write = 0;
 
1513
                pending_read_bytes = 0;
 
1514
                writable = false;
 
1515
                pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
 
1516
            } else
 
1517
                goto fail;
 
1518
        }
 
1519
 
 
1520
        if (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state)) {
 
1521
 
 
1522
            /* We should send two blocks to the device before we expect
 
1523
             * a response. */
 
1524
 
 
1525
            if (u->write_index == 0 && u->read_index <= 0)
 
1526
                do_write = 2;
 
1527
 
 
1528
            if (pollfd && (pollfd->revents & POLLIN)) {
 
1529
                int n_read;
 
1530
 
 
1531
                if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
 
1532
                    n_read = a2dp_process_push(u);
 
1533
                else
 
1534
                    n_read = sco_process_push(u);
 
1535
 
 
1536
                if (n_read < 0)
 
1537
                    goto fail;
 
1538
 
 
1539
                if (n_read > 0) {
 
1540
                    /* We just read something, so we are supposed to write something, too */
 
1541
                    pending_read_bytes += n_read;
 
1542
                    do_write += pending_read_bytes / u->write_block_size;
 
1543
                    pending_read_bytes = pending_read_bytes % u->write_block_size;
 
1544
                }
 
1545
            }
 
1546
        }
 
1547
 
 
1548
        if (u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state)) {
 
1549
 
 
1550
            if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
 
1551
                pa_sink_process_rewind(u->sink, 0);
 
1552
 
 
1553
            if (pollfd) {
 
1554
                if (pollfd->revents & POLLOUT)
 
1555
                    writable = true;
 
1556
 
 
1557
                if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0 && writable) {
 
1558
                    pa_usec_t time_passed;
 
1559
                    pa_usec_t audio_sent;
 
1560
 
 
1561
                    /* Hmm, there is no input stream we could synchronize
 
1562
                     * to. So let's do things by time */
 
1563
 
 
1564
                    time_passed = pa_rtclock_now() - u->started_at;
 
1565
                    audio_sent = pa_bytes_to_usec(u->write_index, &u->sample_spec);
 
1566
 
 
1567
                    if (audio_sent <= time_passed) {
 
1568
                        pa_usec_t audio_to_send = time_passed - audio_sent;
 
1569
 
 
1570
                        /* Never try to catch up for more than 100ms */
 
1571
                        if (u->write_index > 0 && audio_to_send > MAX_PLAYBACK_CATCH_UP_USEC) {
 
1572
                            pa_usec_t skip_usec;
 
1573
                            uint64_t skip_bytes;
 
1574
 
 
1575
                            skip_usec = audio_to_send - MAX_PLAYBACK_CATCH_UP_USEC;
 
1576
                            skip_bytes = pa_usec_to_bytes(skip_usec, &u->sample_spec);
 
1577
 
 
1578
                            if (skip_bytes > 0) {
 
1579
                                pa_memchunk tmp;
 
1580
 
 
1581
                                pa_log_warn("Skipping %llu us (= %llu bytes) in audio stream",
 
1582
                                            (unsigned long long) skip_usec,
 
1583
                                            (unsigned long long) skip_bytes);
 
1584
 
 
1585
                                pa_sink_render_full(u->sink, skip_bytes, &tmp);
 
1586
                                pa_memblock_unref(tmp.memblock);
 
1587
                                u->write_index += skip_bytes;
 
1588
 
 
1589
                                if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
 
1590
                                    a2dp_reduce_bitpool(u);
 
1591
                            }
 
1592
                        }
 
1593
 
 
1594
                        do_write = 1;
 
1595
                        pending_read_bytes = 0;
 
1596
                    }
 
1597
                }
 
1598
 
 
1599
                if (writable && do_write > 0) {
 
1600
                    int n_written;
 
1601
 
 
1602
                    if (u->write_index <= 0)
 
1603
                        u->started_at = pa_rtclock_now();
 
1604
 
 
1605
                    if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
 
1606
                        if ((n_written = a2dp_process_render(u)) < 0)
 
1607
                            goto fail;
 
1608
                    } else {
 
1609
                        if ((n_written = sco_process_render(u)) < 0)
 
1610
                            goto fail;
 
1611
                    }
 
1612
 
 
1613
                    if (n_written == 0)
 
1614
                        pa_log("Broken kernel: we got EAGAIN on write() after POLLOUT!");
 
1615
 
 
1616
                    do_write -= n_written;
 
1617
                    writable = false;
 
1618
                }
 
1619
 
 
1620
                if ((!u->source || !PA_SOURCE_IS_LINKED(u->source->thread_info.state)) && do_write <= 0) {
 
1621
                    pa_usec_t sleep_for;
 
1622
                    pa_usec_t time_passed, next_write_at;
 
1623
 
 
1624
                    if (writable) {
 
1625
                        /* Hmm, there is no input stream we could synchronize
 
1626
                         * to. So let's estimate when we need to wake up the latest */
 
1627
                        time_passed = pa_rtclock_now() - u->started_at;
 
1628
                        next_write_at = pa_bytes_to_usec(u->write_index, &u->sample_spec);
 
1629
                        sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
 
1630
                        /* 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); */
 
1631
                    } else
 
1632
                        /* drop stream every 500 ms */
 
1633
                        sleep_for = PA_USEC_PER_MSEC * 500;
 
1634
 
 
1635
                    pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
 
1636
                    disable_timer = false;
 
1637
                }
 
1638
            }
 
1639
        }
 
1640
 
 
1641
        if (disable_timer)
 
1642
            pa_rtpoll_set_timer_disabled(u->rtpoll);
 
1643
 
 
1644
        /* Hmm, nothing to do. Let's sleep */
 
1645
        if (pollfd)
 
1646
            pollfd->events = (short) (((u->sink && PA_SINK_IS_LINKED(u->sink->thread_info.state) && !writable) ? POLLOUT : 0) |
 
1647
                                      (u->source && PA_SOURCE_IS_LINKED(u->source->thread_info.state) ? POLLIN : 0));
 
1648
 
 
1649
        if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
 
1650
            pa_log_debug("pa_rtpoll_run failed with: %d", ret);
 
1651
            goto fail;
 
1652
        }
 
1653
        if (ret == 0) {
 
1654
            pa_log_debug("IO thread shutdown requested, stopping cleanly");
 
1655
            transport_release(u);
 
1656
            goto finish;
 
1657
        }
 
1658
    }
 
1659
 
 
1660
fail:
 
1661
    /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
 
1662
    pa_log_debug("IO thread failed");
 
1663
    pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
 
1664
    pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
 
1665
 
 
1666
finish:
 
1667
    pa_log_debug("IO thread shutting down");
 
1668
}
 
1669
 
 
1670
static int sco_over_pcm_state_update(struct userdata *u, bool changed)
 
1671
{
 
1672
    pa_assert(u);
 
1673
    pa_assert(USE_SCO_OVER_PCM(u));
 
1674
 
 
1675
    pa_log_debug("Updating SCO over PCM state (profile %s, changed %s, stream fd %d)",
 
1676
                 pa_bluetooth_profile_to_string(u->profile),
 
1677
                 changed ? "yes" : "no", u->stream_fd);
 
1678
 
 
1679
    if (PA_SINK_IS_OPENED(pa_sink_get_state(u->hsp.sco_sink)) ||
 
1680
        PA_SOURCE_IS_OPENED(pa_source_get_state(u->hsp.sco_source))) {
 
1681
 
 
1682
        if (u->stream_fd >= 0)
 
1683
            return 0;
 
1684
 
 
1685
        pa_log_debug("Resuming SCO over PCM");
 
1686
 
 
1687
        if (init_profile(u) < 0) {
 
1688
            pa_log("Can't resume SCO over PCM");
 
1689
            return -1;
 
1690
        }
 
1691
 
 
1692
        setup_stream(u);
 
1693
 
 
1694
        return 0;
 
1695
    }
 
1696
 
 
1697
    if (changed) {
 
1698
        if (u->stream_fd < 0)
 
1699
            return 0;
 
1700
 
 
1701
        if (check_proplist(u) == 1) {
 
1702
            pa_log_debug("Suspend prevention active, not closing SCO over PCM");
 
1703
            return 0;
 
1704
        }
 
1705
 
 
1706
        pa_log_debug("Closing SCO over PCM");
 
1707
 
 
1708
        transport_release(u);
 
1709
    }
 
1710
 
 
1711
    return 0;
 
1712
}
 
1713
 
 
1714
static void stream_died_cb(pa_mainloop_api *ea, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata)
 
1715
{
 
1716
    struct userdata *u = userdata;
 
1717
 
 
1718
    pa_assert(u);
 
1719
    pa_assert(u->transport);
 
1720
 
 
1721
    pa_log_warn("SCO stream went down");
 
1722
 
 
1723
    pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
 
1724
 
 
1725
}
 
1726
 
 
1727
/* Run from main thread */
 
1728
static int start_thread(struct userdata *u) {
 
1729
    pa_assert(u);
 
1730
    pa_assert(!u->thread);
 
1731
    pa_assert(!u->rtpoll);
 
1732
    pa_assert(!u->rtpoll_item);
 
1733
 
 
1734
    u->rtpoll = pa_rtpoll_new();
 
1735
    pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll);
 
1736
 
 
1737
    if (USE_SCO_OVER_PCM(u)) {
 
1738
        if (sco_over_pcm_state_update(u, false) < 0)
 
1739
            return -1;
 
1740
 
 
1741
        pa_log_debug("Installing monitor for SCO stream");
 
1742
 
 
1743
        u->stream_event = u->core->mainloop->io_new(u->core->mainloop,
 
1744
                            u->stream_fd, PA_IO_EVENT_HANGUP | PA_IO_EVENT_ERROR, stream_died_cb, u);
 
1745
        if (!u->stream_event) {
 
1746
            pa_log_error("Failed to setup monitoring for SCO stream");
 
1747
            return -1;
 
1748
        }
 
1749
 
 
1750
        pa_sink_ref(u->sink);
 
1751
        pa_source_ref(u->source);
 
1752
 
 
1753
        return 0;
 
1754
    }
 
1755
 
 
1756
    if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
 
1757
        pa_log_error("Failed to create IO thread");
 
1758
        return -1;
 
1759
    }
 
1760
 
 
1761
    if (u->sink) {
 
1762
        pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
 
1763
        pa_sink_set_rtpoll(u->sink, u->rtpoll);
 
1764
        pa_sink_put(u->sink);
 
1765
 
 
1766
        if (u->sink->set_volume)
 
1767
            u->sink->set_volume(u->sink);
 
1768
    }
 
1769
 
 
1770
    if (u->source) {
 
1771
        pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
 
1772
        pa_source_set_rtpoll(u->source, u->rtpoll);
 
1773
        pa_source_put(u->source);
 
1774
 
 
1775
        if (u->source->set_volume)
 
1776
            u->source->set_volume(u->source);
 
1777
    }
 
1778
 
 
1779
    return 0;
 
1780
}
 
1781
 
 
1782
/* Run from main thread */
 
1783
static void stop_thread(struct userdata *u) {
 
1784
    pa_assert(u);
 
1785
 
 
1786
    if (u->sink && !USE_SCO_OVER_PCM(u))
 
1787
        pa_sink_unlink(u->sink);
 
1788
 
 
1789
    if (u->source && !USE_SCO_OVER_PCM(u))
 
1790
        pa_source_unlink(u->source);
 
1791
 
 
1792
    if (u->thread) {
 
1793
        pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
 
1794
        pa_thread_free(u->thread);
 
1795
        u->thread = NULL;
 
1796
    }
 
1797
 
 
1798
    if (u->rtpoll_item) {
 
1799
        pa_rtpoll_item_free(u->rtpoll_item);
 
1800
        u->rtpoll_item = NULL;
 
1801
    }
 
1802
 
 
1803
    if (u->rtpoll) {
 
1804
        pa_thread_mq_done(&u->thread_mq);
 
1805
        pa_rtpoll_free(u->rtpoll);
 
1806
        u->rtpoll = NULL;
 
1807
    }
 
1808
 
 
1809
    if (u->transport) {
 
1810
        transport_release(u);
 
1811
        /* Do not set transport pointer to NULL. When failing to switch
 
1812
         * profile NULL u->transport would assert. */
 
1813
    }
 
1814
 
 
1815
    if (u->sink) {
 
1816
        pa_sink_unref(u->sink);
 
1817
        u->sink = NULL;
 
1818
    }
 
1819
 
 
1820
    if (u->source) {
 
1821
        pa_source_unref(u->source);
 
1822
        u->source = NULL;
 
1823
    }
 
1824
 
 
1825
    if (u->read_smoother) {
 
1826
        pa_smoother_free(u->read_smoother);
 
1827
        u->read_smoother = NULL;
 
1828
    }
 
1829
}
 
1830
 
 
1831
/* Run from main thread */
 
1832
static char *cleanup_name(const char *name) {
 
1833
    char *t, *s, *d;
 
1834
    bool space = false;
 
1835
 
 
1836
    pa_assert(name);
 
1837
 
 
1838
    while ((*name >= 1 && *name <= 32) || *name >= 127)
 
1839
        name++;
 
1840
 
 
1841
    t = pa_xstrdup(name);
 
1842
 
 
1843
    for (s = d = t; *s; s++) {
 
1844
 
 
1845
        if (*s <= 32 || *s >= 127 || *s == '_') {
 
1846
            space = true;
 
1847
            continue;
 
1848
        }
 
1849
 
 
1850
        if (space) {
 
1851
            *(d++) = ' ';
 
1852
            space = false;
 
1853
        }
 
1854
 
 
1855
        *(d++) = *s;
 
1856
    }
 
1857
 
 
1858
    *d = 0;
 
1859
 
 
1860
    return t;
 
1861
}
 
1862
 
 
1863
/* Run from main thread */
 
1864
static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
 
1865
    pa_available_t result = PA_AVAILABLE_NO;
 
1866
    unsigned i;
 
1867
 
 
1868
    pa_assert(u);
 
1869
    pa_assert(u->device);
 
1870
 
 
1871
    for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
 
1872
        pa_bluetooth_transport *transport;
 
1873
 
 
1874
        if (!(get_profile_direction(i) & direction))
 
1875
            continue;
 
1876
 
 
1877
        if (!(transport = u->device->transports[i]))
 
1878
            continue;
 
1879
 
 
1880
        switch(transport->state) {
 
1881
            case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
 
1882
                continue;
 
1883
 
 
1884
            case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
 
1885
                if (result == PA_AVAILABLE_NO)
 
1886
                    result = PA_AVAILABLE_UNKNOWN;
 
1887
 
 
1888
                break;
 
1889
 
 
1890
            case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
 
1891
                return PA_AVAILABLE_YES;
 
1892
        }
 
1893
    }
 
1894
 
 
1895
    return result;
 
1896
}
 
1897
 
 
1898
/* Run from main thread */
 
1899
static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
 
1900
    switch (state) {
 
1901
        case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
 
1902
            return PA_AVAILABLE_NO;
 
1903
        case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
 
1904
            return PA_AVAILABLE_YES;
 
1905
        default:
 
1906
            return PA_AVAILABLE_UNKNOWN;
 
1907
    }
 
1908
}
 
1909
 
 
1910
/* Run from main thread */
 
1911
static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
 
1912
    pa_device_port *port;
 
1913
    pa_device_port_new_data port_data;
 
1914
    const char *name_prefix, *input_description, *output_description;
 
1915
 
 
1916
    pa_assert(u);
 
1917
    pa_assert(ports);
 
1918
    pa_assert(u->device);
 
1919
 
 
1920
    name_prefix = "unknown";
 
1921
    input_description = _("Bluetooth Input");
 
1922
    output_description = _("Bluetooth Output");
 
1923
 
 
1924
    switch (form_factor_from_class(u->device->class_of_device)) {
 
1925
        case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
 
1926
            name_prefix = "headset";
 
1927
            input_description = output_description = _("Headset");
 
1928
            break;
 
1929
 
 
1930
        case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
 
1931
            name_prefix = "handsfree";
 
1932
            input_description = output_description = _("Handsfree");
 
1933
            break;
 
1934
 
 
1935
        case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
 
1936
            name_prefix = "microphone";
 
1937
            input_description = _("Microphone");
 
1938
            output_description = _("Bluetooth Output");
 
1939
            break;
 
1940
 
 
1941
        case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
 
1942
            name_prefix = "speaker";
 
1943
            input_description = _("Bluetooth Input");
 
1944
            output_description = _("Speaker");
 
1945
            break;
 
1946
 
 
1947
        case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
 
1948
            name_prefix = "headphone";
 
1949
            input_description = _("Bluetooth Input");
 
1950
            output_description = _("Headphone");
 
1951
            break;
 
1952
 
 
1953
        case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
 
1954
            name_prefix = "portable";
 
1955
            input_description = output_description = _("Portable");
 
1956
            break;
 
1957
 
 
1958
        case PA_BLUETOOTH_FORM_FACTOR_CAR:
 
1959
            name_prefix = "car";
 
1960
            input_description = output_description = _("Car");
 
1961
            break;
 
1962
 
 
1963
        case PA_BLUETOOTH_FORM_FACTOR_HIFI:
 
1964
            name_prefix = "hifi";
 
1965
            input_description = output_description = _("HiFi");
 
1966
            break;
 
1967
 
 
1968
        case PA_BLUETOOTH_FORM_FACTOR_PHONE:
 
1969
            name_prefix = "phone";
 
1970
            input_description = output_description = _("Phone");
 
1971
            break;
 
1972
 
 
1973
        case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
 
1974
            name_prefix = "unknown";
 
1975
            input_description = _("Bluetooth Input");
 
1976
            output_description = _("Bluetooth Output");
 
1977
            break;
 
1978
    }
 
1979
 
 
1980
    u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
 
1981
    pa_device_port_new_data_init(&port_data);
 
1982
    pa_device_port_new_data_set_name(&port_data, u->output_port_name);
 
1983
    pa_device_port_new_data_set_description(&port_data, output_description);
 
1984
    pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
 
1985
    pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
 
1986
    pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
 
1987
    pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
 
1988
    pa_device_port_new_data_done(&port_data);
 
1989
 
 
1990
    u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
 
1991
    pa_device_port_new_data_init(&port_data);
 
1992
    pa_device_port_new_data_set_name(&port_data, u->input_port_name);
 
1993
    pa_device_port_new_data_set_description(&port_data, input_description);
 
1994
    pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
 
1995
    pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
 
1996
    pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
 
1997
    pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
 
1998
    pa_device_port_new_data_done(&port_data);
 
1999
}
 
2000
 
 
2001
/* Run from main thread */
 
2002
static pa_card_profile *create_card_profile(struct userdata *u, const char *uuid, pa_hashmap *ports) {
 
2003
    pa_device_port *input_port, *output_port;
 
2004
    pa_card_profile *cp = NULL;
 
2005
    pa_bluetooth_profile_t *p;
 
2006
 
 
2007
    pa_assert(u->input_port_name);
 
2008
    pa_assert(u->output_port_name);
 
2009
    pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
 
2010
    pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
 
2011
 
 
2012
    if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
 
2013
        cp = pa_card_profile_new("a2dp_sink", _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
 
2014
        cp->priority = 10;
 
2015
        cp->n_sinks = 1;
 
2016
        cp->n_sources = 0;
 
2017
        cp->max_sink_channels = 2;
 
2018
        cp->max_source_channels = 0;
 
2019
        pa_hashmap_put(output_port->profiles, cp->name, cp);
 
2020
 
 
2021
        p = PA_CARD_PROFILE_DATA(cp);
 
2022
        *p = PA_BLUETOOTH_PROFILE_A2DP_SINK;
 
2023
    } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
 
2024
        cp = pa_card_profile_new("a2dp_source", _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
 
2025
        cp->priority = 10;
 
2026
        cp->n_sinks = 0;
 
2027
        cp->n_sources = 1;
 
2028
        cp->max_sink_channels = 0;
 
2029
        cp->max_source_channels = 2;
 
2030
        pa_hashmap_put(input_port->profiles, cp->name, cp);
 
2031
 
 
2032
        p = PA_CARD_PROFILE_DATA(cp);
 
2033
        *p = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
 
2034
    } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_HS) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF)) {
 
2035
        cp = pa_card_profile_new("headset_head_unit", _("Headset Head Unit (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
 
2036
        cp->priority = 20;
 
2037
        cp->n_sinks = 1;
 
2038
        cp->n_sources = 1;
 
2039
        cp->max_sink_channels = 1;
 
2040
        cp->max_source_channels = 1;
 
2041
        pa_hashmap_put(input_port->profiles, cp->name, cp);
 
2042
        pa_hashmap_put(output_port->profiles, cp->name, cp);
 
2043
 
 
2044
        p = PA_CARD_PROFILE_DATA(cp);
 
2045
        *p = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
 
2046
    } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG)) {
 
2047
        cp = pa_card_profile_new("headset_audio_gateway", _("Headset Audio Gateway (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
 
2048
        cp->priority = 20;
 
2049
        cp->n_sinks = 1;
 
2050
        cp->n_sources = 1;
 
2051
        cp->max_sink_channels = 1;
 
2052
        cp->max_source_channels = 1;
 
2053
        pa_hashmap_put(input_port->profiles, cp->name, cp);
 
2054
        pa_hashmap_put(output_port->profiles, cp->name, cp);
 
2055
 
 
2056
        p = PA_CARD_PROFILE_DATA(cp);
 
2057
        *p = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
 
2058
    }
 
2059
 
 
2060
    if (cp) {
 
2061
        if (u->device->transports[*p])
 
2062
            cp->available = transport_state_to_availability(u->device->transports[*p]->state);
 
2063
        else
 
2064
            cp->available = PA_AVAILABLE_NO;
 
2065
    }
 
2066
 
 
2067
    return cp;
 
2068
}
 
2069
 
 
2070
/* Run from main thread */
 
2071
static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
 
2072
    struct userdata *u;
 
2073
    pa_bluetooth_profile_t *p;
 
2074
 
 
2075
    pa_assert(c);
 
2076
    pa_assert(new_profile);
 
2077
    pa_assert_se(u = c->userdata);
 
2078
 
 
2079
    p = PA_CARD_PROFILE_DATA(new_profile);
 
2080
 
 
2081
    pa_log_debug("Setting new profile %s for card (current %s)",
 
2082
                 pa_bluetooth_profile_to_string(*p),
 
2083
                 pa_bluetooth_profile_to_string(u->profile));
 
2084
 
 
2085
    if (*p != PA_BLUETOOTH_PROFILE_OFF) {
 
2086
        const pa_bluetooth_device *d = u->device;
 
2087
 
 
2088
        if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
 
2089
            pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
 
2090
            return -PA_ERR_IO;
 
2091
        }
 
2092
    }
 
2093
 
 
2094
    stop_thread(u);
 
2095
 
 
2096
    u->profile = *p;
 
2097
 
 
2098
    if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
 
2099
        if (init_profile(u) < 0)
 
2100
            goto off;
 
2101
 
 
2102
    if (u->sink || u->source)
 
2103
        if (start_thread(u) < 0)
 
2104
            goto off;
 
2105
 
 
2106
    return 0;
 
2107
 
 
2108
off:
 
2109
    stop_thread(u);
 
2110
 
 
2111
    pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
 
2112
 
 
2113
    return -PA_ERR_IO;
 
2114
}
 
2115
 
 
2116
/* Run from main thread */
 
2117
static int add_card(struct userdata *u) {
 
2118
    const pa_bluetooth_device *d;
 
2119
    pa_card_new_data data;
 
2120
    char *alias;
 
2121
    pa_bluetooth_form_factor_t ff;
 
2122
    pa_card_profile *cp;
 
2123
    pa_bluetooth_profile_t *p;
 
2124
    const char *uuid;
 
2125
    void *state;
 
2126
    const char *default_profile;
 
2127
 
 
2128
    pa_assert(u);
 
2129
    pa_assert(u->device);
 
2130
 
 
2131
    d = u->device;
 
2132
 
 
2133
    pa_card_new_data_init(&data);
 
2134
    data.driver = __FILE__;
 
2135
    data.module = u->module;
 
2136
 
 
2137
    alias = cleanup_name(d->alias);
 
2138
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
 
2139
    pa_xfree(alias);
 
2140
 
 
2141
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
 
2142
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
 
2143
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
 
2144
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
 
2145
 
 
2146
    if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
 
2147
        pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
 
2148
 
 
2149
    pa_proplist_sets(data.proplist, "bluez.path", d->path);
 
2150
    pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
 
2151
    pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
 
2152
    data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
 
2153
    data.namereg_fail = false;
 
2154
 
 
2155
    create_card_ports(u, data.ports);
 
2156
 
 
2157
    PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
 
2158
        cp = create_card_profile(u, uuid, data.ports);
 
2159
 
 
2160
        if (!cp)
 
2161
            continue;
 
2162
 
 
2163
        if (pa_hashmap_get(data.profiles, cp->name)) {
 
2164
            pa_card_profile_free(cp);
 
2165
            continue;
 
2166
        }
 
2167
 
 
2168
        pa_hashmap_put(data.profiles, cp->name, cp);
 
2169
    }
 
2170
 
 
2171
    pa_assert(!pa_hashmap_isempty(data.profiles));
 
2172
 
 
2173
    cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
 
2174
    cp->available = PA_AVAILABLE_YES;
 
2175
    p = PA_CARD_PROFILE_DATA(cp);
 
2176
    *p = PA_BLUETOOTH_PROFILE_OFF;
 
2177
    pa_hashmap_put(data.profiles, cp->name, cp);
 
2178
 
 
2179
    if ((default_profile = pa_modargs_get_value(u->modargs, "profile", NULL))) {
 
2180
        if (pa_hashmap_get(data.profiles, default_profile)) {
 
2181
            pa_card_new_data_set_profile(&data, default_profile);
 
2182
            pa_log_debug("Using %s profile as default", default_profile);
 
2183
            u->default_profile = pa_xstrdup(default_profile);
 
2184
        }
 
2185
        else
 
2186
            pa_log_warn("Profile '%s' not valid or not supported by device.", default_profile);
 
2187
    }
 
2188
 
 
2189
    u->card = pa_card_new(u->core, &data);
 
2190
    pa_card_new_data_done(&data);
 
2191
    if (!u->card) {
 
2192
        pa_log("Failed to allocate card.");
 
2193
        return -1;
 
2194
    }
 
2195
 
 
2196
    u->card->userdata = u;
 
2197
    u->card->set_profile = set_profile_cb;
 
2198
 
 
2199
    p = PA_CARD_PROFILE_DATA(u->card->active_profile);
 
2200
 
 
2201
    if (*p != PA_BLUETOOTH_PROFILE_OFF && (!d->transports[*p] ||
 
2202
                              d->transports[*p]->state == PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)) {
 
2203
        pa_log_warn("Default profile not connected, selecting off profile");
 
2204
        u->card->active_profile = pa_hashmap_get(u->card->profiles, "off");
 
2205
        u->card->save_profile = false;
 
2206
    }
 
2207
    else {
 
2208
        pa_xfree(u->default_profile);
 
2209
        u->default_profile = NULL;
 
2210
    }
 
2211
 
 
2212
    p = PA_CARD_PROFILE_DATA(u->card->active_profile);
 
2213
    u->profile = *p;
 
2214
 
 
2215
    pa_log_debug("Created card (current profile %s)",
 
2216
                 pa_bluetooth_profile_to_string(u->profile));
 
2217
 
 
2218
    return 0;
 
2219
}
 
2220
 
 
2221
/* Run from main thread */
 
2222
static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
 
2223
    bool acquire = false;
 
2224
    bool release = false;
 
2225
    pa_card_profile *cp;
 
2226
    pa_device_port *port;
 
2227
 
 
2228
    pa_assert(u);
 
2229
    pa_assert(t);
 
2230
    pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
 
2231
 
 
2232
    pa_log_debug("State of transport for profile %s changed to %s",
 
2233
                 pa_bluetooth_profile_to_string(t->profile),
 
2234
                 pa_bluetooth_transport_state_to_string(t->state));
 
2235
 
 
2236
    pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
 
2237
 
 
2238
    /* Update port availability */
 
2239
    pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
 
2240
    pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
 
2241
    pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
 
2242
    pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
 
2243
 
 
2244
    /* Acquire or release transport as needed */
 
2245
    acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
 
2246
    release = (t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
 
2247
 
 
2248
    if (acquire && transport_acquire(u, true) >= 0) {
 
2249
 
 
2250
        pa_log_debug("Acquiring transport for profile %s",
 
2251
                     pa_bluetooth_profile_to_string(t->profile));
 
2252
 
 
2253
        if (u->source) {
 
2254
            pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
 
2255
 
 
2256
            /* We remove the IDLE suspend cause, because otherwise
 
2257
             * module-loopback doesn't uncork its streams. FIXME: Messing with
 
2258
             * the IDLE suspend cause here is wrong, the correct way to handle
 
2259
             * this would probably be to uncork the loopback streams not only
 
2260
             * when the other end is unsuspended, but also when the other end's
 
2261
             * suspend cause changes to IDLE only (currently there's no
 
2262
             * notification mechanism for suspend cause changes, though). */
 
2263
            pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
 
2264
        }
 
2265
 
 
2266
        if (u->sink) {
 
2267
            pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
 
2268
 
 
2269
            /* FIXME: See the previous comment. */
 
2270
            pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
 
2271
        }
 
2272
    }
 
2273
 
 
2274
    if (release && u->transport_acquired) {
 
2275
        /* FIXME: this release is racy, since the audio stream might have
 
2276
         * been set up again in the meantime (but not processed yet by PA).
 
2277
         * BlueZ should probably release the transport automatically, and in
 
2278
         * that case we would just mark the transport as released */
 
2279
 
 
2280
        pa_log_debug("Releasing transport for profile %s",
 
2281
                     pa_bluetooth_profile_to_string(t->profile));
 
2282
 
 
2283
        /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
 
2284
        if (u->source) {
 
2285
            pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
 
2286
            pa_source_suspend(u->source, true, PA_SUSPEND_USER);
 
2287
        }
 
2288
 
 
2289
        if (u->sink) {
 
2290
            pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
 
2291
            pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
 
2292
        }
 
2293
    }
 
2294
}
 
2295
 
 
2296
/* Run from main thread */
 
2297
static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
 
2298
    pa_assert(d);
 
2299
    pa_assert(u);
 
2300
 
 
2301
    if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
 
2302
        return PA_HOOK_OK;
 
2303
 
 
2304
    pa_log_debug("Unloading module for device %s", d->path);
 
2305
    pa_module_unload(u->core, u->module, true);
 
2306
 
 
2307
    return PA_HOOK_OK;
 
2308
}
 
2309
 
 
2310
static void set_default_profile_cb(pa_mainloop_api *api, pa_defer_event *e, void *user_data) {
 
2311
    struct userdata *u = user_data;
 
2312
 
 
2313
    pa_assert(u);
 
2314
 
 
2315
    if (!u->default_profile)
 
2316
        return;
 
2317
 
 
2318
    pa_log_debug("Setting default profile %s", u->default_profile);
 
2319
 
 
2320
    pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, u->default_profile), false) >= 0);
 
2321
    pa_xfree(u->default_profile);
 
2322
    u->default_profile = NULL;
 
2323
 
 
2324
    api->defer_enable(e, 0);
 
2325
}
 
2326
 
 
2327
/* Run from main thread */
 
2328
static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
 
2329
    pa_assert(t);
 
2330
    pa_assert(u);
 
2331
 
 
2332
    pa_log_debug("State of transport for profile %s has changed to %s",
 
2333
                 pa_bluetooth_profile_to_string(t->profile),
 
2334
                 pa_bluetooth_transport_state_to_string(t->state));
 
2335
 
 
2336
    if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT && t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
 
2337
        pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "headset_head_unit"), false) >= 0);
 
2338
 
 
2339
    else if (u->profile == PA_BLUETOOTH_PROFILE_OFF && pa_bluetooth_device_any_transport_connected(u->device) && u->default_profile)
 
2340
        u->core->mainloop->defer_enable(u->set_default_profile_event, 1);
 
2341
 
 
2342
    else if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
 
2343
        pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
 
2344
 
 
2345
    if (t->device == u->device)
 
2346
        handle_transport_state_change(u, t);
 
2347
 
 
2348
    return PA_HOOK_OK;
 
2349
}
 
2350
 
 
2351
static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
 
2352
    pa_volume_t volume;
 
2353
    pa_cvolume v;
 
2354
    uint16_t gain;
 
2355
 
 
2356
    pa_assert(t);
 
2357
    pa_assert(u);
 
2358
 
 
2359
    if (t != u->transport)
 
2360
      return PA_HOOK_OK;
 
2361
 
 
2362
    gain = t->speaker_gain;
 
2363
    volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
 
2364
 
 
2365
    /* increment volume by one to correct rounding errors */
 
2366
    if (volume < PA_VOLUME_NORM)
 
2367
        volume++;
 
2368
 
 
2369
    pa_cvolume_set(&v, u->sample_spec.channels, volume);
 
2370
    pa_sink_volume_changed(u->sink, &v);
 
2371
 
 
2372
    return PA_HOOK_OK;
 
2373
}
 
2374
 
 
2375
static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
 
2376
    pa_volume_t volume;
 
2377
    pa_cvolume v;
 
2378
    uint16_t gain;
 
2379
 
 
2380
    pa_assert(t);
 
2381
    pa_assert(u);
 
2382
 
 
2383
    if (t != u->transport)
 
2384
      return PA_HOOK_OK;
 
2385
 
 
2386
    gain = t->microphone_gain;
 
2387
    volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
 
2388
 
 
2389
    /* increment volume by one to correct rounding errors */
 
2390
    if (volume < PA_VOLUME_NORM)
 
2391
        volume++;
 
2392
 
 
2393
    pa_cvolume_set(&v, u->sample_spec.channels, volume);
 
2394
    pa_source_volume_changed(u->source, &v);
 
2395
 
 
2396
    return PA_HOOK_OK;
 
2397
}
 
2398
 
 
2399
static pa_hook_result_t sink_state_changed_cb(pa_core *c, pa_sink *s, struct userdata *u) {
 
2400
    pa_assert(c);
 
2401
    pa_sink_assert_ref(s);
 
2402
    pa_assert(u);
 
2403
 
 
2404
    pa_log_debug("Sink %s state has changed", s->name);
 
2405
 
 
2406
    if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_sink)
 
2407
        return PA_HOOK_OK;
 
2408
 
 
2409
    sco_over_pcm_state_update(u, true);
 
2410
 
 
2411
    return PA_HOOK_OK;
 
2412
}
 
2413
 
 
2414
static pa_hook_result_t source_state_changed_cb(pa_core *c, pa_source *s, struct userdata *u) {
 
2415
    pa_assert(c);
 
2416
    pa_source_assert_ref(s);
 
2417
    pa_assert(u);
 
2418
 
 
2419
    pa_log_debug("Source %s state has changed", s->name);
 
2420
 
 
2421
    if (!USE_SCO_OVER_PCM(u) || s != u->hsp.sco_source)
 
2422
        return PA_HOOK_OK;
 
2423
 
 
2424
    sco_over_pcm_state_update(u, true);
 
2425
 
 
2426
    return PA_HOOK_OK;
 
2427
}
 
2428
 
 
2429
/* Run from main thread context */
 
2430
static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
 
2431
    struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
 
2432
    struct userdata *u = m->card->userdata;
 
2433
 
 
2434
    switch (code) {
 
2435
        case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
 
2436
            if (m->card->module->unload_requested)
 
2437
                break;
 
2438
 
 
2439
            pa_log_debug("Switching the profile to off due to IO thread failure.");
 
2440
            pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
 
2441
            break;
 
2442
        case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
 
2443
            pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
 
2444
            break;
 
2445
    }
 
2446
 
 
2447
    return 0;
 
2448
}
 
2449
 
 
2450
int pa__init(pa_module* m) {
 
2451
    struct userdata *u;
 
2452
    const char *path;
 
2453
    pa_modargs *ma;
 
2454
 
 
2455
    pa_assert(m);
 
2456
 
 
2457
    m->userdata = u = pa_xnew0(struct userdata, 1);
 
2458
    u->module = m;
 
2459
    u->core = m->core;
 
2460
 
 
2461
    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
 
2462
        pa_log_error("Failed to parse module arguments");
 
2463
        goto fail;
 
2464
    }
 
2465
 
 
2466
    if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
 
2467
        pa_log_error("Failed to get device path from module arguments");
 
2468
        goto fail;
 
2469
    }
 
2470
 
 
2471
      if (pa_modargs_get_value(ma, "sco_sink", NULL) &&
 
2472
        !(u->hsp.sco_sink = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_sink", NULL), PA_NAMEREG_SINK))) {
 
2473
        pa_log("SCO sink not found");
 
2474
        goto fail;
 
2475
    }
 
2476
 
 
2477
    if (pa_modargs_get_value(ma, "sco_source", NULL) &&
 
2478
        !(u->hsp.sco_source = pa_namereg_get(m->core, pa_modargs_get_value(ma, "sco_source", NULL), PA_NAMEREG_SOURCE))) {
 
2479
        pa_log("SCO source not found");
 
2480
        goto fail;
 
2481
    }
 
2482
 
 
2483
    if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
 
2484
        pa_bluetooth_discovery_ref(u->discovery);
 
2485
    else {
 
2486
        pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
 
2487
        goto fail;
 
2488
    }
 
2489
 
 
2490
    if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
 
2491
        pa_log_error("%s is unknown", path);
 
2492
        goto fail;
 
2493
    }
 
2494
 
 
2495
    u->modargs = ma;
 
2496
 
 
2497
    u->device_connection_changed_slot =
 
2498
        pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
 
2499
                        PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
 
2500
 
 
2501
    u->transport_state_changed_slot =
 
2502
        pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
 
2503
                        PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
 
2504
 
 
2505
    u->transport_speaker_gain_changed_slot =
 
2506
        pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
 
2507
 
 
2508
    u->transport_microphone_gain_changed_slot =
 
2509
        pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
 
2510
 
 
2511
    u->sink_state_changed_slot =
 
2512
        pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED],
 
2513
                        PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_cb, u);
 
2514
 
 
2515
    u->source_state_changed_slot =
 
2516
        pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED],
 
2517
                        PA_HOOK_NORMAL, (pa_hook_cb_t) source_state_changed_cb, u);
 
2518
 
 
2519
    u->sco_sink_proplist_changed_slot =
 
2520
        pa_hook_connect(&u->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED],
 
2521
                        PA_HOOK_NORMAL, (pa_hook_cb_t) update_allow_release_cb, u);
 
2522
 
 
2523
    if (add_card(u) < 0)
 
2524
        goto fail;
 
2525
 
 
2526
    if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
 
2527
        goto fail;
 
2528
 
 
2529
    u->set_default_profile_event = u->core->mainloop->defer_new(u->core->mainloop, set_default_profile_cb, u);
 
2530
    u->core->mainloop->defer_enable(u->set_default_profile_event, 0);
 
2531
 
 
2532
    u->msg->parent.process_msg = device_process_msg;
 
2533
    u->msg->card = u->card;
 
2534
 
 
2535
    if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
 
2536
        if (init_profile(u) < 0)
 
2537
            goto off;
 
2538
 
 
2539
    if (u->sink || u->source)
 
2540
        if (start_thread(u) < 0)
 
2541
            goto off;
 
2542
 
 
2543
    return 0;
 
2544
 
 
2545
off:
 
2546
    stop_thread(u);
 
2547
 
 
2548
    pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
 
2549
 
 
2550
    return 0;
 
2551
 
 
2552
fail:
 
2553
 
 
2554
    if (ma)
 
2555
        pa_modargs_free(ma);
 
2556
 
 
2557
    pa__done(m);
 
2558
 
 
2559
    return -1;
 
2560
}
 
2561
 
 
2562
void pa__done(pa_module *m) {
 
2563
    struct userdata *u;
 
2564
 
 
2565
    pa_assert(m);
 
2566
 
 
2567
    if (!(u = m->userdata))
 
2568
        return;
 
2569
 
 
2570
    stop_thread(u);
 
2571
 
 
2572
    if (u->device_connection_changed_slot)
 
2573
        pa_hook_slot_free(u->device_connection_changed_slot);
 
2574
 
 
2575
    if (u->transport_state_changed_slot)
 
2576
        pa_hook_slot_free(u->transport_state_changed_slot);
 
2577
 
 
2578
    if (u->transport_speaker_gain_changed_slot)
 
2579
        pa_hook_slot_free(u->transport_speaker_gain_changed_slot);
 
2580
 
 
2581
    if (u->transport_microphone_gain_changed_slot)
 
2582
        pa_hook_slot_free(u->transport_microphone_gain_changed_slot);
 
2583
 
 
2584
    if (u->sink_state_changed_slot)
 
2585
        pa_hook_slot_free(u->sink_state_changed_slot);
 
2586
 
 
2587
    if (u->source_state_changed_slot)
 
2588
        pa_hook_slot_free(u->source_state_changed_slot);
 
2589
 
 
2590
    if (u->sco_sink_proplist_changed_slot)
 
2591
        pa_hook_slot_free(u->sco_sink_proplist_changed_slot);
 
2592
 
 
2593
    if (u->sbc_info.buffer)
 
2594
        pa_xfree(u->sbc_info.buffer);
 
2595
 
 
2596
    if (u->sbc_info.sbc_initialized)
 
2597
        sbc_finish(&u->sbc_info.sbc);
 
2598
 
 
2599
    if (u->msg)
 
2600
        pa_xfree(u->msg);
 
2601
 
 
2602
    if (u->card)
 
2603
        pa_card_free(u->card);
 
2604
 
 
2605
    if (u->discovery)
 
2606
        pa_bluetooth_discovery_unref(u->discovery);
 
2607
 
 
2608
    pa_xfree(u->output_port_name);
 
2609
    pa_xfree(u->input_port_name);
 
2610
 
 
2611
    if (u->modargs)
 
2612
        pa_modargs_free(u->modargs);
 
2613
 
 
2614
    if (u->default_profile)
 
2615
        pa_xfree(u->default_profile);
 
2616
 
 
2617
    if (u->set_default_profile_event)
 
2618
        u->core->mainloop->defer_free(u->set_default_profile_event);
 
2619
 
 
2620
    pa_xfree(u);
 
2621
}
 
2622
 
 
2623
int pa__get_n_used(pa_module *m) {
 
2624
    struct userdata *u;
 
2625
 
 
2626
    pa_assert(m);
 
2627
    pa_assert_se(u = m->userdata);
 
2628
 
 
2629
    return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);
 
2630
}