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_3930(APEContext *ctx, int count);
180 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
181 static void predictor_decode_mono_3950(APEContext *ctx, int count);
182 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
186 static av_cold int ape_decode_close(AVCodecContext *avctx)
188 APEContext *s = avctx->priv_data;
191 for (i = 0; i < APE_FILTER_LEVELS; i++)
192 av_freep(&s->filterbuf[i]);
194 av_freep(&s->decoded_buffer);
196 s->decoded_size = s->data_size = 0;
201 static av_cold int ape_decode_init(AVCodecContext *avctx)
203 APEContext *s = avctx->priv_data;
206 if (avctx->extradata_size != 6) {
207 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
208 return AVERROR(EINVAL);
210 if (avctx->channels > 2) {
211 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
212 return AVERROR(EINVAL);
214 s->bps = avctx->bits_per_coded_sample;
217 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
220 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
223 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
226 avpriv_request_sample(avctx,
227 "%d bits per coded sample", s->bps);
228 return AVERROR_PATCHWELCOME;
231 s->channels = avctx->channels;
232 s->fileversion = AV_RL16(avctx->extradata);
233 s->compression_level = AV_RL16(avctx->extradata + 2);
234 s->flags = AV_RL16(avctx->extradata + 4);
236 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
237 s->compression_level, s->flags);
238 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
239 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
240 s->compression_level);
241 return AVERROR_INVALIDDATA;
243 s->fset = s->compression_level / 1000 - 1;
244 for (i = 0; i < APE_FILTER_LEVELS; i++) {
245 if (!ape_filter_orders[s->fset][i])
247 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
248 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
252 if (s->fileversion < 3990) {
253 s->entropy_decode_mono = entropy_decode_mono_3900;
254 s->entropy_decode_stereo = entropy_decode_stereo_3900;
256 s->entropy_decode_mono = entropy_decode_mono_3990;
257 s->entropy_decode_stereo = entropy_decode_stereo_3990;
260 if (s->fileversion < 3950) {
261 s->predictor_decode_mono = predictor_decode_mono_3930;
262 s->predictor_decode_stereo = predictor_decode_stereo_3930;
264 s->predictor_decode_mono = predictor_decode_mono_3950;
265 s->predictor_decode_stereo = predictor_decode_stereo_3950;
268 ff_dsputil_init(&s->dsp, avctx);
269 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
273 ape_decode_close(avctx);
274 return AVERROR(ENOMEM);
278 * @name APE range decoding functions
283 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
284 #define SHIFT_BITS (CODE_BITS - 9)
285 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
286 #define BOTTOM_VALUE (TOP_VALUE >> 8)
288 /** Start the decoder */
289 static inline void range_start_decoding(APEContext *ctx)
291 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
292 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
293 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
296 /** Perform normalization */
297 static inline void range_dec_normalize(APEContext *ctx)
299 while (ctx->rc.range <= BOTTOM_VALUE) {
300 ctx->rc.buffer <<= 8;
301 if(ctx->ptr < ctx->data_end) {
302 ctx->rc.buffer += *ctx->ptr;
307 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
313 * Calculate culmulative frequency for next symbol. Does NO update!
314 * @param ctx decoder context
315 * @param tot_f is the total frequency or (code_value)1<<shift
316 * @return the culmulative frequency
318 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
320 range_dec_normalize(ctx);
321 ctx->rc.help = ctx->rc.range / tot_f;
322 return ctx->rc.low / ctx->rc.help;
326 * Decode value with given size in bits
327 * @param ctx decoder context
328 * @param shift number of bits to decode
330 static inline int range_decode_culshift(APEContext *ctx, int shift)
332 range_dec_normalize(ctx);
333 ctx->rc.help = ctx->rc.range >> shift;
334 return ctx->rc.low / ctx->rc.help;
339 * Update decoding state
340 * @param ctx decoder context
341 * @param sy_f the interval length (frequency of the symbol)
342 * @param lt_f the lower end (frequency sum of < symbols)
344 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
346 ctx->rc.low -= ctx->rc.help * lt_f;
347 ctx->rc.range = ctx->rc.help * sy_f;
350 /** Decode n bits (n <= 16) without modelling */
351 static inline int range_decode_bits(APEContext *ctx, int n)
353 int sym = range_decode_culshift(ctx, n);
354 range_decode_update(ctx, 1, sym);
359 #define MODEL_ELEMENTS 64
362 * Fixed probabilities for symbols in Monkey Audio version 3.97
364 static const uint16_t counts_3970[22] = {
365 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
366 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
367 65450, 65469, 65480, 65487, 65491, 65493,
371 * Probability ranges for symbols in Monkey Audio version 3.97
373 static const uint16_t counts_diff_3970[21] = {
374 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
375 1104, 677, 415, 248, 150, 89, 54, 31,
380 * Fixed probabilities for symbols in Monkey Audio version 3.98
382 static const uint16_t counts_3980[22] = {
383 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
384 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
385 65485, 65488, 65490, 65491, 65492, 65493,
389 * Probability ranges for symbols in Monkey Audio version 3.98
391 static const uint16_t counts_diff_3980[21] = {
392 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
393 261, 119, 65, 31, 19, 10, 6, 3,
399 * @param ctx decoder context
400 * @param counts probability range start position
401 * @param counts_diff probability range widths
403 static inline int range_get_symbol(APEContext *ctx,
404 const uint16_t counts[],
405 const uint16_t counts_diff[])
409 cf = range_decode_culshift(ctx, 16);
412 symbol= cf - 65535 + 63;
413 range_decode_update(ctx, 1, cf);
418 /* figure out the symbol inefficiently; a binary search would be much better */
419 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
421 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
425 /** @} */ // group rangecoder
427 static inline void update_rice(APERice *rice, unsigned int x)
429 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
430 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
432 if (rice->ksum < lim)
434 else if (rice->ksum >= (1 << (rice->k + 5)))
438 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
440 unsigned int x, overflow;
443 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
445 if (overflow == (MODEL_ELEMENTS - 1)) {
446 tmpk = range_decode_bits(ctx, 5);
449 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
452 x = range_decode_bits(ctx, tmpk);
453 else if (tmpk <= 32) {
454 x = range_decode_bits(ctx, 16);
455 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
457 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
458 return AVERROR_INVALIDDATA;
460 x += overflow << tmpk;
462 update_rice(rice, x);
464 /* Convert to signed */
471 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
473 unsigned int x, overflow;
476 pivot = rice->ksum >> 5;
480 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
482 if (overflow == (MODEL_ELEMENTS - 1)) {
483 overflow = range_decode_bits(ctx, 16) << 16;
484 overflow |= range_decode_bits(ctx, 16);
487 if (pivot < 0x10000) {
488 base = range_decode_culfreq(ctx, pivot);
489 range_decode_update(ctx, 1, base);
491 int base_hi = pivot, base_lo;
494 while (base_hi & ~0xFFFF) {
498 base_hi = range_decode_culfreq(ctx, base_hi + 1);
499 range_decode_update(ctx, 1, base_hi);
500 base_lo = range_decode_culfreq(ctx, 1 << bbits);
501 range_decode_update(ctx, 1, base_lo);
503 base = (base_hi << bbits) + base_lo;
506 x = base + overflow * pivot;
508 update_rice(rice, x);
510 /* Convert to signed */
517 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
519 int32_t *decoded0 = ctx->decoded[0];
521 while (blockstodecode--)
522 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
525 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
527 int32_t *decoded0 = ctx->decoded[0];
528 int32_t *decoded1 = ctx->decoded[1];
530 while (blockstodecode--) {
531 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
532 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
536 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
538 int32_t *decoded0 = ctx->decoded[0];
540 while (blockstodecode--)
541 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
544 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
546 int32_t *decoded0 = ctx->decoded[0];
547 int32_t *decoded1 = ctx->decoded[1];
549 while (blockstodecode--) {
550 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
551 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
555 static int init_entropy_decoder(APEContext *ctx)
558 if (ctx->data_end - ctx->ptr < 6)
559 return AVERROR_INVALIDDATA;
560 ctx->CRC = bytestream_get_be32(&ctx->ptr);
562 /* Read the frame flags if they exist */
564 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
565 ctx->CRC &= ~0x80000000;
567 if (ctx->data_end - ctx->ptr < 6)
568 return AVERROR_INVALIDDATA;
569 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
572 /* Initialize the rice structs */
574 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
576 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
578 /* The first 8 bits of input are ignored. */
581 range_start_decoding(ctx);
586 static const int32_t initial_coeffs[4] = {
590 static void init_predictor_decoder(APEContext *ctx)
592 APEPredictor *p = &ctx->predictor;
594 /* Zero the history buffers */
595 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
596 p->buf = p->historybuffer;
598 /* Initialize and zero the coefficients */
599 memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
600 memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
601 memset(p->coeffsB, 0, sizeof(p->coeffsB));
603 p->filterA[0] = p->filterA[1] = 0;
604 p->filterB[0] = p->filterB[1] = 0;
605 p->lastA[0] = p->lastA[1] = 0;
608 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
609 static inline int APESIGN(int32_t x) {
610 return (x < 0) - (x > 0);
613 static av_always_inline int predictor_update_3930(APEPredictor *p,
614 const int decoded, const int filter,
617 int32_t predictionA, sign;
618 int32_t d0, d1, d2, d3;
620 p->buf[delayA] = p->lastA[filter];
621 d0 = p->buf[delayA ];
622 d1 = p->buf[delayA ] - p->buf[delayA - 1];
623 d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
624 d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
626 predictionA = d0 * p->coeffsA[filter][0] +
627 d1 * p->coeffsA[filter][1] +
628 d2 * p->coeffsA[filter][2] +
629 d3 * p->coeffsA[filter][3];
631 p->lastA[filter] = decoded + (predictionA >> 9);
632 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
634 sign = APESIGN(decoded);
635 p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
636 p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
637 p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
638 p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
640 return p->filterA[filter];
643 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
645 APEPredictor *p = &ctx->predictor;
646 int32_t *decoded0 = ctx->decoded[0];
647 int32_t *decoded1 = ctx->decoded[1];
649 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
653 int Y = *decoded1, X = *decoded0;
654 *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
656 *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
662 /* Have we filled the history buffer? */
663 if (p->buf == p->historybuffer + HISTORY_SIZE) {
664 memmove(p->historybuffer, p->buf,
665 PREDICTOR_SIZE * sizeof(*p->historybuffer));
666 p->buf = p->historybuffer;
671 static void predictor_decode_mono_3930(APEContext *ctx, int count)
673 APEPredictor *p = &ctx->predictor;
674 int32_t *decoded0 = ctx->decoded[0];
676 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
679 *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
684 /* Have we filled the history buffer? */
685 if (p->buf == p->historybuffer + HISTORY_SIZE) {
686 memmove(p->historybuffer, p->buf,
687 PREDICTOR_SIZE * sizeof(*p->historybuffer));
688 p->buf = p->historybuffer;
693 static av_always_inline int predictor_update_filter(APEPredictor *p,
694 const int decoded, const int filter,
695 const int delayA, const int delayB,
696 const int adaptA, const int adaptB)
698 int32_t predictionA, predictionB, sign;
700 p->buf[delayA] = p->lastA[filter];
701 p->buf[adaptA] = APESIGN(p->buf[delayA]);
702 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
703 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
705 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
706 p->buf[delayA - 1] * p->coeffsA[filter][1] +
707 p->buf[delayA - 2] * p->coeffsA[filter][2] +
708 p->buf[delayA - 3] * p->coeffsA[filter][3];
710 /* Apply a scaled first-order filter compression */
711 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
712 p->buf[adaptB] = APESIGN(p->buf[delayB]);
713 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
714 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
715 p->filterB[filter] = p->filterA[filter ^ 1];
717 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
718 p->buf[delayB - 1] * p->coeffsB[filter][1] +
719 p->buf[delayB - 2] * p->coeffsB[filter][2] +
720 p->buf[delayB - 3] * p->coeffsB[filter][3] +
721 p->buf[delayB - 4] * p->coeffsB[filter][4];
723 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
724 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
726 sign = APESIGN(decoded);
727 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
728 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
729 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
730 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
731 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
732 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
733 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
734 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
735 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
737 return p->filterA[filter];
740 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
742 APEPredictor *p = &ctx->predictor;
743 int32_t *decoded0 = ctx->decoded[0];
744 int32_t *decoded1 = ctx->decoded[1];
746 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
750 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
751 YADAPTCOEFFSA, YADAPTCOEFFSB);
753 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
754 XADAPTCOEFFSA, XADAPTCOEFFSB);
760 /* Have we filled the history buffer? */
761 if (p->buf == p->historybuffer + HISTORY_SIZE) {
762 memmove(p->historybuffer, p->buf,
763 PREDICTOR_SIZE * sizeof(*p->historybuffer));
764 p->buf = p->historybuffer;
769 static void predictor_decode_mono_3950(APEContext *ctx, int count)
771 APEPredictor *p = &ctx->predictor;
772 int32_t *decoded0 = ctx->decoded[0];
773 int32_t predictionA, currentA, A, sign;
775 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
777 currentA = p->lastA[0];
782 p->buf[YDELAYA] = currentA;
783 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
785 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
786 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
787 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
788 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
790 currentA = A + (predictionA >> 10);
792 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
793 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
796 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
797 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
798 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
799 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
803 /* Have we filled the history buffer? */
804 if (p->buf == p->historybuffer + HISTORY_SIZE) {
805 memmove(p->historybuffer, p->buf,
806 PREDICTOR_SIZE * sizeof(*p->historybuffer));
807 p->buf = p->historybuffer;
810 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
811 *(decoded0++) = p->filterA[0];
814 p->lastA[0] = currentA;
817 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
820 f->historybuffer = buf + order;
821 f->delay = f->historybuffer + order * 2;
822 f->adaptcoeffs = f->historybuffer + order;
824 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
825 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
829 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
831 do_init_filter(&f[0], buf, order);
832 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
835 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
836 int32_t *data, int count, int order, int fracbits)
842 /* round fixedpoint scalar product */
843 res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
844 f->adaptcoeffs - order,
845 order, APESIGN(*data));
846 res = (res + (1 << (fracbits - 1))) >> fracbits;
850 /* Update the output history */
851 *f->delay++ = av_clip_int16(res);
853 if (version < 3980) {
854 /* Version ??? to < 3.98 files (untested) */
855 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
856 f->adaptcoeffs[-4] >>= 1;
857 f->adaptcoeffs[-8] >>= 1;
859 /* Version 3.98 and later files */
861 /* Update the adaption coefficients */
864 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
865 (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
869 f->avg += (absres - f->avg) / 16;
871 f->adaptcoeffs[-1] >>= 1;
872 f->adaptcoeffs[-2] >>= 1;
873 f->adaptcoeffs[-8] >>= 1;
878 /* Have we filled the history buffer? */
879 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
880 memmove(f->historybuffer, f->delay - (order * 2),
881 (order * 2) * sizeof(*f->historybuffer));
882 f->delay = f->historybuffer + order * 2;
883 f->adaptcoeffs = f->historybuffer + order;
888 static void apply_filter(APEContext *ctx, APEFilter *f,
889 int32_t *data0, int32_t *data1,
890 int count, int order, int fracbits)
892 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
894 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
897 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
898 int32_t *decoded1, int count)
902 for (i = 0; i < APE_FILTER_LEVELS; i++) {
903 if (!ape_filter_orders[ctx->fset][i])
905 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
906 ape_filter_orders[ctx->fset][i],
907 ape_filter_fracbits[ctx->fset][i]);
911 static int init_frame_decoder(APEContext *ctx)
914 if ((ret = init_entropy_decoder(ctx)) < 0)
916 init_predictor_decoder(ctx);
918 for (i = 0; i < APE_FILTER_LEVELS; i++) {
919 if (!ape_filter_orders[ctx->fset][i])
921 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
922 ape_filter_orders[ctx->fset][i]);
927 static void ape_unpack_mono(APEContext *ctx, int count)
929 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
930 /* We are pure silence, so we're done. */
931 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
935 ctx->entropy_decode_mono(ctx, count);
937 /* Now apply the predictor decoding */
938 ctx->predictor_decode_mono(ctx, count);
940 /* Pseudo-stereo - just copy left channel to right channel */
941 if (ctx->channels == 2) {
942 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
946 static void ape_unpack_stereo(APEContext *ctx, int count)
949 int32_t *decoded0 = ctx->decoded[0];
950 int32_t *decoded1 = ctx->decoded[1];
952 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
953 /* We are pure silence, so we're done. */
954 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
958 ctx->entropy_decode_stereo(ctx, count);
960 /* Now apply the predictor decoding */
961 ctx->predictor_decode_stereo(ctx, count);
963 /* Decorrelate and scale to output depth */
965 left = *decoded1 - (*decoded0 / 2);
966 right = left + *decoded0;
968 *(decoded0++) = left;
969 *(decoded1++) = right;
973 static int ape_decode_frame(AVCodecContext *avctx, void *data,
974 int *got_frame_ptr, AVPacket *avpkt)
976 AVFrame *frame = data;
977 const uint8_t *buf = avpkt->data;
978 APEContext *s = avctx->priv_data;
986 /* this should never be negative, but bad things will happen if it is, so
987 check it just to make sure. */
988 av_assert0(s->samples >= 0);
991 uint32_t nblocks, offset;
998 if (avpkt->size < 8) {
999 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1000 return AVERROR_INVALIDDATA;
1002 buf_size = avpkt->size & ~3;
1003 if (buf_size != avpkt->size) {
1004 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1005 "extra bytes at the end will be skipped.\n");
1007 if (s->fileversion < 3950) // previous versions overread two bytes
1009 av_fast_malloc(&s->data, &s->data_size, buf_size);
1011 return AVERROR(ENOMEM);
1012 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
1013 memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1015 s->data_end = s->data + buf_size;
1017 nblocks = bytestream_get_be32(&s->ptr);
1018 offset = bytestream_get_be32(&s->ptr);
1020 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1022 return AVERROR_INVALIDDATA;
1024 if (s->data_end - s->ptr < offset) {
1025 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1026 return AVERROR_INVALIDDATA;
1030 if (!nblocks || nblocks > INT_MAX) {
1031 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
1032 return AVERROR_INVALIDDATA;
1034 s->samples = nblocks;
1036 /* Initialize the frame decoder */
1037 if (init_frame_decoder(s) < 0) {
1038 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1039 return AVERROR_INVALIDDATA;
1042 bytes_used = avpkt->size;
1050 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1052 /* reallocate decoded sample buffer if needed */
1053 av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
1054 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
1055 if (!s->decoded_buffer)
1056 return AVERROR(ENOMEM);
1057 memset(s->decoded_buffer, 0, s->decoded_size);
1058 s->decoded[0] = s->decoded_buffer;
1059 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1061 /* get output buffer */
1062 frame->nb_samples = blockstodecode;
1063 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1064 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1070 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1071 ape_unpack_mono(s, blockstodecode);
1073 ape_unpack_stereo(s, blockstodecode);
1078 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1079 return AVERROR_INVALIDDATA;
1084 for (ch = 0; ch < s->channels; ch++) {
1085 sample8 = (uint8_t *)frame->data[ch];
1086 for (i = 0; i < blockstodecode; i++)
1087 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1091 for (ch = 0; ch < s->channels; ch++) {
1092 sample16 = (int16_t *)frame->data[ch];
1093 for (i = 0; i < blockstodecode; i++)
1094 *sample16++ = s->decoded[ch][i];
1098 for (ch = 0; ch < s->channels; ch++) {
1099 sample24 = (int32_t *)frame->data[ch];
1100 for (i = 0; i < blockstodecode; i++)
1101 *sample24++ = s->decoded[ch][i] << 8;
1106 s->samples -= blockstodecode;
1113 static void ape_flush(AVCodecContext *avctx)
1115 APEContext *s = avctx->priv_data;
1119 #define OFFSET(x) offsetof(APEContext, x)
1120 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1121 static const AVOption options[] = {
1122 { "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" },
1123 { "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" },
1127 static const AVClass ape_decoder_class = {
1128 .class_name = "APE decoder",
1129 .item_name = av_default_item_name,
1131 .version = LIBAVUTIL_VERSION_INT,
1134 AVCodec ff_ape_decoder = {
1136 .type = AVMEDIA_TYPE_AUDIO,
1137 .id = AV_CODEC_ID_APE,
1138 .priv_data_size = sizeof(APEContext),
1139 .init = ape_decode_init,
1140 .close = ape_decode_close,
1141 .decode = ape_decode_frame,
1142 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
1144 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1145 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1148 AV_SAMPLE_FMT_NONE },
1149 .priv_class = &ape_decoder_class,