FFmpeg
Loading...
Searching...
No Matches
tta.c
Go to the documentation of this file.
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
33#include "libavutil/crc.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#define FORMAT_ENCRYPTED 2
49
66
76
77static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
78{
79 uint32_t crc, CRC;
80
81 CRC = AV_RL32(buf + buf_size);
82 crc = av_crc(s->crc_table, 0xFFFFFFFFU, buf, buf_size);
83 if (CRC != (crc ^ 0xFFFFFFFFU)) {
84 av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
86 }
87
88 return 0;
89}
90
91static uint64_t tta_check_crc64(uint8_t *pass)
92{
93 uint64_t crc = UINT64_MAX, poly = 0x42F0E1EBA9EA3693U;
94 uint8_t *end = pass + strlen(pass);
95 int i;
96
97 while (pass < end) {
98 crc ^= (uint64_t)*pass++ << 56;
99 for (i = 0; i < 8; i++)
100 crc = (crc << 1) ^ (poly & (((int64_t) crc) >> 63));
101 }
102
103 return crc ^ UINT64_MAX;
104}
105
107{
108 TTAContext *s = avctx->priv_data;
109
110 if (s->bps < 3) {
111 s->decode_buffer = av_calloc(s->frame_length,
112 sizeof(*s->decode_buffer) * s->channels);
113 if (!s->decode_buffer)
114 return AVERROR(ENOMEM);
115 } else
116 s->decode_buffer = NULL;
117 s->ch_ctx = av_malloc_array(avctx->ch_layout.nb_channels, sizeof(*s->ch_ctx));
118 if (!s->ch_ctx)
119 return AVERROR(ENOMEM);
120
121 return 0;
122}
123
125{
126 TTAContext *s = avctx->priv_data;
127 GetBitContext gb;
128 int total_frames;
129 int ret;
130
131 s->avctx = avctx;
132
133 // 22 bytes for a TTA1 header
134 if (avctx->extradata_size < 22)
135 return AVERROR_INVALIDDATA;
136
138 ret = init_get_bits8(&gb, avctx->extradata, avctx->extradata_size);
139 if (ret < 0)
140 return ret;
141
142 if (show_bits_long(&gb, 32) == AV_RL32("TTA1")) {
143 /* signature */
144 skip_bits_long(&gb, 32);
145
146 s->format = get_bits(&gb, 16);
147 if (s->format > 2) {
148 av_log(avctx, AV_LOG_ERROR, "Invalid format\n");
149 return AVERROR_INVALIDDATA;
150 }
151 if (s->format == FORMAT_ENCRYPTED) {
152 if (!s->pass) {
153 av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");
154 return AVERROR(EINVAL);
155 }
156 AV_WL64(s->crc_pass, tta_check_crc64(s->pass));
157 }
158
159 s->channels = get_bits(&gb, 16);
160
162 if (s->channels > 1 && s->channels < 9) {
164 }
165 if (avctx->ch_layout.nb_channels == 0) {
167 avctx->ch_layout.nb_channels = s->channels;
168 }
169
170 avctx->bits_per_raw_sample = get_bits(&gb, 16);
171 s->bps = (avctx->bits_per_raw_sample + 7) / 8;
172 avctx->sample_rate = get_bits_long(&gb, 32);
173 s->data_length = get_bits_long(&gb, 32);
174 skip_bits_long(&gb, 32); // CRC32 of header
175
176 if (s->channels == 0 || s->channels > 16) {
177 av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
178 return AVERROR_INVALIDDATA;
179 } else if (avctx->sample_rate == 0) {
180 av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");
181 return AVERROR_INVALIDDATA;
182 }
183
184 switch(s->bps) {
185 case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
186 case 2:
188 break;
189 case 3:
191 break;
192 //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
193 default:
194 av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
195 return AVERROR_INVALIDDATA;
196 }
197
198 // prevent overflow
199 if (avctx->sample_rate > 0x7FFFFFu) {
200 av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
201 return AVERROR(EINVAL);
202 }
203 s->frame_length = 256 * avctx->sample_rate / 245;
204
205 s->last_frame_length = s->data_length % s->frame_length;
206 total_frames = s->data_length / s->frame_length +
207 (s->last_frame_length ? 1 : 0);
208
209 av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
210 s->format, avctx->ch_layout.nb_channels, avctx->bits_per_coded_sample, avctx->sample_rate,
211 avctx->block_align);
212 av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
213 s->data_length, s->frame_length, s->last_frame_length, total_frames);
214
215 if (s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))) {
216 av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
217 return AVERROR_INVALIDDATA;
218 }
219 } else {
220 av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
221 return AVERROR_INVALIDDATA;
222 }
223
224 ff_ttadsp_init(&s->dsp);
225
226 return allocate_buffers(avctx);
227}
228
230 int *got_frame_ptr, AVPacket *avpkt)
231{
232 const uint8_t *buf = avpkt->data;
233 int buf_size = avpkt->size;
234 TTAContext *s = avctx->priv_data;
235 GetBitContext gb;
236 int i, ret;
237 int cur_chan = 0, framelen = s->frame_length;
238 uint32_t *p;
239
240 if (avctx->err_recognition & AV_EF_CRCCHECK) {
241 if (buf_size < 4 ||
242 (tta_check_crc(s, buf, buf_size - 4) && avctx->err_recognition & AV_EF_EXPLODE))
243 return AVERROR_INVALIDDATA;
244 }
245
246 if ((ret = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
247 return ret;
248
249 /* get output buffer */
250 frame->nb_samples = framelen;
251 if ((ret = ff_thread_get_buffer(avctx, frame, 0)) < 0)
252 return ret;
253
254 // decode directly to output buffer for 24-bit sample format
255 if (s->bps == 3)
256 s->decode_buffer = (int32_t *)frame->data[0];
257
258 // init per channel states
259 for (i = 0; i < s->channels; i++) {
260 TTAFilter *filter = &s->ch_ctx[i].filter;
261 s->ch_ctx[i].predictor = 0;
263 if (s->format == FORMAT_ENCRYPTED) {
264 for (int j = 0; j < 8; j++)
265 filter->qm[j] = sign_extend(s->crc_pass[j], 8);
266 }
267 ff_tta_rice_init(&s->ch_ctx[i].rice, 10, 10);
268 }
269
270 i = 0;
271 for (p = s->decode_buffer; (int32_t*)p < s->decode_buffer + (framelen * s->channels); p++) {
272 int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
273 TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
274 TTARice *rice = &s->ch_ctx[cur_chan].rice;
275 uint32_t unary, depth, k;
277
278 unary = get_unary(&gb, 0, get_bits_left(&gb));
279
280 if (unary == 0) {
281 depth = 0;
282 k = rice->k0;
283 } else {
284 depth = 1;
285 k = rice->k1;
286 unary--;
287 }
288
289 if (get_bits_left(&gb) < k) {
291 goto error;
292 }
293
294 if (k) {
295 if (k > MIN_CACHE_BITS || unary > INT32_MAX >> k) {
297 goto error;
298 }
299 value = (unary << k) + get_bits(&gb, k);
300 } else
301 value = unary;
302
303 // FIXME: copy paste from original
304 switch (depth) {
305 case 1:
306 rice->sum1 += value - (rice->sum1 >> 4);
307 if (rice->k1 > 0 && rice->sum1 < ff_tta_shift_16[rice->k1])
308 rice->k1--;
309 else if (rice->sum1 > ff_tta_shift_16[rice->k1 + 1])
310 rice->k1++;
311 value += ff_tta_shift_1[rice->k0];
313 default:
314 rice->sum0 += value - (rice->sum0 >> 4);
315 if (rice->k0 > 0 && rice->sum0 < ff_tta_shift_16[rice->k0])
316 rice->k0--;
317 else if (rice->sum0 > ff_tta_shift_16[rice->k0 + 1])
318 rice->k0++;
319 }
320
321 // extract coded value
322 value = 1 + ((value >> 1) ^ ((value & 1) - 1));
323
324 // run hybrid filter
325 value = s->dsp.filter_process(filter->qm, filter->dx, filter->dl,
326 &filter->error, value,
327 filter->shift, filter->round);
328
329 // fixed order prediction
330#define PRED(x, k) (int32_t)((((uint64_t)(x) << (k)) - (x)) >> (k))
331 switch (s->bps) {
332 case 1: value += PRED(*predictor, 4); break;
333 case 2:
334 case 3: value += PRED(*predictor, 5); break;
335 case 4: value += *predictor; break;
336 }
337 *predictor = *p = value;
338
339 // flip channels
340 if (cur_chan < (s->channels-1))
341 cur_chan++;
342 else {
343 // decorrelate in case of multiple channels
344 if (s->channels > 1) {
345 int32_t *r = p - 1;
346 for (*p += *r / 2; r > (int32_t*)p - s->channels; r--)
347 *r = *(r + 1) - (unsigned)*r;
348 }
349 cur_chan = 0;
350 i++;
351 // check for last frame
352 if (i == s->last_frame_length && get_bits_left(&gb) / 8 == 4) {
353 frame->nb_samples = framelen = s->last_frame_length;
354 break;
355 }
356 }
357 }
358
359 align_get_bits(&gb);
360 if (get_bits_left(&gb) < 32) {
362 goto error;
363 }
364 skip_bits_long(&gb, 32); // frame crc
365
366 // convert to output buffer
367 switch (s->bps) {
368 case 1: {
369 uint8_t *samples = (uint8_t *)frame->data[0];
370 p = s->decode_buffer;
371 for (i = 0; i < framelen * s->channels; i++)
372 samples[i] = p[i] + 0x80;
373 break;
374 }
375 case 2: {
376 int16_t *samples = (int16_t *)frame->data[0];
377 p = s->decode_buffer;
378 for (i = 0; i < framelen * s->channels; i++)
379 samples[i] = p[i];
380 break;
381 }
382 case 3: {
383 // shift samples for 24-bit sample format
384 int32_t *samples = (int32_t *)frame->data[0];
385
386 for (i = 0; i < framelen * s->channels; i++)
387 samples[i] = samples[i] * 256U;
388 // reset decode buffer
389 s->decode_buffer = NULL;
390 break;
391 }
392 }
393
394 *got_frame_ptr = 1;
395
396 return buf_size;
397error:
398 // reset decode buffer
399 if (s->bps == 3)
400 s->decode_buffer = NULL;
401 return ret;
402}
403
405{
406 TTAContext *s = avctx->priv_data;
407
408 if (s->bps < 3)
409 av_freep(&s->decode_buffer);
410 s->decode_buffer = NULL;
411 av_freep(&s->ch_ctx);
412
413 return 0;
414}
415
416#define OFFSET(x) offsetof(TTAContext, x)
417#define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
418static const AVOption options[] = {
419 { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
420 { NULL },
421};
422
424 .class_name = "TTA Decoder",
425 .item_name = av_default_item_name,
426 .option = options,
427 .version = LIBAVUTIL_VERSION_INT,
428};
429
431 .p.name = "tta",
432 CODEC_LONG_NAME("TTA (True Audio)"),
433 .p.type = AVMEDIA_TYPE_AUDIO,
434 .p.id = AV_CODEC_ID_TTA,
435 .priv_data_size = sizeof(TTAContext),
440 .p.priv_class = &tta_decoder_class,
441 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
442};
const FFCodec ff_tta_decoder
Definition tta.c:430
static av_cold void close(AVCodecParserContext *s)
Definition apv_parser.c:197
int32_t
Libavcodec external API header.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
Public libavutil channel layout APIs header.
#define FF_CODEC_DECODE_CB(func)
#define CODEC_LONG_NAME(str)
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
#define AV_EF_CRCCHECK
Verify checksums embedded in the bitstream (could be of either encoded or decoded data,...
Definition defs.h:48
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition defs.h:51
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:608
double value
Definition eval.c:102
static void predictor(uint8_t *src, ptrdiff_t size)
Definition exrenc.c:170
bitstream reader API header.
static unsigned int show_bits_long(GetBitContext *s, int n)
Show 0-32 bits.
Definition get_bits.h:498
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition get_bits.h:424
static int get_bits_left(GetBitContext *gb)
Definition get_bits.h:688
static void skip_bits_long(GetBitContext *s, int n)
Skips the specified number of bits.
Definition get_bits.h:280
#define MIN_CACHE_BITS
Definition get_bits.h:167
static int init_get_bits8(GetBitContext *s, const uint8_t *buffer, int byte_size)
Initialize GetBitContext.
Definition get_bits.h:544
static const uint8_t * align_get_bits(GetBitContext *s)
Definition get_bits.h:560
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition get_bits.h:337
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
#define AV_CH_LAYOUT_QUAD
#define AV_CH_LAYOUT_7POINT1_WIDE
#define AV_CH_LAYOUT_STEREO
#define AV_CH_LAYOUT_5POINT1_BACK
#define AV_CH_BACK_CENTER
#define AV_CH_LOW_FREQUENCY
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
#define AV_CODEC_CAP_CHANNEL_CONF
Codec should fill in channel configuration and samplerate instead of container.
Definition codec.h:94
#define AV_CODEC_CAP_FRAME_THREADS
Codec supports frame-level multithreading.
Definition codec.h:98
@ AV_CODEC_ID_TTA
Definition codec_id.h:475
void av_channel_layout_uninit(AVChannelLayout *channel_layout)
Free any allocated data in the channel layout and reset the channel count to 0.
int av_channel_layout_from_mask(AVChannelLayout *channel_layout, uint64_t mask)
Initialize a native channel layout from a bitmask indicating which channels are present.
@ AV_CHANNEL_ORDER_UNSPEC
Only the channel count is specified, without any further information about the channel order.
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
uint32_t AVCRC
Definition crc.h:46
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition crc.c:421
@ AV_CRC_32_IEEE_LE
Definition crc.h:53
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AV_SAMPLE_FMT_S32
signed 32 bits
Definition samplefmt.h:59
@ AV_SAMPLE_FMT_U8
unsigned 8 bits
Definition samplefmt.h:57
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition samplefmt.h:58
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define r
Definition input.c:42
#define AV_WL64(p, v)
#define AV_RL32(p)
Multithreading API for decoders.
static const AVClass tta_decoder_class
Definition tta.c:423
#define FORMAT_ENCRYPTED
Definition tta.c:48
static uint64_t tta_check_crc64(uint8_t *pass)
Definition tta.c:91
static av_cold int tta_decode_close(AVCodecContext *avctx)
Definition tta.c:404
static int allocate_buffers(AVCodecContext *avctx)
Definition tta.c:106
static const int64_t tta_channel_layouts[7]
Definition tta.c:67
#define PRED(x, k)
static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
Definition tta.c:77
#define OFFSET(x)
Definition tta.c:416
static av_cold int tta_decode_init(AVCodecContext *avctx)
Definition tta.c:124
static int tta_decode_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, AVPacket *avpkt)
Definition tta.c:229
av_cold void ff_ttadsp_init(TTADSPContext *c)
Definition ttadsp.c:58
#define av_fallthrough
Definition attributes.h:67
#define av_cold
Definition attributes.h:117
#define DEC
Definition librsvgdec.c:149
static av_const int sign_extend(int val, unsigned bits)
Definition mathops.h:135
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:264
Memory handling functions.
AVOptions.
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f, int flags)
Wrapper around get_buffer() for frame-multithreaded codecs.
enum AVChannelOrder order
Channel order used in this layout.
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
AVChannelLayout ch_layout
Audio channel layout.
Definition avcodec.h:1055
enum AVSampleFormat sample_fmt
audio sample format
Definition avcodec.h:1047
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition avcodec.h:1564
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition avcodec.h:1571
int sample_rate
samples per second
Definition avcodec.h:1040
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
int extradata_size
Definition avcodec.h:527
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs.
Definition avcodec.h:1075
void * priv_data
Definition avcodec.h:470
int err_recognition
Error recognition; may misdetect some more or less valid parts as errors.
Definition avcodec.h:1416
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
int size
Definition packet.h:604
uint8_t * data
Definition packet.h:603
uint8_t * pass
Definition tta.c:62
const AVCRC * crc_table
Definition tta.c:53
int last_frame_length
Definition tta.c:57
TTAChannel * ch_ctx
Definition tta.c:63
int bps
Definition tta.c:55
uint8_t crc_pass[8]
Definition tta.c:61
unsigned data_length
Definition tta.c:56
AVCodecContext * avctx
Definition tta.c:52
int frame_length
Definition tta.c:57
int32_t * decode_buffer
Definition tta.c:59
int format
Definition tta.c:55
TTADSPContext dsp
Definition tta.c:64
int channels
Definition tta.c:55
uint32_t k1
Definition ttadata.h:37
uint32_t sum0
Definition ttadata.h:37
uint32_t k0
Definition ttadata.h:37
uint32_t sum1
Definition ttadata.h:37
#define av_malloc_array(a, b)
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
void(* filter)(uint8_t *src, ptrdiff_t stride, int qscale)
Definition h263dsp.c:29
const uint32_t *const ff_tta_shift_16
Definition ttadata.c:38
const uint32_t ff_tta_shift_1[]
Definition ttadata.c:24
void ff_tta_rice_init(TTARice *c, uint32_t k0, uint32_t k1)
Definition ttadata.c:42
void ff_tta_filter_init(TTAFilter *c, int32_t shift)
Definition ttadata.c:50
const uint8_t ff_tta_filter_configs[]
Definition ttadata.c:40
static int get_unary(GetBitContext *gb, int stop, int len)
Get unary code of limited length.
Definition unary.h:46