]> git.sesse.net Git - ffmpeg/blob - libavcodec/tta.c
vaapi: return early from ff_vaapi_render_picture() without picture
[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_bits(&gb, avctx->extradata, avctx->extradata_size * 8);
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 || tta_check_crc(s, buf, buf_size - 4))
255             return AVERROR_INVALIDDATA;
256     }
257
258     if ((ret = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
259         return ret;
260
261     /* get output buffer */
262     frame->nb_samples = framelen;
263     if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)
264         return ret;
265
266     // decode directly to output buffer for 24-bit sample format
267     if (s->bps == 3)
268         s->decode_buffer = (int32_t *)frame->data[0];
269
270     // init per channel states
271     for (i = 0; i < s->channels; i++) {
272         TTAFilter *filter = &s->ch_ctx[i].filter;
273         s->ch_ctx[i].predictor = 0;
274         ff_tta_filter_init(filter, ff_tta_filter_configs[s->bps-1]);
275         if (s->format == FORMAT_ENCRYPTED) {
276             int i;
277             for (i = 0; i < 8; i++)
278                 filter->qm[i] = sign_extend(s->crc_pass[i], 8);
279         }
280         ff_tta_rice_init(&s->ch_ctx[i].rice, 10, 10);
281     }
282
283     i = 0;
284     for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
285         int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
286         TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
287         TTARice *rice = &s->ch_ctx[cur_chan].rice;
288         uint32_t unary, depth, k;
289         int32_t value;
290
291         unary = get_unary(&gb, 0, get_bits_left(&gb));
292
293         if (unary == 0) {
294             depth = 0;
295             k = rice->k0;
296         } else {
297             depth = 1;
298             k = rice->k1;
299             unary--;
300         }
301
302         if (get_bits_left(&gb) < k) {
303             ret = AVERROR_INVALIDDATA;
304             goto error;
305         }
306
307         if (k) {
308             if (k > MIN_CACHE_BITS) {
309                 ret = AVERROR_INVALIDDATA;
310                 goto error;
311             }
312             value = (unary << k) + get_bits(&gb, k);
313         } else
314             value = unary;
315
316         // FIXME: copy paste from original
317         switch (depth) {
318         case 1:
319             rice->sum1 += value - (rice->sum1 >> 4);
320             if (rice->k1 > 0 && rice->sum1 < ff_tta_shift_16[rice->k1])
321                 rice->k1--;
322             else if(rice->sum1 > ff_tta_shift_16[rice->k1 + 1])
323                 rice->k1++;
324             value += ff_tta_shift_1[rice->k0];
325         default:
326             rice->sum0 += value - (rice->sum0 >> 4);
327             if (rice->k0 > 0 && rice->sum0 < ff_tta_shift_16[rice->k0])
328                 rice->k0--;
329             else if(rice->sum0 > ff_tta_shift_16[rice->k0 + 1])
330                 rice->k0++;
331         }
332
333         // extract coded value
334         *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
335
336         // run hybrid filter
337         ttafilter_process(filter, p);
338
339         // fixed order prediction
340 #define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
341         switch (s->bps) {
342         case 1: *p += PRED(*predictor, 4); break;
343         case 2:
344         case 3: *p += PRED(*predictor, 5); break;
345         case 4: *p +=      *predictor;     break;
346         }
347         *predictor = *p;
348
349         // flip channels
350         if (cur_chan < (s->channels-1))
351             cur_chan++;
352         else {
353             // decorrelate in case of multiple channels
354             if (s->channels > 1) {
355                 int32_t *r = p - 1;
356                 for (*p += *r / 2; r > p - s->channels; r--)
357                     *r = *(r + 1) - *r;
358             }
359             cur_chan = 0;
360             i++;
361             // check for last frame
362             if (i == s->last_frame_length && get_bits_left(&gb) / 8 == 4) {
363                 frame->nb_samples = framelen = s->last_frame_length;
364                 break;
365             }
366         }
367     }
368
369     align_get_bits(&gb);
370     if (get_bits_left(&gb) < 32) {
371         ret = AVERROR_INVALIDDATA;
372         goto error;
373     }
374     skip_bits_long(&gb, 32); // frame crc
375
376     // convert to output buffer
377     switch (s->bps) {
378     case 1: {
379         uint8_t *samples = (uint8_t *)frame->data[0];
380         for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
381             *samples++ = *p + 0x80;
382         break;
383         }
384     case 2: {
385         int16_t *samples = (int16_t *)frame->data[0];
386         for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
387             *samples++ = *p;
388         break;
389         }
390     case 3: {
391         // shift samples for 24-bit sample format
392         int32_t *samples = (int32_t *)frame->data[0];
393         for (i = 0; i < framelen * s->channels; i++)
394             *samples++ <<= 8;
395         // reset decode buffer
396         s->decode_buffer = NULL;
397         break;
398         }
399     }
400
401     *got_frame_ptr = 1;
402
403     return buf_size;
404 error:
405     // reset decode buffer
406     if (s->bps == 3)
407         s->decode_buffer = NULL;
408     return ret;
409 }
410
411 static int init_thread_copy(AVCodecContext *avctx)
412 {
413     TTAContext *s = avctx->priv_data;
414     s->avctx = avctx;
415     return allocate_buffers(avctx);
416 }
417
418 static av_cold int tta_decode_close(AVCodecContext *avctx) {
419     TTAContext *s = avctx->priv_data;
420
421     if (s->bps < 3)
422         av_free(s->decode_buffer);
423     s->decode_buffer = NULL;
424     av_freep(&s->ch_ctx);
425
426     return 0;
427 }
428
429 #define OFFSET(x) offsetof(TTAContext, x)
430 #define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
431 static const AVOption options[] = {
432     { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
433     { NULL },
434 };
435
436 static const AVClass tta_decoder_class = {
437     .class_name = "TTA Decoder",
438     .item_name  = av_default_item_name,
439     .option     = options,
440     .version    = LIBAVUTIL_VERSION_INT,
441 };
442
443 AVCodec ff_tta_decoder = {
444     .name           = "tta",
445     .type           = AVMEDIA_TYPE_AUDIO,
446     .id             = AV_CODEC_ID_TTA,
447     .priv_data_size = sizeof(TTAContext),
448     .init           = tta_decode_init,
449     .close          = tta_decode_close,
450     .decode         = tta_decode_frame,
451     .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
452     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
453     .long_name      = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
454     .priv_class     = &tta_decoder_class,
455 };