]> git.sesse.net Git - ffmpeg/blob - libavcodec/apedec.c
82d567f4cfcf560403f6ff2d312888c448f32084
[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 #define ALT_BITSTREAM_READER_LE
24 #include "avcodec.h"
25 #include "dsputil.h"
26 #include "bitstream.h"
27 #include "bytestream.h"
28
29 /**
30  * @file apedec.c
31  * Monkey's Audio lossless audio decoder
32  */
33
34 #define BLOCKS_PER_LOOP     4608
35 #define MAX_CHANNELS        2
36 #define MAX_BYTESPERSAMPLE  3
37
38 #define APE_FRAMECODE_MONO_SILENCE    1
39 #define APE_FRAMECODE_STEREO_SILENCE  3
40 #define APE_FRAMECODE_PSEUDO_STEREO   4
41
42 #define HISTORY_SIZE 512
43 #define PREDICTOR_ORDER 8
44 /** Total size of all predictor histories */
45 #define PREDICTOR_SIZE 50
46
47 #define YDELAYA (18 + PREDICTOR_ORDER*4)
48 #define YDELAYB (18 + PREDICTOR_ORDER*3)
49 #define XDELAYA (18 + PREDICTOR_ORDER*2)
50 #define XDELAYB (18 + PREDICTOR_ORDER)
51
52 #define YADAPTCOEFFSA 18
53 #define XADAPTCOEFFSA 14
54 #define YADAPTCOEFFSB 10
55 #define XADAPTCOEFFSB 5
56
57 /**
58  * Possible compression levels
59  * @{
60  */
61 enum APECompressionLevel {
62     COMPRESSION_LEVEL_FAST       = 1000,
63     COMPRESSION_LEVEL_NORMAL     = 2000,
64     COMPRESSION_LEVEL_HIGH       = 3000,
65     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
66     COMPRESSION_LEVEL_INSANE     = 5000
67 };
68 /** @} */
69
70 #define APE_FILTER_LEVELS 3
71
72 /** Filter orders depending on compression level */
73 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
74     {  0,   0,    0 },
75     { 16,   0,    0 },
76     { 64,   0,    0 },
77     { 32, 256,    0 },
78     { 16, 256, 1280 }
79 };
80
81 /** Filter fraction bits depending on compression level */
82 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
83     {  0,  0,  0 },
84     { 11,  0,  0 },
85     { 11,  0,  0 },
86     { 10, 13,  0 },
87     { 11, 13, 15 }
88 };
89
90
91 /** Filters applied to the decoded data */
92 typedef struct APEFilter {
93     int16_t *coeffs;        ///< actual coefficients used in filtering
94     int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
95     int16_t *historybuffer; ///< filter memory
96     int16_t *delay;         ///< filtered values
97
98     int avg;
99 } APEFilter;
100
101 typedef struct APERice {
102     uint32_t k;
103     uint32_t ksum;
104 } APERice;
105
106 typedef struct APERangecoder {
107     uint32_t low;           ///< low end of interval
108     uint32_t range;         ///< length of interval
109     uint32_t help;          ///< bytes_to_follow resp. intermediate value
110     unsigned int buffer;    ///< buffer for input/output
111 } APERangecoder;
112
113 /** Filter histories */
114 typedef struct APEPredictor {
115     int32_t *buf;
116
117     int32_t lastA[2];
118
119     int32_t filterA[2];
120     int32_t filterB[2];
121
122     int32_t coeffsA[2][4];  ///< adaption coefficients
123     int32_t coeffsB[2][5];  ///< adaption coefficients
124     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
125 } APEPredictor;
126
127 /** Decoder context */
128 typedef struct APEContext {
129     AVCodecContext *avctx;
130     DSPContext dsp;
131     int channels;
132     int samples;                             ///< samples left to decode in current frame
133
134     int fileversion;                         ///< codec version, very important in decoding process
135     int compression_level;                   ///< compression levels
136     int fset;                                ///< which filter set to use (calculated from compression level)
137     int flags;                               ///< global decoder flags
138
139     uint32_t CRC;                            ///< frame CRC
140     int frameflags;                          ///< frame flags
141     int currentframeblocks;                  ///< samples (per channel) in current frame
142     int blocksdecoded;                       ///< count of decoded samples in current frame
143     APEPredictor predictor;                  ///< predictor used for final reconstruction
144
145     int32_t decoded0[BLOCKS_PER_LOOP];       ///< decoded data for the first channel
146     int32_t decoded1[BLOCKS_PER_LOOP];       ///< decoded data for the second channel
147
148     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
149
150     APERangecoder rc;                        ///< rangecoder used to decode actual values
151     APERice riceX;                           ///< rice code parameters for the second channel
152     APERice riceY;                           ///< rice code parameters for the first channel
153     APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
154
155     uint8_t *data;                           ///< current frame data
156     uint8_t *data_end;                       ///< frame data end
157     const uint8_t *ptr;                      ///< current position in frame data
158     const uint8_t *last_ptr;                 ///< position where last 4608-sample block ended
159
160     int error;
161 } APEContext;
162
163 // TODO: dsputilize
164
165 static av_cold int ape_decode_init(AVCodecContext * avctx)
166 {
167     APEContext *s = avctx->priv_data;
168     int i;
169
170     if (avctx->extradata_size != 6) {
171         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
172         return -1;
173     }
174     if (avctx->bits_per_coded_sample != 16) {
175         av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
176         return -1;
177     }
178     if (avctx->channels > 2) {
179         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
180         return -1;
181     }
182     s->avctx             = avctx;
183     s->channels          = avctx->channels;
184     s->fileversion       = AV_RL16(avctx->extradata);
185     s->compression_level = AV_RL16(avctx->extradata + 2);
186     s->flags             = AV_RL16(avctx->extradata + 4);
187
188     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);
189     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
190         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);
191         return -1;
192     }
193     s->fset = s->compression_level / 1000 - 1;
194     for (i = 0; i < APE_FILTER_LEVELS; i++) {
195         if (!ape_filter_orders[s->fset][i])
196             break;
197         s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);
198     }
199
200     dsputil_init(&s->dsp, avctx);
201     avctx->sample_fmt = SAMPLE_FMT_S16;
202     return 0;
203 }
204
205 static av_cold int ape_decode_close(AVCodecContext * avctx)
206 {
207     APEContext *s = avctx->priv_data;
208     int i;
209
210     for (i = 0; i < APE_FILTER_LEVELS; i++)
211         av_freep(&s->filterbuf[i]);
212
213     return 0;
214 }
215
216 /**
217  * @defgroup rangecoder APE range decoder
218  * @{
219  */
220
221 #define CODE_BITS    32
222 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
223 #define SHIFT_BITS   (CODE_BITS - 9)
224 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
225 #define BOTTOM_VALUE (TOP_VALUE >> 8)
226
227 /** Start the decoder */
228 static inline void range_start_decoding(APEContext * ctx)
229 {
230     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
231     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
232     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
233 }
234
235 /** Perform normalization */
236 static inline void range_dec_normalize(APEContext * ctx)
237 {
238     while (ctx->rc.range <= BOTTOM_VALUE) {
239         ctx->rc.buffer <<= 8;
240         if(ctx->ptr < ctx->data_end)
241             ctx->rc.buffer += *ctx->ptr;
242         ctx->ptr++;
243         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
244         ctx->rc.range  <<= 8;
245     }
246 }
247
248 /**
249  * Calculate culmulative frequency for next symbol. Does NO update!
250  * @param tot_f is the total frequency or (code_value)1<<shift
251  * @return the culmulative frequency
252  */
253 static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
254 {
255     range_dec_normalize(ctx);
256     ctx->rc.help = ctx->rc.range / tot_f;
257     return ctx->rc.low / ctx->rc.help;
258 }
259
260 /**
261  * Decode value with given size in bits
262  * @param shift number of bits to decode
263  */
264 static inline int range_decode_culshift(APEContext * ctx, int shift)
265 {
266     range_dec_normalize(ctx);
267     ctx->rc.help = ctx->rc.range >> shift;
268     return ctx->rc.low / ctx->rc.help;
269 }
270
271
272 /**
273  * Update decoding state
274  * @param sy_f the interval length (frequency of the symbol)
275  * @param lt_f the lower end (frequency sum of < symbols)
276  */
277 static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
278 {
279     ctx->rc.low  -= ctx->rc.help * lt_f;
280     ctx->rc.range = ctx->rc.help * sy_f;
281 }
282
283 /** Decode n bits (n <= 16) without modelling */
284 static inline int range_decode_bits(APEContext * ctx, int n)
285 {
286     int sym = range_decode_culshift(ctx, n);
287     range_decode_update(ctx, 1, sym);
288     return sym;
289 }
290
291
292 #define MODEL_ELEMENTS 64
293
294 /**
295  * Fixed probabilities for symbols in Monkey Audio version 3.97
296  */
297 static const uint16_t counts_3970[22] = {
298         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
299     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
300     65450, 65469, 65480, 65487, 65491, 65493,
301 };
302
303 /**
304  * Probability ranges for symbols in Monkey Audio version 3.97
305  */
306 static const uint16_t counts_diff_3970[21] = {
307     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
308     1104, 677, 415, 248, 150, 89, 54, 31,
309     19, 11, 7, 4, 2,
310 };
311
312 /**
313  * Fixed probabilities for symbols in Monkey Audio version 3.98
314  */
315 static const uint16_t counts_3980[22] = {
316         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
317     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
318     65485, 65488, 65490, 65491, 65492, 65493,
319 };
320
321 /**
322  * Probability ranges for symbols in Monkey Audio version 3.98
323  */
324 static const uint16_t counts_diff_3980[21] = {
325     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
326     261, 119, 65, 31, 19, 10, 6, 3,
327     3, 2, 1, 1, 1,
328 };
329
330 /**
331  * Decode symbol
332  * @param counts probability range start position
333  * @param count_diffs probability range widths
334  */
335 static inline int range_get_symbol(APEContext * ctx,
336                                    const uint16_t counts[],
337                                    const uint16_t counts_diff[])
338 {
339     int symbol, cf;
340
341     cf = range_decode_culshift(ctx, 16);
342
343     if(cf > 65492){
344         symbol= cf - 65535 + 63;
345         range_decode_update(ctx, 1, cf);
346         if(cf > 65535)
347             ctx->error=1;
348         return symbol;
349     }
350     /* figure out the symbol inefficiently; a binary search would be much better */
351     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
352
353     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
354
355     return symbol;
356 }
357 /** @} */ // group rangecoder
358
359 static inline void update_rice(APERice *rice, int x)
360 {
361     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
362     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
363
364     if (rice->ksum < lim)
365         rice->k--;
366     else if (rice->ksum >= (1 << (rice->k + 5)))
367         rice->k++;
368 }
369
370 static inline int ape_decode_value(APEContext * ctx, APERice *rice)
371 {
372     int x, overflow;
373
374     if (ctx->fileversion < 3990) {
375         int tmpk;
376
377         overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
378
379         if (overflow == (MODEL_ELEMENTS - 1)) {
380             tmpk = range_decode_bits(ctx, 5);
381             overflow = 0;
382         } else
383             tmpk = (rice->k < 1) ? 0 : rice->k - 1;
384
385         if (tmpk <= 16)
386             x = range_decode_bits(ctx, tmpk);
387         else {
388             x = range_decode_bits(ctx, 16);
389             x |= (range_decode_bits(ctx, tmpk - 16) << 16);
390         }
391         x += overflow << tmpk;
392     } else {
393         int base, pivot;
394
395         pivot = rice->ksum >> 5;
396         if (pivot == 0)
397             pivot = 1;
398
399         overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
400
401         if (overflow == (MODEL_ELEMENTS - 1)) {
402             overflow  = range_decode_bits(ctx, 16) << 16;
403             overflow |= range_decode_bits(ctx, 16);
404         }
405
406         base = range_decode_culfreq(ctx, pivot);
407         range_decode_update(ctx, 1, base);
408
409         x = base + overflow * pivot;
410     }
411
412     update_rice(rice, x);
413
414     /* Convert to signed */
415     if (x & 1)
416         return (x >> 1) + 1;
417     else
418         return -(x >> 1);
419 }
420
421 static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
422 {
423     int32_t *decoded0 = ctx->decoded0;
424     int32_t *decoded1 = ctx->decoded1;
425
426     ctx->blocksdecoded = blockstodecode;
427
428     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
429         /* We are pure silence, just memset the output buffer. */
430         memset(decoded0, 0, blockstodecode * sizeof(int32_t));
431         memset(decoded1, 0, blockstodecode * sizeof(int32_t));
432     } else {
433         while (blockstodecode--) {
434             *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
435             if (stereo)
436                 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
437         }
438     }
439
440     if (ctx->blocksdecoded == ctx->currentframeblocks)
441         range_dec_normalize(ctx);   /* normalize to use up all bytes */
442 }
443
444 static void init_entropy_decoder(APEContext * ctx)
445 {
446     /* Read the CRC */
447     ctx->CRC = bytestream_get_be32(&ctx->ptr);
448
449     /* Read the frame flags if they exist */
450     ctx->frameflags = 0;
451     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
452         ctx->CRC &= ~0x80000000;
453
454         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
455     }
456
457     /* Keep a count of the blocks decoded in this frame */
458     ctx->blocksdecoded = 0;
459
460     /* Initialize the rice structs */
461     ctx->riceX.k = 10;
462     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
463     ctx->riceY.k = 10;
464     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
465
466     /* The first 8 bits of input are ignored. */
467     ctx->ptr++;
468
469     range_start_decoding(ctx);
470 }
471
472 static const int32_t initial_coeffs[4] = {
473     360, 317, -109, 98
474 };
475
476 static void init_predictor_decoder(APEContext * ctx)
477 {
478     APEPredictor *p = &ctx->predictor;
479
480     /* Zero the history buffers */
481     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
482     p->buf = p->historybuffer;
483
484     /* Initialize and zero the coefficients */
485     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
486     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
487     memset(p->coeffsB, 0, sizeof(p->coeffsB));
488
489     p->filterA[0] = p->filterA[1] = 0;
490     p->filterB[0] = p->filterB[1] = 0;
491     p->lastA[0]   = p->lastA[1]   = 0;
492 }
493
494 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
495 static inline int APESIGN(int32_t x) {
496     return (x < 0) - (x > 0);
497 }
498
499 static int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
500 {
501     int32_t predictionA, predictionB;
502
503     p->buf[delayA]     = p->lastA[filter];
504     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
505     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
506     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
507
508     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
509                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
510                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
511                   p->buf[delayA - 3] * p->coeffsA[filter][3];
512
513     /*  Apply a scaled first-order filter compression */
514     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
515     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
516     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
517     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
518     p->filterB[filter] = p->filterA[filter ^ 1];
519
520     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
521                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
522                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
523                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
524                   p->buf[delayB - 4] * p->coeffsB[filter][4];
525
526     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
527     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
528
529     if (!decoded) // no need updating filter coefficients
530         return p->filterA[filter];
531
532     if (decoded > 0) {
533         p->coeffsA[filter][0] -= p->buf[adaptA    ];
534         p->coeffsA[filter][1] -= p->buf[adaptA - 1];
535         p->coeffsA[filter][2] -= p->buf[adaptA - 2];
536         p->coeffsA[filter][3] -= p->buf[adaptA - 3];
537
538         p->coeffsB[filter][0] -= p->buf[adaptB    ];
539         p->coeffsB[filter][1] -= p->buf[adaptB - 1];
540         p->coeffsB[filter][2] -= p->buf[adaptB - 2];
541         p->coeffsB[filter][3] -= p->buf[adaptB - 3];
542         p->coeffsB[filter][4] -= p->buf[adaptB - 4];
543     } else {
544         p->coeffsA[filter][0] += p->buf[adaptA    ];
545         p->coeffsA[filter][1] += p->buf[adaptA - 1];
546         p->coeffsA[filter][2] += p->buf[adaptA - 2];
547         p->coeffsA[filter][3] += p->buf[adaptA - 3];
548
549         p->coeffsB[filter][0] += p->buf[adaptB    ];
550         p->coeffsB[filter][1] += p->buf[adaptB - 1];
551         p->coeffsB[filter][2] += p->buf[adaptB - 2];
552         p->coeffsB[filter][3] += p->buf[adaptB - 3];
553         p->coeffsB[filter][4] += p->buf[adaptB - 4];
554     }
555     return p->filterA[filter];
556 }
557
558 static void predictor_decode_stereo(APEContext * ctx, int count)
559 {
560     int32_t predictionA, predictionB;
561     APEPredictor *p = &ctx->predictor;
562     int32_t *decoded0 = ctx->decoded0;
563     int32_t *decoded1 = ctx->decoded1;
564
565     while (count--) {
566         /* Predictor Y */
567         predictionA = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
568         predictionB = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
569         *(decoded0++) = predictionA;
570         *(decoded1++) = predictionB;
571
572         /* Combined */
573         p->buf++;
574
575         /* Have we filled the history buffer? */
576         if (p->buf == p->historybuffer + HISTORY_SIZE) {
577             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
578             p->buf = p->historybuffer;
579         }
580     }
581 }
582
583 static void predictor_decode_mono(APEContext * ctx, int count)
584 {
585     APEPredictor *p = &ctx->predictor;
586     int32_t *decoded0 = ctx->decoded0;
587     int32_t predictionA, currentA, A;
588
589     currentA = p->lastA[0];
590
591     while (count--) {
592         A = *decoded0;
593
594         p->buf[YDELAYA] = currentA;
595         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
596
597         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
598                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
599                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
600                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
601
602         currentA = A + (predictionA >> 10);
603
604         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
605         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
606
607         if (A > 0) {
608             p->coeffsA[0][0] -= p->buf[YADAPTCOEFFSA    ];
609             p->coeffsA[0][1] -= p->buf[YADAPTCOEFFSA - 1];
610             p->coeffsA[0][2] -= p->buf[YADAPTCOEFFSA - 2];
611             p->coeffsA[0][3] -= p->buf[YADAPTCOEFFSA - 3];
612         } else if (A < 0) {
613             p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ];
614             p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1];
615             p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2];
616             p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3];
617         }
618
619         p->buf++;
620
621         /* Have we filled the history buffer? */
622         if (p->buf == p->historybuffer + HISTORY_SIZE) {
623             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
624             p->buf = p->historybuffer;
625         }
626
627         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
628         *(decoded0++) = p->filterA[0];
629     }
630
631     p->lastA[0] = currentA;
632 }
633
634 static void do_init_filter(APEFilter *f, int16_t * buf, int order)
635 {
636     f->coeffs = buf;
637     f->historybuffer = buf + order;
638     f->delay       = f->historybuffer + order * 2;
639     f->adaptcoeffs = f->historybuffer + order;
640
641     memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
642     memset(f->coeffs, 0, order * sizeof(int16_t));
643     f->avg = 0;
644 }
645
646 static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
647 {
648     do_init_filter(&f[0], buf, order);
649     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
650 }
651
652 static inline void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
653 {
654     int res;
655     int absres;
656
657     while (count--) {
658         /* round fixedpoint scalar product */
659         res = (ctx->dsp.scalarproduct_int16(f->delay - order, f->coeffs, order, 0) + (1 << (fracbits - 1))) >> fracbits;
660
661         if (*data < 0)
662             ctx->dsp.add_int16(f->coeffs, f->adaptcoeffs - order, order);
663         else if (*data > 0)
664             ctx->dsp.sub_int16(f->coeffs, f->adaptcoeffs - order, order);
665
666         res += *data;
667
668         *data++ = res;
669
670         /* Update the output history */
671         *f->delay++ = av_clip_int16(res);
672
673         if (version < 3980) {
674             /* Version ??? to < 3.98 files (untested) */
675             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
676             f->adaptcoeffs[-4] >>= 1;
677             f->adaptcoeffs[-8] >>= 1;
678         } else {
679             /* Version 3.98 and later files */
680
681             /* Update the adaption coefficients */
682             absres = (res < 0 ? -res : res);
683
684             if (absres > (f->avg * 3))
685                 *f->adaptcoeffs = ((res >> 25) & 64) - 32;
686             else if (absres > (f->avg * 4) / 3)
687                 *f->adaptcoeffs = ((res >> 26) & 32) - 16;
688             else if (absres > 0)
689                 *f->adaptcoeffs = ((res >> 27) & 16) - 8;
690             else
691                 *f->adaptcoeffs = 0;
692
693             f->avg += (absres - f->avg) / 16;
694
695             f->adaptcoeffs[-1] >>= 1;
696             f->adaptcoeffs[-2] >>= 1;
697             f->adaptcoeffs[-8] >>= 1;
698         }
699
700         f->adaptcoeffs++;
701
702         /* Have we filled the history buffer? */
703         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
704             memmove(f->historybuffer, f->delay - (order * 2),
705                     (order * 2) * sizeof(int16_t));
706             f->delay = f->historybuffer + order * 2;
707             f->adaptcoeffs = f->historybuffer + order;
708         }
709     }
710 }
711
712 static void apply_filter(APEContext * ctx, APEFilter *f,
713                          int32_t * data0, int32_t * data1,
714                          int count, int order, int fracbits)
715 {
716     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
717     if (data1)
718         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
719 }
720
721 static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
722                               int32_t * decoded1, int count)
723 {
724     int i;
725
726     for (i = 0; i < APE_FILTER_LEVELS; i++) {
727         if (!ape_filter_orders[ctx->fset][i])
728             break;
729         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
730     }
731 }
732
733 static void init_frame_decoder(APEContext * ctx)
734 {
735     int i;
736     init_entropy_decoder(ctx);
737     init_predictor_decoder(ctx);
738
739     for (i = 0; i < APE_FILTER_LEVELS; i++) {
740         if (!ape_filter_orders[ctx->fset][i])
741             break;
742         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
743     }
744 }
745
746 static void ape_unpack_mono(APEContext * ctx, int count)
747 {
748     int32_t left;
749     int32_t *decoded0 = ctx->decoded0;
750     int32_t *decoded1 = ctx->decoded1;
751
752     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
753         entropy_decode(ctx, count, 0);
754         /* We are pure silence, so we're done. */
755         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
756         return;
757     }
758
759     entropy_decode(ctx, count, 0);
760     ape_apply_filters(ctx, decoded0, NULL, count);
761
762     /* Now apply the predictor decoding */
763     predictor_decode_mono(ctx, count);
764
765     /* Pseudo-stereo - just copy left channel to right channel */
766     if (ctx->channels == 2) {
767         while (count--) {
768             left = *decoded0;
769             *(decoded1++) = *(decoded0++) = left;
770         }
771     }
772 }
773
774 static void ape_unpack_stereo(APEContext * ctx, int count)
775 {
776     int32_t left, right;
777     int32_t *decoded0 = ctx->decoded0;
778     int32_t *decoded1 = ctx->decoded1;
779
780     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
781         /* We are pure silence, so we're done. */
782         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
783         return;
784     }
785
786     entropy_decode(ctx, count, 1);
787     ape_apply_filters(ctx, decoded0, decoded1, count);
788
789     /* Now apply the predictor decoding */
790     predictor_decode_stereo(ctx, count);
791
792     /* Decorrelate and scale to output depth */
793     while (count--) {
794         left = *decoded1 - (*decoded0 / 2);
795         right = left + *decoded0;
796
797         *(decoded0++) = left;
798         *(decoded1++) = right;
799     }
800 }
801
802 static int ape_decode_frame(AVCodecContext * avctx,
803                             void *data, int *data_size,
804                             const uint8_t * buf, int buf_size)
805 {
806     APEContext *s = avctx->priv_data;
807     int16_t *samples = data;
808     int nblocks;
809     int i, n;
810     int blockstodecode;
811     int bytes_used;
812
813     if (buf_size == 0 && !s->samples) {
814         *data_size = 0;
815         return 0;
816     }
817
818     /* should not happen but who knows */
819     if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
820         av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);
821         return -1;
822     }
823
824     if(!s->samples){
825         s->data = av_realloc(s->data, (buf_size + 3) & ~3);
826         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
827         s->ptr = s->last_ptr = s->data;
828         s->data_end = s->data + buf_size;
829
830         nblocks = s->samples = bytestream_get_be32(&s->ptr);
831         n =  bytestream_get_be32(&s->ptr);
832         if(n < 0 || n > 3){
833             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
834             s->data = NULL;
835             return -1;
836         }
837         s->ptr += n;
838
839         s->currentframeblocks = nblocks;
840         buf += 4;
841         if (s->samples <= 0) {
842             *data_size = 0;
843             return buf_size;
844         }
845
846         memset(s->decoded0,  0, sizeof(s->decoded0));
847         memset(s->decoded1,  0, sizeof(s->decoded1));
848
849         /* Initialize the frame decoder */
850         init_frame_decoder(s);
851     }
852
853     if (!s->data) {
854         *data_size = 0;
855         return buf_size;
856     }
857
858     nblocks = s->samples;
859     blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
860
861     s->error=0;
862
863     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
864         ape_unpack_mono(s, blockstodecode);
865     else
866         ape_unpack_stereo(s, blockstodecode);
867
868     if(s->error || s->ptr > s->data_end){
869         s->samples=0;
870         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
871         return -1;
872     }
873
874     for (i = 0; i < blockstodecode; i++) {
875         *samples++ = s->decoded0[i];
876         if(s->channels == 2)
877             *samples++ = s->decoded1[i];
878     }
879
880     s->samples -= blockstodecode;
881
882     *data_size = blockstodecode * 2 * s->channels;
883     bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
884     s->last_ptr = s->ptr;
885     return bytes_used;
886 }
887
888 AVCodec ape_decoder = {
889     "ape",
890     CODEC_TYPE_AUDIO,
891     CODEC_ID_APE,
892     sizeof(APEContext),
893     ape_decode_init,
894     NULL,
895     ape_decode_close,
896     ape_decode_frame,
897     .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
898 };