]> git.sesse.net Git - ffmpeg/blob - libavcodec/apedec.c
avcodec/apedec: Fixes integer overflow of res+*data in do_apply_filter()
[ffmpeg] / libavcodec / apedec.c
1 /*
2  * Monkey's Audio lossless audio decoder
3  * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4  *  based upon libdemac from Dave Chapman.
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <inttypes.h>
24
25 #include "libavutil/avassert.h"
26 #include "libavutil/channel_layout.h"
27 #include "libavutil/opt.h"
28 #include "lossless_audiodsp.h"
29 #include "avcodec.h"
30 #include "bswapdsp.h"
31 #include "bytestream.h"
32 #include "internal.h"
33 #include "get_bits.h"
34 #include "unary.h"
35
36 /**
37  * @file
38  * Monkey's Audio lossless audio decoder
39  */
40
41 #define MAX_CHANNELS        2
42 #define MAX_BYTESPERSAMPLE  3
43
44 #define APE_FRAMECODE_MONO_SILENCE    1
45 #define APE_FRAMECODE_STEREO_SILENCE  3
46 #define APE_FRAMECODE_PSEUDO_STEREO   4
47
48 #define HISTORY_SIZE 512
49 #define PREDICTOR_ORDER 8
50 /** Total size of all predictor histories */
51 #define PREDICTOR_SIZE 50
52
53 #define YDELAYA (18 + PREDICTOR_ORDER*4)
54 #define YDELAYB (18 + PREDICTOR_ORDER*3)
55 #define XDELAYA (18 + PREDICTOR_ORDER*2)
56 #define XDELAYB (18 + PREDICTOR_ORDER)
57
58 #define YADAPTCOEFFSA 18
59 #define XADAPTCOEFFSA 14
60 #define YADAPTCOEFFSB 10
61 #define XADAPTCOEFFSB 5
62
63 /**
64  * Possible compression levels
65  * @{
66  */
67 enum APECompressionLevel {
68     COMPRESSION_LEVEL_FAST       = 1000,
69     COMPRESSION_LEVEL_NORMAL     = 2000,
70     COMPRESSION_LEVEL_HIGH       = 3000,
71     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
72     COMPRESSION_LEVEL_INSANE     = 5000
73 };
74 /** @} */
75
76 #define APE_FILTER_LEVELS 3
77
78 /** Filter orders depending on compression level */
79 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
80     {  0,   0,    0 },
81     { 16,   0,    0 },
82     { 64,   0,    0 },
83     { 32, 256,    0 },
84     { 16, 256, 1280 }
85 };
86
87 /** Filter fraction bits depending on compression level */
88 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
89     {  0,  0,  0 },
90     { 11,  0,  0 },
91     { 11,  0,  0 },
92     { 10, 13,  0 },
93     { 11, 13, 15 }
94 };
95
96
97 /** Filters applied to the decoded data */
98 typedef struct APEFilter {
99     int16_t *coeffs;        ///< actual coefficients used in filtering
100     int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
101     int16_t *historybuffer; ///< filter memory
102     int16_t *delay;         ///< filtered values
103
104     int avg;
105 } APEFilter;
106
107 typedef struct APERice {
108     uint32_t k;
109     uint32_t ksum;
110 } APERice;
111
112 typedef struct APERangecoder {
113     uint32_t low;           ///< low end of interval
114     uint32_t range;         ///< length of interval
115     uint32_t help;          ///< bytes_to_follow resp. intermediate value
116     unsigned int buffer;    ///< buffer for input/output
117 } APERangecoder;
118
119 /** Filter histories */
120 typedef struct APEPredictor {
121     int32_t *buf;
122
123     int32_t lastA[2];
124
125     int32_t filterA[2];
126     int32_t filterB[2];
127
128     uint32_t coeffsA[2][4];  ///< adaption coefficients
129     uint32_t coeffsB[2][5];  ///< adaption coefficients
130     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
131
132     unsigned int sample_pos;
133 } APEPredictor;
134
135 /** Decoder context */
136 typedef struct APEContext {
137     AVClass *class;                          ///< class for AVOptions
138     AVCodecContext *avctx;
139     BswapDSPContext bdsp;
140     LLAudDSPContext adsp;
141     int channels;
142     int samples;                             ///< samples left to decode in current frame
143     int bps;
144
145     int fileversion;                         ///< codec version, very important in decoding process
146     int compression_level;                   ///< compression levels
147     int fset;                                ///< which filter set to use (calculated from compression level)
148     int flags;                               ///< global decoder flags
149
150     uint32_t CRC;                            ///< frame CRC
151     int frameflags;                          ///< frame flags
152     APEPredictor predictor;                  ///< predictor used for final reconstruction
153
154     int32_t *decoded_buffer;
155     int decoded_size;
156     int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel
157     int blocks_per_loop;                     ///< maximum number of samples to decode for each call
158
159     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
160
161     APERangecoder rc;                        ///< rangecoder used to decode actual values
162     APERice riceX;                           ///< rice code parameters for the second channel
163     APERice riceY;                           ///< rice code parameters for the first channel
164     APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
165     GetBitContext gb;
166
167     uint8_t *data;                           ///< current frame data
168     uint8_t *data_end;                       ///< frame data end
169     int data_size;                           ///< frame data allocated size
170     const uint8_t *ptr;                      ///< current position in frame data
171
172     int error;
173
174     void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
175     void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
176     void (*predictor_decode_mono)(struct APEContext *ctx, int count);
177     void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
178 } APEContext;
179
180 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
181                               int32_t *decoded1, int count);
182
183 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
184 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
185 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
186 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
187 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
188 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
189 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
190 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
191 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
192
193 static void predictor_decode_mono_3800(APEContext *ctx, int count);
194 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
195 static void predictor_decode_mono_3930(APEContext *ctx, int count);
196 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
197 static void predictor_decode_mono_3950(APEContext *ctx, int count);
198 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
199
200 static av_cold int ape_decode_close(AVCodecContext *avctx)
201 {
202     APEContext *s = avctx->priv_data;
203     int i;
204
205     for (i = 0; i < APE_FILTER_LEVELS; i++)
206         av_freep(&s->filterbuf[i]);
207
208     av_freep(&s->decoded_buffer);
209     av_freep(&s->data);
210     s->decoded_size = s->data_size = 0;
211
212     return 0;
213 }
214
215 static av_cold int ape_decode_init(AVCodecContext *avctx)
216 {
217     APEContext *s = avctx->priv_data;
218     int i;
219
220     if (avctx->extradata_size != 6) {
221         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
222         return AVERROR(EINVAL);
223     }
224     if (avctx->channels > 2) {
225         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
226         return AVERROR(EINVAL);
227     }
228     s->bps = avctx->bits_per_coded_sample;
229     switch (s->bps) {
230     case 8:
231         avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
232         break;
233     case 16:
234         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
235         break;
236     case 24:
237         avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
238         break;
239     default:
240         avpriv_request_sample(avctx,
241                               "%d bits per coded sample", s->bps);
242         return AVERROR_PATCHWELCOME;
243     }
244     s->avctx             = avctx;
245     s->channels          = avctx->channels;
246     s->fileversion       = AV_RL16(avctx->extradata);
247     s->compression_level = AV_RL16(avctx->extradata + 2);
248     s->flags             = AV_RL16(avctx->extradata + 4);
249
250     av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
251            s->compression_level, s->flags);
252     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
253         !s->compression_level ||
254         (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
255         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
256                s->compression_level);
257         return AVERROR_INVALIDDATA;
258     }
259     s->fset = s->compression_level / 1000 - 1;
260     for (i = 0; i < APE_FILTER_LEVELS; i++) {
261         if (!ape_filter_orders[s->fset][i])
262             break;
263         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
264                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
265                          filter_alloc_fail);
266     }
267
268     if (s->fileversion < 3860) {
269         s->entropy_decode_mono   = entropy_decode_mono_0000;
270         s->entropy_decode_stereo = entropy_decode_stereo_0000;
271     } else if (s->fileversion < 3900) {
272         s->entropy_decode_mono   = entropy_decode_mono_3860;
273         s->entropy_decode_stereo = entropy_decode_stereo_3860;
274     } else if (s->fileversion < 3930) {
275         s->entropy_decode_mono   = entropy_decode_mono_3900;
276         s->entropy_decode_stereo = entropy_decode_stereo_3900;
277     } else if (s->fileversion < 3990) {
278         s->entropy_decode_mono   = entropy_decode_mono_3900;
279         s->entropy_decode_stereo = entropy_decode_stereo_3930;
280     } else {
281         s->entropy_decode_mono   = entropy_decode_mono_3990;
282         s->entropy_decode_stereo = entropy_decode_stereo_3990;
283     }
284
285     if (s->fileversion < 3930) {
286         s->predictor_decode_mono   = predictor_decode_mono_3800;
287         s->predictor_decode_stereo = predictor_decode_stereo_3800;
288     } else if (s->fileversion < 3950) {
289         s->predictor_decode_mono   = predictor_decode_mono_3930;
290         s->predictor_decode_stereo = predictor_decode_stereo_3930;
291     } else {
292         s->predictor_decode_mono   = predictor_decode_mono_3950;
293         s->predictor_decode_stereo = predictor_decode_stereo_3950;
294     }
295
296     ff_bswapdsp_init(&s->bdsp);
297     ff_llauddsp_init(&s->adsp);
298     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
299
300     return 0;
301 filter_alloc_fail:
302     ape_decode_close(avctx);
303     return AVERROR(ENOMEM);
304 }
305
306 /**
307  * @name APE range decoding functions
308  * @{
309  */
310
311 #define CODE_BITS    32
312 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
313 #define SHIFT_BITS   (CODE_BITS - 9)
314 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
315 #define BOTTOM_VALUE (TOP_VALUE >> 8)
316
317 /** Start the decoder */
318 static inline void range_start_decoding(APEContext *ctx)
319 {
320     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
321     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
322     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
323 }
324
325 /** Perform normalization */
326 static inline void range_dec_normalize(APEContext *ctx)
327 {
328     while (ctx->rc.range <= BOTTOM_VALUE) {
329         ctx->rc.buffer <<= 8;
330         if(ctx->ptr < ctx->data_end) {
331             ctx->rc.buffer += *ctx->ptr;
332             ctx->ptr++;
333         } else {
334             ctx->error = 1;
335         }
336         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
337         ctx->rc.range  <<= 8;
338     }
339 }
340
341 /**
342  * Calculate cumulative frequency for next symbol. Does NO update!
343  * @param ctx decoder context
344  * @param tot_f is the total frequency or (code_value)1<<shift
345  * @return the cumulative frequency
346  */
347 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
348 {
349     range_dec_normalize(ctx);
350     ctx->rc.help = ctx->rc.range / tot_f;
351     return ctx->rc.low / ctx->rc.help;
352 }
353
354 /**
355  * Decode value with given size in bits
356  * @param ctx decoder context
357  * @param shift number of bits to decode
358  */
359 static inline int range_decode_culshift(APEContext *ctx, int shift)
360 {
361     range_dec_normalize(ctx);
362     ctx->rc.help = ctx->rc.range >> shift;
363     return ctx->rc.low / ctx->rc.help;
364 }
365
366
367 /**
368  * Update decoding state
369  * @param ctx decoder context
370  * @param sy_f the interval length (frequency of the symbol)
371  * @param lt_f the lower end (frequency sum of < symbols)
372  */
373 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
374 {
375     ctx->rc.low  -= ctx->rc.help * lt_f;
376     ctx->rc.range = ctx->rc.help * sy_f;
377 }
378
379 /** Decode n bits (n <= 16) without modelling */
380 static inline int range_decode_bits(APEContext *ctx, int n)
381 {
382     int sym = range_decode_culshift(ctx, n);
383     range_decode_update(ctx, 1, sym);
384     return sym;
385 }
386
387
388 #define MODEL_ELEMENTS 64
389
390 /**
391  * Fixed probabilities for symbols in Monkey Audio version 3.97
392  */
393 static const uint16_t counts_3970[22] = {
394         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
395     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
396     65450, 65469, 65480, 65487, 65491, 65493,
397 };
398
399 /**
400  * Probability ranges for symbols in Monkey Audio version 3.97
401  */
402 static const uint16_t counts_diff_3970[21] = {
403     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
404     1104, 677, 415, 248, 150, 89, 54, 31,
405     19, 11, 7, 4, 2,
406 };
407
408 /**
409  * Fixed probabilities for symbols in Monkey Audio version 3.98
410  */
411 static const uint16_t counts_3980[22] = {
412         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
413     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
414     65485, 65488, 65490, 65491, 65492, 65493,
415 };
416
417 /**
418  * Probability ranges for symbols in Monkey Audio version 3.98
419  */
420 static const uint16_t counts_diff_3980[21] = {
421     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
422     261, 119, 65, 31, 19, 10, 6, 3,
423     3, 2, 1, 1, 1,
424 };
425
426 /**
427  * Decode symbol
428  * @param ctx decoder context
429  * @param counts probability range start position
430  * @param counts_diff probability range widths
431  */
432 static inline int range_get_symbol(APEContext *ctx,
433                                    const uint16_t counts[],
434                                    const uint16_t counts_diff[])
435 {
436     int symbol, cf;
437
438     cf = range_decode_culshift(ctx, 16);
439
440     if(cf > 65492){
441         symbol= cf - 65535 + 63;
442         range_decode_update(ctx, 1, cf);
443         if(cf > 65535)
444             ctx->error=1;
445         return symbol;
446     }
447     /* figure out the symbol inefficiently; a binary search would be much better */
448     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
449
450     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
451
452     return symbol;
453 }
454 /** @} */ // group rangecoder
455
456 static inline void update_rice(APERice *rice, unsigned int x)
457 {
458     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
459     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
460
461     if (rice->ksum < lim)
462         rice->k--;
463     else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
464         rice->k++;
465 }
466
467 static inline int get_rice_ook(GetBitContext *gb, int k)
468 {
469     unsigned int x;
470
471     x = get_unary(gb, 1, get_bits_left(gb));
472
473     if (k)
474         x = (x << k) | get_bits(gb, k);
475
476     return x;
477 }
478
479 static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
480                                         APERice *rice)
481 {
482     unsigned int x, overflow;
483
484     overflow = get_unary(gb, 1, get_bits_left(gb));
485
486     if (ctx->fileversion > 3880) {
487         while (overflow >= 16) {
488             overflow -= 16;
489             rice->k  += 4;
490         }
491     }
492
493     if (!rice->k)
494         x = overflow;
495     else if(rice->k <= MIN_CACHE_BITS) {
496         x = (overflow << rice->k) + get_bits(gb, rice->k);
497     } else {
498         av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
499         return AVERROR_INVALIDDATA;
500     }
501     rice->ksum += x - (rice->ksum + 8 >> 4);
502     if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
503         rice->k--;
504     else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
505         rice->k++;
506
507     /* Convert to signed */
508     return ((x >> 1) ^ ((x & 1) - 1)) + 1;
509 }
510
511 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
512 {
513     unsigned int x, overflow;
514     int tmpk;
515
516     overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
517
518     if (overflow == (MODEL_ELEMENTS - 1)) {
519         tmpk = range_decode_bits(ctx, 5);
520         overflow = 0;
521     } else
522         tmpk = (rice->k < 1) ? 0 : rice->k - 1;
523
524     if (tmpk <= 16 || ctx->fileversion < 3910) {
525         if (tmpk > 23) {
526             av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
527             return AVERROR_INVALIDDATA;
528         }
529         x = range_decode_bits(ctx, tmpk);
530     } else if (tmpk <= 31) {
531         x = range_decode_bits(ctx, 16);
532         x |= (range_decode_bits(ctx, tmpk - 16) << 16);
533     } else {
534         av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
535         return AVERROR_INVALIDDATA;
536     }
537     x += overflow << tmpk;
538
539     update_rice(rice, x);
540
541     /* Convert to signed */
542     return ((x >> 1) ^ ((x & 1) - 1)) + 1;
543 }
544
545 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
546 {
547     unsigned int x, overflow;
548     int base, pivot;
549
550     pivot = rice->ksum >> 5;
551     if (pivot == 0)
552         pivot = 1;
553
554     overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
555
556     if (overflow == (MODEL_ELEMENTS - 1)) {
557         overflow  = (unsigned)range_decode_bits(ctx, 16) << 16;
558         overflow |= range_decode_bits(ctx, 16);
559     }
560
561     if (pivot < 0x10000) {
562         base = range_decode_culfreq(ctx, pivot);
563         range_decode_update(ctx, 1, base);
564     } else {
565         int base_hi = pivot, base_lo;
566         int bbits = 0;
567
568         while (base_hi & ~0xFFFF) {
569             base_hi >>= 1;
570             bbits++;
571         }
572         base_hi = range_decode_culfreq(ctx, base_hi + 1);
573         range_decode_update(ctx, 1, base_hi);
574         base_lo = range_decode_culfreq(ctx, 1 << bbits);
575         range_decode_update(ctx, 1, base_lo);
576
577         base = (base_hi << bbits) + base_lo;
578     }
579
580     x = base + overflow * pivot;
581
582     update_rice(rice, x);
583
584     /* Convert to signed */
585     return ((x >> 1) ^ ((x & 1) - 1)) + 1;
586 }
587
588 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
589                               int32_t *out, APERice *rice, int blockstodecode)
590 {
591     int i;
592     unsigned ksummax, ksummin;
593
594     rice->ksum = 0;
595     for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
596         out[i] = get_rice_ook(&ctx->gb, 10);
597         rice->ksum += out[i];
598     }
599     rice->k = av_log2(rice->ksum / 10) + 1;
600     if (rice->k >= 24)
601         return;
602     for (; i < FFMIN(blockstodecode, 64); i++) {
603         out[i] = get_rice_ook(&ctx->gb, rice->k);
604         rice->ksum += out[i];
605         rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
606         if (rice->k >= 24)
607             return;
608     }
609     ksummax = 1 << rice->k + 7;
610     ksummin = rice->k ? (1 << rice->k + 6) : 0;
611     for (; i < blockstodecode; i++) {
612         if (get_bits_left(&ctx->gb) < 1) {
613             ctx->error = 1;
614             return ;
615         }
616         out[i] = get_rice_ook(&ctx->gb, rice->k);
617         rice->ksum += out[i] - out[i - 64];
618         while (rice->ksum < ksummin) {
619             rice->k--;
620             ksummin = rice->k ? ksummin >> 1 : 0;
621             ksummax >>= 1;
622         }
623         while (rice->ksum >= ksummax) {
624             rice->k++;
625             if (rice->k > 24)
626                 return;
627             ksummax <<= 1;
628             ksummin = ksummin ? ksummin << 1 : 128;
629         }
630     }
631
632     for (i = 0; i < blockstodecode; i++)
633         out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
634 }
635
636 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
637 {
638     decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
639                       blockstodecode);
640 }
641
642 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
643 {
644     decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
645                       blockstodecode);
646     decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
647                       blockstodecode);
648 }
649
650 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
651 {
652     int32_t *decoded0 = ctx->decoded[0];
653
654     while (blockstodecode--)
655         *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
656 }
657
658 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
659 {
660     int32_t *decoded0 = ctx->decoded[0];
661     int32_t *decoded1 = ctx->decoded[1];
662     int blocks = blockstodecode;
663
664     while (blockstodecode--)
665         *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
666     while (blocks--)
667         *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
668 }
669
670 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
671 {
672     int32_t *decoded0 = ctx->decoded[0];
673
674     while (blockstodecode--)
675         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
676 }
677
678 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
679 {
680     int32_t *decoded0 = ctx->decoded[0];
681     int32_t *decoded1 = ctx->decoded[1];
682     int blocks = blockstodecode;
683
684     while (blockstodecode--)
685         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
686     range_dec_normalize(ctx);
687     // because of some implementation peculiarities we need to backpedal here
688     ctx->ptr -= 1;
689     range_start_decoding(ctx);
690     while (blocks--)
691         *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
692 }
693
694 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
695 {
696     int32_t *decoded0 = ctx->decoded[0];
697     int32_t *decoded1 = ctx->decoded[1];
698
699     while (blockstodecode--) {
700         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
701         *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
702     }
703 }
704
705 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
706 {
707     int32_t *decoded0 = ctx->decoded[0];
708
709     while (blockstodecode--)
710         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
711 }
712
713 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
714 {
715     int32_t *decoded0 = ctx->decoded[0];
716     int32_t *decoded1 = ctx->decoded[1];
717
718     while (blockstodecode--) {
719         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
720         *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
721     }
722 }
723
724 static int init_entropy_decoder(APEContext *ctx)
725 {
726     /* Read the CRC */
727     if (ctx->fileversion >= 3900) {
728         if (ctx->data_end - ctx->ptr < 6)
729             return AVERROR_INVALIDDATA;
730         ctx->CRC = bytestream_get_be32(&ctx->ptr);
731     } else {
732         ctx->CRC = get_bits_long(&ctx->gb, 32);
733     }
734
735     /* Read the frame flags if they exist */
736     ctx->frameflags = 0;
737     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
738         ctx->CRC &= ~0x80000000;
739
740         if (ctx->data_end - ctx->ptr < 6)
741             return AVERROR_INVALIDDATA;
742         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
743     }
744
745     /* Initialize the rice structs */
746     ctx->riceX.k = 10;
747     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
748     ctx->riceY.k = 10;
749     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
750
751     if (ctx->fileversion >= 3900) {
752         /* The first 8 bits of input are ignored. */
753         ctx->ptr++;
754
755         range_start_decoding(ctx);
756     }
757
758     return 0;
759 }
760
761 static const int32_t initial_coeffs_fast_3320[1] = {
762     375,
763 };
764
765 static const int32_t initial_coeffs_a_3800[3] = {
766     64, 115, 64,
767 };
768
769 static const int32_t initial_coeffs_b_3800[2] = {
770     740, 0
771 };
772
773 static const int32_t initial_coeffs_3930[4] = {
774     360, 317, -109, 98
775 };
776
777 static void init_predictor_decoder(APEContext *ctx)
778 {
779     APEPredictor *p = &ctx->predictor;
780
781     /* Zero the history buffers */
782     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
783     p->buf = p->historybuffer;
784
785     /* Initialize and zero the coefficients */
786     if (ctx->fileversion < 3930) {
787         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
788             memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
789                    sizeof(initial_coeffs_fast_3320));
790             memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
791                    sizeof(initial_coeffs_fast_3320));
792         } else {
793             memcpy(p->coeffsA[0], initial_coeffs_a_3800,
794                    sizeof(initial_coeffs_a_3800));
795             memcpy(p->coeffsA[1], initial_coeffs_a_3800,
796                    sizeof(initial_coeffs_a_3800));
797         }
798     } else {
799         memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
800         memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
801     }
802     memset(p->coeffsB, 0, sizeof(p->coeffsB));
803     if (ctx->fileversion < 3930) {
804         memcpy(p->coeffsB[0], initial_coeffs_b_3800,
805                sizeof(initial_coeffs_b_3800));
806         memcpy(p->coeffsB[1], initial_coeffs_b_3800,
807                sizeof(initial_coeffs_b_3800));
808     }
809
810     p->filterA[0] = p->filterA[1] = 0;
811     p->filterB[0] = p->filterB[1] = 0;
812     p->lastA[0]   = p->lastA[1]   = 0;
813
814     p->sample_pos = 0;
815 }
816
817 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
818 static inline int APESIGN(int32_t x) {
819     return (x < 0) - (x > 0);
820 }
821
822 static av_always_inline int filter_fast_3320(APEPredictor *p,
823                                              const int decoded, const int filter,
824                                              const int delayA)
825 {
826     int32_t predictionA;
827
828     p->buf[delayA] = p->lastA[filter];
829     if (p->sample_pos < 3) {
830         p->lastA[filter]   = decoded;
831         p->filterA[filter] = decoded;
832         return decoded;
833     }
834
835     predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
836     p->lastA[filter] = decoded + ((int32_t)(predictionA  * p->coeffsA[filter][0]) >> 9);
837
838     if ((decoded ^ predictionA) > 0)
839         p->coeffsA[filter][0]++;
840     else
841         p->coeffsA[filter][0]--;
842
843     p->filterA[filter] += (unsigned)p->lastA[filter];
844
845     return p->filterA[filter];
846 }
847
848 static av_always_inline int filter_3800(APEPredictor *p,
849                                         const unsigned decoded, const int filter,
850                                         const int delayA,  const int delayB,
851                                         const int start,   const int shift)
852 {
853     int32_t predictionA, predictionB, sign;
854     int32_t d0, d1, d2, d3, d4;
855
856     p->buf[delayA] = p->lastA[filter];
857     p->buf[delayB] = p->filterB[filter];
858     if (p->sample_pos < start) {
859         predictionA = decoded + p->filterA[filter];
860         p->lastA[filter]   = decoded;
861         p->filterB[filter] = decoded;
862         p->filterA[filter] = predictionA;
863         return predictionA;
864     }
865     d2 =  p->buf[delayA];
866     d1 = (p->buf[delayA] - p->buf[delayA - 1]) * 2U;
867     d0 =  p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) * 8U);
868     d3 =  p->buf[delayB] * 2U - p->buf[delayB - 1];
869     d4 =  p->buf[delayB];
870
871     predictionA = d0 * p->coeffsA[filter][0] +
872                   d1 * p->coeffsA[filter][1] +
873                   d2 * p->coeffsA[filter][2];
874
875     sign = APESIGN(decoded);
876     p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
877     p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
878     p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
879
880     predictionB = d3 * p->coeffsB[filter][0] -
881                   d4 * p->coeffsB[filter][1];
882     p->lastA[filter] = decoded + (predictionA >> 11);
883     sign = APESIGN(p->lastA[filter]);
884     p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
885     p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
886
887     p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
888     p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
889
890     return p->filterA[filter];
891 }
892
893 static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
894 {
895     int i, j;
896     int32_t dotprod, sign;
897     int32_t coeffs[256], delay[256];
898
899     if (order >= length)
900         return;
901
902     memset(coeffs, 0, order * sizeof(*coeffs));
903     for (i = 0; i < order; i++)
904         delay[i] = buffer[i];
905     for (i = order; i < length; i++) {
906         dotprod = 0;
907         sign = APESIGN(buffer[i]);
908         for (j = 0; j < order; j++) {
909             dotprod += delay[j] * (unsigned)coeffs[j];
910             coeffs[j] += ((delay[j] >> 31) | 1) * sign;
911         }
912         buffer[i] -= dotprod >> shift;
913         for (j = 0; j < order - 1; j++)
914             delay[j] = delay[j + 1];
915         delay[order - 1] = buffer[i];
916     }
917 }
918
919 static void long_filter_ehigh_3830(int32_t *buffer, int length)
920 {
921     int i, j;
922     int32_t dotprod, sign;
923     int32_t delay[8] = { 0 };
924     uint32_t coeffs[8] = { 0 };
925
926     for (i = 0; i < length; i++) {
927         dotprod = 0;
928         sign = APESIGN(buffer[i]);
929         for (j = 7; j >= 0; j--) {
930             dotprod += delay[j] * coeffs[j];
931             coeffs[j] += ((delay[j] >> 31) | 1) * sign;
932         }
933         for (j = 7; j > 0; j--)
934             delay[j] = delay[j - 1];
935         delay[0] = buffer[i];
936         buffer[i] -= dotprod >> 9;
937     }
938 }
939
940 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
941 {
942     APEPredictor *p = &ctx->predictor;
943     int32_t *decoded0 = ctx->decoded[0];
944     int32_t *decoded1 = ctx->decoded[1];
945     int start = 4, shift = 10;
946
947     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
948         start = 16;
949         long_filter_high_3800(decoded0, 16, 9, count);
950         long_filter_high_3800(decoded1, 16, 9, count);
951     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
952         int order = 128, shift2 = 11;
953
954         if (ctx->fileversion >= 3830) {
955             order <<= 1;
956             shift++;
957             shift2++;
958             long_filter_ehigh_3830(decoded0 + order, count - order);
959             long_filter_ehigh_3830(decoded1 + order, count - order);
960         }
961         start = order;
962         long_filter_high_3800(decoded0, order, shift2, count);
963         long_filter_high_3800(decoded1, order, shift2, count);
964     }
965
966     while (count--) {
967         int X = *decoded0, Y = *decoded1;
968         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
969             *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
970             decoded0++;
971             *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
972             decoded1++;
973         } else {
974             *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
975                                     start, shift);
976             decoded0++;
977             *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
978                                     start, shift);
979             decoded1++;
980         }
981
982         /* Combined */
983         p->buf++;
984         p->sample_pos++;
985
986         /* Have we filled the history buffer? */
987         if (p->buf == p->historybuffer + HISTORY_SIZE) {
988             memmove(p->historybuffer, p->buf,
989                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
990             p->buf = p->historybuffer;
991         }
992     }
993 }
994
995 static void predictor_decode_mono_3800(APEContext *ctx, int count)
996 {
997     APEPredictor *p = &ctx->predictor;
998     int32_t *decoded0 = ctx->decoded[0];
999     int start = 4, shift = 10;
1000
1001     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1002         start = 16;
1003         long_filter_high_3800(decoded0, 16, 9, count);
1004     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1005         int order = 128, shift2 = 11;
1006
1007         if (ctx->fileversion >= 3830) {
1008             order <<= 1;
1009             shift++;
1010             shift2++;
1011             long_filter_ehigh_3830(decoded0 + order, count - order);
1012         }
1013         start = order;
1014         long_filter_high_3800(decoded0, order, shift2, count);
1015     }
1016
1017     while (count--) {
1018         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1019             *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1020             decoded0++;
1021         } else {
1022             *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1023                                     start, shift);
1024             decoded0++;
1025         }
1026
1027         /* Combined */
1028         p->buf++;
1029         p->sample_pos++;
1030
1031         /* Have we filled the history buffer? */
1032         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1033             memmove(p->historybuffer, p->buf,
1034                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1035             p->buf = p->historybuffer;
1036         }
1037     }
1038 }
1039
1040 static av_always_inline int predictor_update_3930(APEPredictor *p,
1041                                                   const int decoded, const int filter,
1042                                                   const int delayA)
1043 {
1044     int32_t predictionA, sign;
1045     int32_t d0, d1, d2, d3;
1046
1047     p->buf[delayA]     = p->lastA[filter];
1048     d0 = p->buf[delayA    ];
1049     d1 = p->buf[delayA    ] - p->buf[delayA - 1];
1050     d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1051     d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1052
1053     predictionA = d0 * p->coeffsA[filter][0] +
1054                   d1 * p->coeffsA[filter][1] +
1055                   d2 * p->coeffsA[filter][2] +
1056                   d3 * p->coeffsA[filter][3];
1057
1058     p->lastA[filter] = decoded + (predictionA >> 9);
1059     p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1060
1061     sign = APESIGN(decoded);
1062     p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1063     p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1064     p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1065     p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1066
1067     return p->filterA[filter];
1068 }
1069
1070 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1071 {
1072     APEPredictor *p = &ctx->predictor;
1073     int32_t *decoded0 = ctx->decoded[0];
1074     int32_t *decoded1 = ctx->decoded[1];
1075
1076     ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1077
1078     while (count--) {
1079         /* Predictor Y */
1080         int Y = *decoded1, X = *decoded0;
1081         *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1082         decoded0++;
1083         *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1084         decoded1++;
1085
1086         /* Combined */
1087         p->buf++;
1088
1089         /* Have we filled the history buffer? */
1090         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1091             memmove(p->historybuffer, p->buf,
1092                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1093             p->buf = p->historybuffer;
1094         }
1095     }
1096 }
1097
1098 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1099 {
1100     APEPredictor *p = &ctx->predictor;
1101     int32_t *decoded0 = ctx->decoded[0];
1102
1103     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1104
1105     while (count--) {
1106         *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1107         decoded0++;
1108
1109         p->buf++;
1110
1111         /* Have we filled the history buffer? */
1112         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1113             memmove(p->historybuffer, p->buf,
1114                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1115             p->buf = p->historybuffer;
1116         }
1117     }
1118 }
1119
1120 static av_always_inline int predictor_update_filter(APEPredictor *p,
1121                                                     const int decoded, const int filter,
1122                                                     const int delayA,  const int delayB,
1123                                                     const int adaptA,  const int adaptB)
1124 {
1125     int32_t predictionA, predictionB, sign;
1126
1127     p->buf[delayA]     = p->lastA[filter];
1128     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
1129     p->buf[delayA - 1] = p->buf[delayA] - (unsigned)p->buf[delayA - 1];
1130     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1131
1132     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
1133                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
1134                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
1135                   p->buf[delayA - 3] * p->coeffsA[filter][3];
1136
1137     /*  Apply a scaled first-order filter compression */
1138     p->buf[delayB]     = p->filterA[filter ^ 1] - ((int)(p->filterB[filter] * 31U) >> 5);
1139     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
1140     p->buf[delayB - 1] = p->buf[delayB] - (unsigned)p->buf[delayB - 1];
1141     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1142     p->filterB[filter] = p->filterA[filter ^ 1];
1143
1144     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
1145                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
1146                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
1147                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
1148                   p->buf[delayB - 4] * p->coeffsB[filter][4];
1149
1150     p->lastA[filter] = decoded + ((int)((unsigned)predictionA + (predictionB >> 1)) >> 10);
1151     p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1152
1153     sign = APESIGN(decoded);
1154     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
1155     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1156     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1157     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1158     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
1159     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1160     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1161     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1162     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1163
1164     return p->filterA[filter];
1165 }
1166
1167 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1168 {
1169     APEPredictor *p = &ctx->predictor;
1170     int32_t *decoded0 = ctx->decoded[0];
1171     int32_t *decoded1 = ctx->decoded[1];
1172
1173     ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1174
1175     while (count--) {
1176         /* Predictor Y */
1177         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1178                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
1179         decoded0++;
1180         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1181                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
1182         decoded1++;
1183
1184         /* Combined */
1185         p->buf++;
1186
1187         /* Have we filled the history buffer? */
1188         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1189             memmove(p->historybuffer, p->buf,
1190                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1191             p->buf = p->historybuffer;
1192         }
1193     }
1194 }
1195
1196 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1197 {
1198     APEPredictor *p = &ctx->predictor;
1199     int32_t *decoded0 = ctx->decoded[0];
1200     int32_t predictionA, currentA, A, sign;
1201
1202     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1203
1204     currentA = p->lastA[0];
1205
1206     while (count--) {
1207         A = *decoded0;
1208
1209         p->buf[YDELAYA] = currentA;
1210         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
1211
1212         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
1213                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1214                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1215                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1216
1217         currentA = A + (predictionA >> 10);
1218
1219         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
1220         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1221
1222         sign = APESIGN(A);
1223         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
1224         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1225         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1226         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1227
1228         p->buf++;
1229
1230         /* Have we filled the history buffer? */
1231         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1232             memmove(p->historybuffer, p->buf,
1233                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1234             p->buf = p->historybuffer;
1235         }
1236
1237         p->filterA[0] = currentA + ((int)(p->filterA[0] * 31U) >> 5);
1238         *(decoded0++) = p->filterA[0];
1239     }
1240
1241     p->lastA[0] = currentA;
1242 }
1243
1244 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1245 {
1246     f->coeffs = buf;
1247     f->historybuffer = buf + order;
1248     f->delay       = f->historybuffer + order * 2;
1249     f->adaptcoeffs = f->historybuffer + order;
1250
1251     memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1252     memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1253     f->avg = 0;
1254 }
1255
1256 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1257 {
1258     do_init_filter(&f[0], buf, order);
1259     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1260 }
1261
1262 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1263                             int32_t *data, int count, int order, int fracbits)
1264 {
1265     int res;
1266     int absres;
1267
1268     while (count--) {
1269         /* round fixedpoint scalar product */
1270         res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1271                                                      f->delay - order,
1272                                                      f->adaptcoeffs - order,
1273                                                      order, APESIGN(*data));
1274         res = (int)(res + (1U << (fracbits - 1))) >> fracbits;
1275         res += (unsigned)*data;
1276         *data++ = res;
1277
1278         /* Update the output history */
1279         *f->delay++ = av_clip_int16(res);
1280
1281         if (version < 3980) {
1282             /* Version ??? to < 3.98 files (untested) */
1283             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1284             f->adaptcoeffs[-4] >>= 1;
1285             f->adaptcoeffs[-8] >>= 1;
1286         } else {
1287             /* Version 3.98 and later files */
1288
1289             /* Update the adaption coefficients */
1290             absres = res < 0 ? -(unsigned)res : res;
1291             if (absres)
1292                 *f->adaptcoeffs = APESIGN(res) *
1293                                   (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1294                 /* equivalent to the following code
1295                     if (absres <= f->avg * 4 / 3)
1296                         *f->adaptcoeffs = APESIGN(res) * 8;
1297                     else if (absres <= f->avg * 3)
1298                         *f->adaptcoeffs = APESIGN(res) * 16;
1299                     else
1300                         *f->adaptcoeffs = APESIGN(res) * 32;
1301                 */
1302             else
1303                 *f->adaptcoeffs = 0;
1304
1305             f->avg += (absres - f->avg) / 16;
1306
1307             f->adaptcoeffs[-1] >>= 1;
1308             f->adaptcoeffs[-2] >>= 1;
1309             f->adaptcoeffs[-8] >>= 1;
1310         }
1311
1312         f->adaptcoeffs++;
1313
1314         /* Have we filled the history buffer? */
1315         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1316             memmove(f->historybuffer, f->delay - (order * 2),
1317                     (order * 2) * sizeof(*f->historybuffer));
1318             f->delay = f->historybuffer + order * 2;
1319             f->adaptcoeffs = f->historybuffer + order;
1320         }
1321     }
1322 }
1323
1324 static void apply_filter(APEContext *ctx, APEFilter *f,
1325                          int32_t *data0, int32_t *data1,
1326                          int count, int order, int fracbits)
1327 {
1328     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1329     if (data1)
1330         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1331 }
1332
1333 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1334                               int32_t *decoded1, int count)
1335 {
1336     int i;
1337
1338     for (i = 0; i < APE_FILTER_LEVELS; i++) {
1339         if (!ape_filter_orders[ctx->fset][i])
1340             break;
1341         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1342                      ape_filter_orders[ctx->fset][i],
1343                      ape_filter_fracbits[ctx->fset][i]);
1344     }
1345 }
1346
1347 static int init_frame_decoder(APEContext *ctx)
1348 {
1349     int i, ret;
1350     if ((ret = init_entropy_decoder(ctx)) < 0)
1351         return ret;
1352     init_predictor_decoder(ctx);
1353
1354     for (i = 0; i < APE_FILTER_LEVELS; i++) {
1355         if (!ape_filter_orders[ctx->fset][i])
1356             break;
1357         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1358                     ape_filter_orders[ctx->fset][i]);
1359     }
1360     return 0;
1361 }
1362
1363 static void ape_unpack_mono(APEContext *ctx, int count)
1364 {
1365     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1366         /* We are pure silence, so we're done. */
1367         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1368         return;
1369     }
1370
1371     ctx->entropy_decode_mono(ctx, count);
1372     if (ctx->error)
1373         return;
1374
1375     /* Now apply the predictor decoding */
1376     ctx->predictor_decode_mono(ctx, count);
1377
1378     /* Pseudo-stereo - just copy left channel to right channel */
1379     if (ctx->channels == 2) {
1380         memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1381     }
1382 }
1383
1384 static void ape_unpack_stereo(APEContext *ctx, int count)
1385 {
1386     unsigned left, right;
1387     int32_t *decoded0 = ctx->decoded[0];
1388     int32_t *decoded1 = ctx->decoded[1];
1389
1390     if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
1391         /* We are pure silence, so we're done. */
1392         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1393         return;
1394     }
1395
1396     ctx->entropy_decode_stereo(ctx, count);
1397     if (ctx->error)
1398         return;
1399
1400     /* Now apply the predictor decoding */
1401     ctx->predictor_decode_stereo(ctx, count);
1402
1403     /* Decorrelate and scale to output depth */
1404     while (count--) {
1405         left = *decoded1 - (unsigned)(*decoded0 / 2);
1406         right = left + *decoded0;
1407
1408         *(decoded0++) = left;
1409         *(decoded1++) = right;
1410     }
1411 }
1412
1413 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1414                             int *got_frame_ptr, AVPacket *avpkt)
1415 {
1416     AVFrame *frame     = data;
1417     const uint8_t *buf = avpkt->data;
1418     APEContext *s = avctx->priv_data;
1419     uint8_t *sample8;
1420     int16_t *sample16;
1421     int32_t *sample24;
1422     int i, ch, ret;
1423     int blockstodecode;
1424     uint64_t decoded_buffer_size;
1425
1426     /* this should never be negative, but bad things will happen if it is, so
1427        check it just to make sure. */
1428     av_assert0(s->samples >= 0);
1429
1430     if(!s->samples){
1431         uint32_t nblocks, offset;
1432         int buf_size;
1433
1434         if (!avpkt->size) {
1435             *got_frame_ptr = 0;
1436             return 0;
1437         }
1438         if (avpkt->size < 8) {
1439             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1440             return AVERROR_INVALIDDATA;
1441         }
1442         buf_size = avpkt->size & ~3;
1443         if (buf_size != avpkt->size) {
1444             av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1445                    "extra bytes at the end will be skipped.\n");
1446         }
1447         if (s->fileversion < 3950) // previous versions overread two bytes
1448             buf_size += 2;
1449         av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1450         if (!s->data)
1451             return AVERROR(ENOMEM);
1452         s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1453                           buf_size >> 2);
1454         memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1455         s->ptr = s->data;
1456         s->data_end = s->data + buf_size;
1457
1458         nblocks = bytestream_get_be32(&s->ptr);
1459         offset  = bytestream_get_be32(&s->ptr);
1460         if (s->fileversion >= 3900) {
1461             if (offset > 3) {
1462                 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1463                 av_freep(&s->data);
1464                 s->data_size = 0;
1465                 return AVERROR_INVALIDDATA;
1466             }
1467             if (s->data_end - s->ptr < offset) {
1468                 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1469                 return AVERROR_INVALIDDATA;
1470             }
1471             s->ptr += offset;
1472         } else {
1473             if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1474                 return ret;
1475             if (s->fileversion > 3800)
1476                 skip_bits_long(&s->gb, offset * 8);
1477             else
1478                 skip_bits_long(&s->gb, offset);
1479         }
1480
1481         if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1482             av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1483                    nblocks);
1484             return AVERROR_INVALIDDATA;
1485         }
1486
1487         /* Initialize the frame decoder */
1488         if (init_frame_decoder(s) < 0) {
1489             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1490             return AVERROR_INVALIDDATA;
1491         }
1492         s->samples = nblocks;
1493     }
1494
1495     if (!s->data) {
1496         *got_frame_ptr = 0;
1497         return avpkt->size;
1498     }
1499
1500     blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1501     // for old files coefficients were not interleaved,
1502     // so we need to decode all of them at once
1503     if (s->fileversion < 3930)
1504         blockstodecode = s->samples;
1505
1506     /* reallocate decoded sample buffer if needed */
1507     decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1508     av_assert0(decoded_buffer_size <= INT_MAX);
1509
1510     /* get output buffer */
1511     frame->nb_samples = blockstodecode;
1512     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1513         s->samples=0;
1514         return ret;
1515     }
1516
1517     av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1518     if (!s->decoded_buffer)
1519         return AVERROR(ENOMEM);
1520     memset(s->decoded_buffer, 0, decoded_buffer_size);
1521     s->decoded[0] = s->decoded_buffer;
1522     s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1523
1524     s->error=0;
1525
1526     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1527         ape_unpack_mono(s, blockstodecode);
1528     else
1529         ape_unpack_stereo(s, blockstodecode);
1530     emms_c();
1531
1532     if (s->error) {
1533         s->samples=0;
1534         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1535         return AVERROR_INVALIDDATA;
1536     }
1537
1538     switch (s->bps) {
1539     case 8:
1540         for (ch = 0; ch < s->channels; ch++) {
1541             sample8 = (uint8_t *)frame->data[ch];
1542             for (i = 0; i < blockstodecode; i++)
1543                 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1544         }
1545         break;
1546     case 16:
1547         for (ch = 0; ch < s->channels; ch++) {
1548             sample16 = (int16_t *)frame->data[ch];
1549             for (i = 0; i < blockstodecode; i++)
1550                 *sample16++ = s->decoded[ch][i];
1551         }
1552         break;
1553     case 24:
1554         for (ch = 0; ch < s->channels; ch++) {
1555             sample24 = (int32_t *)frame->data[ch];
1556             for (i = 0; i < blockstodecode; i++)
1557                 *sample24++ = s->decoded[ch][i] << 8;
1558         }
1559         break;
1560     }
1561
1562     s->samples -= blockstodecode;
1563
1564     *got_frame_ptr = 1;
1565
1566     return !s->samples ? avpkt->size : 0;
1567 }
1568
1569 static void ape_flush(AVCodecContext *avctx)
1570 {
1571     APEContext *s = avctx->priv_data;
1572     s->samples= 0;
1573 }
1574
1575 #define OFFSET(x) offsetof(APEContext, x)
1576 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1577 static const AVOption options[] = {
1578     { "max_samples", "maximum number of samples decoded per call",             OFFSET(blocks_per_loop), AV_OPT_TYPE_INT,   { .i64 = 4608 },    1,       INT_MAX, PAR, "max_samples" },
1579     { "all",         "no maximum. decode all samples for each packet at once", 0,                       AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
1580     { NULL},
1581 };
1582
1583 static const AVClass ape_decoder_class = {
1584     .class_name = "APE decoder",
1585     .item_name  = av_default_item_name,
1586     .option     = options,
1587     .version    = LIBAVUTIL_VERSION_INT,
1588 };
1589
1590 AVCodec ff_ape_decoder = {
1591     .name           = "ape",
1592     .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1593     .type           = AVMEDIA_TYPE_AUDIO,
1594     .id             = AV_CODEC_ID_APE,
1595     .priv_data_size = sizeof(APEContext),
1596     .init           = ape_decode_init,
1597     .close          = ape_decode_close,
1598     .decode         = ape_decode_frame,
1599     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1600                       AV_CODEC_CAP_DR1,
1601     .flush          = ape_flush,
1602     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1603                                                       AV_SAMPLE_FMT_S16P,
1604                                                       AV_SAMPLE_FMT_S32P,
1605                                                       AV_SAMPLE_FMT_NONE },
1606     .priv_class     = &ape_decoder_class,
1607 };