]> git.sesse.net Git - ffmpeg/blob - libavcodec/takdec.c
Merge commit '9953ff3cd844eb5f6d8dfce98cad94b78a0fc7dc'
[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 int tak_set_bps(AVCodecContext *avctx, int bps)
150 {
151     switch (bps) {
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     default:
162         av_log(avctx, AV_LOG_ERROR, "invalid/unsupported bits per sample\n");
163         return AVERROR_INVALIDDATA;
164     }
165
166     return 0;
167 }
168
169 static int get_shift(int sample_rate)
170 {
171     int shift;
172
173     if (sample_rate < 11025)
174         shift = 3;
175     else if (sample_rate < 22050)
176         shift = 2;
177     else if (sample_rate < 44100)
178         shift = 1;
179     else
180         shift = 0;
181
182     return shift;
183 }
184
185 static int get_scale(int sample_rate, int shift)
186 {
187     return FFALIGN(sample_rate + 511 >> 9, 4) << shift;
188 }
189
190 static av_cold int tak_decode_init(AVCodecContext *avctx)
191 {
192     TAKDecContext *s = avctx->priv_data;
193     int ret;
194
195     ff_tak_init_crc();
196     ff_dsputil_init(&s->dsp, avctx);
197
198     s->avctx = avctx;
199     avcodec_get_frame_defaults(&s->frame);
200     avctx->coded_frame = &s->frame;
201
202     s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
203     s->subframe_scale = get_scale(avctx->sample_rate, 1);
204
205     if ((ret = tak_set_bps(avctx, avctx->bits_per_coded_sample)) < 0)
206         return ret;
207
208     return 0;
209 }
210
211 static int get_code(GetBitContext *gb, int nbits)
212 {
213     if (nbits == 1) {
214         skip_bits1(gb);
215         return 0;
216     } else {
217         return get_sbits(gb, nbits);
218     }
219 }
220
221 static void decode_lpc(int32_t *coeffs, int mode, int length)
222 {
223     int i, a1, a2, a3, a4, a5;
224
225     if (length < 2)
226         return;
227
228     if (mode == 1) {
229         a1 = *coeffs++;
230         for (i = 0; i < (length - 1 >> 1); i++) {
231             *coeffs   += a1;
232             coeffs[1] += *coeffs;
233             a1      = coeffs[1];
234             coeffs    += 2;
235         }
236         if ((length - 1) & 1)
237             *coeffs += a1;
238     } else if (mode == 2) {
239         a1     = coeffs[1];
240         a2     = a1 + *coeffs;
241         coeffs[1] = a2;
242         if (length > 2) {
243             coeffs += 2;
244             for (i = 0; i < (length - 2 >> 1); i++) {
245                 a3     = *coeffs + a1;
246                 a4     = a3 + a2;
247                 *coeffs   = a4;
248                 a1     = coeffs[1] + a3;
249                 a2     = a1 + a4;
250                 coeffs[1] = a2;
251                 coeffs   += 2;
252             }
253             if (length & 1)
254                 *coeffs  += a1 + a2;
255         }
256     } else if (mode == 3) {
257         a1     = coeffs[1];
258         a2     = a1 + *coeffs;
259         coeffs[1] = a2;
260         if (length > 2) {
261             a3   = coeffs[2];
262             a4   = a3 + a1;
263             a5   = a4 + a2;
264             coeffs += 3;
265             for (i = 0; i < length - 3; i++) {
266                 a3  += *coeffs;
267                 a4  += a3;
268                 a5  += a4;
269                 *coeffs = a5;
270                 coeffs++;
271             }
272         }
273     }
274 }
275
276 static int decode_segment(TAKDecContext *s, int8_t value, int32_t *dst, int len)
277 {
278     GetBitContext *gb = &s->gb;
279
280     if (!value) {
281         memset(dst, 0, len * 4);
282     } else {
283         int x, y, z, i = 0;
284
285         value--;
286         do {
287             while (1) {
288                 x = get_bits_long(gb, xcodes[value].init);
289                 if (x >= xcodes[value].escape)
290                     break;
291                 dst[i++] = (x >> 1) ^ -(x & 1);
292                 if (i >= len)
293                     return 0;
294             }
295
296             y = get_bits1(gb);
297             x = (y << xcodes[value].init) | x;
298             if (x >= xcodes[value].aescape) {
299                 int c = get_unary(gb, 1, 9);
300
301                 if (c == 9) {
302                     int d;
303
304                     z = x + xcodes[value].bias;
305                     d = get_bits(gb, 3);
306                     if (d == 7) {
307                         d = get_bits(gb, 5) + 7;
308                         if (d > 29)
309                             return AVERROR_INVALIDDATA;
310                     }
311                     if (d)
312                         z += xcodes[value].scale * (get_bits_long(gb, d) + 1);
313                 } else {
314                     z = xcodes[value].scale * c + x - xcodes[value].escape;
315                 }
316             } else {
317                 z = x - (xcodes[value].escape & -y);
318             }
319             dst[i++] = (z >> 1) ^ -(z & 1);
320         } while (i < len);
321     }
322
323     return 0;
324 }
325
326 static int xget(TAKDecContext *s, int d, int q)
327 {
328     int x;
329
330     x = d / q;
331
332     s->rval = d - (x * q);
333
334     if (s->rval < q / 2) {
335         s->rval += q;
336     } else {
337         x++;
338     }
339
340     if (x <= 1 || x > 128)
341         return -1;
342
343     return x;
344 }
345
346 static int get_len(TAKDecContext *s, int b)
347 {
348     if (b >= s->wlength - 1)
349         return s->rval;
350     else
351         return s->uval;
352 }
353
354 static int decode_coeffs(TAKDecContext *s, int32_t *dst, int length)
355 {
356     GetBitContext *gb = &s->gb;
357     int i, v, ret;
358
359     if (length > s->nb_samples)
360         return AVERROR_INVALIDDATA;
361
362     if (get_bits1(gb)) {
363         if ((s->wlength = xget(s, length, s->uval)) < 0)
364             return AVERROR_INVALIDDATA;
365
366         s->coding_mode[0] = v = get_bits(gb, 6);
367         if (s->coding_mode[0] > FF_ARRAY_ELEMS(xcodes))
368             return AVERROR_INVALIDDATA;
369
370         for (i = 1; i < s->wlength; i++) {
371             int c = get_unary(gb, 1, 6);
372
373             if (c > 5) {
374                 v = get_bits(gb, 6);
375             } else if (c > 2) {
376                 int t = get_bits1(gb);
377
378                 v += (-t ^ (c - 1)) + t;
379             } else {
380                 v += (-(c & 1) ^ (((c & 1) + c) >> 1)) + (c & 1);
381             }
382
383             if (v > FF_ARRAY_ELEMS(xcodes))
384                 return AVERROR_INVALIDDATA;
385             s->coding_mode[i] = v;
386         }
387
388         i = 0;
389         while (i < s->wlength) {
390             int len = 0;
391
392             v = s->coding_mode[i];
393             do {
394                 len += get_len(s, i);
395                 i++;
396
397                 if (i == s->wlength)
398                     break;
399             } while (v == s->coding_mode[i]);
400
401             if ((ret = decode_segment(s, v, dst, len)) < 0)
402                 return ret;
403             dst += len;
404         }
405     } else {
406         v = get_bits(gb, 6);
407         if (v > FF_ARRAY_ELEMS(xcodes))
408             return AVERROR_INVALIDDATA;
409         if ((ret = decode_segment(s, v, dst, length)) < 0)
410             return ret;
411     }
412
413     return 0;
414 }
415
416 static int get_b(GetBitContext *gb)
417 {
418     if (get_bits1(gb))
419         return get_bits(gb, 4) + 1;
420     else
421         return 0;
422 }
423
424 static int decode_subframe(TAKDecContext *s, int32_t *ptr, int subframe_size,
425                            int prev_subframe_size)
426 {
427     GetBitContext  *gb = &s->gb;
428     int tmp, x, y, i, j, ret = 0;
429     int tfilter[MAX_PREDICTORS];
430
431     if (get_bits1(gb)) {
432         s->filter_order = predictor_sizes[get_bits(gb, 4)];
433
434         if (prev_subframe_size > 0 && get_bits1(gb)) {
435             if (s->filter_order > prev_subframe_size)
436                 return AVERROR_INVALIDDATA;
437
438             ptr           -= s->filter_order;
439             subframe_size += s->filter_order;
440
441             if (s->filter_order > subframe_size)
442                 return AVERROR_INVALIDDATA;
443         } else {
444             int lpc;
445
446             if (s->filter_order > subframe_size)
447                 return AVERROR_INVALIDDATA;
448
449             lpc = get_bits(gb, 2);
450             if (lpc > 2)
451                 return AVERROR_INVALIDDATA;
452
453             if ((ret = decode_coeffs(s, ptr, s->filter_order)) < 0)
454                 return ret;
455
456             decode_lpc(ptr, lpc, s->filter_order);
457         }
458
459         s->xred = get_b(gb);
460         s->size = get_bits1(gb) + 5;
461
462         if (get_bits1(gb)) {
463             s->ared = get_bits(gb, 3) + 1;
464             if (s->ared > 7)
465                 return AVERROR_INVALIDDATA;
466         } else {
467             s->ared = 0;
468         }
469         s->predictors[0] = get_code(gb, 10);
470         s->predictors[1] = get_code(gb, 10);
471         s->predictors[2] = get_code(gb, s->size + 1) << (9 - s->size);
472         s->predictors[3] = get_code(gb, s->size + 1) << (9 - s->size);
473         if (s->filter_order > 4) {
474             tmp = s->size + 1 - get_bits1(gb);
475
476             for (i = 4; i < s->filter_order; i++) {
477                 if (!(i & 3))
478                     x = tmp - get_bits(gb, 2);
479                 s->predictors[i] = get_code(gb, x) << (9 - s->size);
480             }
481         }
482
483         tfilter[0] = s->predictors[0] << 6;
484         for (i = 1; i < s->filter_order; i++) {
485             int32_t *p1 = &tfilter[0];
486             int32_t *p2 = &tfilter[i - 1];
487
488             for (j = 0; j < (i + 1) / 2; j++) {
489                 x     = *p1 + (s->predictors[i] * *p2 + 256 >> 9);
490                 *p2  += s->predictors[i] * *p1 + 256 >> 9;
491                 *p1++ = x;
492                 p2--;
493             }
494
495             tfilter[i] = s->predictors[i] << 6;
496         }
497
498         x = -1 << (32 - (s->ared + 5));
499         y =  1 << ((s->ared + 5) - 1);
500         for (i = 0, j = s->filter_order - 1; i < s->filter_order / 2; i++, j--) {
501             tmp = y + tfilter[j];
502             s->filter[j] = -(x & -(y + tfilter[i] >> 31) |
503                             (y + tfilter[i]) >> (s->ared + 5));
504             s->filter[i] = -(x & -(tmp >> 31) | (tmp >> s->ared + 5));
505         }
506
507         if ((ret = decode_coeffs(s, &ptr[s->filter_order],
508                                  subframe_size - s->filter_order)) < 0)
509             return ret;
510
511         for (i = 0; i < s->filter_order; i++)
512             s->residues[i] = *ptr++ >> s->xred;
513
514         y    = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
515         x    = subframe_size - s->filter_order;
516         while (x > 0) {
517             tmp = FFMIN(y, x);
518
519             for (i = 0; i < tmp; i++) {
520                 int v, w, m;
521
522                 v = 1 << (10 - s->ared - 1);
523                 if (!(s->filter_order & 15)) {
524                     v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
525                                                     s->filter_order);
526                 } else if (s->filter_order & 4) {
527                     for (j = 0; j < s->filter_order; j += 4) {
528                         v += s->residues[i + j + 3] * s->filter[j + 3] +
529                              s->residues[i + j + 2] * s->filter[j + 2] +
530                              s->residues[i + j + 1] * s->filter[j + 1] +
531                              s->residues[i + j    ] * s->filter[j    ];
532                     }
533                 } else {
534                     for (j = 0; j < s->filter_order; j += 8) {
535                         v += s->residues[i + j + 7] * s->filter[j + 7] +
536                              s->residues[i + j + 6] * s->filter[j + 6] +
537                              s->residues[i + j + 5] * s->filter[j + 5] +
538                              s->residues[i + j + 4] * s->filter[j + 4] +
539                              s->residues[i + j + 3] * s->filter[j + 3] +
540                              s->residues[i + j + 2] * s->filter[j + 2] +
541                              s->residues[i + j + 1] * s->filter[j + 1] +
542                              s->residues[i + j    ] * s->filter[j    ];
543                     }
544                 }
545                 m = (-1 << (32 - (10 - s->ared))) & -(v >> 31) | (v >> 10 - s->ared);
546                 m = av_clip(m, -8192, 8191);
547                 w = (m << s->xred) - *ptr;
548                 *ptr++ = w;
549                 s->residues[s->filter_order + i] = w >> s->xred;
550             }
551
552             x -= tmp;
553             if (x > 0)
554                 memcpy(s->residues, &s->residues[y], 2 * s->filter_order);
555         }
556
557         emms_c();
558     } else {
559         ret = decode_coeffs(s, ptr, subframe_size);
560     }
561
562     return ret;
563 }
564
565 static int decode_channel(TAKDecContext *s, int chan)
566 {
567     AVCodecContext *avctx = s->avctx;
568     GetBitContext  *gb = &s->gb;
569     int32_t *dst = s->decoded[chan];
570     int i = 0, ret, prev = 0;
571     int left = s->nb_samples - 1;
572
573     s->sample_shift[chan] = get_b(gb);
574     if (s->sample_shift[chan] >= avctx->bits_per_raw_sample)
575         return AVERROR_INVALIDDATA;
576
577     *dst++ = get_code(gb, avctx->bits_per_raw_sample - s->sample_shift[chan]);
578     s->lpc_mode[chan] = get_bits(gb, 2);
579     s->nb_subframes   = get_bits(gb, 3) + 1;
580
581     if (s->nb_subframes > 1) {
582         if (get_bits_left(gb) < (s->nb_subframes - 1) * 6)
583             return AVERROR_INVALIDDATA;
584
585         for (; i < s->nb_subframes - 1; i++) {
586             int v = get_bits(gb, 6);
587
588             s->subframe_len[i] = (v - prev) * s->subframe_scale;
589             if (s->subframe_len[i] <= 0)
590                 return AVERROR_INVALIDDATA;
591
592             left -= s->subframe_len[i];
593             prev  = v;
594         }
595
596         if (left <= 0)
597             return AVERROR_INVALIDDATA;
598     }
599
600     s->subframe_len[i] = left;
601     prev = 0;
602     for (i = 0; i < s->nb_subframes; i++) {
603         if ((ret = decode_subframe(s, dst, s->subframe_len[i], prev)) < 0)
604             return ret;
605         dst += s->subframe_len[i];
606         prev = s->subframe_len[i];
607     }
608
609     return 0;
610 }
611
612 static int decorrelate(TAKDecContext *s, int c1, int c2, int length)
613 {
614     GetBitContext  *gb = &s->gb;
615     uint32_t *p1 = s->decoded[c1] + 1;
616     uint32_t *p2 = s->decoded[c2] + 1;
617     int a, b, i, x, tmp;
618
619     if (s->dmode > 3) {
620         s->dshift = get_b(gb);
621         if (s->dmode > 5) {
622             if (get_bits1(gb))
623                 s->filter_order = 16;
624             else
625                 s->filter_order = 8;
626
627             s->dval1 = get_bits1(gb);
628             s->dval2 = get_bits1(gb);
629
630             for (i = 0; i < s->filter_order; i++) {
631                 if (!(i & 3))
632                     x = 14 - get_bits(gb, 3);
633                 s->filter[i] = get_code(gb, x);
634             }
635         } else {
636             s->dfactor = get_code(gb, 10);
637         }
638     }
639
640     switch (s->dmode) {
641     case 1:
642         for (i = 0; i < length; i++, p1++, p2++)
643             *p2 += *p1;
644         break;
645     case 2:
646         for (i = 0; i < length; i++, p1++, p2++)
647             *p1 = *p2 - *p1;
648         break;
649     case 3:
650         for (i = 0; i < length; i++, p1++, p2++) {
651             x   = (*p2 & 1) + 2 * *p1;
652             a   = -*p2 + x;
653             b   =  *p2 + x;
654             *p1 = a & 0x80000000 | (a >> 1);
655             *p2 = b & 0x80000000 | (b >> 1);
656         }
657         break;
658     case 4:
659         FFSWAP(uint32_t *, p1, p2);
660     case 5:
661         if (s->dshift)
662             tmp = -1 << (32 - s->dshift);
663         else
664             tmp = 0;
665
666         for (i = 0; i < length; i++, p1++, p2++) {
667             x   = s->dfactor * (tmp & -(*p2 >> 31) | (*p2 >> s->dshift)) + 128;
668             *p1 = ((-(x >> 31) & 0xFF000000 | (x >> 8)) << s->dshift) - *p1;
669         }
670         break;
671     case 6:
672         FFSWAP(uint32_t *, p1, p2);
673     case 7:
674         if (length < 256)
675             return AVERROR_INVALIDDATA;
676
677         a = s->filter_order / 2;
678         b = length - (s->filter_order - 1);
679
680         if (s->dval1) {
681             for (i = 0; i < a; i++)
682                 p1[i] += p2[i];
683         }
684
685         if (s->dval2) {
686             x = a + b;
687             for (i = 0; i < length - x; i++)
688                 p1[x + i] += p2[x + i];
689         }
690
691         for (i = 0; i < s->filter_order; i++)
692             s->residues[i] = *p2++ >> s->dshift;
693
694         p1 += a;
695         x = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
696         for (; b > 0; b -= tmp) {
697             tmp = FFMIN(b, x);
698
699             for (i = 0; i < tmp; i++)
700                 s->residues[s->filter_order + i] = *p2++ >> s->dshift;
701
702             for (i = 0; i < tmp; i++) {
703                 int v, w, m;
704
705                 v = 1 << 9;
706
707                 if (s->filter_order == 16) {
708                     v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
709                                                     s->filter_order);
710                 } else {
711                     v += s->residues[i + 7] * s->filter[7] +
712                          s->residues[i + 6] * s->filter[6] +
713                          s->residues[i + 5] * s->filter[5] +
714                          s->residues[i + 4] * s->filter[4] +
715                          s->residues[i + 3] * s->filter[3] +
716                          s->residues[i + 2] * s->filter[2] +
717                          s->residues[i + 1] * s->filter[1] +
718                          s->residues[i    ] * s->filter[0];
719                 }
720
721                 m = (-1 << 22) & -(v >> 31) | (v >> 10);
722                 m = av_clip(m, -8192, 8191);
723                 w = (m << s->dshift) - *p1;
724                 *p1++ = w;
725             }
726
727             memcpy(s->residues, &s->residues[tmp], 2 * s->filter_order);
728         }
729
730         emms_c();
731         break;
732     }
733
734     return 0;
735 }
736
737 static int tak_decode_frame(AVCodecContext *avctx, void *data,
738                             int *got_frame_ptr, AVPacket *pkt)
739 {
740     TAKDecContext  *s = avctx->priv_data;
741     GetBitContext *gb = &s->gb;
742     int chan, i, ret, hsize;
743     int32_t *p;
744
745     if (pkt->size < TAK_MIN_FRAME_HEADER_BYTES)
746         return AVERROR_INVALIDDATA;
747
748     init_get_bits(gb, pkt->data, pkt->size * 8);
749
750     if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti, 0)) < 0)
751         return ret;
752
753     if (avctx->err_recognition & AV_EF_CRCCHECK) {
754         hsize = get_bits_count(gb) / 8;
755         if (ff_tak_check_crc(pkt->data, hsize)) {
756             av_log(avctx, AV_LOG_ERROR, "CRC error\n");
757             return AVERROR_INVALIDDATA;
758         }
759     }
760
761     if (s->ti.codec != 2 && s->ti.codec != 4) {
762         av_log(avctx, AV_LOG_ERROR, "unsupported codec: %d\n", s->ti.codec);
763         return AVERROR_PATCHWELCOME;
764     }
765     if (s->ti.data_type) {
766         av_log(avctx, AV_LOG_ERROR, "unsupported data type: %d\n", s->ti.data_type);
767         return AVERROR_INVALIDDATA;
768     }
769     if (s->ti.codec == 2 && s->ti.channels > 2) {
770         av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", s->ti.channels);
771         return AVERROR_INVALIDDATA;
772     }
773     if (s->ti.channels > 6) {
774         av_log(avctx, AV_LOG_ERROR, "unsupported number of channels: %d\n", s->ti.channels);
775         return AVERROR_INVALIDDATA;
776     }
777
778     if (s->ti.frame_samples <= 0) {
779         av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of samples\n");
780         return AVERROR_INVALIDDATA;
781     }
782
783     if (s->ti.bps != avctx->bits_per_raw_sample) {
784         avctx->bits_per_raw_sample = s->ti.bps;
785         if ((ret = tak_set_bps(avctx, avctx->bits_per_raw_sample)) < 0)
786             return ret;
787     }
788     if (s->ti.sample_rate != avctx->sample_rate) {
789         avctx->sample_rate = s->ti.sample_rate;
790         s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
791         s->subframe_scale = get_scale(avctx->sample_rate, 1);
792     }
793     if (s->ti.ch_layout)
794         avctx->channel_layout = s->ti.ch_layout;
795     avctx->channels = s->ti.channels;
796
797     s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples :
798                                                s->ti.frame_samples;
799
800     s->frame.nb_samples = s->nb_samples;
801     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0)
802         return ret;
803
804     if (avctx->bits_per_raw_sample <= 16) {
805         av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size,
806                        sizeof(*s->decode_buffer) * FFALIGN(s->nb_samples, 8) *
807                        avctx->channels + FF_INPUT_BUFFER_PADDING_SIZE);
808         if (!s->decode_buffer)
809             return AVERROR(ENOMEM);
810         for (chan = 0; chan < avctx->channels; chan++)
811             s->decoded[chan] = s->decode_buffer +
812                                chan * FFALIGN(s->nb_samples, 8);
813     } else {
814         for (chan = 0; chan < avctx->channels; chan++)
815             s->decoded[chan] = (int32_t *)s->frame.data[chan];
816     }
817
818     if (s->nb_samples < 16) {
819         for (chan = 0; chan < avctx->channels; chan++) {
820             p = s->decoded[chan];
821             for (i = 0; i < s->nb_samples; i++)
822                 *p++ = get_code(gb, avctx->bits_per_raw_sample);
823         }
824     } else {
825         if (s->ti.codec == 2) {
826             for (chan = 0; chan < avctx->channels; chan++) {
827                 if (ret = decode_channel(s, chan))
828                     return ret;
829             }
830
831             if (avctx->channels == 2) {
832                 s->nb_subframes = get_bits(gb, 1) + 1;
833                 if (s->nb_subframes > 1)
834                     s->subframe_len[1] = get_bits(gb, 6);
835
836                 s->dmode = get_bits(gb, 3);
837                 if (ret = decorrelate(s, 0, 1, s->nb_samples - 1))
838                     return ret;
839             }
840         } else if (s->ti.codec == 4) {
841             if (get_bits1(gb)) {
842                 int ch_mask = 0;
843
844                 chan = get_bits(gb, 4) + 1;
845                 if (chan > avctx->channels)
846                     return AVERROR_INVALIDDATA;
847
848                 for (i = 0; i < chan; i++) {
849                     int nbit = get_bits(gb, 4);
850
851                     if (nbit >= avctx->channels)
852                         return AVERROR_INVALIDDATA;
853
854                     if (ch_mask & 1 << nbit)
855                         return AVERROR_INVALIDDATA;
856
857                     s->mcdparams[i].present = get_bits1(gb);
858                     if (s->mcdparams[i].present) {
859                         s->mcdparams[i].index = get_bits(gb, 2);
860                         s->mcdparams[i].chan2 = get_bits(gb, 4);
861                         if (s->mcdparams[i].index == 1) {
862                             if ((nbit == s->mcdparams[i].chan2) ||
863                                 (ch_mask & 1 << s->mcdparams[i].chan2))
864                                 return AVERROR_INVALIDDATA;
865
866                             ch_mask |= 1 << s->mcdparams[i].chan2;
867                         } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) {
868                             return AVERROR_INVALIDDATA;
869                         }
870                     }
871                     s->mcdparams[i].chan1 = nbit;
872
873                     ch_mask |= 1 << nbit;
874                 }
875             } else {
876                 chan = avctx->channels;
877                 for (i = 0; i < chan; i++) {
878                     s->mcdparams[i].present = 0;
879                     s->mcdparams[i].chan1   = i;
880                 }
881             }
882
883             for (i = 0; i < chan; i++) {
884                 if (s->mcdparams[i].present && s->mcdparams[i].index == 1) {
885                     if (ret = decode_channel(s, s->mcdparams[i].chan2))
886                         return ret;
887                 }
888
889                 if (ret = decode_channel(s, s->mcdparams[i].chan1))
890                     return ret;
891
892                 if (s->mcdparams[i].present) {
893                     s->dmode = mc_dmodes[s->mcdparams[i].index];
894                     if (ret = decorrelate(s, s->mcdparams[i].chan2,
895                                              s->mcdparams[i].chan1,
896                                              s->nb_samples - 1))
897                         return ret;
898                 }
899             }
900         }
901
902         for (chan = 0; chan < avctx->channels; chan++) {
903             p = s->decoded[chan];
904             decode_lpc(p, s->lpc_mode[chan], s->nb_samples);
905
906             if (s->sample_shift[chan] > 0) {
907                 for (i = 0; i < s->nb_samples; i++)
908                     *p++ <<= s->sample_shift[chan];
909             }
910         }
911     }
912
913     align_get_bits(gb);
914     skip_bits(gb, 24);
915     if (get_bits_left(gb) < 0)
916         av_log(avctx, AV_LOG_DEBUG, "overread\n");
917     else if (get_bits_left(gb) > 0)
918         av_log(avctx, AV_LOG_DEBUG, "underread\n");
919
920     if (avctx->err_recognition & AV_EF_CRCCHECK) {
921         if (ff_tak_check_crc(pkt->data + hsize,
922                              get_bits_count(gb) / 8 - hsize)) {
923             av_log(avctx, AV_LOG_ERROR, "CRC error\n");
924             return AVERROR_INVALIDDATA;
925         }
926     }
927
928     // convert to output buffer
929     switch (avctx->bits_per_raw_sample) {
930     case 8:
931         for (chan = 0; chan < avctx->channels; chan++) {
932             uint8_t *samples = (uint8_t *)s->frame.data[chan];
933             p = s->decoded[chan];
934             for (i = 0; i < s->nb_samples; i++, p++)
935                 *samples++ = *p + 0x80;
936         }
937         break;
938     case 16:
939         for (chan = 0; chan < avctx->channels; chan++) {
940             int16_t *samples = (int16_t *)s->frame.data[chan];
941             p = s->decoded[chan];
942             for (i = 0; i < s->nb_samples; i++, p++)
943                 *samples++ = *p;
944         }
945         break;
946     case 24:
947         for (chan = 0; chan < avctx->channels; chan++) {
948             int32_t *samples = (int32_t *)s->frame.data[chan];
949             for (i = 0; i < s->nb_samples; i++)
950                 *samples++ <<= 8;
951         }
952         break;
953     }
954
955     *got_frame_ptr   = 1;
956     *(AVFrame *)data = s->frame;
957
958     return pkt->size;
959 }
960
961 static av_cold int tak_decode_close(AVCodecContext *avctx)
962 {
963     TAKDecContext *s = avctx->priv_data;
964
965     av_freep(&s->decode_buffer);
966
967     return 0;
968 }
969
970 AVCodec ff_tak_decoder = {
971     .name           = "tak",
972     .type           = AVMEDIA_TYPE_AUDIO,
973     .id             = AV_CODEC_ID_TAK,
974     .priv_data_size = sizeof(TAKDecContext),
975     .init           = tak_decode_init,
976     .close          = tak_decode_close,
977     .decode         = tak_decode_frame,
978     .capabilities   = CODEC_CAP_DR1,
979     .long_name      = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
980 };