]> git.sesse.net Git - ffmpeg/blob - libavcodec/tta.c
Add a lavc Makefile dependency for the elbg filter.
[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 #include <limits.h>
32 #include "ttadata.h"
33 #include "avcodec.h"
34 #include "get_bits.h"
35 #include "thread.h"
36 #include "unary.h"
37 #include "internal.h"
38 #include "libavutil/crc.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/opt.h"
41
42 #define FORMAT_SIMPLE    1
43 #define FORMAT_ENCRYPTED 2
44
45 typedef struct TTAContext {
46     AVClass *class;
47     AVCodecContext *avctx;
48     const AVCRC *crc_table;
49
50     int format, channels, bps;
51     unsigned data_length;
52     int frame_length, last_frame_length;
53
54     int32_t *decode_buffer;
55
56     uint8_t crc_pass[8];
57     uint8_t *pass;
58     TTAChannel *ch_ctx;
59 } TTAContext;
60
61 static inline void ttafilter_process(TTAFilter *c, int32_t *in)
62 {
63     register int32_t *dl = c->dl, *qm = c->qm, *dx = c->dx, sum = c->round;
64
65     if (c->error < 0) {
66         qm[0] -= dx[0]; qm[1] -= dx[1]; qm[2] -= dx[2]; qm[3] -= dx[3];
67         qm[4] -= dx[4]; qm[5] -= dx[5]; qm[6] -= dx[6]; qm[7] -= dx[7];
68     } else if (c->error > 0) {
69         qm[0] += dx[0]; qm[1] += dx[1]; qm[2] += dx[2]; qm[3] += dx[3];
70         qm[4] += dx[4]; qm[5] += dx[5]; qm[6] += dx[6]; qm[7] += dx[7];
71     }
72
73     sum += dl[0] * qm[0] + dl[1] * qm[1] + dl[2] * qm[2] + dl[3] * qm[3] +
74            dl[4] * qm[4] + dl[5] * qm[5] + dl[6] * qm[6] + dl[7] * qm[7];
75
76     dx[0] = dx[1]; dx[1] = dx[2]; dx[2] = dx[3]; dx[3] = dx[4];
77     dl[0] = dl[1]; dl[1] = dl[2]; dl[2] = dl[3]; dl[3] = dl[4];
78
79     dx[4] = ((dl[4] >> 30) | 1);
80     dx[5] = ((dl[5] >> 30) | 2) & ~1;
81     dx[6] = ((dl[6] >> 30) | 2) & ~1;
82     dx[7] = ((dl[7] >> 30) | 4) & ~3;
83
84     c->error = *in;
85     *in += (sum >> c->shift);
86
87     dl[4] = -dl[5]; dl[5] = -dl[6];
88     dl[6] = *in - dl[7]; dl[7] = *in;
89     dl[5] += dl[6]; dl[4] += dl[5];
90 }
91
92 static const int64_t tta_channel_layouts[7] = {
93     AV_CH_LAYOUT_STEREO,
94     AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY,
95     AV_CH_LAYOUT_QUAD,
96     0,
97     AV_CH_LAYOUT_5POINT1_BACK,
98     AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER,
99     AV_CH_LAYOUT_7POINT1_WIDE
100 };
101
102 static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
103 {
104     uint32_t crc, CRC;
105
106     CRC = AV_RL32(buf + buf_size);
107     crc = av_crc(s->crc_table, 0xFFFFFFFFU, buf, buf_size);
108     if (CRC != (crc ^ 0xFFFFFFFFU)) {
109         av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
110         return AVERROR_INVALIDDATA;
111     }
112
113     return 0;
114 }
115
116 static uint64_t tta_check_crc64(uint8_t *pass)
117 {
118     uint64_t crc = UINT64_MAX, poly = 0x42F0E1EBA9EA3693U;
119     uint8_t *end = pass + strlen(pass);
120     int i;
121
122     while (pass < end) {
123         crc ^= (uint64_t)*pass++ << 56;
124         for (i = 0; i < 8; i++)
125             crc = (crc << 1) ^ (poly & (((int64_t) crc) >> 63));
126     }
127
128     return crc ^ UINT64_MAX;
129 }
130
131 static int allocate_buffers(AVCodecContext *avctx)
132 {
133     TTAContext *s = avctx->priv_data;
134
135     if (s->bps < 3) {
136         s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);
137         if (!s->decode_buffer)
138             return AVERROR(ENOMEM);
139     } else
140         s->decode_buffer = NULL;
141     s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));
142     if (!s->ch_ctx) {
143         av_freep(&s->decode_buffer);
144         return AVERROR(ENOMEM);
145     }
146
147     return 0;
148 }
149
150 static av_cold int tta_decode_init(AVCodecContext * avctx)
151 {
152     TTAContext *s = avctx->priv_data;
153     GetBitContext gb;
154     int total_frames;
155
156     s->avctx = avctx;
157
158     // 30bytes includes TTA1 header
159     if (avctx->extradata_size < 22)
160         return AVERROR_INVALIDDATA;
161
162     s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
163     init_get_bits8(&gb, avctx->extradata, avctx->extradata_size);
164     if (show_bits_long(&gb, 32) == AV_RL32("TTA1")) {
165         /* signature */
166         skip_bits_long(&gb, 32);
167
168         s->format = get_bits(&gb, 16);
169         if (s->format > 2) {
170             av_log(avctx, AV_LOG_ERROR, "Invalid format\n");
171             return AVERROR_INVALIDDATA;
172         }
173         if (s->format == FORMAT_ENCRYPTED) {
174             if (!s->pass) {
175                 av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");
176                 return AVERROR(EINVAL);
177             }
178             AV_WL64(s->crc_pass, tta_check_crc64(s->pass));
179         }
180         avctx->channels = s->channels = get_bits(&gb, 16);
181         if (s->channels > 1 && s->channels < 9)
182             avctx->channel_layout = tta_channel_layouts[s->channels-2];
183         avctx->bits_per_raw_sample = get_bits(&gb, 16);
184         s->bps = (avctx->bits_per_raw_sample + 7) / 8;
185         avctx->sample_rate = get_bits_long(&gb, 32);
186         s->data_length = get_bits_long(&gb, 32);
187         skip_bits_long(&gb, 32); // CRC32 of header
188
189         if (s->channels == 0) {
190             av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
191             return AVERROR_INVALIDDATA;
192         } else if (avctx->sample_rate == 0) {
193             av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");
194             return AVERROR_INVALIDDATA;
195         }
196
197         switch(s->bps) {
198         case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
199         case 2:
200             avctx->sample_fmt = AV_SAMPLE_FMT_S16;
201             break;
202         case 3:
203             avctx->sample_fmt = AV_SAMPLE_FMT_S32;
204             break;
205         //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
206         default:
207             av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
208             return AVERROR_INVALIDDATA;
209         }
210
211         // prevent overflow
212         if (avctx->sample_rate > 0x7FFFFFu) {
213             av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
214             return AVERROR(EINVAL);
215         }
216         s->frame_length = 256 * avctx->sample_rate / 245;
217
218         s->last_frame_length = s->data_length % s->frame_length;
219         total_frames = s->data_length / s->frame_length +
220                        (s->last_frame_length ? 1 : 0);
221
222         av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
223             s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate,
224             avctx->block_align);
225         av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
226             s->data_length, s->frame_length, s->last_frame_length, total_frames);
227
228         if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){
229             av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
230             return AVERROR_INVALIDDATA;
231         }
232     } else {
233         av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
234         return AVERROR_INVALIDDATA;
235     }
236
237     return allocate_buffers(avctx);
238 }
239
240 static int tta_decode_frame(AVCodecContext *avctx, void *data,
241                             int *got_frame_ptr, AVPacket *avpkt)
242 {
243     AVFrame *frame     = data;
244     ThreadFrame tframe = { .f = data };
245     const uint8_t *buf = avpkt->data;
246     int buf_size = avpkt->size;
247     TTAContext *s = avctx->priv_data;
248     GetBitContext gb;
249     int i, ret;
250     int cur_chan = 0, framelen = s->frame_length;
251     int32_t *p;
252
253     if (avctx->err_recognition & AV_EF_CRCCHECK) {
254         if (buf_size < 4 ||
255             (tta_check_crc(s, buf, buf_size - 4) && avctx->err_recognition & AV_EF_EXPLODE))
256             return AVERROR_INVALIDDATA;
257     }
258
259     if ((ret = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
260         return ret;
261
262     /* get output buffer */
263     frame->nb_samples = framelen;
264     if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)
265         return ret;
266
267     // decode directly to output buffer for 24-bit sample format
268     if (s->bps == 3)
269         s->decode_buffer = (int32_t *)frame->data[0];
270
271     // init per channel states
272     for (i = 0; i < s->channels; i++) {
273         TTAFilter *filter = &s->ch_ctx[i].filter;
274         s->ch_ctx[i].predictor = 0;
275         ff_tta_filter_init(filter, ff_tta_filter_configs[s->bps-1]);
276         if (s->format == FORMAT_ENCRYPTED) {
277             int i;
278             for (i = 0; i < 8; i++)
279                 filter->qm[i] = sign_extend(s->crc_pass[i], 8);
280         }
281         ff_tta_rice_init(&s->ch_ctx[i].rice, 10, 10);
282     }
283
284     i = 0;
285     for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
286         int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
287         TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
288         TTARice *rice = &s->ch_ctx[cur_chan].rice;
289         uint32_t unary, depth, k;
290         int32_t value;
291
292         unary = get_unary(&gb, 0, get_bits_left(&gb));
293
294         if (unary == 0) {
295             depth = 0;
296             k = rice->k0;
297         } else {
298             depth = 1;
299             k = rice->k1;
300             unary--;
301         }
302
303         if (get_bits_left(&gb) < k) {
304             ret = AVERROR_INVALIDDATA;
305             goto error;
306         }
307
308         if (k) {
309             if (k > MIN_CACHE_BITS) {
310                 ret = AVERROR_INVALIDDATA;
311                 goto error;
312             }
313             value = (unary << k) + get_bits(&gb, k);
314         } else
315             value = unary;
316
317         // FIXME: copy paste from original
318         switch (depth) {
319         case 1:
320             rice->sum1 += value - (rice->sum1 >> 4);
321             if (rice->k1 > 0 && rice->sum1 < ff_tta_shift_16[rice->k1])
322                 rice->k1--;
323             else if(rice->sum1 > ff_tta_shift_16[rice->k1 + 1])
324                 rice->k1++;
325             value += ff_tta_shift_1[rice->k0];
326         default:
327             rice->sum0 += value - (rice->sum0 >> 4);
328             if (rice->k0 > 0 && rice->sum0 < ff_tta_shift_16[rice->k0])
329                 rice->k0--;
330             else if(rice->sum0 > ff_tta_shift_16[rice->k0 + 1])
331                 rice->k0++;
332         }
333
334         // extract coded value
335         *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
336
337         // run hybrid filter
338         ttafilter_process(filter, p);
339
340         // fixed order prediction
341 #define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
342         switch (s->bps) {
343         case 1: *p += PRED(*predictor, 4); break;
344         case 2:
345         case 3: *p += PRED(*predictor, 5); break;
346         case 4: *p +=      *predictor;     break;
347         }
348         *predictor = *p;
349
350         // flip channels
351         if (cur_chan < (s->channels-1))
352             cur_chan++;
353         else {
354             // decorrelate in case of multiple channels
355             if (s->channels > 1) {
356                 int32_t *r = p - 1;
357                 for (*p += *r / 2; r > p - s->channels; r--)
358                     *r = *(r + 1) - *r;
359             }
360             cur_chan = 0;
361             i++;
362             // check for last frame
363             if (i == s->last_frame_length && get_bits_left(&gb) / 8 == 4) {
364                 frame->nb_samples = framelen = s->last_frame_length;
365                 break;
366             }
367         }
368     }
369
370     align_get_bits(&gb);
371     if (get_bits_left(&gb) < 32) {
372         ret = AVERROR_INVALIDDATA;
373         goto error;
374     }
375     skip_bits_long(&gb, 32); // frame crc
376
377     // convert to output buffer
378     switch (s->bps) {
379     case 1: {
380         uint8_t *samples = (uint8_t *)frame->data[0];
381         for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
382             *samples++ = *p + 0x80;
383         break;
384         }
385     case 2: {
386         int16_t *samples = (int16_t *)frame->data[0];
387         for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
388             *samples++ = *p;
389         break;
390         }
391     case 3: {
392         // shift samples for 24-bit sample format
393         int32_t *samples = (int32_t *)frame->data[0];
394         for (i = 0; i < framelen * s->channels; i++)
395             *samples++ <<= 8;
396         // reset decode buffer
397         s->decode_buffer = NULL;
398         break;
399         }
400     }
401
402     *got_frame_ptr = 1;
403
404     return buf_size;
405 error:
406     // reset decode buffer
407     if (s->bps == 3)
408         s->decode_buffer = NULL;
409     return ret;
410 }
411
412 static int init_thread_copy(AVCodecContext *avctx)
413 {
414     TTAContext *s = avctx->priv_data;
415     s->avctx = avctx;
416     return allocate_buffers(avctx);
417 }
418
419 static av_cold int tta_decode_close(AVCodecContext *avctx) {
420     TTAContext *s = avctx->priv_data;
421
422     if (s->bps < 3)
423         av_free(s->decode_buffer);
424     s->decode_buffer = NULL;
425     av_freep(&s->ch_ctx);
426
427     return 0;
428 }
429
430 #define OFFSET(x) offsetof(TTAContext, x)
431 #define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
432 static const AVOption options[] = {
433     { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
434     { NULL },
435 };
436
437 static const AVClass tta_decoder_class = {
438     .class_name = "TTA Decoder",
439     .item_name  = av_default_item_name,
440     .option     = options,
441     .version    = LIBAVUTIL_VERSION_INT,
442 };
443
444 AVCodec ff_tta_decoder = {
445     .name           = "tta",
446     .long_name      = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
447     .type           = AVMEDIA_TYPE_AUDIO,
448     .id             = AV_CODEC_ID_TTA,
449     .priv_data_size = sizeof(TTAContext),
450     .init           = tta_decode_init,
451     .close          = tta_decode_close,
452     .decode         = tta_decode_frame,
453     .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
454     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
455     .priv_class     = &tta_decoder_class,
456 };