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