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