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