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