]> git.sesse.net Git - ffmpeg/blob - libavcodec/takdec.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / takdec.c
1 /*
2  * TAK decoder
3  * Copyright (c) 2012 Paul B Mahol
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  * TAK (Tom's lossless Audio Kompressor) decoder
25  * @author Paul B Mahol
26  */
27
28 #include "tak.h"
29 #include "avcodec.h"
30 #include "unary.h"
31 #include "dsputil.h"
32
33 #define MAX_SUBFRAMES   8                       ///< max number of subframes per channel
34 #define MAX_PREDICTORS  256
35
36 typedef struct MCDParam {
37     int8_t     present;                         ///< is decorrelation parameters available for this channel
38     int8_t     index;                           ///< index into array of decorrelation types
39     int8_t     chan1;
40     int8_t     chan2;
41 } MCDParam;
42
43 typedef struct TAKDecContext {
44     AVCodecContext *avctx;                      ///< parent AVCodecContext
45     AVFrame        frame;                       ///< AVFrame for decoded output
46     DSPContext     dsp;
47     TAKStreamInfo  ti;
48     GetBitContext  gb;                          ///< bitstream reader initialized to start at the current frame
49
50     int            nb_samples;                  ///< number of samples in the current frame
51     int32_t        *decode_buffer;
52     int            decode_buffer_size;
53     int32_t        *decoded[TAK_MAX_CHANNELS];  ///< decoded samples for each channel
54
55     int8_t         lpc_mode[TAK_MAX_CHANNELS];
56     int8_t         sample_shift[TAK_MAX_CHANNELS];  ///< shift applied to every sample in the channel
57     int32_t        xred;
58     int            size;
59     int            ared;
60     int            filter_order;
61     int16_t        predictors[MAX_PREDICTORS];
62     int            nb_subframes;                ///< number of subframes in the current frame
63     int16_t        subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
64     int            subframe_scale;
65
66     int8_t         dmode;                       ///< channel decorrelation type in the current frame
67     int8_t         dshift;
68     int16_t        dfactor;
69     int8_t         dval1;
70     int8_t         dval2;
71
72     MCDParam       mcdparams[TAK_MAX_CHANNELS]; ///< multichannel decorrelation parameters
73
74     int            wlength;
75     int            uval;
76     int            rval;
77     int8_t         coding_mode[128];
78     DECLARE_ALIGNED(16, int16_t, filter)[MAX_PREDICTORS];
79     DECLARE_ALIGNED(16, int16_t, residues)[544];
80 } TAKDecContext;
81
82 static const int8_t mc_dmodes[] = {
83     1, 3, 4, 6,
84 };
85
86 static const uint16_t predictor_sizes[] = {
87     4, 8, 12, 16, 24, 32, 48, 64, 80, 96, 128, 160, 192, 224, 256, 0,
88 };
89
90 static const struct CParam {
91     int        init;
92     int        escape;
93     int        scale;
94     int        aescape;
95     int        bias;
96 } xcodes[50] = {
97     { 0x01, 0x0000001, 0x0000001, 0x0000003, 0x0000008 },
98     { 0x02, 0x0000003, 0x0000001, 0x0000007, 0x0000006 },
99     { 0x03, 0x0000005, 0x0000002, 0x000000E, 0x000000D },
100     { 0x03, 0x0000003, 0x0000003, 0x000000D, 0x0000018 },
101     { 0x04, 0x000000B, 0x0000004, 0x000001C, 0x0000019 },
102     { 0x04, 0x0000006, 0x0000006, 0x000001A, 0x0000030 },
103     { 0x05, 0x0000016, 0x0000008, 0x0000038, 0x0000032 },
104     { 0x05, 0x000000C, 0x000000C, 0x0000034, 0x0000060 },
105     { 0x06, 0x000002C, 0x0000010, 0x0000070, 0x0000064 },
106     { 0x06, 0x0000018, 0x0000018, 0x0000068, 0x00000C0 },
107     { 0x07, 0x0000058, 0x0000020, 0x00000E0, 0x00000C8 },
108     { 0x07, 0x0000030, 0x0000030, 0x00000D0, 0x0000180 },
109     { 0x08, 0x00000B0, 0x0000040, 0x00001C0, 0x0000190 },
110     { 0x08, 0x0000060, 0x0000060, 0x00001A0, 0x0000300 },
111     { 0x09, 0x0000160, 0x0000080, 0x0000380, 0x0000320 },
112     { 0x09, 0x00000C0, 0x00000C0, 0x0000340, 0x0000600 },
113     { 0x0A, 0x00002C0, 0x0000100, 0x0000700, 0x0000640 },
114     { 0x0A, 0x0000180, 0x0000180, 0x0000680, 0x0000C00 },
115     { 0x0B, 0x0000580, 0x0000200, 0x0000E00, 0x0000C80 },
116     { 0x0B, 0x0000300, 0x0000300, 0x0000D00, 0x0001800 },
117     { 0x0C, 0x0000B00, 0x0000400, 0x0001C00, 0x0001900 },
118     { 0x0C, 0x0000600, 0x0000600, 0x0001A00, 0x0003000 },
119     { 0x0D, 0x0001600, 0x0000800, 0x0003800, 0x0003200 },
120     { 0x0D, 0x0000C00, 0x0000C00, 0x0003400, 0x0006000 },
121     { 0x0E, 0x0002C00, 0x0001000, 0x0007000, 0x0006400 },
122     { 0x0E, 0x0001800, 0x0001800, 0x0006800, 0x000C000 },
123     { 0x0F, 0x0005800, 0x0002000, 0x000E000, 0x000C800 },
124     { 0x0F, 0x0003000, 0x0003000, 0x000D000, 0x0018000 },
125     { 0x10, 0x000B000, 0x0004000, 0x001C000, 0x0019000 },
126     { 0x10, 0x0006000, 0x0006000, 0x001A000, 0x0030000 },
127     { 0x11, 0x0016000, 0x0008000, 0x0038000, 0x0032000 },
128     { 0x11, 0x000C000, 0x000C000, 0x0034000, 0x0060000 },
129     { 0x12, 0x002C000, 0x0010000, 0x0070000, 0x0064000 },
130     { 0x12, 0x0018000, 0x0018000, 0x0068000, 0x00C0000 },
131     { 0x13, 0x0058000, 0x0020000, 0x00E0000, 0x00C8000 },
132     { 0x13, 0x0030000, 0x0030000, 0x00D0000, 0x0180000 },
133     { 0x14, 0x00B0000, 0x0040000, 0x01C0000, 0x0190000 },
134     { 0x14, 0x0060000, 0x0060000, 0x01A0000, 0x0300000 },
135     { 0x15, 0x0160000, 0x0080000, 0x0380000, 0x0320000 },
136     { 0x15, 0x00C0000, 0x00C0000, 0x0340000, 0x0600000 },
137     { 0x16, 0x02C0000, 0x0100000, 0x0700000, 0x0640000 },
138     { 0x16, 0x0180000, 0x0180000, 0x0680000, 0x0C00000 },
139     { 0x17, 0x0580000, 0x0200000, 0x0E00000, 0x0C80000 },
140     { 0x17, 0x0300000, 0x0300000, 0x0D00000, 0x1800000 },
141     { 0x18, 0x0B00000, 0x0400000, 0x1C00000, 0x1900000 },
142     { 0x18, 0x0600000, 0x0600000, 0x1A00000, 0x3000000 },
143     { 0x19, 0x1600000, 0x0800000, 0x3800000, 0x3200000 },
144     { 0x19, 0x0C00000, 0x0C00000, 0x3400000, 0x6000000 },
145     { 0x1A, 0x2C00000, 0x1000000, 0x7000000, 0x6400000 },
146     { 0x1A, 0x1800000, 0x1800000, 0x6800000, 0xC000000 },
147 };
148
149 static void tak_set_bps(AVCodecContext *avctx)
150 {
151     switch (avctx->bits_per_coded_sample) {
152     case 8:
153         avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
154         break;
155     case 16:
156         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
157         break;
158     case 24:
159         avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
160         break;
161     }
162 }
163
164 static int get_shift(int sample_rate)
165 {
166     int shift;
167
168     if (sample_rate < 11025)
169         shift = 3;
170     else if (sample_rate < 22050)
171         shift = 2;
172     else if (sample_rate < 44100)
173         shift = 1;
174     else
175         shift = 0;
176
177     return shift;
178 }
179
180 static int get_scale(int sample_rate, int shift)
181 {
182     return FFALIGN(sample_rate + 511 >> 9, 4) << shift;
183 }
184
185 static av_cold int tak_decode_init(AVCodecContext *avctx)
186 {
187     TAKDecContext *s = avctx->priv_data;
188
189     ff_tak_init_crc();
190     ff_dsputil_init(&s->dsp, avctx);
191
192     s->avctx = avctx;
193     avcodec_get_frame_defaults(&s->frame);
194     avctx->coded_frame = &s->frame;
195
196     s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
197     s->subframe_scale = get_scale(avctx->sample_rate, 1);
198
199     tak_set_bps(avctx);
200
201     return 0;
202 }
203
204 static int get_code(GetBitContext *gb, int nbits)
205 {
206     if (nbits == 1) {
207         skip_bits1(gb);
208         return 0;
209     } else {
210         return get_sbits(gb, nbits);
211     }
212 }
213
214 static void decode_lpc(int32_t *coeffs, int mode, int length)
215 {
216     int i, a1, a2, a3, a4, a5;
217
218     if (length < 2)
219         return;
220
221     if (mode == 1) {
222         a1 = *coeffs++;
223         for (i = 0; i < (length - 1 >> 1); i++) {
224             *coeffs   += a1;
225             coeffs[1] += *coeffs;
226             a1      = coeffs[1];
227             coeffs    += 2;
228         }
229         if ((length - 1) & 1)
230             *coeffs += a1;
231     } else if (mode == 2) {
232         a1     = coeffs[1];
233         a2     = a1 + *coeffs;
234         coeffs[1] = a2;
235         if (length > 2) {
236             coeffs += 2;
237             for (i = 0; i < (length - 2 >> 1); i++) {
238                 a3     = *coeffs + a1;
239                 a4     = a3 + a2;
240                 *coeffs   = a4;
241                 a1     = coeffs[1] + a3;
242                 a2     = a1 + a4;
243                 coeffs[1] = a2;
244                 coeffs   += 2;
245             }
246             if (length & 1)
247                 *coeffs  += a1 + a2;
248         }
249     } else if (mode == 3) {
250         a1     = coeffs[1];
251         a2     = a1 + *coeffs;
252         coeffs[1] = a2;
253         if (length > 2) {
254             a3   = coeffs[2];
255             a4   = a3 + a1;
256             a5   = a4 + a2;
257             coeffs += 3;
258             for (i = 0; i < length - 3; i++) {
259                 a3  += *coeffs;
260                 a4  += a3;
261                 a5  += a4;
262                 *coeffs = a5;
263                 coeffs++;
264             }
265         }
266     }
267 }
268
269 static int decode_segment(TAKDecContext *s, int8_t value, int32_t *dst, int len)
270 {
271     GetBitContext *gb = &s->gb;
272
273     if (!value) {
274         memset(dst, 0, len * 4);
275     } else {
276         int x, y, z, i = 0;
277
278         value--;
279         do {
280             while (1) {
281                 x = get_bits_long(gb, xcodes[value].init);
282                 if (x >= xcodes[value].escape)
283                     break;
284                 dst[i++] = (x >> 1) ^ -(x & 1);
285                 if (i >= len)
286                     return 0;
287             }
288
289             y = get_bits1(gb);
290             x = (y << xcodes[value].init) | x;
291             if (x >= xcodes[value].aescape) {
292                 int c = get_unary(gb, 1, 9);
293
294                 if (c == 9) {
295                     int d;
296
297                     z = x + xcodes[value].bias;
298                     d = get_bits(gb, 3);
299                     if (d == 7) {
300                         d = get_bits(gb, 5) + 7;
301                         if (d > 29)
302                             return AVERROR_INVALIDDATA;
303                     }
304                     if (d)
305                         z += xcodes[value].scale * (get_bits_long(gb, d) + 1);
306                 } else {
307                     z = xcodes[value].scale * c + x - xcodes[value].escape;
308                 }
309             } else {
310                 z = x - (xcodes[value].escape & -y);
311             }
312             dst[i++] = (z >> 1) ^ -(z & 1);
313         } while (i < len);
314     }
315
316     return 0;
317 }
318
319 static int xget(TAKDecContext *s, int d, int q)
320 {
321     int x;
322
323     x = d / q;
324
325     s->rval = d - (x * q);
326
327     if (s->rval < q / 2) {
328         s->rval += q;
329     } else {
330         x++;
331     }
332
333     if (x <= 1 || x > 128)
334         return -1;
335
336     return x;
337 }
338
339 static int get_len(TAKDecContext *s, int b)
340 {
341     if (b >= s->wlength - 1)
342         return s->rval;
343     else
344         return s->uval;
345 }
346
347 static int decode_coeffs(TAKDecContext *s, int32_t *dst, int length)
348 {
349     GetBitContext *gb = &s->gb;
350     int i, v, ret;
351
352     if (length > s->nb_samples)
353         return AVERROR_INVALIDDATA;
354
355     if (get_bits1(gb)) {
356         if ((s->wlength = xget(s, length, s->uval)) < 0)
357             return AVERROR_INVALIDDATA;
358
359         s->coding_mode[0] = v = get_bits(gb, 6);
360         if (s->coding_mode[0] > FF_ARRAY_ELEMS(xcodes))
361             return AVERROR_INVALIDDATA;
362
363         for (i = 1; i < s->wlength; i++) {
364             int c = get_unary(gb, 1, 6);
365
366             if (c > 5) {
367                 v = get_bits(gb, 6);
368             } else if (c > 2) {
369                 int t = get_bits1(gb);
370
371                 v += (-t ^ (c - 1)) + t;
372             } else {
373                 v += (-(c & 1) ^ (((c & 1) + c) >> 1)) + (c & 1);
374             }
375
376             if (v > FF_ARRAY_ELEMS(xcodes))
377                 return AVERROR_INVALIDDATA;
378             s->coding_mode[i] = v;
379         }
380
381         i = 0;
382         while (i < s->wlength) {
383             int len = 0;
384
385             v = s->coding_mode[i];
386             do {
387                 len += get_len(s, i);
388                 i++;
389
390                 if (i == s->wlength)
391                     break;
392             } while (v == s->coding_mode[i]);
393
394             if ((ret = decode_segment(s, v, dst, len)) < 0)
395                 return ret;
396             dst += len;
397         }
398     } else {
399         v = get_bits(gb, 6);
400         if (v > FF_ARRAY_ELEMS(xcodes))
401             return AVERROR_INVALIDDATA;
402         if ((ret = decode_segment(s, v, dst, length)) < 0)
403             return ret;
404     }
405
406     return 0;
407 }
408
409 static int get_b(GetBitContext *gb)
410 {
411     if (get_bits1(gb))
412         return get_bits(gb, 4) + 1;
413     else
414         return 0;
415 }
416
417 static int decode_subframe(TAKDecContext *s, int32_t *ptr, int subframe_size,
418                            int prev_subframe_size)
419 {
420     GetBitContext  *gb = &s->gb;
421     int tmp, x, y, i, j, ret = 0;
422     int tfilter[MAX_PREDICTORS];
423
424     if (get_bits1(gb)) {
425         s->filter_order = predictor_sizes[get_bits(gb, 4)];
426
427         if (prev_subframe_size > 0 && get_bits1(gb)) {
428             if (s->filter_order > prev_subframe_size)
429                 return AVERROR_INVALIDDATA;
430
431             ptr           -= s->filter_order;
432             subframe_size += s->filter_order;
433
434             if (s->filter_order > subframe_size)
435                 return AVERROR_INVALIDDATA;
436         } else {
437             int lpc;
438
439             if (s->filter_order > subframe_size)
440                 return AVERROR_INVALIDDATA;
441
442             lpc = get_bits(gb, 2);
443             if (lpc > 2)
444                 return AVERROR_INVALIDDATA;
445
446             if ((ret = decode_coeffs(s, ptr, s->filter_order)) < 0)
447                 return ret;
448
449             decode_lpc(ptr, lpc, s->filter_order);
450         }
451
452         s->xred = get_b(gb);
453         s->size = get_bits1(gb) + 5;
454
455         if (get_bits1(gb)) {
456             s->ared = get_bits(gb, 3) + 1;
457             if (s->ared > 7)
458                 return AVERROR_INVALIDDATA;
459         } else {
460             s->ared = 0;
461         }
462         s->predictors[0] = get_code(gb, 10);
463         s->predictors[1] = get_code(gb, 10);
464         s->predictors[2] = get_code(gb, s->size + 1) << (9 - s->size);
465         s->predictors[3] = get_code(gb, s->size + 1) << (9 - s->size);
466         if (s->filter_order > 4) {
467             tmp = s->size + 1 - get_bits1(gb);
468
469             for (i = 4; i < s->filter_order; i++) {
470                 if (!(i & 3))
471                     x = tmp - get_bits(gb, 2);
472                 s->predictors[i] = get_code(gb, x) << (9 - s->size);
473             }
474         }
475
476         tfilter[0] = s->predictors[0] << 6;
477         for (i = 1; i < s->filter_order; i++) {
478             int32_t *p1 = &tfilter[0];
479             int32_t *p2 = &tfilter[i - 1];
480
481             for (j = 0; j < (i + 1) / 2; j++) {
482                 x     = *p1 + (s->predictors[i] * *p2 + 256 >> 9);
483                 *p2  += s->predictors[i] * *p1 + 256 >> 9;
484                 *p1++ = x;
485                 p2--;
486             }
487
488             tfilter[i] = s->predictors[i] << 6;
489         }
490
491         x = -1 << (32 - (s->ared + 5));
492         y =  1 << ((s->ared + 5) - 1);
493         for (i = 0, j = s->filter_order - 1; i < s->filter_order / 2; i++, j--) {
494             tmp = y + tfilter[j];
495             s->filter[j] = -(x & -(y + tfilter[i] >> 31) |
496                             (y + tfilter[i]) >> (s->ared + 5));
497             s->filter[i] = -(x & -(tmp >> 31) | (tmp >> s->ared + 5));
498         }
499
500         if ((ret = decode_coeffs(s, &ptr[s->filter_order],
501                                  subframe_size - s->filter_order)) < 0)
502             return ret;
503
504         for (i = 0; i < s->filter_order; i++)
505             s->residues[i] = *ptr++ >> s->xred;
506
507         y    = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
508         x    = subframe_size - s->filter_order;
509         while (x > 0) {
510             tmp = FFMIN(y, x);
511
512             for (i = 0; i < tmp; i++) {
513                 int v, w, m;
514
515                 v = 1 << (10 - s->ared - 1);
516                 if (!(s->filter_order & 15)) {
517                     v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
518                                                     s->filter_order);
519                 } else if (s->filter_order & 4) {
520                     for (j = 0; j < s->filter_order; j += 4) {
521                         v += s->residues[i + j + 3] * s->filter[j + 3] +
522                              s->residues[i + j + 2] * s->filter[j + 2] +
523                              s->residues[i + j + 1] * s->filter[j + 1] +
524                              s->residues[i + j    ] * s->filter[j    ];
525                     }
526                 } else {
527                     for (j = 0; j < s->filter_order; j += 8) {
528                         v += s->residues[i + j + 7] * s->filter[j + 7] +
529                              s->residues[i + j + 6] * s->filter[j + 6] +
530                              s->residues[i + j + 5] * s->filter[j + 5] +
531                              s->residues[i + j + 4] * s->filter[j + 4] +
532                              s->residues[i + j + 3] * s->filter[j + 3] +
533                              s->residues[i + j + 2] * s->filter[j + 2] +
534                              s->residues[i + j + 1] * s->filter[j + 1] +
535                              s->residues[i + j    ] * s->filter[j    ];
536                     }
537                 }
538                 m = (-1 << (32 - (10 - s->ared))) & -(v >> 31) | (v >> 10 - s->ared);
539                 m = av_clip(m, -8192, 8191);
540                 w = (m << s->xred) - *ptr;
541                 *ptr++ = w;
542                 s->residues[s->filter_order + i] = w >> s->xred;
543             }
544
545             x -= tmp;
546             if (x > 0)
547                 memcpy(s->residues, &s->residues[y], 2 * s->filter_order);
548         }
549
550         emms_c();
551     } else {
552         ret = decode_coeffs(s, ptr, subframe_size);
553     }
554
555     return ret;
556 }
557
558 static int decode_channel(TAKDecContext *s, int chan)
559 {
560     AVCodecContext *avctx = s->avctx;
561     GetBitContext  *gb = &s->gb;
562     int32_t *dst = s->decoded[chan];
563     int i = 0, ret, prev = 0;
564     int left = s->nb_samples - 1;
565
566     s->sample_shift[chan] = get_b(gb);
567     if (s->sample_shift[chan] >= avctx->bits_per_coded_sample)
568         return AVERROR_INVALIDDATA;
569
570     *dst++ = get_code(gb, avctx->bits_per_coded_sample - s->sample_shift[chan]);
571     s->lpc_mode[chan] = get_bits(gb, 2);
572     s->nb_subframes   = get_bits(gb, 3) + 1;
573
574     if (s->nb_subframes > 1) {
575         if (get_bits_left(gb) < (s->nb_subframes - 1) * 6)
576             return AVERROR_INVALIDDATA;
577
578         for (; i < s->nb_subframes - 1; i++) {
579             int v = get_bits(gb, 6);
580
581             s->subframe_len[i] = (v - prev) * s->subframe_scale;
582             if (s->subframe_len[i] <= 0)
583                 return AVERROR_INVALIDDATA;
584
585             left -= s->subframe_len[i];
586             prev  = v;
587         }
588
589         if (left <= 0)
590             return AVERROR_INVALIDDATA;
591     }
592
593     s->subframe_len[i] = left;
594     prev = 0;
595     for (i = 0; i < s->nb_subframes; i++) {
596         if ((ret = decode_subframe(s, dst, s->subframe_len[i], prev)) < 0)
597             return ret;
598         dst += s->subframe_len[i];
599         prev = s->subframe_len[i];
600     }
601
602     return 0;
603 }
604
605 static int decorrelate(TAKDecContext *s, int c1, int c2, int length)
606 {
607     GetBitContext  *gb = &s->gb;
608     uint32_t *p1 = s->decoded[c1] + 1;
609     uint32_t *p2 = s->decoded[c2] + 1;
610     int a, b, i, x, tmp;
611
612     if (s->dmode > 3) {
613         s->dshift = get_b(gb);
614         if (s->dmode > 5) {
615             if (get_bits1(gb))
616                 s->filter_order = 16;
617             else
618                 s->filter_order = 8;
619
620             s->dval1 = get_bits1(gb);
621             s->dval2 = get_bits1(gb);
622
623             for (i = 0; i < s->filter_order; i++) {
624                 if (!(i & 3))
625                     x = 14 - get_bits(gb, 3);
626                 s->filter[i] = get_code(gb, x);
627             }
628         } else {
629             s->dfactor = get_code(gb, 10);
630         }
631     }
632
633     switch (s->dmode) {
634     case 1:
635         for (i = 0; i < length; i++, p1++, p2++)
636             *p2 += *p1;
637         break;
638     case 2:
639         for (i = 0; i < length; i++, p1++, p2++)
640             *p1 = *p2 - *p1;
641         break;
642     case 3:
643         for (i = 0; i < length; i++, p1++, p2++) {
644             x   = (*p2 & 1) + 2 * *p1;
645             a   = -*p2 + x;
646             b   =  *p2 + x;
647             *p1 = a & 0x80000000 | (a >> 1);
648             *p2 = b & 0x80000000 | (b >> 1);
649         }
650         break;
651     case 4:
652         FFSWAP(uint32_t *, p1, p2);
653     case 5:
654         if (s->dshift)
655             tmp = -1 << (32 - s->dshift);
656         else
657             tmp = 0;
658
659         for (i = 0; i < length; i++, p1++, p2++) {
660             x   = s->dfactor * (tmp & -(*p2 >> 31) | (*p2 >> s->dshift)) + 128;
661             *p1 = ((-(x >> 31) & 0xFF000000 | (x >> 8)) << s->dshift) - *p1;
662         }
663         break;
664     case 6:
665         FFSWAP(uint32_t *, p1, p2);
666     case 7:
667         if (length < 256)
668             return AVERROR_INVALIDDATA;
669
670         a = s->filter_order / 2;
671         b = length - (s->filter_order - 1);
672
673         if (s->dval1) {
674             for (i = 0; i < a; i++)
675                 p1[i] += p2[i];
676         }
677
678         if (s->dval2) {
679             x = a + b;
680             for (i = 0; i < length - x; i++)
681                 p1[x + i] += p2[x + i];
682         }
683
684         for (i = 0; i < s->filter_order; i++)
685             s->residues[i] = *p2++ >> s->dshift;
686
687         p1 += a;
688         x = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
689         for (; b > 0; b -= tmp) {
690             tmp = FFMIN(b, x);
691
692             for (i = 0; i < tmp; i++)
693                 s->residues[s->filter_order + i] = *p2++ >> s->dshift;
694
695             for (i = 0; i < tmp; i++) {
696                 int v, w, m;
697
698                 v = 1 << 9;
699
700                 if (s->filter_order == 16) {
701                     v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
702                                                     s->filter_order);
703                 } else {
704                     v += s->residues[i + 7] * s->filter[7] +
705                          s->residues[i + 6] * s->filter[6] +
706                          s->residues[i + 5] * s->filter[5] +
707                          s->residues[i + 4] * s->filter[4] +
708                          s->residues[i + 3] * s->filter[3] +
709                          s->residues[i + 2] * s->filter[2] +
710                          s->residues[i + 1] * s->filter[1] +
711                          s->residues[i    ] * s->filter[0];
712                 }
713
714                 m = (-1 << 22) & -(v >> 31) | (v >> 10);
715                 m = av_clip(m, -8192, 8191);
716                 w = (m << s->dshift) - *p1;
717                 *p1++ = w;
718             }
719
720             memcpy(s->residues, &s->residues[tmp], 2 * s->filter_order);
721         }
722
723         emms_c();
724         break;
725     }
726
727     return 0;
728 }
729
730 static int tak_decode_frame(AVCodecContext *avctx, void *data,
731                             int *got_frame_ptr, AVPacket *pkt)
732 {
733     TAKDecContext  *s = avctx->priv_data;
734     GetBitContext *gb = &s->gb;
735     int chan, i, ret, hsize;
736     int32_t *p;
737
738     if (pkt->size < TAK_MIN_FRAME_HEADER_BYTES)
739         return AVERROR_INVALIDDATA;
740
741     init_get_bits(gb, pkt->data, pkt->size * 8);
742
743     if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti, 0)) < 0)
744         return ret;
745
746     if (avctx->err_recognition & AV_EF_CRCCHECK) {
747         hsize = get_bits_count(gb) / 8;
748         if (ff_tak_check_crc(pkt->data, hsize)) {
749             av_log(avctx, AV_LOG_ERROR, "CRC error\n");
750             return AVERROR_INVALIDDATA;
751         }
752     }
753
754     if (s->ti.codec != 2 && s->ti.codec != 4) {
755         av_log(avctx, AV_LOG_ERROR, "unsupported codec: %d\n", s->ti.codec);
756         return AVERROR_PATCHWELCOME;
757     }
758     if (s->ti.data_type) {
759         av_log(avctx, AV_LOG_ERROR, "unsupported data type: %d\n", s->ti.data_type);
760         return AVERROR_INVALIDDATA;
761     }
762     if (s->ti.codec == 2 && s->ti.channels > 2) {
763         av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", s->ti.channels);
764         return AVERROR_INVALIDDATA;
765     }
766     if (s->ti.channels > 6) {
767         av_log(avctx, AV_LOG_ERROR, "unsupported number of channels: %d\n", s->ti.channels);
768         return AVERROR_INVALIDDATA;
769     }
770
771     if (s->ti.frame_samples <= 0) {
772         av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of samples\n");
773         return AVERROR_INVALIDDATA;
774     }
775
776     if (s->ti.bps != avctx->bits_per_coded_sample) {
777         avctx->bits_per_coded_sample = s->ti.bps;
778         tak_set_bps(avctx);
779     }
780     if (s->ti.sample_rate != avctx->sample_rate) {
781         avctx->sample_rate = s->ti.sample_rate;
782         s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
783         s->subframe_scale = get_scale(avctx->sample_rate, 1);
784     }
785     if (s->ti.ch_layout)
786         avctx->channel_layout = s->ti.ch_layout;
787     avctx->channels = s->ti.channels;
788
789     s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples :
790                                                s->ti.frame_samples;
791
792     s->frame.nb_samples = s->nb_samples;
793     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0)
794         return ret;
795
796     if (avctx->bits_per_coded_sample <= 16) {
797         av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size,
798                        sizeof(*s->decode_buffer) * FFALIGN(s->nb_samples, 8) *
799                        avctx->channels + FF_INPUT_BUFFER_PADDING_SIZE);
800         if (!s->decode_buffer)
801             return AVERROR(ENOMEM);
802         for (chan = 0; chan < avctx->channels; chan++)
803             s->decoded[chan] = s->decode_buffer +
804                                chan * FFALIGN(s->nb_samples, 8);
805     } else {
806         for (chan = 0; chan < avctx->channels; chan++)
807             s->decoded[chan] = (int32_t *)s->frame.data[chan];
808     }
809
810     if (s->nb_samples < 16) {
811         for (chan = 0; chan < avctx->channels; chan++) {
812             p = s->decoded[chan];
813             for (i = 0; i < s->nb_samples; i++)
814                 *p++ = get_code(gb, avctx->bits_per_coded_sample);
815         }
816     } else {
817         if (s->ti.codec == 2) {
818             for (chan = 0; chan < avctx->channels; chan++) {
819                 if (ret = decode_channel(s, chan))
820                     return ret;
821             }
822
823             if (avctx->channels == 2) {
824                 s->nb_subframes = get_bits(gb, 1) + 1;
825                 if (s->nb_subframes > 1)
826                     s->subframe_len[1] = get_bits(gb, 6);
827
828                 s->dmode = get_bits(gb, 3);
829                 if (ret = decorrelate(s, 0, 1, s->nb_samples - 1))
830                     return ret;
831             }
832         } else if (s->ti.codec == 4) {
833             if (get_bits1(gb)) {
834                 int ch_mask = 0;
835
836                 chan = get_bits(gb, 4) + 1;
837                 if (chan > avctx->channels)
838                     return AVERROR_INVALIDDATA;
839
840                 for (i = 0; i < chan; i++) {
841                     int nbit = get_bits(gb, 4);
842
843                     if (nbit >= avctx->channels)
844                         return AVERROR_INVALIDDATA;
845
846                     if (ch_mask & 1 << nbit)
847                         return AVERROR_INVALIDDATA;
848
849                     s->mcdparams[i].present = get_bits1(gb);
850                     if (s->mcdparams[i].present) {
851                         s->mcdparams[i].index = get_bits(gb, 2);
852                         s->mcdparams[i].chan2 = get_bits(gb, 4);
853                         if (s->mcdparams[i].index == 1) {
854                             if ((nbit == s->mcdparams[i].chan2) ||
855                                 (ch_mask & 1 << s->mcdparams[i].chan2))
856                                 return AVERROR_INVALIDDATA;
857
858                             ch_mask |= 1 << s->mcdparams[i].chan2;
859                         } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) {
860                             return AVERROR_INVALIDDATA;
861                         }
862                     }
863                     s->mcdparams[i].chan1 = nbit;
864
865                     ch_mask |= 1 << nbit;
866                 }
867             } else {
868                 chan = avctx->channels;
869                 for (i = 0; i < chan; i++) {
870                     s->mcdparams[i].present = 0;
871                     s->mcdparams[i].chan1   = i;
872                 }
873             }
874
875             for (i = 0; i < chan; i++) {
876                 if (s->mcdparams[i].present && s->mcdparams[i].index == 1) {
877                     if (ret = decode_channel(s, s->mcdparams[i].chan2))
878                         return ret;
879                 }
880
881                 if (ret = decode_channel(s, s->mcdparams[i].chan1))
882                     return ret;
883
884                 if (s->mcdparams[i].present) {
885                     s->dmode = mc_dmodes[s->mcdparams[i].index];
886                     if (ret = decorrelate(s, s->mcdparams[i].chan2,
887                                              s->mcdparams[i].chan1,
888                                              s->nb_samples - 1))
889                         return ret;
890                 }
891             }
892         }
893
894         for (chan = 0; chan < avctx->channels; chan++) {
895             p = s->decoded[chan];
896             decode_lpc(p, s->lpc_mode[chan], s->nb_samples);
897
898             if (s->sample_shift[chan] > 0) {
899                 for (i = 0; i < s->nb_samples; i++)
900                     *p++ <<= s->sample_shift[chan];
901             }
902         }
903     }
904
905     align_get_bits(gb);
906     skip_bits(gb, 24);
907     if (get_bits_left(gb) < 0)
908         av_log(avctx, AV_LOG_DEBUG, "overread\n");
909     else if (get_bits_left(gb) > 0)
910         av_log(avctx, AV_LOG_DEBUG, "underread\n");
911
912     if (avctx->err_recognition & AV_EF_CRCCHECK) {
913         if (ff_tak_check_crc(pkt->data + hsize,
914                              get_bits_count(gb) / 8 - hsize)) {
915             av_log(avctx, AV_LOG_ERROR, "CRC error\n");
916             return AVERROR_INVALIDDATA;
917         }
918     }
919
920     // convert to output buffer
921     switch (avctx->bits_per_coded_sample) {
922     case 8:
923         for (chan = 0; chan < avctx->channels; chan++) {
924             uint8_t *samples = (uint8_t *)s->frame.data[chan];
925             p = s->decoded[chan];
926             for (i = 0; i < s->nb_samples; i++, p++)
927                 *samples++ = *p + 0x80;
928         }
929         break;
930     case 16:
931         for (chan = 0; chan < avctx->channels; chan++) {
932             int16_t *samples = (int16_t *)s->frame.data[chan];
933             p = s->decoded[chan];
934             for (i = 0; i < s->nb_samples; i++, p++)
935                 *samples++ = *p;
936         }
937         break;
938     case 24:
939         for (chan = 0; chan < avctx->channels; chan++) {
940             int32_t *samples = (int32_t *)s->frame.data[chan];
941             for (i = 0; i < s->nb_samples; i++)
942                 *samples++ <<= 8;
943         }
944         break;
945     }
946
947     *got_frame_ptr   = 1;
948     *(AVFrame *)data = s->frame;
949
950     return pkt->size;
951 }
952
953 static av_cold int tak_decode_close(AVCodecContext *avctx)
954 {
955     TAKDecContext *s = avctx->priv_data;
956
957     av_freep(&s->decode_buffer);
958
959     return 0;
960 }
961
962 AVCodec ff_tak_decoder = {
963     .name           = "tak",
964     .type           = AVMEDIA_TYPE_AUDIO,
965     .id             = AV_CODEC_ID_TAK,
966     .priv_data_size = sizeof(TAKDecContext),
967     .init           = tak_decode_init,
968     .close          = tak_decode_close,
969     .decode         = tak_decode_frame,
970     .capabilities   = CODEC_CAP_DR1,
971     .long_name      = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
972 };