Coverage Report

Created: 2025-11-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/tta.c
Line
Count
Source
1
/*
2
 * TTA (The Lossless True Audio) decoder
3
 * Copyright (c) 2006 Alex Beregszaszi
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
/**
23
 * @file
24
 * TTA (The Lossless True Audio) decoder
25
 * @see http://www.true-audio.com/
26
 * @see http://tta.corecodec.org/
27
 * @author Alex Beregszaszi
28
 */
29
30
#include <limits.h>
31
32
#include "libavutil/channel_layout.h"
33
#include "libavutil/crc.h"
34
#include "libavutil/intreadwrite.h"
35
#include "libavutil/mem.h"
36
#include "libavutil/opt.h"
37
38
#define BITSTREAM_READER_LE
39
#include "ttadata.h"
40
#include "ttadsp.h"
41
#include "avcodec.h"
42
#include "codec_internal.h"
43
#include "get_bits.h"
44
#include "thread.h"
45
#include "unary.h"
46
47
#define FORMAT_SIMPLE    1
48
435k
#define FORMAT_ENCRYPTED 2
49
50
typedef struct TTAContext {
51
    AVClass *class;
52
    AVCodecContext *avctx;
53
    const AVCRC *crc_table;
54
55
    int format, channels, bps;
56
    unsigned data_length;
57
    int frame_length, last_frame_length;
58
59
    int32_t *decode_buffer;
60
61
    uint8_t crc_pass[8];
62
    uint8_t *pass;
63
    TTAChannel *ch_ctx;
64
    TTADSPContext dsp;
65
} TTAContext;
66
67
static const int64_t tta_channel_layouts[7] = {
68
    AV_CH_LAYOUT_STEREO,
69
    AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY,
70
    AV_CH_LAYOUT_QUAD,
71
    0,
72
    AV_CH_LAYOUT_5POINT1_BACK,
73
    AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER,
74
    AV_CH_LAYOUT_7POINT1_WIDE
75
};
76
77
static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
78
67.6k
{
79
67.6k
    uint32_t crc, CRC;
80
81
67.6k
    CRC = AV_RL32(buf + buf_size);
82
67.6k
    crc = av_crc(s->crc_table, 0xFFFFFFFFU, buf, buf_size);
83
67.6k
    if (CRC != (crc ^ 0xFFFFFFFFU)) {
84
67.2k
        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
85
67.2k
        return AVERROR_INVALIDDATA;
86
67.2k
    }
87
88
454
    return 0;
89
67.6k
}
90
91
static uint64_t tta_check_crc64(uint8_t *pass)
92
0
{
93
0
    uint64_t crc = UINT64_MAX, poly = 0x42F0E1EBA9EA3693U;
94
0
    uint8_t *end = pass + strlen(pass);
95
0
    int i;
96
97
0
    while (pass < end) {
98
0
        crc ^= (uint64_t)*pass++ << 56;
99
0
        for (i = 0; i < 8; i++)
100
0
            crc = (crc << 1) ^ (poly & (((int64_t) crc) >> 63));
101
0
    }
102
103
0
    return crc ^ UINT64_MAX;
104
0
}
105
106
static int allocate_buffers(AVCodecContext *avctx)
107
798
{
108
798
    TTAContext *s = avctx->priv_data;
109
110
798
    if (s->bps < 3) {
111
597
        s->decode_buffer = av_calloc(s->frame_length,
112
597
                                     sizeof(*s->decode_buffer) * s->channels);
113
597
        if (!s->decode_buffer)
114
0
            return AVERROR(ENOMEM);
115
597
    } else
116
201
        s->decode_buffer = NULL;
117
798
    s->ch_ctx = av_malloc_array(avctx->ch_layout.nb_channels, sizeof(*s->ch_ctx));
118
798
    if (!s->ch_ctx)
119
0
        return AVERROR(ENOMEM);
120
121
798
    return 0;
122
798
}
123
124
static av_cold int tta_decode_init(AVCodecContext * avctx)
125
1.20k
{
126
1.20k
    TTAContext *s = avctx->priv_data;
127
1.20k
    GetBitContext gb;
128
1.20k
    int total_frames;
129
1.20k
    int ret;
130
131
1.20k
    s->avctx = avctx;
132
133
    // 22 bytes for a TTA1 header
134
1.20k
    if (avctx->extradata_size < 22)
135
227
        return AVERROR_INVALIDDATA;
136
137
974
    s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
138
974
    ret = init_get_bits8(&gb, avctx->extradata, avctx->extradata_size);
139
974
    if (ret < 0)
140
0
        return ret;
141
142
974
    if (show_bits_long(&gb, 32) == AV_RL32("TTA1")) {
143
        /* signature */
144
899
        skip_bits_long(&gb, 32);
145
146
899
        s->format = get_bits(&gb, 16);
147
899
        if (s->format > 2) {
148
15
            av_log(avctx, AV_LOG_ERROR, "Invalid format\n");
149
15
            return AVERROR_INVALIDDATA;
150
15
        }
151
884
        if (s->format == FORMAT_ENCRYPTED) {
152
1
            if (!s->pass) {
153
1
                av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");
154
1
                return AVERROR(EINVAL);
155
1
            }
156
0
            AV_WL64(s->crc_pass, tta_check_crc64(s->pass));
157
0
        }
158
159
883
        s->channels = get_bits(&gb, 16);
160
161
883
        av_channel_layout_uninit(&avctx->ch_layout);
162
883
        if (s->channels > 1 && s->channels < 9) {
163
256
            av_channel_layout_from_mask(&avctx->ch_layout, tta_channel_layouts[s->channels-2]);
164
256
        }
165
883
        if (avctx->ch_layout.nb_channels == 0) {
166
672
            avctx->ch_layout.order       = AV_CHANNEL_ORDER_UNSPEC;
167
672
            avctx->ch_layout.nb_channels = s->channels;
168
672
        }
169
170
883
        avctx->bits_per_raw_sample = get_bits(&gb, 16);
171
883
        s->bps = (avctx->bits_per_raw_sample + 7) / 8;
172
883
        avctx->sample_rate = get_bits_long(&gb, 32);
173
883
        s->data_length = get_bits_long(&gb, 32);
174
883
        skip_bits_long(&gb, 32); // CRC32 of header
175
176
883
        if (s->channels == 0 || s->channels > 16) {
177
26
            av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
178
26
            return AVERROR_INVALIDDATA;
179
857
        } else if (avctx->sample_rate == 0) {
180
1
            av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");
181
1
            return AVERROR_INVALIDDATA;
182
1
        }
183
184
856
        switch(s->bps) {
185
343
        case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
186
278
        case 2:
187
278
            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
188
278
            break;
189
213
        case 3:
190
213
            avctx->sample_fmt = AV_SAMPLE_FMT_S32;
191
213
            break;
192
        //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
193
22
        default:
194
22
            av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
195
22
            return AVERROR_INVALIDDATA;
196
856
        }
197
198
        // prevent overflow
199
834
        if (avctx->sample_rate > 0x7FFFFFu) {
200
36
            av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
201
36
            return AVERROR(EINVAL);
202
36
        }
203
798
        s->frame_length = 256 * avctx->sample_rate / 245;
204
205
798
        s->last_frame_length = s->data_length % s->frame_length;
206
798
        total_frames = s->data_length / s->frame_length +
207
798
                       (s->last_frame_length ? 1 : 0);
208
209
798
        av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
210
798
            s->format, avctx->ch_layout.nb_channels, avctx->bits_per_coded_sample, avctx->sample_rate,
211
798
            avctx->block_align);
212
798
        av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
213
798
            s->data_length, s->frame_length, s->last_frame_length, total_frames);
214
215
798
        if (s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))) {
216
0
            av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
217
0
            return AVERROR_INVALIDDATA;
218
0
        }
219
798
    } else {
220
75
        av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
221
75
        return AVERROR_INVALIDDATA;
222
75
    }
223
224
798
    ff_ttadsp_init(&s->dsp);
225
226
798
    return allocate_buffers(avctx);
227
974
}
228
229
static int tta_decode_frame(AVCodecContext *avctx, AVFrame *frame,
230
                            int *got_frame_ptr, AVPacket *avpkt)
231
279k
{
232
279k
    const uint8_t *buf = avpkt->data;
233
279k
    int buf_size = avpkt->size;
234
279k
    TTAContext *s = avctx->priv_data;
235
279k
    GetBitContext gb;
236
279k
    int i, ret;
237
279k
    int cur_chan = 0, framelen = s->frame_length;
238
279k
    uint32_t *p;
239
240
279k
    if (avctx->err_recognition & AV_EF_CRCCHECK) {
241
118k
        if (buf_size < 4 ||
242
67.6k
            (tta_check_crc(s, buf, buf_size - 4) && avctx->err_recognition & AV_EF_EXPLODE))
243
51.4k
            return AVERROR_INVALIDDATA;
244
118k
    }
245
246
227k
    if ((ret = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
247
0
        return ret;
248
249
    /* get output buffer */
250
227k
    frame->nb_samples = framelen;
251
227k
    if ((ret = ff_thread_get_buffer(avctx, frame, 0)) < 0)
252
1.15k
        return ret;
253
254
    // decode directly to output buffer for 24-bit sample format
255
226k
    if (s->bps == 3)
256
76.7k
        s->decode_buffer = (int32_t *)frame->data[0];
257
258
    // init per channel states
259
660k
    for (i = 0; i < s->channels; i++) {
260
434k
        TTAFilter *filter = &s->ch_ctx[i].filter;
261
434k
        s->ch_ctx[i].predictor = 0;
262
434k
        ff_tta_filter_init(filter, ff_tta_filter_configs[s->bps-1]);
263
434k
        if (s->format == FORMAT_ENCRYPTED) {
264
0
            int i;
265
0
            for (i = 0; i < 8; i++)
266
0
                filter->qm[i] = sign_extend(s->crc_pass[i], 8);
267
0
        }
268
434k
        ff_tta_rice_init(&s->ch_ctx[i].rice, 10, 10);
269
434k
    }
270
271
226k
    i = 0;
272
64.3M
    for (p = s->decode_buffer; (int32_t*)p < s->decode_buffer + (framelen * s->channels); p++) {
273
64.3M
        int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
274
64.3M
        TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
275
64.3M
        TTARice *rice = &s->ch_ctx[cur_chan].rice;
276
64.3M
        uint32_t unary, depth, k;
277
64.3M
        int32_t value;
278
279
64.3M
        unary = get_unary(&gb, 0, get_bits_left(&gb));
280
281
64.3M
        if (unary == 0) {
282
62.8M
            depth = 0;
283
62.8M
            k = rice->k0;
284
62.8M
        } else {
285
1.45M
            depth = 1;
286
1.45M
            k = rice->k1;
287
1.45M
            unary--;
288
1.45M
        }
289
290
64.3M
        if (get_bits_left(&gb) < k) {
291
148k
            ret = AVERROR_INVALIDDATA;
292
148k
            goto error;
293
148k
        }
294
295
64.1M
        if (k) {
296
2.43M
            if (k > MIN_CACHE_BITS || unary > INT32_MAX >> k) {
297
649
                ret = AVERROR_INVALIDDATA;
298
649
                goto error;
299
649
            }
300
2.43M
            value = (unary << k) + get_bits(&gb, k);
301
2.43M
        } else
302
61.7M
            value = unary;
303
304
        // FIXME: copy paste from original
305
64.1M
        switch (depth) {
306
1.36M
        case 1:
307
1.36M
            rice->sum1 += value - (rice->sum1 >> 4);
308
1.36M
            if (rice->k1 > 0 && rice->sum1 < ff_tta_shift_16[rice->k1])
309
61.6k
                rice->k1--;
310
1.30M
            else if (rice->sum1 > ff_tta_shift_16[rice->k1 + 1])
311
55.6k
                rice->k1++;
312
1.36M
            value += ff_tta_shift_1[rice->k0];
313
64.1M
        default:
314
64.1M
            rice->sum0 += value - (rice->sum0 >> 4);
315
64.1M
            if (rice->k0 > 0 && rice->sum0 < ff_tta_shift_16[rice->k0])
316
241k
                rice->k0--;
317
63.9M
            else if (rice->sum0 > ff_tta_shift_16[rice->k0 + 1])
318
146k
                rice->k0++;
319
64.1M
        }
320
321
        // extract coded value
322
64.1M
        *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
323
324
        // run hybrid filter
325
64.1M
        s->dsp.filter_process(filter->qm, filter->dx, filter->dl, &filter->error, p,
326
64.1M
                              filter->shift, filter->round);
327
328
        // fixed order prediction
329
64.1M
#define PRED(x, k) (int32_t)((((uint64_t)(x) << (k)) - (x)) >> (k))
330
64.1M
        switch (s->bps) {
331
13.2M
        case 1: *p += PRED(*predictor, 4); break;
332
13.0M
        case 2:
333
50.9M
        case 3: *p += PRED(*predictor, 5); break;
334
0
        case 4: *p +=      *predictor;     break;
335
64.1M
        }
336
64.1M
        *predictor = *p;
337
338
        // flip channels
339
64.1M
        if (cur_chan < (s->channels-1))
340
6.54M
            cur_chan++;
341
57.6M
        else {
342
            // decorrelate in case of multiple channels
343
57.6M
            if (s->channels > 1) {
344
1.12M
                int32_t *r = p - 1;
345
7.62M
                for (*p += *r / 2; r > (int32_t*)p - s->channels; r--)
346
6.50M
                    *r = *(r + 1) - (unsigned)*r;
347
1.12M
            }
348
57.6M
            cur_chan = 0;
349
57.6M
            i++;
350
            // check for last frame
351
57.6M
            if (i == s->last_frame_length && get_bits_left(&gb) / 8 == 4) {
352
11.4k
                frame->nb_samples = framelen = s->last_frame_length;
353
11.4k
                break;
354
11.4k
            }
355
57.6M
        }
356
64.1M
    }
357
358
77.1k
    align_get_bits(&gb);
359
77.1k
    if (get_bits_left(&gb) < 32) {
360
3.09k
        ret = AVERROR_INVALIDDATA;
361
3.09k
        goto error;
362
3.09k
    }
363
74.0k
    skip_bits_long(&gb, 32); // frame crc
364
365
    // convert to output buffer
366
74.0k
    switch (s->bps) {
367
51.4k
    case 1: {
368
51.4k
        uint8_t *samples = (uint8_t *)frame->data[0];
369
51.4k
        p = s->decode_buffer;
370
986k
        for (i = 0; i < framelen * s->channels; i++)
371
934k
            samples[i] = p[i] + 0x80;
372
51.4k
        break;
373
0
        }
374
5.84k
    case 2: {
375
5.84k
        int16_t *samples = (int16_t *)frame->data[0];
376
5.84k
        p = s->decode_buffer;
377
2.55M
        for (i = 0; i < framelen * s->channels; i++)
378
2.54M
            samples[i] = p[i];
379
5.84k
        break;
380
0
        }
381
16.7k
    case 3: {
382
        // shift samples for 24-bit sample format
383
16.7k
        int32_t *samples = (int32_t *)frame->data[0];
384
385
1.36M
        for (i = 0; i < framelen * s->channels; i++)
386
1.35M
            samples[i] = samples[i] * 256U;
387
        // reset decode buffer
388
16.7k
        s->decode_buffer = NULL;
389
16.7k
        break;
390
0
        }
391
74.0k
    }
392
393
74.0k
    *got_frame_ptr = 1;
394
395
74.0k
    return buf_size;
396
152k
error:
397
    // reset decode buffer
398
152k
    if (s->bps == 3)
399
60.0k
        s->decode_buffer = NULL;
400
152k
    return ret;
401
74.0k
}
402
403
static av_cold int tta_decode_close(AVCodecContext *avctx)
404
1.20k
{
405
1.20k
    TTAContext *s = avctx->priv_data;
406
407
1.20k
    if (s->bps < 3)
408
950
        av_freep(&s->decode_buffer);
409
1.20k
    s->decode_buffer = NULL;
410
1.20k
    av_freep(&s->ch_ctx);
411
412
1.20k
    return 0;
413
1.20k
}
414
415
#define OFFSET(x) offsetof(TTAContext, x)
416
#define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
417
static const AVOption options[] = {
418
    { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
419
    { NULL },
420
};
421
422
static const AVClass tta_decoder_class = {
423
    .class_name = "TTA Decoder",
424
    .item_name  = av_default_item_name,
425
    .option     = options,
426
    .version    = LIBAVUTIL_VERSION_INT,
427
};
428
429
const FFCodec ff_tta_decoder = {
430
    .p.name         = "tta",
431
    CODEC_LONG_NAME("TTA (True Audio)"),
432
    .p.type         = AVMEDIA_TYPE_AUDIO,
433
    .p.id           = AV_CODEC_ID_TTA,
434
    .priv_data_size = sizeof(TTAContext),
435
    .init           = tta_decode_init,
436
    .close          = tta_decode_close,
437
    FF_CODEC_DECODE_CB(tta_decode_frame),
438
    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_CHANNEL_CONF,
439
    .p.priv_class   = &tta_decoder_class,
440
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
441
};