2 * Monkey's Audio lossless audio decoder
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
6 * This file is part of FFmpeg.
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.
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.
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
23 #define ALT_BITSTREAM_READER_LE
26 #include "bitstream.h"
27 #include "bytestream.h"
31 * Monkey's Audio lossless audio decoder
34 #define BLOCKS_PER_LOOP 4608
35 #define MAX_CHANNELS 2
36 #define MAX_BYTESPERSAMPLE 3
38 #define APE_FRAMECODE_MONO_SILENCE 1
39 #define APE_FRAMECODE_STEREO_SILENCE 3
40 #define APE_FRAMECODE_PSEUDO_STEREO 4
42 #define HISTORY_SIZE 512
43 #define PREDICTOR_ORDER 8
44 /** Total size of all predictor histories */
45 #define PREDICTOR_SIZE 50
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)
52 #define YADAPTCOEFFSA 18
53 #define XADAPTCOEFFSA 14
54 #define YADAPTCOEFFSB 10
55 #define XADAPTCOEFFSB 5
58 * Possible compression levels
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
70 #define APE_FILTER_LEVELS 3
72 /** Filter orders depending on compression level */
73 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
81 /** Filter fraction bits depending on compression level */
82 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
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
101 typedef struct APERice {
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
113 /** Filter histories */
114 typedef struct APEPredictor {
122 int32_t coeffsA[2][4]; ///< adaption coefficients
123 int32_t coeffsB[2][5]; ///< adaption coefficients
124 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
127 /** Decoder context */
128 typedef struct APEContext {
129 AVCodecContext *avctx;
132 int samples; ///< samples left to decode in current frame
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
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
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
148 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
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
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
165 static av_cold int ape_decode_init(AVCodecContext * avctx)
167 APEContext *s = avctx->priv_data;
170 if (avctx->extradata_size != 6) {
171 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
174 if (avctx->bits_per_coded_sample != 16) {
175 av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
178 if (avctx->channels > 2) {
179 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
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);
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);
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])
197 s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);
200 dsputil_init(&s->dsp, avctx);
201 avctx->sample_fmt = SAMPLE_FMT_S16;
202 avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
206 static av_cold int ape_decode_close(AVCodecContext * avctx)
208 APEContext *s = avctx->priv_data;
211 for (i = 0; i < APE_FILTER_LEVELS; i++)
212 av_freep(&s->filterbuf[i]);
218 * @defgroup rangecoder APE range decoder
223 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
224 #define SHIFT_BITS (CODE_BITS - 9)
225 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
226 #define BOTTOM_VALUE (TOP_VALUE >> 8)
228 /** Start the decoder */
229 static inline void range_start_decoding(APEContext * ctx)
231 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
232 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
233 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
236 /** Perform normalization */
237 static inline void range_dec_normalize(APEContext * ctx)
239 while (ctx->rc.range <= BOTTOM_VALUE) {
240 ctx->rc.buffer <<= 8;
241 if(ctx->ptr < ctx->data_end)
242 ctx->rc.buffer += *ctx->ptr;
244 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
250 * Calculate culmulative frequency for next symbol. Does NO update!
251 * @param tot_f is the total frequency or (code_value)1<<shift
252 * @return the culmulative frequency
254 static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
256 range_dec_normalize(ctx);
257 ctx->rc.help = ctx->rc.range / tot_f;
258 return ctx->rc.low / ctx->rc.help;
262 * Decode value with given size in bits
263 * @param shift number of bits to decode
265 static inline int range_decode_culshift(APEContext * ctx, int shift)
267 range_dec_normalize(ctx);
268 ctx->rc.help = ctx->rc.range >> shift;
269 return ctx->rc.low / ctx->rc.help;
274 * Update decoding state
275 * @param sy_f the interval length (frequency of the symbol)
276 * @param lt_f the lower end (frequency sum of < symbols)
278 static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
280 ctx->rc.low -= ctx->rc.help * lt_f;
281 ctx->rc.range = ctx->rc.help * sy_f;
284 /** Decode n bits (n <= 16) without modelling */
285 static inline int range_decode_bits(APEContext * ctx, int n)
287 int sym = range_decode_culshift(ctx, n);
288 range_decode_update(ctx, 1, sym);
293 #define MODEL_ELEMENTS 64
296 * Fixed probabilities for symbols in Monkey Audio version 3.97
298 static const uint16_t counts_3970[22] = {
299 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
300 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
301 65450, 65469, 65480, 65487, 65491, 65493,
305 * Probability ranges for symbols in Monkey Audio version 3.97
307 static const uint16_t counts_diff_3970[21] = {
308 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
309 1104, 677, 415, 248, 150, 89, 54, 31,
314 * Fixed probabilities for symbols in Monkey Audio version 3.98
316 static const uint16_t counts_3980[22] = {
317 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
318 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
319 65485, 65488, 65490, 65491, 65492, 65493,
323 * Probability ranges for symbols in Monkey Audio version 3.98
325 static const uint16_t counts_diff_3980[21] = {
326 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
327 261, 119, 65, 31, 19, 10, 6, 3,
333 * @param counts probability range start position
334 * @param count_diffs probability range widths
336 static inline int range_get_symbol(APEContext * ctx,
337 const uint16_t counts[],
338 const uint16_t counts_diff[])
342 cf = range_decode_culshift(ctx, 16);
345 symbol= cf - 65535 + 63;
346 range_decode_update(ctx, 1, cf);
351 /* figure out the symbol inefficiently; a binary search would be much better */
352 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
354 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
358 /** @} */ // group rangecoder
360 static inline void update_rice(APERice *rice, int x)
362 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
363 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
365 if (rice->ksum < lim)
367 else if (rice->ksum >= (1 << (rice->k + 5)))
371 static inline int ape_decode_value(APEContext * ctx, APERice *rice)
375 if (ctx->fileversion < 3990) {
378 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
380 if (overflow == (MODEL_ELEMENTS - 1)) {
381 tmpk = range_decode_bits(ctx, 5);
384 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
387 x = range_decode_bits(ctx, tmpk);
389 x = range_decode_bits(ctx, 16);
390 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
392 x += overflow << tmpk;
396 pivot = rice->ksum >> 5;
400 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
402 if (overflow == (MODEL_ELEMENTS - 1)) {
403 overflow = range_decode_bits(ctx, 16) << 16;
404 overflow |= range_decode_bits(ctx, 16);
407 base = range_decode_culfreq(ctx, pivot);
408 range_decode_update(ctx, 1, base);
410 x = base + overflow * pivot;
413 update_rice(rice, x);
415 /* Convert to signed */
422 static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
424 int32_t *decoded0 = ctx->decoded0;
425 int32_t *decoded1 = ctx->decoded1;
427 ctx->blocksdecoded = blockstodecode;
429 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
430 /* We are pure silence, just memset the output buffer. */
431 memset(decoded0, 0, blockstodecode * sizeof(int32_t));
432 memset(decoded1, 0, blockstodecode * sizeof(int32_t));
434 while (blockstodecode--) {
435 *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
437 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
441 if (ctx->blocksdecoded == ctx->currentframeblocks)
442 range_dec_normalize(ctx); /* normalize to use up all bytes */
445 static void init_entropy_decoder(APEContext * ctx)
448 ctx->CRC = bytestream_get_be32(&ctx->ptr);
450 /* Read the frame flags if they exist */
452 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
453 ctx->CRC &= ~0x80000000;
455 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
458 /* Keep a count of the blocks decoded in this frame */
459 ctx->blocksdecoded = 0;
461 /* Initialize the rice structs */
463 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
465 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
467 /* The first 8 bits of input are ignored. */
470 range_start_decoding(ctx);
473 static const int32_t initial_coeffs[4] = {
477 static void init_predictor_decoder(APEContext * ctx)
479 APEPredictor *p = &ctx->predictor;
481 /* Zero the history buffers */
482 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
483 p->buf = p->historybuffer;
485 /* Initialize and zero the coefficients */
486 memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
487 memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
488 memset(p->coeffsB, 0, sizeof(p->coeffsB));
490 p->filterA[0] = p->filterA[1] = 0;
491 p->filterB[0] = p->filterB[1] = 0;
492 p->lastA[0] = p->lastA[1] = 0;
495 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
496 static inline int APESIGN(int32_t x) {
497 return (x < 0) - (x > 0);
500 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)
502 int32_t predictionA, predictionB;
504 p->buf[delayA] = p->lastA[filter];
505 p->buf[adaptA] = APESIGN(p->buf[delayA]);
506 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
507 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
509 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
510 p->buf[delayA - 1] * p->coeffsA[filter][1] +
511 p->buf[delayA - 2] * p->coeffsA[filter][2] +
512 p->buf[delayA - 3] * p->coeffsA[filter][3];
514 /* Apply a scaled first-order filter compression */
515 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
516 p->buf[adaptB] = APESIGN(p->buf[delayB]);
517 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
518 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
519 p->filterB[filter] = p->filterA[filter ^ 1];
521 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
522 p->buf[delayB - 1] * p->coeffsB[filter][1] +
523 p->buf[delayB - 2] * p->coeffsB[filter][2] +
524 p->buf[delayB - 3] * p->coeffsB[filter][3] +
525 p->buf[delayB - 4] * p->coeffsB[filter][4];
527 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
528 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
530 if (!decoded) // no need updating filter coefficients
531 return p->filterA[filter];
534 p->coeffsA[filter][0] -= p->buf[adaptA ];
535 p->coeffsA[filter][1] -= p->buf[adaptA - 1];
536 p->coeffsA[filter][2] -= p->buf[adaptA - 2];
537 p->coeffsA[filter][3] -= p->buf[adaptA - 3];
539 p->coeffsB[filter][0] -= p->buf[adaptB ];
540 p->coeffsB[filter][1] -= p->buf[adaptB - 1];
541 p->coeffsB[filter][2] -= p->buf[adaptB - 2];
542 p->coeffsB[filter][3] -= p->buf[adaptB - 3];
543 p->coeffsB[filter][4] -= p->buf[adaptB - 4];
545 p->coeffsA[filter][0] += p->buf[adaptA ];
546 p->coeffsA[filter][1] += p->buf[adaptA - 1];
547 p->coeffsA[filter][2] += p->buf[adaptA - 2];
548 p->coeffsA[filter][3] += p->buf[adaptA - 3];
550 p->coeffsB[filter][0] += p->buf[adaptB ];
551 p->coeffsB[filter][1] += p->buf[adaptB - 1];
552 p->coeffsB[filter][2] += p->buf[adaptB - 2];
553 p->coeffsB[filter][3] += p->buf[adaptB - 3];
554 p->coeffsB[filter][4] += p->buf[adaptB - 4];
556 return p->filterA[filter];
559 static void predictor_decode_stereo(APEContext * ctx, int count)
561 int32_t predictionA, predictionB;
562 APEPredictor *p = &ctx->predictor;
563 int32_t *decoded0 = ctx->decoded0;
564 int32_t *decoded1 = ctx->decoded1;
568 predictionA = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
569 predictionB = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
570 *(decoded0++) = predictionA;
571 *(decoded1++) = predictionB;
576 /* Have we filled the history buffer? */
577 if (p->buf == p->historybuffer + HISTORY_SIZE) {
578 memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
579 p->buf = p->historybuffer;
584 static void predictor_decode_mono(APEContext * ctx, int count)
586 APEPredictor *p = &ctx->predictor;
587 int32_t *decoded0 = ctx->decoded0;
588 int32_t predictionA, currentA, A;
590 currentA = p->lastA[0];
595 p->buf[YDELAYA] = currentA;
596 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
598 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
599 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
600 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
601 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
603 currentA = A + (predictionA >> 10);
605 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
606 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
609 p->coeffsA[0][0] -= p->buf[YADAPTCOEFFSA ];
610 p->coeffsA[0][1] -= p->buf[YADAPTCOEFFSA - 1];
611 p->coeffsA[0][2] -= p->buf[YADAPTCOEFFSA - 2];
612 p->coeffsA[0][3] -= p->buf[YADAPTCOEFFSA - 3];
614 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ];
615 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1];
616 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2];
617 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3];
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;
628 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
629 *(decoded0++) = p->filterA[0];
632 p->lastA[0] = currentA;
635 static void do_init_filter(APEFilter *f, int16_t * buf, int order)
638 f->historybuffer = buf + order;
639 f->delay = f->historybuffer + order * 2;
640 f->adaptcoeffs = f->historybuffer + order;
642 memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
643 memset(f->coeffs, 0, order * sizeof(int16_t));
647 static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
649 do_init_filter(&f[0], buf, order);
650 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
653 static inline void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
659 /* round fixedpoint scalar product */
660 res = (ctx->dsp.scalarproduct_int16(f->delay - order, f->coeffs, order, 0) + (1 << (fracbits - 1))) >> fracbits;
663 ctx->dsp.add_int16(f->coeffs, f->adaptcoeffs - order, order);
665 ctx->dsp.sub_int16(f->coeffs, f->adaptcoeffs - order, order);
671 /* Update the output history */
672 *f->delay++ = av_clip_int16(res);
674 if (version < 3980) {
675 /* Version ??? to < 3.98 files (untested) */
676 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
677 f->adaptcoeffs[-4] >>= 1;
678 f->adaptcoeffs[-8] >>= 1;
680 /* Version 3.98 and later files */
682 /* Update the adaption coefficients */
683 absres = (res < 0 ? -res : res);
685 if (absres > (f->avg * 3))
686 *f->adaptcoeffs = ((res >> 25) & 64) - 32;
687 else if (absres > (f->avg * 4) / 3)
688 *f->adaptcoeffs = ((res >> 26) & 32) - 16;
690 *f->adaptcoeffs = ((res >> 27) & 16) - 8;
694 f->avg += (absres - f->avg) / 16;
696 f->adaptcoeffs[-1] >>= 1;
697 f->adaptcoeffs[-2] >>= 1;
698 f->adaptcoeffs[-8] >>= 1;
703 /* Have we filled the history buffer? */
704 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
705 memmove(f->historybuffer, f->delay - (order * 2),
706 (order * 2) * sizeof(int16_t));
707 f->delay = f->historybuffer + order * 2;
708 f->adaptcoeffs = f->historybuffer + order;
713 static void apply_filter(APEContext * ctx, APEFilter *f,
714 int32_t * data0, int32_t * data1,
715 int count, int order, int fracbits)
717 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
719 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
722 static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
723 int32_t * decoded1, int count)
727 for (i = 0; i < APE_FILTER_LEVELS; i++) {
728 if (!ape_filter_orders[ctx->fset][i])
730 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
734 static void init_frame_decoder(APEContext * ctx)
737 init_entropy_decoder(ctx);
738 init_predictor_decoder(ctx);
740 for (i = 0; i < APE_FILTER_LEVELS; i++) {
741 if (!ape_filter_orders[ctx->fset][i])
743 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
747 static void ape_unpack_mono(APEContext * ctx, int count)
750 int32_t *decoded0 = ctx->decoded0;
751 int32_t *decoded1 = ctx->decoded1;
753 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
754 entropy_decode(ctx, count, 0);
755 /* We are pure silence, so we're done. */
756 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
760 entropy_decode(ctx, count, 0);
761 ape_apply_filters(ctx, decoded0, NULL, count);
763 /* Now apply the predictor decoding */
764 predictor_decode_mono(ctx, count);
766 /* Pseudo-stereo - just copy left channel to right channel */
767 if (ctx->channels == 2) {
770 *(decoded1++) = *(decoded0++) = left;
775 static void ape_unpack_stereo(APEContext * ctx, int count)
778 int32_t *decoded0 = ctx->decoded0;
779 int32_t *decoded1 = ctx->decoded1;
781 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
782 /* We are pure silence, so we're done. */
783 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
787 entropy_decode(ctx, count, 1);
788 ape_apply_filters(ctx, decoded0, decoded1, count);
790 /* Now apply the predictor decoding */
791 predictor_decode_stereo(ctx, count);
793 /* Decorrelate and scale to output depth */
795 left = *decoded1 - (*decoded0 / 2);
796 right = left + *decoded0;
798 *(decoded0++) = left;
799 *(decoded1++) = right;
803 static int ape_decode_frame(AVCodecContext * avctx,
804 void *data, int *data_size,
805 const uint8_t * buf, int buf_size)
807 APEContext *s = avctx->priv_data;
808 int16_t *samples = data;
814 if (buf_size == 0 && !s->samples) {
819 /* should not happen but who knows */
820 if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
821 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);
826 s->data = av_realloc(s->data, (buf_size + 3) & ~3);
827 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
828 s->ptr = s->last_ptr = s->data;
829 s->data_end = s->data + buf_size;
831 nblocks = s->samples = bytestream_get_be32(&s->ptr);
832 n = bytestream_get_be32(&s->ptr);
834 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
840 s->currentframeblocks = nblocks;
842 if (s->samples <= 0) {
847 memset(s->decoded0, 0, sizeof(s->decoded0));
848 memset(s->decoded1, 0, sizeof(s->decoded1));
850 /* Initialize the frame decoder */
851 init_frame_decoder(s);
859 nblocks = s->samples;
860 blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
864 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
865 ape_unpack_mono(s, blockstodecode);
867 ape_unpack_stereo(s, blockstodecode);
869 if(s->error || s->ptr > s->data_end){
871 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
875 for (i = 0; i < blockstodecode; i++) {
876 *samples++ = s->decoded0[i];
878 *samples++ = s->decoded1[i];
881 s->samples -= blockstodecode;
883 *data_size = blockstodecode * 2 * s->channels;
884 bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
885 s->last_ptr = s->ptr;
889 AVCodec ape_decoder = {
898 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),