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