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