Use bitstream_init8() where appropriate
[libav.git] / libavcodec / tta.c
1 /*
2 * TTA (The Lossless True Audio) decoder
3 * Copyright (c) 2006 Alex Beregszaszi
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; 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/crc.h"
33
34 #define BITSTREAM_READER_LE
35 #include "avcodec.h"
36 #include "bitstream.h"
37 #include "internal.h"
38 #include "unary.h"
39
40 #define FORMAT_SIMPLE 1
41 #define FORMAT_ENCRYPTED 2
42
43 #define MAX_ORDER 16
44 typedef struct TTAFilter {
45 int32_t shift, round, error;
46 int32_t qm[MAX_ORDER];
47 int32_t dx[MAX_ORDER];
48 int32_t dl[MAX_ORDER];
49 } TTAFilter;
50
51 typedef struct TTARice {
52 uint32_t k0, k1, sum0, sum1;
53 } TTARice;
54
55 typedef struct TTAChannel {
56 int32_t predictor;
57 TTAFilter filter;
58 TTARice rice;
59 } TTAChannel;
60
61 typedef struct TTAContext {
62 AVCodecContext *avctx;
63 BitstreamContext bc;
64 const AVCRC *crc_table;
65
66 int format, channels, bps;
67 unsigned data_length;
68 int frame_length, last_frame_length;
69
70 int32_t *decode_buffer;
71
72 TTAChannel *ch_ctx;
73 } TTAContext;
74
75 static const uint32_t shift_1[] = {
76 0x00000001, 0x00000002, 0x00000004, 0x00000008,
77 0x00000010, 0x00000020, 0x00000040, 0x00000080,
78 0x00000100, 0x00000200, 0x00000400, 0x00000800,
79 0x00001000, 0x00002000, 0x00004000, 0x00008000,
80 0x00010000, 0x00020000, 0x00040000, 0x00080000,
81 0x00100000, 0x00200000, 0x00400000, 0x00800000,
82 0x01000000, 0x02000000, 0x04000000, 0x08000000,
83 0x10000000, 0x20000000, 0x40000000, 0x80000000,
84 0x80000000, 0x80000000, 0x80000000, 0x80000000,
85 0x80000000, 0x80000000, 0x80000000, 0x80000000
86 };
87
88 static const uint32_t * const shift_16 = shift_1 + 4;
89
90 static const int32_t ttafilter_configs[4] = {
91 10,
92 9,
93 10,
94 12
95 };
96
97 static void ttafilter_init(TTAFilter *c, int32_t shift) {
98 memset(c, 0, sizeof(TTAFilter));
99 c->shift = shift;
100 c->round = shift_1[shift-1];
101 // c->round = 1 << (shift - 1);
102 }
103
104 // FIXME: copy paste from original
105 static inline void memshl(register int32_t *a, register int32_t *b) {
106 *a++ = *b++;
107 *a++ = *b++;
108 *a++ = *b++;
109 *a++ = *b++;
110 *a++ = *b++;
111 *a++ = *b++;
112 *a++ = *b++;
113 *a = *b;
114 }
115
116 static inline void ttafilter_process(TTAFilter *c, int32_t *in)
117 {
118 register int32_t *dl = c->dl, *qm = c->qm, *dx = c->dx, sum = c->round;
119
120 if (!c->error) {
121 sum += *dl++ * *qm, qm++;
122 sum += *dl++ * *qm, qm++;
123 sum += *dl++ * *qm, qm++;
124 sum += *dl++ * *qm, qm++;
125 sum += *dl++ * *qm, qm++;
126 sum += *dl++ * *qm, qm++;
127 sum += *dl++ * *qm, qm++;
128 sum += *dl++ * *qm, qm++;
129 dx += 8;
130 } else if(c->error < 0) {
131 sum += *dl++ * (*qm -= *dx++), qm++;
132 sum += *dl++ * (*qm -= *dx++), qm++;
133 sum += *dl++ * (*qm -= *dx++), qm++;
134 sum += *dl++ * (*qm -= *dx++), qm++;
135 sum += *dl++ * (*qm -= *dx++), qm++;
136 sum += *dl++ * (*qm -= *dx++), qm++;
137 sum += *dl++ * (*qm -= *dx++), qm++;
138 sum += *dl++ * (*qm -= *dx++), qm++;
139 } else {
140 sum += *dl++ * (*qm += *dx++), qm++;
141 sum += *dl++ * (*qm += *dx++), qm++;
142 sum += *dl++ * (*qm += *dx++), qm++;
143 sum += *dl++ * (*qm += *dx++), qm++;
144 sum += *dl++ * (*qm += *dx++), qm++;
145 sum += *dl++ * (*qm += *dx++), qm++;
146 sum += *dl++ * (*qm += *dx++), qm++;
147 sum += *dl++ * (*qm += *dx++), qm++;
148 }
149
150 *(dx-0) = ((*(dl-1) >> 30) | 1) << 2;
151 *(dx-1) = ((*(dl-2) >> 30) | 1) << 1;
152 *(dx-2) = ((*(dl-3) >> 30) | 1) << 1;
153 *(dx-3) = ((*(dl-4) >> 30) | 1);
154
155 c->error = *in;
156 *in += (sum >> c->shift);
157 *dl = *in;
158
159 *(dl-1) = *dl - *(dl-1);
160 *(dl-2) = *(dl-1) - *(dl-2);
161 *(dl-3) = *(dl-2) - *(dl-3);
162
163 memshl(c->dl, c->dl + 1);
164 memshl(c->dx, c->dx + 1);
165 }
166
167 static void rice_init(TTARice *c, uint32_t k0, uint32_t k1)
168 {
169 c->k0 = k0;
170 c->k1 = k1;
171 c->sum0 = shift_16[k0];
172 c->sum1 = shift_16[k1];
173 }
174
175 static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
176 {
177 uint32_t crc, CRC;
178
179 CRC = AV_RL32(buf + buf_size);
180 crc = av_crc(s->crc_table, 0xFFFFFFFFU, buf, buf_size);
181 if (CRC != (crc ^ 0xFFFFFFFFU)) {
182 av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
183 return AVERROR_INVALIDDATA;
184 }
185
186 return 0;
187 }
188
189 static av_cold int tta_decode_init(AVCodecContext * avctx)
190 {
191 TTAContext *s = avctx->priv_data;
192 int total_frames;
193
194 s->avctx = avctx;
195
196 // 30bytes includes a seektable with one frame
197 if (avctx->extradata_size < 30)
198 return -1;
199
200 bitstream_init8(&s->bc, avctx->extradata, avctx->extradata_size);
201 if (bitstream_peek(&s->bc, 32) == AV_RL32("TTA1")) {
202 if (avctx->err_recognition & AV_EF_CRCCHECK) {
203 s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
204 tta_check_crc(s, avctx->extradata, 18);
205 }
206
207 /* signature */
208 bitstream_skip(&s->bc, 32);
209
210 s->format = bitstream_read(&s->bc, 16);
211 if (s->format > 2) {
212 av_log(s->avctx, AV_LOG_ERROR, "Invalid format\n");
213 return -1;
214 }
215 if (s->format == FORMAT_ENCRYPTED) {
216 avpriv_report_missing_feature(s->avctx, "Encrypted TTA");
217 return AVERROR_PATCHWELCOME;
218 }
219 avctx->channels =
220 s->channels = bitstream_read(&s->bc, 16);
221 avctx->bits_per_coded_sample = bitstream_read(&s->bc, 16);
222 s->bps = (avctx->bits_per_coded_sample + 7) / 8;
223 avctx->sample_rate = bitstream_read(&s->bc, 32);
224 s->data_length = bitstream_read(&s->bc, 32);
225 bitstream_skip(&s->bc, 32); // CRC32 of header
226
227 if (s->channels == 0) {
228 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of channels\n");
229 return AVERROR_INVALIDDATA;
230 } else if (avctx->sample_rate == 0) {
231 av_log(s->avctx, AV_LOG_ERROR, "Invalid samplerate\n");
232 return AVERROR_INVALIDDATA;
233 }
234
235 switch(s->bps) {
236 case 2:
237 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
238 avctx->bits_per_raw_sample = 16;
239 break;
240 case 3:
241 avctx->sample_fmt = AV_SAMPLE_FMT_S32;
242 avctx->bits_per_raw_sample = 24;
243 break;
244 default:
245 av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
246 return AVERROR_INVALIDDATA;
247 }
248
249 // prevent overflow
250 if (avctx->sample_rate > 0x7FFFFFu) {
251 av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
252 return AVERROR(EINVAL);
253 }
254 s->frame_length = 256 * avctx->sample_rate / 245;
255
256 s->last_frame_length = s->data_length % s->frame_length;
257 total_frames = s->data_length / s->frame_length +
258 (s->last_frame_length ? 1 : 0);
259
260 av_log(s->avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
261 s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate,
262 avctx->block_align);
263 av_log(s->avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
264 s->data_length, s->frame_length, s->last_frame_length, total_frames);
265
266 // FIXME: seek table
267 if (avctx->extradata_size <= 26 || total_frames > INT_MAX / 4 ||
268 avctx->extradata_size - 26 < total_frames * 4)
269 av_log(avctx, AV_LOG_WARNING, "Seek table missing or too small\n");
270 else if (avctx->err_recognition & AV_EF_CRCCHECK) {
271 int ret = tta_check_crc(s, avctx->extradata + 22, total_frames * 4);
272 if (ret < 0 && avctx->err_recognition & AV_EF_EXPLODE)
273 return AVERROR_INVALIDDATA;
274 }
275 bitstream_skip(&s->bc, 32 * total_frames);
276 bitstream_skip(&s->bc, 32); // CRC32 of seektable
277
278 if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){
279 av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
280 return -1;
281 }
282
283 if (s->bps == 2) {
284 s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);
285 if (!s->decode_buffer)
286 return AVERROR(ENOMEM);
287 }
288 s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));
289 if (!s->ch_ctx) {
290 av_freep(&s->decode_buffer);
291 return AVERROR(ENOMEM);
292 }
293 } else {
294 av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
295 return -1;
296 }
297
298 return 0;
299 }
300
301 static int tta_decode_frame(AVCodecContext *avctx, void *data,
302 int *got_frame_ptr, AVPacket *avpkt)
303 {
304 AVFrame *frame = data;
305 const uint8_t *buf = avpkt->data;
306 int buf_size = avpkt->size;
307 TTAContext *s = avctx->priv_data;
308 int i, ret;
309 int cur_chan = 0, framelen = s->frame_length;
310 int32_t *p;
311
312 if (avctx->err_recognition & AV_EF_CRCCHECK) {
313 if (buf_size < 4 ||
314 (tta_check_crc(s, buf, buf_size - 4) && avctx->err_recognition & AV_EF_EXPLODE))
315 return AVERROR_INVALIDDATA;
316 }
317
318 bitstream_init8(&s->bc, buf, buf_size);
319
320 /* get output buffer */
321 frame->nb_samples = framelen;
322 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
323 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
324 return ret;
325 }
326
327 // decode directly to output buffer for 24-bit sample format
328 if (s->bps == 3)
329 s->decode_buffer = (int32_t *)frame->data[0];
330
331 // init per channel states
332 for (i = 0; i < s->channels; i++) {
333 s->ch_ctx[i].predictor = 0;
334 ttafilter_init(&s->ch_ctx[i].filter, ttafilter_configs[s->bps-1]);
335 rice_init(&s->ch_ctx[i].rice, 10, 10);
336 }
337
338 i = 0;
339 for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
340 int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
341 TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
342 TTARice *rice = &s->ch_ctx[cur_chan].rice;
343 uint32_t unary, depth, k;
344 int32_t value;
345
346 unary = get_unary(&s->bc, 0, bitstream_bits_left(&s->bc));
347
348 if (unary == 0) {
349 depth = 0;
350 k = rice->k0;
351 } else {
352 depth = 1;
353 k = rice->k1;
354 unary--;
355 }
356
357 if (bitstream_bits_left(&s->bc) < k) {
358 ret = AVERROR_INVALIDDATA;
359 goto error;
360 }
361
362 if (k) {
363 if (k >= 32 || unary > INT32_MAX >> k) {
364 ret = AVERROR_INVALIDDATA;
365 goto error;
366 }
367 value = (unary << k) + bitstream_read(&s->bc, k);
368 } else
369 value = unary;
370
371 // FIXME: copy paste from original
372 switch (depth) {
373 case 1:
374 rice->sum1 += value - (rice->sum1 >> 4);
375 if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])
376 rice->k1--;
377 else if(rice->sum1 > shift_16[rice->k1 + 1])
378 rice->k1++;
379 value += shift_1[rice->k0];
380 default:
381 rice->sum0 += value - (rice->sum0 >> 4);
382 if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])
383 rice->k0--;
384 else if(rice->sum0 > shift_16[rice->k0 + 1])
385 rice->k0++;
386 }
387
388 // extract coded value
389 *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
390
391 // run hybrid filter
392 ttafilter_process(filter, p);
393
394 // fixed order prediction
395 #define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
396 switch (s->bps) {
397 case 1: *p += PRED(*predictor, 4); break;
398 case 2:
399 case 3: *p += PRED(*predictor, 5); break;
400 case 4: *p += *predictor; break;
401 }
402 *predictor = *p;
403
404 // flip channels
405 if (cur_chan < (s->channels-1))
406 cur_chan++;
407 else {
408 // decorrelate in case of multiple channels
409 if (s->channels > 1) {
410 int32_t *r = p - 1;
411 for (*p += *r / 2; r > p - s->channels; r--)
412 *r = *(r + 1) - *r;
413 }
414 cur_chan = 0;
415 i++;
416 // check for last frame
417 if (i == s->last_frame_length && bitstream_bits_left(&s->bc) / 8 == 4) {
418 frame->nb_samples = framelen = s->last_frame_length;
419 break;
420 }
421 }
422 }
423
424 bitstream_align(&s->bc);
425 if (bitstream_bits_left(&s->bc) < 32) {
426 ret = AVERROR_INVALIDDATA;
427 goto error;
428 }
429 bitstream_skip(&s->bc, 32); // frame CRC
430
431 // convert to output buffer
432 if (s->bps == 2) {
433 int16_t *samples = (int16_t *)frame->data[0];
434 for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
435 *samples++ = *p;
436 } else {
437 // shift samples for 24-bit sample format
438 int32_t *samples = (int32_t *)frame->data[0];
439 for (i = 0; i < framelen * s->channels; i++)
440 *samples++ <<= 8;
441 // reset decode buffer
442 s->decode_buffer = NULL;
443 }
444
445 *got_frame_ptr = 1;
446
447 return buf_size;
448 error:
449 // reset decode buffer
450 if (s->bps == 3)
451 s->decode_buffer = NULL;
452 return ret;
453 }
454
455 static av_cold int tta_decode_close(AVCodecContext *avctx) {
456 TTAContext *s = avctx->priv_data;
457
458 av_free(s->decode_buffer);
459 av_freep(&s->ch_ctx);
460
461 return 0;
462 }
463
464 AVCodec ff_tta_decoder = {
465 .name = "tta",
466 .long_name = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
467 .type = AVMEDIA_TYPE_AUDIO,
468 .id = AV_CODEC_ID_TTA,
469 .priv_data_size = sizeof(TTAContext),
470 .init = tta_decode_init,
471 .close = tta_decode_close,
472 .decode = tta_decode_frame,
473 .capabilities = AV_CODEC_CAP_DR1,
474 };