OSDN Git Service

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