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 #include "libavutil/avassert.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/opt.h"
28 #include "bytestream.h"
33 * Monkey's Audio lossless audio decoder
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 AVClass *class; ///< class for AVOptions
131 AVCodecContext *avctx;
134 int samples; ///< samples left to decode in current frame
137 int fileversion; ///< codec version, very important in decoding process
138 int compression_level; ///< compression levels
139 int fset; ///< which filter set to use (calculated from compression level)
140 int flags; ///< global decoder flags
142 uint32_t CRC; ///< frame CRC
143 int frameflags; ///< frame flags
144 APEPredictor predictor; ///< predictor used for final reconstruction
146 int32_t *decoded_buffer;
148 int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
149 int blocks_per_loop; ///< maximum number of samples to decode for each call
151 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
153 APERangecoder rc; ///< rangecoder used to decode actual values
154 APERice riceX; ///< rice code parameters for the second channel
155 APERice riceY; ///< rice code parameters for the first channel
156 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
158 uint8_t *data; ///< current frame data
159 uint8_t *data_end; ///< frame data end
160 int data_size; ///< frame data allocated size
161 const uint8_t *ptr; ///< current position in frame data
165 void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
166 void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
167 void (*predictor_decode_mono)(struct APEContext *ctx, int count);
168 void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
171 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
172 int32_t *decoded1, int count);
174 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
175 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
176 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
177 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
179 static void predictor_decode_mono_3950(APEContext *ctx, int count);
180 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
184 static av_cold int ape_decode_close(AVCodecContext *avctx)
186 APEContext *s = avctx->priv_data;
189 for (i = 0; i < APE_FILTER_LEVELS; i++)
190 av_freep(&s->filterbuf[i]);
192 av_freep(&s->decoded_buffer);
194 s->decoded_size = s->data_size = 0;
199 static av_cold int ape_decode_init(AVCodecContext *avctx)
201 APEContext *s = avctx->priv_data;
204 if (avctx->extradata_size != 6) {
205 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
206 return AVERROR(EINVAL);
208 if (avctx->channels > 2) {
209 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
210 return AVERROR(EINVAL);
212 s->bps = avctx->bits_per_coded_sample;
215 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
218 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
221 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
224 avpriv_request_sample(avctx,
225 "%d bits per coded sample", s->bps);
226 return AVERROR_PATCHWELCOME;
229 s->channels = avctx->channels;
230 s->fileversion = AV_RL16(avctx->extradata);
231 s->compression_level = AV_RL16(avctx->extradata + 2);
232 s->flags = AV_RL16(avctx->extradata + 4);
234 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
235 s->compression_level, s->flags);
236 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
237 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
238 s->compression_level);
239 return AVERROR_INVALIDDATA;
241 s->fset = s->compression_level / 1000 - 1;
242 for (i = 0; i < APE_FILTER_LEVELS; i++) {
243 if (!ape_filter_orders[s->fset][i])
245 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
246 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
250 if (s->fileversion < 3990) {
251 s->entropy_decode_mono = entropy_decode_mono_3900;
252 s->entropy_decode_stereo = entropy_decode_stereo_3900;
254 s->entropy_decode_mono = entropy_decode_mono_3990;
255 s->entropy_decode_stereo = entropy_decode_stereo_3990;
258 s->predictor_decode_mono = predictor_decode_mono_3950;
259 s->predictor_decode_stereo = predictor_decode_stereo_3950;
261 ff_dsputil_init(&s->dsp, avctx);
262 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
266 ape_decode_close(avctx);
267 return AVERROR(ENOMEM);
271 * @name APE range decoding functions
276 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
277 #define SHIFT_BITS (CODE_BITS - 9)
278 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
279 #define BOTTOM_VALUE (TOP_VALUE >> 8)
281 /** Start the decoder */
282 static inline void range_start_decoding(APEContext *ctx)
284 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
285 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
286 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
289 /** Perform normalization */
290 static inline void range_dec_normalize(APEContext *ctx)
292 while (ctx->rc.range <= BOTTOM_VALUE) {
293 ctx->rc.buffer <<= 8;
294 if(ctx->ptr < ctx->data_end) {
295 ctx->rc.buffer += *ctx->ptr;
300 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
306 * Calculate culmulative frequency for next symbol. Does NO update!
307 * @param ctx decoder context
308 * @param tot_f is the total frequency or (code_value)1<<shift
309 * @return the culmulative frequency
311 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
313 range_dec_normalize(ctx);
314 ctx->rc.help = ctx->rc.range / tot_f;
315 return ctx->rc.low / ctx->rc.help;
319 * Decode value with given size in bits
320 * @param ctx decoder context
321 * @param shift number of bits to decode
323 static inline int range_decode_culshift(APEContext *ctx, int shift)
325 range_dec_normalize(ctx);
326 ctx->rc.help = ctx->rc.range >> shift;
327 return ctx->rc.low / ctx->rc.help;
332 * Update decoding state
333 * @param ctx decoder context
334 * @param sy_f the interval length (frequency of the symbol)
335 * @param lt_f the lower end (frequency sum of < symbols)
337 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
339 ctx->rc.low -= ctx->rc.help * lt_f;
340 ctx->rc.range = ctx->rc.help * sy_f;
343 /** Decode n bits (n <= 16) without modelling */
344 static inline int range_decode_bits(APEContext *ctx, int n)
346 int sym = range_decode_culshift(ctx, n);
347 range_decode_update(ctx, 1, sym);
352 #define MODEL_ELEMENTS 64
355 * Fixed probabilities for symbols in Monkey Audio version 3.97
357 static const uint16_t counts_3970[22] = {
358 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
359 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
360 65450, 65469, 65480, 65487, 65491, 65493,
364 * Probability ranges for symbols in Monkey Audio version 3.97
366 static const uint16_t counts_diff_3970[21] = {
367 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
368 1104, 677, 415, 248, 150, 89, 54, 31,
373 * Fixed probabilities for symbols in Monkey Audio version 3.98
375 static const uint16_t counts_3980[22] = {
376 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
377 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
378 65485, 65488, 65490, 65491, 65492, 65493,
382 * Probability ranges for symbols in Monkey Audio version 3.98
384 static const uint16_t counts_diff_3980[21] = {
385 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
386 261, 119, 65, 31, 19, 10, 6, 3,
392 * @param ctx decoder context
393 * @param counts probability range start position
394 * @param counts_diff probability range widths
396 static inline int range_get_symbol(APEContext *ctx,
397 const uint16_t counts[],
398 const uint16_t counts_diff[])
402 cf = range_decode_culshift(ctx, 16);
405 symbol= cf - 65535 + 63;
406 range_decode_update(ctx, 1, cf);
411 /* figure out the symbol inefficiently; a binary search would be much better */
412 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
414 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
418 /** @} */ // group rangecoder
420 static inline void update_rice(APERice *rice, unsigned int x)
422 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
423 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
425 if (rice->ksum < lim)
427 else if (rice->ksum >= (1 << (rice->k + 5)))
431 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
433 unsigned int x, overflow;
436 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
438 if (overflow == (MODEL_ELEMENTS - 1)) {
439 tmpk = range_decode_bits(ctx, 5);
442 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
445 x = range_decode_bits(ctx, tmpk);
446 else if (tmpk <= 32) {
447 x = range_decode_bits(ctx, 16);
448 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
450 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
451 return AVERROR_INVALIDDATA;
453 x += overflow << tmpk;
455 update_rice(rice, x);
457 /* Convert to signed */
464 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
466 unsigned int x, overflow;
469 pivot = rice->ksum >> 5;
473 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
475 if (overflow == (MODEL_ELEMENTS - 1)) {
476 overflow = range_decode_bits(ctx, 16) << 16;
477 overflow |= range_decode_bits(ctx, 16);
480 if (pivot < 0x10000) {
481 base = range_decode_culfreq(ctx, pivot);
482 range_decode_update(ctx, 1, base);
484 int base_hi = pivot, base_lo;
487 while (base_hi & ~0xFFFF) {
491 base_hi = range_decode_culfreq(ctx, base_hi + 1);
492 range_decode_update(ctx, 1, base_hi);
493 base_lo = range_decode_culfreq(ctx, 1 << bbits);
494 range_decode_update(ctx, 1, base_lo);
496 base = (base_hi << bbits) + base_lo;
499 x = base + overflow * pivot;
501 update_rice(rice, x);
503 /* Convert to signed */
510 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
512 int32_t *decoded0 = ctx->decoded[0];
514 while (blockstodecode--)
515 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
518 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
520 int32_t *decoded0 = ctx->decoded[0];
521 int32_t *decoded1 = ctx->decoded[1];
523 while (blockstodecode--) {
524 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
525 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
529 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
531 int32_t *decoded0 = ctx->decoded[0];
533 while (blockstodecode--)
534 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
537 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
539 int32_t *decoded0 = ctx->decoded[0];
540 int32_t *decoded1 = ctx->decoded[1];
542 while (blockstodecode--) {
543 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
544 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
548 static int init_entropy_decoder(APEContext *ctx)
551 if (ctx->data_end - ctx->ptr < 6)
552 return AVERROR_INVALIDDATA;
553 ctx->CRC = bytestream_get_be32(&ctx->ptr);
555 /* Read the frame flags if they exist */
557 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
558 ctx->CRC &= ~0x80000000;
560 if (ctx->data_end - ctx->ptr < 6)
561 return AVERROR_INVALIDDATA;
562 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
565 /* Initialize the rice structs */
567 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
569 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
571 /* The first 8 bits of input are ignored. */
574 range_start_decoding(ctx);
579 static const int32_t initial_coeffs[4] = {
583 static void init_predictor_decoder(APEContext *ctx)
585 APEPredictor *p = &ctx->predictor;
587 /* Zero the history buffers */
588 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
589 p->buf = p->historybuffer;
591 /* Initialize and zero the coefficients */
592 memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
593 memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
594 memset(p->coeffsB, 0, sizeof(p->coeffsB));
596 p->filterA[0] = p->filterA[1] = 0;
597 p->filterB[0] = p->filterB[1] = 0;
598 p->lastA[0] = p->lastA[1] = 0;
601 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
602 static inline int APESIGN(int32_t x) {
603 return (x < 0) - (x > 0);
606 static av_always_inline int predictor_update_filter(APEPredictor *p,
607 const int decoded, const int filter,
608 const int delayA, const int delayB,
609 const int adaptA, const int adaptB)
611 int32_t predictionA, predictionB, sign;
613 p->buf[delayA] = p->lastA[filter];
614 p->buf[adaptA] = APESIGN(p->buf[delayA]);
615 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
616 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
618 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
619 p->buf[delayA - 1] * p->coeffsA[filter][1] +
620 p->buf[delayA - 2] * p->coeffsA[filter][2] +
621 p->buf[delayA - 3] * p->coeffsA[filter][3];
623 /* Apply a scaled first-order filter compression */
624 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
625 p->buf[adaptB] = APESIGN(p->buf[delayB]);
626 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
627 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
628 p->filterB[filter] = p->filterA[filter ^ 1];
630 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
631 p->buf[delayB - 1] * p->coeffsB[filter][1] +
632 p->buf[delayB - 2] * p->coeffsB[filter][2] +
633 p->buf[delayB - 3] * p->coeffsB[filter][3] +
634 p->buf[delayB - 4] * p->coeffsB[filter][4];
636 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
637 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
639 sign = APESIGN(decoded);
640 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
641 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
642 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
643 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
644 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
645 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
646 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
647 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
648 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
650 return p->filterA[filter];
653 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
655 APEPredictor *p = &ctx->predictor;
656 int32_t *decoded0 = ctx->decoded[0];
657 int32_t *decoded1 = ctx->decoded[1];
659 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
663 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
664 YADAPTCOEFFSA, YADAPTCOEFFSB);
666 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
667 XADAPTCOEFFSA, XADAPTCOEFFSB);
673 /* Have we filled the history buffer? */
674 if (p->buf == p->historybuffer + HISTORY_SIZE) {
675 memmove(p->historybuffer, p->buf,
676 PREDICTOR_SIZE * sizeof(*p->historybuffer));
677 p->buf = p->historybuffer;
682 static void predictor_decode_mono_3950(APEContext *ctx, int count)
684 APEPredictor *p = &ctx->predictor;
685 int32_t *decoded0 = ctx->decoded[0];
686 int32_t predictionA, currentA, A, sign;
688 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
690 currentA = p->lastA[0];
695 p->buf[YDELAYA] = currentA;
696 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
698 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
699 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
700 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
701 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
703 currentA = A + (predictionA >> 10);
705 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
706 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
709 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
710 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
711 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
712 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
716 /* Have we filled the history buffer? */
717 if (p->buf == p->historybuffer + HISTORY_SIZE) {
718 memmove(p->historybuffer, p->buf,
719 PREDICTOR_SIZE * sizeof(*p->historybuffer));
720 p->buf = p->historybuffer;
723 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
724 *(decoded0++) = p->filterA[0];
727 p->lastA[0] = currentA;
730 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
733 f->historybuffer = buf + order;
734 f->delay = f->historybuffer + order * 2;
735 f->adaptcoeffs = f->historybuffer + order;
737 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
738 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
742 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
744 do_init_filter(&f[0], buf, order);
745 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
748 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
749 int32_t *data, int count, int order, int fracbits)
755 /* round fixedpoint scalar product */
756 res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
757 f->adaptcoeffs - order,
758 order, APESIGN(*data));
759 res = (res + (1 << (fracbits - 1))) >> fracbits;
763 /* Update the output history */
764 *f->delay++ = av_clip_int16(res);
766 if (version < 3980) {
767 /* Version ??? to < 3.98 files (untested) */
768 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
769 f->adaptcoeffs[-4] >>= 1;
770 f->adaptcoeffs[-8] >>= 1;
772 /* Version 3.98 and later files */
774 /* Update the adaption coefficients */
777 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
778 (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
782 f->avg += (absres - f->avg) / 16;
784 f->adaptcoeffs[-1] >>= 1;
785 f->adaptcoeffs[-2] >>= 1;
786 f->adaptcoeffs[-8] >>= 1;
791 /* Have we filled the history buffer? */
792 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
793 memmove(f->historybuffer, f->delay - (order * 2),
794 (order * 2) * sizeof(*f->historybuffer));
795 f->delay = f->historybuffer + order * 2;
796 f->adaptcoeffs = f->historybuffer + order;
801 static void apply_filter(APEContext *ctx, APEFilter *f,
802 int32_t *data0, int32_t *data1,
803 int count, int order, int fracbits)
805 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
807 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
810 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
811 int32_t *decoded1, int count)
815 for (i = 0; i < APE_FILTER_LEVELS; i++) {
816 if (!ape_filter_orders[ctx->fset][i])
818 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
819 ape_filter_orders[ctx->fset][i],
820 ape_filter_fracbits[ctx->fset][i]);
824 static int init_frame_decoder(APEContext *ctx)
827 if ((ret = init_entropy_decoder(ctx)) < 0)
829 init_predictor_decoder(ctx);
831 for (i = 0; i < APE_FILTER_LEVELS; i++) {
832 if (!ape_filter_orders[ctx->fset][i])
834 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
835 ape_filter_orders[ctx->fset][i]);
840 static void ape_unpack_mono(APEContext *ctx, int count)
842 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
843 /* We are pure silence, so we're done. */
844 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
848 ctx->entropy_decode_mono(ctx, count);
850 /* Now apply the predictor decoding */
851 ctx->predictor_decode_mono(ctx, count);
853 /* Pseudo-stereo - just copy left channel to right channel */
854 if (ctx->channels == 2) {
855 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
859 static void ape_unpack_stereo(APEContext *ctx, int count)
862 int32_t *decoded0 = ctx->decoded[0];
863 int32_t *decoded1 = ctx->decoded[1];
865 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
866 /* We are pure silence, so we're done. */
867 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
871 ctx->entropy_decode_stereo(ctx, count);
873 /* Now apply the predictor decoding */
874 ctx->predictor_decode_stereo(ctx, count);
876 /* Decorrelate and scale to output depth */
878 left = *decoded1 - (*decoded0 / 2);
879 right = left + *decoded0;
881 *(decoded0++) = left;
882 *(decoded1++) = right;
886 static int ape_decode_frame(AVCodecContext *avctx, void *data,
887 int *got_frame_ptr, AVPacket *avpkt)
889 AVFrame *frame = data;
890 const uint8_t *buf = avpkt->data;
891 APEContext *s = avctx->priv_data;
899 /* this should never be negative, but bad things will happen if it is, so
900 check it just to make sure. */
901 av_assert0(s->samples >= 0);
904 uint32_t nblocks, offset;
911 if (avpkt->size < 8) {
912 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
913 return AVERROR_INVALIDDATA;
915 buf_size = avpkt->size & ~3;
916 if (buf_size != avpkt->size) {
917 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
918 "extra bytes at the end will be skipped.\n");
921 av_fast_malloc(&s->data, &s->data_size, buf_size);
923 return AVERROR(ENOMEM);
924 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
926 s->data_end = s->data + buf_size;
928 nblocks = bytestream_get_be32(&s->ptr);
929 offset = bytestream_get_be32(&s->ptr);
931 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
933 return AVERROR_INVALIDDATA;
935 if (s->data_end - s->ptr < offset) {
936 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
937 return AVERROR_INVALIDDATA;
941 if (!nblocks || nblocks > INT_MAX) {
942 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
943 return AVERROR_INVALIDDATA;
945 s->samples = nblocks;
947 /* Initialize the frame decoder */
948 if (init_frame_decoder(s) < 0) {
949 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
950 return AVERROR_INVALIDDATA;
953 bytes_used = avpkt->size;
961 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
963 /* reallocate decoded sample buffer if needed */
964 av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
965 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
966 if (!s->decoded_buffer)
967 return AVERROR(ENOMEM);
968 memset(s->decoded_buffer, 0, s->decoded_size);
969 s->decoded[0] = s->decoded_buffer;
970 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
972 /* get output buffer */
973 frame->nb_samples = blockstodecode;
974 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
975 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
981 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
982 ape_unpack_mono(s, blockstodecode);
984 ape_unpack_stereo(s, blockstodecode);
989 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
990 return AVERROR_INVALIDDATA;
995 for (ch = 0; ch < s->channels; ch++) {
996 sample8 = (uint8_t *)frame->data[ch];
997 for (i = 0; i < blockstodecode; i++)
998 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1002 for (ch = 0; ch < s->channels; ch++) {
1003 sample16 = (int16_t *)frame->data[ch];
1004 for (i = 0; i < blockstodecode; i++)
1005 *sample16++ = s->decoded[ch][i];
1009 for (ch = 0; ch < s->channels; ch++) {
1010 sample24 = (int32_t *)frame->data[ch];
1011 for (i = 0; i < blockstodecode; i++)
1012 *sample24++ = s->decoded[ch][i] << 8;
1017 s->samples -= blockstodecode;
1024 static void ape_flush(AVCodecContext *avctx)
1026 APEContext *s = avctx->priv_data;
1030 #define OFFSET(x) offsetof(APEContext, x)
1031 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1032 static const AVOption options[] = {
1033 { "max_samples", "maximum number of samples decoded per call", OFFSET(blocks_per_loop), AV_OPT_TYPE_INT, { .i64 = 4608 }, 1, INT_MAX, PAR, "max_samples" },
1034 { "all", "no maximum. decode all samples for each packet at once", 0, AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
1038 static const AVClass ape_decoder_class = {
1039 .class_name = "APE decoder",
1040 .item_name = av_default_item_name,
1042 .version = LIBAVUTIL_VERSION_INT,
1045 AVCodec ff_ape_decoder = {
1047 .type = AVMEDIA_TYPE_AUDIO,
1048 .id = AV_CODEC_ID_APE,
1049 .priv_data_size = sizeof(APEContext),
1050 .init = ape_decode_init,
1051 .close = ape_decode_close,
1052 .decode = ape_decode_frame,
1053 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
1055 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1056 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1059 AV_SAMPLE_FMT_NONE },
1060 .priv_class = &ape_decoder_class,