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 Libav.
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.
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.
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
23 #define ALT_BITSTREAM_READER_LE
27 #include "bytestream.h"
28 #include "libavutil/audioconvert.h"
32 * Monkey's Audio lossless audio decoder
35 #define BLOCKS_PER_LOOP 4608
36 #define MAX_CHANNELS 2
37 #define MAX_BYTESPERSAMPLE 3
39 #define APE_FRAMECODE_MONO_SILENCE 1
40 #define APE_FRAMECODE_STEREO_SILENCE 3
41 #define APE_FRAMECODE_PSEUDO_STEREO 4
43 #define HISTORY_SIZE 512
44 #define PREDICTOR_ORDER 8
45 /** Total size of all predictor histories */
46 #define PREDICTOR_SIZE 50
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)
53 #define YADAPTCOEFFSA 18
54 #define XADAPTCOEFFSA 14
55 #define YADAPTCOEFFSB 10
56 #define XADAPTCOEFFSB 5
59 * Possible compression levels
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
71 #define APE_FILTER_LEVELS 3
73 /** Filter orders depending on compression level */
74 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
82 /** Filter fraction bits depending on compression level */
83 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
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
102 typedef struct APERice {
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
114 /** Filter histories */
115 typedef struct APEPredictor {
123 int32_t coeffsA[2][4]; ///< adaption coefficients
124 int32_t coeffsB[2][5]; ///< adaption coefficients
125 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
128 /** Decoder context */
129 typedef struct APEContext {
130 AVCodecContext *avctx;
133 int samples; ///< samples left to decode in current frame
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
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
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
149 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
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
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
166 static av_cold int ape_decode_close(AVCodecContext *avctx)
168 APEContext *s = avctx->priv_data;
171 for (i = 0; i < APE_FILTER_LEVELS; i++)
172 av_freep(&s->filterbuf[i]);
178 static av_cold int ape_decode_init(AVCodecContext *avctx)
180 APEContext *s = avctx->priv_data;
183 if (avctx->extradata_size != 6) {
184 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
185 return AVERROR(EINVAL);
187 if (avctx->bits_per_coded_sample != 16) {
188 av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
189 return AVERROR(EINVAL);
191 if (avctx->channels > 2) {
192 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
193 return AVERROR(EINVAL);
196 s->channels = avctx->channels;
197 s->fileversion = AV_RL16(avctx->extradata);
198 s->compression_level = AV_RL16(avctx->extradata + 2);
199 s->flags = AV_RL16(avctx->extradata + 4);
201 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
202 s->compression_level, s->flags);
203 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
204 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
205 s->compression_level);
206 return AVERROR_INVALIDDATA;
208 s->fset = s->compression_level / 1000 - 1;
209 for (i = 0; i < APE_FILTER_LEVELS; i++) {
210 if (!ape_filter_orders[s->fset][i])
212 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
213 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
217 dsputil_init(&s->dsp, avctx);
218 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
219 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
222 ape_decode_close(avctx);
223 return AVERROR(ENOMEM);
227 * @name APE range decoding functions
232 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
233 #define SHIFT_BITS (CODE_BITS - 9)
234 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
235 #define BOTTOM_VALUE (TOP_VALUE >> 8)
237 /** Start the decoder */
238 static inline void range_start_decoding(APEContext *ctx)
240 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
241 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
242 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
245 /** Perform normalization */
246 static inline void range_dec_normalize(APEContext *ctx)
248 while (ctx->rc.range <= BOTTOM_VALUE) {
249 ctx->rc.buffer <<= 8;
250 if(ctx->ptr < ctx->data_end)
251 ctx->rc.buffer += *ctx->ptr;
253 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
259 * Calculate culmulative frequency for next symbol. Does NO update!
260 * @param ctx decoder context
261 * @param tot_f is the total frequency or (code_value)1<<shift
262 * @return the culmulative frequency
264 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
266 range_dec_normalize(ctx);
267 ctx->rc.help = ctx->rc.range / tot_f;
268 return ctx->rc.low / ctx->rc.help;
272 * Decode value with given size in bits
273 * @param ctx decoder context
274 * @param shift number of bits to decode
276 static inline int range_decode_culshift(APEContext *ctx, int shift)
278 range_dec_normalize(ctx);
279 ctx->rc.help = ctx->rc.range >> shift;
280 return ctx->rc.low / ctx->rc.help;
285 * Update decoding state
286 * @param ctx decoder context
287 * @param sy_f the interval length (frequency of the symbol)
288 * @param lt_f the lower end (frequency sum of < symbols)
290 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
292 ctx->rc.low -= ctx->rc.help * lt_f;
293 ctx->rc.range = ctx->rc.help * sy_f;
296 /** Decode n bits (n <= 16) without modelling */
297 static inline int range_decode_bits(APEContext *ctx, int n)
299 int sym = range_decode_culshift(ctx, n);
300 range_decode_update(ctx, 1, sym);
305 #define MODEL_ELEMENTS 64
308 * Fixed probabilities for symbols in Monkey Audio version 3.97
310 static const uint16_t counts_3970[22] = {
311 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
312 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
313 65450, 65469, 65480, 65487, 65491, 65493,
317 * Probability ranges for symbols in Monkey Audio version 3.97
319 static const uint16_t counts_diff_3970[21] = {
320 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
321 1104, 677, 415, 248, 150, 89, 54, 31,
326 * Fixed probabilities for symbols in Monkey Audio version 3.98
328 static const uint16_t counts_3980[22] = {
329 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
330 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
331 65485, 65488, 65490, 65491, 65492, 65493,
335 * Probability ranges for symbols in Monkey Audio version 3.98
337 static const uint16_t counts_diff_3980[21] = {
338 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
339 261, 119, 65, 31, 19, 10, 6, 3,
345 * @param ctx decoder context
346 * @param counts probability range start position
347 * @param counts_diff probability range widths
349 static inline int range_get_symbol(APEContext *ctx,
350 const uint16_t counts[],
351 const uint16_t counts_diff[])
355 cf = range_decode_culshift(ctx, 16);
358 symbol= cf - 65535 + 63;
359 range_decode_update(ctx, 1, cf);
364 /* figure out the symbol inefficiently; a binary search would be much better */
365 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
367 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
371 /** @} */ // group rangecoder
373 static inline void update_rice(APERice *rice, int x)
375 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
376 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
378 if (rice->ksum < lim)
380 else if (rice->ksum >= (1 << (rice->k + 5)))
384 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
388 if (ctx->fileversion < 3990) {
391 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
393 if (overflow == (MODEL_ELEMENTS - 1)) {
394 tmpk = range_decode_bits(ctx, 5);
397 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
400 x = range_decode_bits(ctx, tmpk);
402 x = range_decode_bits(ctx, 16);
403 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
405 x += overflow << tmpk;
409 pivot = rice->ksum >> 5;
413 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
415 if (overflow == (MODEL_ELEMENTS - 1)) {
416 overflow = range_decode_bits(ctx, 16) << 16;
417 overflow |= range_decode_bits(ctx, 16);
420 if (pivot < 0x10000) {
421 base = range_decode_culfreq(ctx, pivot);
422 range_decode_update(ctx, 1, base);
424 int base_hi = pivot, base_lo;
427 while (base_hi & ~0xFFFF) {
431 base_hi = range_decode_culfreq(ctx, base_hi + 1);
432 range_decode_update(ctx, 1, base_hi);
433 base_lo = range_decode_culfreq(ctx, 1 << bbits);
434 range_decode_update(ctx, 1, base_lo);
436 base = (base_hi << bbits) + base_lo;
439 x = base + overflow * pivot;
442 update_rice(rice, x);
444 /* Convert to signed */
451 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
453 int32_t *decoded0 = ctx->decoded0;
454 int32_t *decoded1 = ctx->decoded1;
456 ctx->blocksdecoded = blockstodecode;
458 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
459 /* We are pure silence, just memset the output buffer. */
460 memset(decoded0, 0, blockstodecode * sizeof(int32_t));
461 memset(decoded1, 0, blockstodecode * sizeof(int32_t));
463 while (blockstodecode--) {
464 *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
466 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
470 if (ctx->blocksdecoded == ctx->currentframeblocks)
471 range_dec_normalize(ctx); /* normalize to use up all bytes */
474 static void init_entropy_decoder(APEContext *ctx)
477 ctx->CRC = bytestream_get_be32(&ctx->ptr);
479 /* Read the frame flags if they exist */
481 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
482 ctx->CRC &= ~0x80000000;
484 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
487 /* Keep a count of the blocks decoded in this frame */
488 ctx->blocksdecoded = 0;
490 /* Initialize the rice structs */
492 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
494 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
496 /* The first 8 bits of input are ignored. */
499 range_start_decoding(ctx);
502 static const int32_t initial_coeffs[4] = {
506 static void init_predictor_decoder(APEContext *ctx)
508 APEPredictor *p = &ctx->predictor;
510 /* Zero the history buffers */
511 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
512 p->buf = p->historybuffer;
514 /* Initialize and zero the coefficients */
515 memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
516 memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
517 memset(p->coeffsB, 0, sizeof(p->coeffsB));
519 p->filterA[0] = p->filterA[1] = 0;
520 p->filterB[0] = p->filterB[1] = 0;
521 p->lastA[0] = p->lastA[1] = 0;
524 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
525 static inline int APESIGN(int32_t x) {
526 return (x < 0) - (x > 0);
529 static av_always_inline int predictor_update_filter(APEPredictor *p,
530 const int decoded, const int filter,
531 const int delayA, const int delayB,
532 const int adaptA, const int adaptB)
534 int32_t predictionA, predictionB, sign;
536 p->buf[delayA] = p->lastA[filter];
537 p->buf[adaptA] = APESIGN(p->buf[delayA]);
538 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
539 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
541 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
542 p->buf[delayA - 1] * p->coeffsA[filter][1] +
543 p->buf[delayA - 2] * p->coeffsA[filter][2] +
544 p->buf[delayA - 3] * p->coeffsA[filter][3];
546 /* Apply a scaled first-order filter compression */
547 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
548 p->buf[adaptB] = APESIGN(p->buf[delayB]);
549 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
550 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
551 p->filterB[filter] = p->filterA[filter ^ 1];
553 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
554 p->buf[delayB - 1] * p->coeffsB[filter][1] +
555 p->buf[delayB - 2] * p->coeffsB[filter][2] +
556 p->buf[delayB - 3] * p->coeffsB[filter][3] +
557 p->buf[delayB - 4] * p->coeffsB[filter][4];
559 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
560 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
562 sign = APESIGN(decoded);
563 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
564 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
565 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
566 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
567 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
568 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
569 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
570 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
571 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
573 return p->filterA[filter];
576 static void predictor_decode_stereo(APEContext *ctx, int count)
578 APEPredictor *p = &ctx->predictor;
579 int32_t *decoded0 = ctx->decoded0;
580 int32_t *decoded1 = ctx->decoded1;
584 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
585 YADAPTCOEFFSA, YADAPTCOEFFSB);
587 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
588 XADAPTCOEFFSA, XADAPTCOEFFSB);
594 /* Have we filled the history buffer? */
595 if (p->buf == p->historybuffer + HISTORY_SIZE) {
596 memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
597 p->buf = p->historybuffer;
602 static void predictor_decode_mono(APEContext *ctx, int count)
604 APEPredictor *p = &ctx->predictor;
605 int32_t *decoded0 = ctx->decoded0;
606 int32_t predictionA, currentA, A, sign;
608 currentA = p->lastA[0];
613 p->buf[YDELAYA] = currentA;
614 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
616 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
617 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
618 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
619 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
621 currentA = A + (predictionA >> 10);
623 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
624 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
627 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
628 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
629 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
630 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
634 /* Have we filled the history buffer? */
635 if (p->buf == p->historybuffer + HISTORY_SIZE) {
636 memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
637 p->buf = p->historybuffer;
640 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
641 *(decoded0++) = p->filterA[0];
644 p->lastA[0] = currentA;
647 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
650 f->historybuffer = buf + order;
651 f->delay = f->historybuffer + order * 2;
652 f->adaptcoeffs = f->historybuffer + order;
654 memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
655 memset(f->coeffs, 0, order * sizeof(int16_t));
659 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
661 do_init_filter(&f[0], buf, order);
662 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
665 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
666 int32_t *data, int count, int order, int fracbits)
672 /* round fixedpoint scalar product */
673 res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
674 f->adaptcoeffs - order,
675 order, APESIGN(*data));
676 res = (res + (1 << (fracbits - 1))) >> fracbits;
680 /* Update the output history */
681 *f->delay++ = av_clip_int16(res);
683 if (version < 3980) {
684 /* Version ??? to < 3.98 files (untested) */
685 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
686 f->adaptcoeffs[-4] >>= 1;
687 f->adaptcoeffs[-8] >>= 1;
689 /* Version 3.98 and later files */
691 /* Update the adaption coefficients */
694 *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >>
695 (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
699 f->avg += (absres - f->avg) / 16;
701 f->adaptcoeffs[-1] >>= 1;
702 f->adaptcoeffs[-2] >>= 1;
703 f->adaptcoeffs[-8] >>= 1;
708 /* Have we filled the history buffer? */
709 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
710 memmove(f->historybuffer, f->delay - (order * 2),
711 (order * 2) * sizeof(int16_t));
712 f->delay = f->historybuffer + order * 2;
713 f->adaptcoeffs = f->historybuffer + order;
718 static void apply_filter(APEContext *ctx, APEFilter *f,
719 int32_t *data0, int32_t *data1,
720 int count, int order, int fracbits)
722 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
724 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
727 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
728 int32_t *decoded1, int count)
732 for (i = 0; i < APE_FILTER_LEVELS; i++) {
733 if (!ape_filter_orders[ctx->fset][i])
735 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
736 ape_filter_orders[ctx->fset][i],
737 ape_filter_fracbits[ctx->fset][i]);
741 static void init_frame_decoder(APEContext *ctx)
744 init_entropy_decoder(ctx);
745 init_predictor_decoder(ctx);
747 for (i = 0; i < APE_FILTER_LEVELS; i++) {
748 if (!ape_filter_orders[ctx->fset][i])
750 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
751 ape_filter_orders[ctx->fset][i]);
755 static void ape_unpack_mono(APEContext *ctx, int count)
757 int32_t *decoded0 = ctx->decoded0;
758 int32_t *decoded1 = ctx->decoded1;
760 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
761 entropy_decode(ctx, count, 0);
762 /* We are pure silence, so we're done. */
763 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
767 entropy_decode(ctx, count, 0);
768 ape_apply_filters(ctx, decoded0, NULL, count);
770 /* Now apply the predictor decoding */
771 predictor_decode_mono(ctx, count);
773 /* Pseudo-stereo - just copy left channel to right channel */
774 if (ctx->channels == 2) {
775 memcpy(decoded1, decoded0, count * sizeof(*decoded1));
779 static void ape_unpack_stereo(APEContext *ctx, int count)
782 int32_t *decoded0 = ctx->decoded0;
783 int32_t *decoded1 = ctx->decoded1;
785 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
786 /* We are pure silence, so we're done. */
787 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
791 entropy_decode(ctx, count, 1);
792 ape_apply_filters(ctx, decoded0, decoded1, count);
794 /* Now apply the predictor decoding */
795 predictor_decode_stereo(ctx, count);
797 /* Decorrelate and scale to output depth */
799 left = *decoded1 - (*decoded0 / 2);
800 right = left + *decoded0;
802 *(decoded0++) = left;
803 *(decoded1++) = right;
807 static int ape_decode_frame(AVCodecContext *avctx,
808 void *data, int *data_size,
811 const uint8_t *buf = avpkt->data;
812 int buf_size = avpkt->size;
813 APEContext *s = avctx->priv_data;
814 int16_t *samples = data;
820 /* should not happen but who knows */
821 if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
822 av_log (avctx, AV_LOG_ERROR, "Output buffer is too small.\n");
823 return AVERROR(EINVAL);
827 void *tmp_data = av_realloc(s->data, (buf_size + 3) & ~3);
829 return AVERROR(ENOMEM);
831 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
832 s->ptr = s->last_ptr = s->data;
833 s->data_end = s->data + buf_size;
835 nblocks = bytestream_get_be32(&s->ptr);
836 n = bytestream_get_be32(&s->ptr);
838 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
840 return AVERROR_INVALIDDATA;
845 if (!nblocks || nblocks > INT_MAX) {
846 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
847 return AVERROR_INVALIDDATA;
849 s->currentframeblocks = s->samples = nblocks;
851 memset(s->decoded0, 0, sizeof(s->decoded0));
852 memset(s->decoded1, 0, sizeof(s->decoded1));
854 /* Initialize the frame decoder */
855 init_frame_decoder(s);
863 nblocks = s->samples;
864 blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
868 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
869 ape_unpack_mono(s, blockstodecode);
871 ape_unpack_stereo(s, blockstodecode);
874 if(s->error || s->ptr > s->data_end){
876 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
877 return AVERROR_INVALIDDATA;
880 for (i = 0; i < blockstodecode; i++) {
881 *samples++ = s->decoded0[i];
883 *samples++ = s->decoded1[i];
886 s->samples -= blockstodecode;
888 *data_size = blockstodecode * 2 * s->channels;
889 bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
890 s->last_ptr = s->ptr;
894 static void ape_flush(AVCodecContext *avctx)
896 APEContext *s = avctx->priv_data;
900 AVCodec ff_ape_decoder = {
902 .type = AVMEDIA_TYPE_AUDIO,
904 .priv_data_size = sizeof(APEContext),
905 .init = ape_decode_init,
906 .close = ape_decode_close,
907 .decode = ape_decode_frame,
908 .capabilities = CODEC_CAP_SUBFRAMES,
910 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),