summaryrefslogtreecommitdiff
path: root/src/modules/bluetooth/bt-codec-msbc.c
blob: 7df837e760bff7daa22d49daeaba044179176fa6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/***
  This file is part of PulseAudio.

  PulseAudio is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the
  License, or (at your option) any later version.

  PulseAudio is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
***/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <pulsecore/core.h>
#include "bt-codec-api.h"

#include "bt-codec-msbc.h"
#include <sbc/sbc.h>

typedef struct sbc_info {
    sbc_t sbc;                           /* Codec data */
    size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
    uint8_t msbc_seq:2;                  /* mSBC packet sequence number, 2 bits only */

    uint16_t msbc_push_offset;
    uint8_t input_buffer[MSBC_PACKET_SIZE];                        /* Codec transfer buffer */

    pa_sample_spec sample_spec;
} sbc_info_t;

static void *init(bool for_encoding, bool for_backchannel, const uint8_t *config_buffer, uint8_t config_size, pa_sample_spec *sample_spec, pa_core *core) {
    struct sbc_info *info;
    int ret;

    info = pa_xnew0(struct sbc_info, 1);

    ret = sbc_init_msbc(&info->sbc, 0);
    if (ret != 0) {
        pa_xfree(info);
        pa_log_error("mSBC initialization failed: %d", ret);
        return NULL;
    }

    info->sbc.endian = SBC_LE;

    info->codesize = sbc_get_codesize(&info->sbc);
    info->frame_length = sbc_get_frame_length(&info->sbc);
    pa_log_info("mSBC codesize=%d, frame_length=%d",
                (int)info->codesize,
                (int)info->frame_length);

    info->sample_spec.format = PA_SAMPLE_S16LE;
    info->sample_spec.channels = 1;
    info->sample_spec.rate = 16000;

    pa_assert(pa_frame_aligned(info->codesize, &info->sample_spec));

    *sample_spec = info->sample_spec;

    return info;
}

static void deinit(void *codec_info) {
    struct sbc_info *sbc_info = (struct sbc_info *) codec_info;

    sbc_finish(&sbc_info->sbc);
    pa_xfree(sbc_info);
}

static int reset(void *codec_info) {
    struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
    int ret;

    /* SBC library release 1.5 has a bug in sbc_reinit_msbc:
     * it forgets to restore priv->msbc flag after clearing priv content.
     * This causes decoder assertion on first call since codesize would be
     * different from expected for mSBC configuration.
     *
     * Do not use sbc_reinit_msbc until it is fixed.
     */

    sbc_finish(&sbc_info->sbc);
    ret = sbc_init_msbc(&sbc_info->sbc, 0);
    if (ret != 0) {
        pa_xfree(sbc_info);
        pa_log_error("mSBC initialization failed: %d", ret);
        return -1;
    }

    sbc_info->sbc.endian = SBC_LE;

    sbc_info->msbc_seq = 0;
    sbc_info->msbc_push_offset = 0;

    return 0;
}

static size_t get_read_block_size(void *codec_info, size_t link_mtu) {
    struct sbc_info *info = (struct sbc_info *) codec_info;
    size_t block_size = info->codesize;

    /* this never happens as sbc_info->codesize is always frame-aligned */
    if (!pa_frame_aligned(block_size, &info->sample_spec)) {
        pa_log_debug("Got invalid block size: %lu, rounding down", block_size);
        block_size = pa_frame_align(block_size, &info->sample_spec);
    }

    return block_size;
}

static size_t get_write_block_size(void *codec_info, size_t link_mtu) {
    struct sbc_info *info = (struct sbc_info *) codec_info;
    return info->codesize;
}

static size_t get_encoded_block_size(void *codec_info, size_t input_size) {
    struct sbc_info *info = (struct sbc_info *) codec_info;
    size_t encoded_size = MSBC_PACKET_SIZE;

    /* input size should be aligned to write block size */
    pa_assert_fp(input_size % info->codesize == 0);

    return encoded_size * (input_size / info->codesize);
}

static size_t reduce_encoder_bitrate(void *codec_info, size_t write_link_mtu) {
    return 0;
}

static size_t increase_encoder_bitrate(void *codec_info, size_t write_link_mtu) {
    return 0;
}

static size_t encode_buffer(void *codec_info, uint32_t timestamp, const uint8_t *input_buffer, size_t input_size, uint8_t *output_buffer, size_t output_size, size_t *processed) {
    struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
    struct msbc_frame *frame;
    uint8_t seq;
    ssize_t encoded;
    ssize_t written;

    pa_assert(input_size == sbc_info->codesize);

    /* must be room to render packet */
    pa_assert(output_size >= MSBC_PACKET_SIZE);

    frame = (struct msbc_frame *)output_buffer;
    seq = sbc_info->msbc_seq++;
    frame->hdr.id0 = MSBC_H2_ID0;
    frame->hdr.id1.s.id1 = MSBC_H2_ID1;
    if (seq & 0x02)
        frame->hdr.id1.s.sn1 = 3;
    else
        frame->hdr.id1.s.sn1 = 0;
    if (seq & 0x01)
        frame->hdr.id1.s.sn0 = 3;
    else
        frame->hdr.id1.s.sn0 = 0;

    encoded = sbc_encode(&sbc_info->sbc,
                         input_buffer, input_size,
                         frame->payload, MSBC_FRAME_SIZE,
                         &written);

    frame->padding = 0x00;

    if (PA_UNLIKELY(encoded <= 0)) {
        pa_log_error("SBC encoding error (%li) for input size %lu, SBC codesize %lu",
                    (long) encoded, input_size, sbc_get_codesize(&sbc_info->sbc));

        if (encoded < 0) {
            *processed = 0;
            return -1;
        } else {
            *processed = input_size;
            return 0;
        }
    }

    pa_assert_fp((size_t) encoded == sbc_info->codesize);
    pa_assert_fp((size_t) written == sbc_info->frame_length);

    *processed = encoded;

    return MSBC_PACKET_SIZE;
}

static inline bool is_all_zero(const uint8_t *ptr, size_t len) {
    size_t i;

    for (i = 0; i < len; ++i)
        if (ptr[i] != 0)
            return false;

    return true;
}

/*
 * We build a msbc frame up in the sbc_info buffer until we have a whole one
 */
static struct msbc_frame *msbc_find_frame(struct sbc_info *si, ssize_t *len,
                                          const uint8_t *buf, int *pseq)
{
    int i;
    uint8_t *p = si->input_buffer;

    /* skip input if it has all zero bytes
     * this could happen with older kernels inserting all-zero blocks
     * inside otherwise valid mSBC stream */
    if (*len > 0 && is_all_zero(buf, *len))
        *len = 0;

    for (i = 0; i < *len; i++) {
        union msbc_h2_id1 id1;

        if (si->msbc_push_offset == 0) {
            if (buf[i] != MSBC_H2_ID0)
                continue;
        } else if (si->msbc_push_offset == 1) {
            id1.b = buf[i];

            if (id1.s.id1 != MSBC_H2_ID1)
                goto error;
            if (id1.s.sn0 != 3 && id1.s.sn0 != 0)
                goto error;
            if (id1.s.sn1 != 3 && id1.s.sn1 != 0)
                goto error;
        } else if (si->msbc_push_offset == 2) {
            if (buf[i] != MSBC_SYNC_BYTE)
                goto error;
        }
        p[si->msbc_push_offset++] = buf[i];

        if (si->msbc_push_offset == MSBC_PACKET_SIZE) {
            id1.b = p[1];
            *pseq = (id1.s.sn0 & 0x1) | (id1.s.sn1 & 0x2);
            si->msbc_push_offset = 0;
            *len = *len - i;
            return (struct msbc_frame *)p;
        }
        continue;

        error:
        si->msbc_push_offset = 0;
    }
    *len = 0;
    return NULL;
}

static size_t decode_buffer(void *codec_info, const uint8_t *input_buffer, size_t input_size, uint8_t *output_buffer, size_t output_size, size_t *processed) {
    struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
    ssize_t remaining;
    ssize_t decoded;
    size_t written = 0;
    struct msbc_frame *frame;
    int seq;

    remaining = input_size;
    frame = msbc_find_frame(sbc_info, &remaining, input_buffer, &seq);

    /* only process when we have a full frame */
    if (!frame) {
        *processed = input_size - remaining;
        return 0;
    }

    uint8_t lost_packets = (4 + seq - sbc_info->msbc_seq++) % 4;

    if (lost_packets) {
        pa_log_debug("Lost %d input audio packet(s)", lost_packets);
        sbc_info->msbc_seq = seq + 1;
    }

    decoded = sbc_decode(&sbc_info->sbc, frame->payload, MSBC_FRAME_SIZE, output_buffer, output_size, &written);

    /* now we've consumed the sbc_info buffer, start a new one with
     * the partial frame we have */
    if (remaining > 0)
        msbc_find_frame(sbc_info, &remaining, input_buffer + input_size - remaining, &seq);

    pa_assert_fp(remaining == 0);

    if (PA_UNLIKELY(decoded <= 0)) {
        pa_log_error("mSBC decoding error (%li)", (long) decoded);
        pa_silence_memory(output_buffer, sbc_info->codesize, &sbc_info->sample_spec);
        decoded = sbc_info->frame_length;
        written = sbc_info->codesize;
    }

    pa_assert_fp((size_t)decoded == sbc_info->frame_length);
    pa_assert_fp((size_t)written == sbc_info->codesize);

    *processed = input_size - remaining;
    return written;
}

/* Modified SBC codec for HFP Wideband Speech*/
const pa_bt_codec pa_bt_codec_msbc = {
    .name = "mSBC",
    .description = "mSBC",
    .init = init,
    .deinit = deinit,
    .reset = reset,
    .get_read_block_size = get_read_block_size,
    .get_write_block_size = get_write_block_size,
    .get_encoded_block_size = get_encoded_block_size,
    .reduce_encoder_bitrate = reduce_encoder_bitrate,
    .increase_encoder_bitrate = increase_encoder_bitrate,
    .encode_buffer = encode_buffer,
    .decode_buffer = decode_buffer,
};