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