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