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