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"
35 * Monkey's Audio lossless audio decoder
38 #define MAX_CHANNELS 2
39 #define MAX_BYTESPERSAMPLE 3
41 #define APE_FRAMECODE_MONO_SILENCE 1
42 #define APE_FRAMECODE_STEREO_SILENCE 3
43 #define APE_FRAMECODE_PSEUDO_STEREO 4
45 #define HISTORY_SIZE 512
46 #define PREDICTOR_ORDER 8
47 /** Total size of all predictor histories */
48 #define PREDICTOR_SIZE 50
50 #define YDELAYA (18 + PREDICTOR_ORDER*4)
51 #define YDELAYB (18 + PREDICTOR_ORDER*3)
52 #define XDELAYA (18 + PREDICTOR_ORDER*2)
53 #define XDELAYB (18 + PREDICTOR_ORDER)
55 #define YADAPTCOEFFSA 18
56 #define XADAPTCOEFFSA 14
57 #define YADAPTCOEFFSB 10
58 #define XADAPTCOEFFSB 5
61 * Possible compression levels
64 enum APECompressionLevel {
65 COMPRESSION_LEVEL_FAST = 1000,
66 COMPRESSION_LEVEL_NORMAL = 2000,
67 COMPRESSION_LEVEL_HIGH = 3000,
68 COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
69 COMPRESSION_LEVEL_INSANE = 5000
73 #define APE_FILTER_LEVELS 3
75 /** Filter orders depending on compression level */
76 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
84 /** Filter fraction bits depending on compression level */
85 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
94 /** Filters applied to the decoded data */
95 typedef struct APEFilter {
96 int16_t *coeffs; ///< actual coefficients used in filtering
97 int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
98 int16_t *historybuffer; ///< filter memory
99 int16_t *delay; ///< filtered values
104 typedef struct APERice {
109 typedef struct APERangecoder {
110 uint32_t low; ///< low end of interval
111 uint32_t range; ///< length of interval
112 uint32_t help; ///< bytes_to_follow resp. intermediate value
113 unsigned int buffer; ///< buffer for input/output
116 /** Filter histories */
117 typedef struct APEPredictor {
125 int32_t coeffsA[2][4]; ///< adaption coefficients
126 int32_t coeffsB[2][5]; ///< adaption coefficients
127 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
129 unsigned int sample_pos;
132 /** Decoder context */
133 typedef struct APEContext {
134 AVClass *class; ///< class for AVOptions
135 AVCodecContext *avctx;
138 int samples; ///< samples left to decode in current frame
141 int fileversion; ///< codec version, very important in decoding process
142 int compression_level; ///< compression levels
143 int fset; ///< which filter set to use (calculated from compression level)
144 int flags; ///< global decoder flags
146 uint32_t CRC; ///< frame CRC
147 int frameflags; ///< frame flags
148 APEPredictor predictor; ///< predictor used for final reconstruction
150 int32_t *decoded_buffer;
152 int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
153 int blocks_per_loop; ///< maximum number of samples to decode for each call
155 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
157 APERangecoder rc; ///< rangecoder used to decode actual values
158 APERice riceX; ///< rice code parameters for the second channel
159 APERice riceY; ///< rice code parameters for the first channel
160 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
163 uint8_t *data; ///< current frame data
164 uint8_t *data_end; ///< frame data end
165 int data_size; ///< frame data allocated size
166 const uint8_t *ptr; ///< current position in frame data
170 void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
171 void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
172 void (*predictor_decode_mono)(struct APEContext *ctx, int count);
173 void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
176 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
177 int32_t *decoded1, int count);
179 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
180 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
181 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
182 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
183 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
184 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
185 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
186 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
187 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
189 static void predictor_decode_mono_3800(APEContext *ctx, int count);
190 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
191 static void predictor_decode_mono_3930(APEContext *ctx, int count);
192 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
193 static void predictor_decode_mono_3950(APEContext *ctx, int count);
194 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
198 static av_cold int ape_decode_close(AVCodecContext *avctx)
200 APEContext *s = avctx->priv_data;
203 for (i = 0; i < APE_FILTER_LEVELS; i++)
204 av_freep(&s->filterbuf[i]);
206 av_freep(&s->decoded_buffer);
208 s->decoded_size = s->data_size = 0;
213 static av_cold int ape_decode_init(AVCodecContext *avctx)
215 APEContext *s = avctx->priv_data;
218 if (avctx->extradata_size != 6) {
219 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
220 return AVERROR(EINVAL);
222 if (avctx->channels > 2) {
223 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
224 return AVERROR(EINVAL);
226 s->bps = avctx->bits_per_coded_sample;
229 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
232 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
235 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
238 avpriv_request_sample(avctx,
239 "%d bits per coded sample", s->bps);
240 return AVERROR_PATCHWELCOME;
243 s->channels = avctx->channels;
244 s->fileversion = AV_RL16(avctx->extradata);
245 s->compression_level = AV_RL16(avctx->extradata + 2);
246 s->flags = AV_RL16(avctx->extradata + 4);
248 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
249 s->compression_level, s->flags);
250 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
251 (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
252 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
253 s->compression_level);
254 return AVERROR_INVALIDDATA;
256 s->fset = s->compression_level / 1000 - 1;
257 for (i = 0; i < APE_FILTER_LEVELS; i++) {
258 if (!ape_filter_orders[s->fset][i])
260 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
261 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
265 if (s->fileversion < 3860) {
266 s->entropy_decode_mono = entropy_decode_mono_0000;
267 s->entropy_decode_stereo = entropy_decode_stereo_0000;
268 } else if (s->fileversion < 3900) {
269 s->entropy_decode_mono = entropy_decode_mono_3860;
270 s->entropy_decode_stereo = entropy_decode_stereo_3860;
271 } else if (s->fileversion < 3930) {
272 s->entropy_decode_mono = entropy_decode_mono_3900;
273 s->entropy_decode_stereo = entropy_decode_stereo_3900;
274 } else if (s->fileversion < 3990) {
275 s->entropy_decode_mono = entropy_decode_mono_3900;
276 s->entropy_decode_stereo = entropy_decode_stereo_3930;
278 s->entropy_decode_mono = entropy_decode_mono_3990;
279 s->entropy_decode_stereo = entropy_decode_stereo_3990;
282 if (s->fileversion < 3930) {
283 s->predictor_decode_mono = predictor_decode_mono_3800;
284 s->predictor_decode_stereo = predictor_decode_stereo_3800;
285 } else if (s->fileversion < 3950) {
286 s->predictor_decode_mono = predictor_decode_mono_3930;
287 s->predictor_decode_stereo = predictor_decode_stereo_3930;
289 s->predictor_decode_mono = predictor_decode_mono_3950;
290 s->predictor_decode_stereo = predictor_decode_stereo_3950;
293 ff_dsputil_init(&s->dsp, avctx);
294 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
298 ape_decode_close(avctx);
299 return AVERROR(ENOMEM);
303 * @name APE range decoding functions
308 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
309 #define SHIFT_BITS (CODE_BITS - 9)
310 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
311 #define BOTTOM_VALUE (TOP_VALUE >> 8)
313 /** Start the decoder */
314 static inline void range_start_decoding(APEContext *ctx)
316 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
317 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
318 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
321 /** Perform normalization */
322 static inline void range_dec_normalize(APEContext *ctx)
324 while (ctx->rc.range <= BOTTOM_VALUE) {
325 ctx->rc.buffer <<= 8;
326 if(ctx->ptr < ctx->data_end) {
327 ctx->rc.buffer += *ctx->ptr;
332 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
338 * Calculate culmulative frequency for next symbol. Does NO update!
339 * @param ctx decoder context
340 * @param tot_f is the total frequency or (code_value)1<<shift
341 * @return the culmulative frequency
343 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
345 range_dec_normalize(ctx);
346 ctx->rc.help = ctx->rc.range / tot_f;
347 return ctx->rc.low / ctx->rc.help;
351 * Decode value with given size in bits
352 * @param ctx decoder context
353 * @param shift number of bits to decode
355 static inline int range_decode_culshift(APEContext *ctx, int shift)
357 range_dec_normalize(ctx);
358 ctx->rc.help = ctx->rc.range >> shift;
359 return ctx->rc.low / ctx->rc.help;
364 * Update decoding state
365 * @param ctx decoder context
366 * @param sy_f the interval length (frequency of the symbol)
367 * @param lt_f the lower end (frequency sum of < symbols)
369 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
371 ctx->rc.low -= ctx->rc.help * lt_f;
372 ctx->rc.range = ctx->rc.help * sy_f;
375 /** Decode n bits (n <= 16) without modelling */
376 static inline int range_decode_bits(APEContext *ctx, int n)
378 int sym = range_decode_culshift(ctx, n);
379 range_decode_update(ctx, 1, sym);
384 #define MODEL_ELEMENTS 64
387 * Fixed probabilities for symbols in Monkey Audio version 3.97
389 static const uint16_t counts_3970[22] = {
390 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
391 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
392 65450, 65469, 65480, 65487, 65491, 65493,
396 * Probability ranges for symbols in Monkey Audio version 3.97
398 static const uint16_t counts_diff_3970[21] = {
399 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
400 1104, 677, 415, 248, 150, 89, 54, 31,
405 * Fixed probabilities for symbols in Monkey Audio version 3.98
407 static const uint16_t counts_3980[22] = {
408 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
409 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
410 65485, 65488, 65490, 65491, 65492, 65493,
414 * Probability ranges for symbols in Monkey Audio version 3.98
416 static const uint16_t counts_diff_3980[21] = {
417 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
418 261, 119, 65, 31, 19, 10, 6, 3,
424 * @param ctx decoder context
425 * @param counts probability range start position
426 * @param counts_diff probability range widths
428 static inline int range_get_symbol(APEContext *ctx,
429 const uint16_t counts[],
430 const uint16_t counts_diff[])
434 cf = range_decode_culshift(ctx, 16);
437 symbol= cf - 65535 + 63;
438 range_decode_update(ctx, 1, cf);
443 /* figure out the symbol inefficiently; a binary search would be much better */
444 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
446 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
450 /** @} */ // group rangecoder
452 static inline void update_rice(APERice *rice, unsigned int x)
454 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
455 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
457 if (rice->ksum < lim)
459 else if (rice->ksum >= (1 << (rice->k + 5)))
463 static inline int get_rice_ook(GetBitContext *gb, int k)
467 x = get_unary(gb, 1, get_bits_left(gb));
470 x = (x << k) | get_bits(gb, k);
475 static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
478 unsigned int x, overflow;
480 overflow = get_unary(gb, 1, get_bits_left(gb));
482 if (ctx->fileversion > 3880) {
483 while (overflow >= 16) {
492 x = (overflow << rice->k) + get_bits(gb, rice->k);
494 rice->ksum += x - (rice->ksum + 8 >> 4);
495 if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
497 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
500 /* Convert to signed */
507 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
509 unsigned int x, overflow;
512 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
514 if (overflow == (MODEL_ELEMENTS - 1)) {
515 tmpk = range_decode_bits(ctx, 5);
518 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
520 if (tmpk <= 16 || ctx->fileversion < 3910)
521 x = range_decode_bits(ctx, tmpk);
522 else if (tmpk <= 32) {
523 x = range_decode_bits(ctx, 16);
524 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
526 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
527 return AVERROR_INVALIDDATA;
529 x += overflow << tmpk;
531 update_rice(rice, x);
533 /* Convert to signed */
540 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
542 unsigned int x, overflow;
545 pivot = rice->ksum >> 5;
549 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
551 if (overflow == (MODEL_ELEMENTS - 1)) {
552 overflow = range_decode_bits(ctx, 16) << 16;
553 overflow |= range_decode_bits(ctx, 16);
556 if (pivot < 0x10000) {
557 base = range_decode_culfreq(ctx, pivot);
558 range_decode_update(ctx, 1, base);
560 int base_hi = pivot, base_lo;
563 while (base_hi & ~0xFFFF) {
567 base_hi = range_decode_culfreq(ctx, base_hi + 1);
568 range_decode_update(ctx, 1, base_hi);
569 base_lo = range_decode_culfreq(ctx, 1 << bbits);
570 range_decode_update(ctx, 1, base_lo);
572 base = (base_hi << bbits) + base_lo;
575 x = base + overflow * pivot;
577 update_rice(rice, x);
579 /* Convert to signed */
586 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
587 int32_t *out, APERice *rice, int blockstodecode)
590 int ksummax, ksummin;
593 for (i = 0; i < 5; i++) {
594 out[i] = get_rice_ook(&ctx->gb, 10);
595 rice->ksum += out[i];
597 rice->k = av_log2(rice->ksum / 10) + 1;
598 for (; i < 64; i++) {
599 out[i] = get_rice_ook(&ctx->gb, rice->k);
600 rice->ksum += out[i];
601 rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
603 ksummax = 1 << rice->k + 7;
604 ksummin = rice->k ? (1 << rice->k + 6) : 0;
605 for (; i < blockstodecode; i++) {
606 out[i] = get_rice_ook(&ctx->gb, rice->k);
607 rice->ksum += out[i] - out[i - 64];
608 while (rice->ksum < ksummin) {
610 ksummin = rice->k ? ksummin >> 1 : 0;
613 while (rice->ksum >= ksummax) {
618 ksummin = ksummin ? ksummin << 1 : 128;
622 for (i = 0; i < blockstodecode; i++) {
624 out[i] = (out[i] >> 1) + 1;
626 out[i] = -(out[i] >> 1);
630 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
632 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
636 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
638 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
640 decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
644 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
646 int32_t *decoded0 = ctx->decoded[0];
648 while (blockstodecode--)
649 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
652 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
654 int32_t *decoded0 = ctx->decoded[0];
655 int32_t *decoded1 = ctx->decoded[1];
656 int blocks = blockstodecode;
658 while (blockstodecode--)
659 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
661 *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
664 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
666 int32_t *decoded0 = ctx->decoded[0];
668 while (blockstodecode--)
669 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
672 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
674 int32_t *decoded0 = ctx->decoded[0];
675 int32_t *decoded1 = ctx->decoded[1];
676 int blocks = blockstodecode;
678 while (blockstodecode--)
679 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
680 range_dec_normalize(ctx);
681 // because of some implementation peculiarities we need to backpedal here
683 range_start_decoding(ctx);
685 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
688 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
690 int32_t *decoded0 = ctx->decoded[0];
691 int32_t *decoded1 = ctx->decoded[1];
693 while (blockstodecode--) {
694 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
695 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
699 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
701 int32_t *decoded0 = ctx->decoded[0];
703 while (blockstodecode--)
704 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
707 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
709 int32_t *decoded0 = ctx->decoded[0];
710 int32_t *decoded1 = ctx->decoded[1];
712 while (blockstodecode--) {
713 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
714 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
718 static int init_entropy_decoder(APEContext *ctx)
721 if (ctx->fileversion >= 3900) {
722 if (ctx->data_end - ctx->ptr < 6)
723 return AVERROR_INVALIDDATA;
724 ctx->CRC = bytestream_get_be32(&ctx->ptr);
726 ctx->CRC = get_bits_long(&ctx->gb, 32);
729 /* Read the frame flags if they exist */
731 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
732 ctx->CRC &= ~0x80000000;
734 if (ctx->data_end - ctx->ptr < 6)
735 return AVERROR_INVALIDDATA;
736 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
739 /* Initialize the rice structs */
741 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
743 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
745 if (ctx->fileversion >= 3900) {
746 /* The first 8 bits of input are ignored. */
749 range_start_decoding(ctx);
755 static const int32_t initial_coeffs_fast_3320[1] = {
759 static const int32_t initial_coeffs_a_3800[3] = {
763 static const int32_t initial_coeffs_b_3800[2] = {
767 static const int32_t initial_coeffs_3930[4] = {
771 static void init_predictor_decoder(APEContext *ctx)
773 APEPredictor *p = &ctx->predictor;
775 /* Zero the history buffers */
776 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
777 p->buf = p->historybuffer;
779 /* Initialize and zero the coefficients */
780 if (ctx->fileversion < 3930) {
781 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
782 memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
783 sizeof(initial_coeffs_fast_3320));
784 memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
785 sizeof(initial_coeffs_fast_3320));
787 memcpy(p->coeffsA[0], initial_coeffs_a_3800,
788 sizeof(initial_coeffs_a_3800));
789 memcpy(p->coeffsA[1], initial_coeffs_a_3800,
790 sizeof(initial_coeffs_a_3800));
793 memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
794 memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
796 memset(p->coeffsB, 0, sizeof(p->coeffsB));
797 if (ctx->fileversion < 3930) {
798 memcpy(p->coeffsB[0], initial_coeffs_b_3800,
799 sizeof(initial_coeffs_b_3800));
800 memcpy(p->coeffsB[1], initial_coeffs_b_3800,
801 sizeof(initial_coeffs_b_3800));
804 p->filterA[0] = p->filterA[1] = 0;
805 p->filterB[0] = p->filterB[1] = 0;
806 p->lastA[0] = p->lastA[1] = 0;
811 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
812 static inline int APESIGN(int32_t x) {
813 return (x < 0) - (x > 0);
816 static av_always_inline int filter_fast_3320(APEPredictor *p,
817 const int decoded, const int filter,
822 p->buf[delayA] = p->lastA[filter];
823 if (p->sample_pos < 3) {
824 p->lastA[filter] = decoded;
825 p->filterA[filter] = decoded;
829 predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
830 p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9);
832 if ((decoded ^ predictionA) > 0)
833 p->coeffsA[filter][0]++;
835 p->coeffsA[filter][0]--;
837 p->filterA[filter] += p->lastA[filter];
839 return p->filterA[filter];
842 static av_always_inline int filter_3800(APEPredictor *p,
843 const int decoded, const int filter,
844 const int delayA, const int delayB,
845 const int start, const int shift)
847 int32_t predictionA, predictionB, sign;
848 int32_t d0, d1, d2, d3, d4;
850 p->buf[delayA] = p->lastA[filter];
851 p->buf[delayB] = p->filterB[filter];
852 if (p->sample_pos < start) {
853 predictionA = decoded + p->filterA[filter];
854 p->lastA[filter] = decoded;
855 p->filterB[filter] = decoded;
856 p->filterA[filter] = predictionA;
860 d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
861 d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
862 d3 = p->buf[delayB] * 2 - p->buf[delayB - 1];
865 predictionA = d0 * p->coeffsA[filter][0] +
866 d1 * p->coeffsA[filter][1] +
867 d2 * p->coeffsA[filter][2];
869 sign = APESIGN(decoded);
870 p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
871 p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
872 p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
874 predictionB = d3 * p->coeffsB[filter][0] -
875 d4 * p->coeffsB[filter][1];
876 p->lastA[filter] = decoded + (predictionA >> 11);
877 sign = APESIGN(p->lastA[filter]);
878 p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
879 p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
881 p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
882 p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
884 return p->filterA[filter];
887 static void long_filter_high_3800(int32_t *buffer, int order, int shift,
888 int32_t *coeffs, int32_t *delay, int length)
891 int32_t dotprod, sign;
893 memset(coeffs, 0, order * sizeof(*coeffs));
894 for (i = 0; i < order; i++)
895 delay[i] = buffer[i];
896 for (i = order; i < length; i++) {
898 sign = APESIGN(buffer[i]);
899 for (j = 0; j < order; j++) {
900 dotprod += delay[j] * coeffs[j];
901 coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
903 buffer[i] -= dotprod >> shift;
904 for (j = 0; j < order - 1; j++)
905 delay[j] = delay[j + 1];
906 delay[order - 1] = buffer[i];
910 static void long_filter_ehigh_3830(int32_t *buffer, int length)
913 int32_t dotprod, sign;
914 int32_t coeffs[8], delay[8];
916 memset(coeffs, 0, sizeof(coeffs));
917 memset(delay, 0, sizeof(delay));
918 for (i = 0; i < length; i++) {
920 sign = APESIGN(buffer[i]);
921 for (j = 7; j >= 0; j--) {
922 dotprod += delay[j] * coeffs[j];
923 coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
925 for (j = 7; j > 0; j--)
926 delay[j] = delay[j - 1];
927 delay[0] = buffer[i];
928 buffer[i] -= dotprod >> 9;
932 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
934 APEPredictor *p = &ctx->predictor;
935 int32_t *decoded0 = ctx->decoded[0];
936 int32_t *decoded1 = ctx->decoded[1];
937 int32_t coeffs[256], delay[256];
938 int start = 4, shift = 10;
940 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
942 long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
943 long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
944 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
945 int order = 128, shift2 = 11;
947 if (ctx->fileversion >= 3830) {
951 long_filter_ehigh_3830(decoded0 + order, count - order);
952 long_filter_ehigh_3830(decoded1 + order, count - order);
955 long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
956 long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
960 int X = *decoded0, Y = *decoded1;
961 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
962 *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
964 *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
967 *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
970 *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
979 /* Have we filled the history buffer? */
980 if (p->buf == p->historybuffer + HISTORY_SIZE) {
981 memmove(p->historybuffer, p->buf,
982 PREDICTOR_SIZE * sizeof(*p->historybuffer));
983 p->buf = p->historybuffer;
988 static void predictor_decode_mono_3800(APEContext *ctx, int count)
990 APEPredictor *p = &ctx->predictor;
991 int32_t *decoded0 = ctx->decoded[0];
992 int32_t coeffs[256], delay[256];
993 int start = 4, shift = 10;
995 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
997 long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
998 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
999 int order = 128, shift2 = 11;
1001 if (ctx->fileversion >= 3830) {
1005 long_filter_ehigh_3830(decoded0 + order, count - order);
1008 long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
1012 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1013 *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1016 *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1025 /* Have we filled the history buffer? */
1026 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1027 memmove(p->historybuffer, p->buf,
1028 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1029 p->buf = p->historybuffer;
1034 static av_always_inline int predictor_update_3930(APEPredictor *p,
1035 const int decoded, const int filter,
1038 int32_t predictionA, sign;
1039 int32_t d0, d1, d2, d3;
1041 p->buf[delayA] = p->lastA[filter];
1042 d0 = p->buf[delayA ];
1043 d1 = p->buf[delayA ] - p->buf[delayA - 1];
1044 d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1045 d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1047 predictionA = d0 * p->coeffsA[filter][0] +
1048 d1 * p->coeffsA[filter][1] +
1049 d2 * p->coeffsA[filter][2] +
1050 d3 * p->coeffsA[filter][3];
1052 p->lastA[filter] = decoded + (predictionA >> 9);
1053 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1055 sign = APESIGN(decoded);
1056 p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1057 p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1058 p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1059 p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1061 return p->filterA[filter];
1064 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1066 APEPredictor *p = &ctx->predictor;
1067 int32_t *decoded0 = ctx->decoded[0];
1068 int32_t *decoded1 = ctx->decoded[1];
1070 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1074 int Y = *decoded1, X = *decoded0;
1075 *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1077 *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1083 /* Have we filled the history buffer? */
1084 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1085 memmove(p->historybuffer, p->buf,
1086 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1087 p->buf = p->historybuffer;
1092 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1094 APEPredictor *p = &ctx->predictor;
1095 int32_t *decoded0 = ctx->decoded[0];
1097 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1100 *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1105 /* Have we filled the history buffer? */
1106 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1107 memmove(p->historybuffer, p->buf,
1108 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1109 p->buf = p->historybuffer;
1114 static av_always_inline int predictor_update_filter(APEPredictor *p,
1115 const int decoded, const int filter,
1116 const int delayA, const int delayB,
1117 const int adaptA, const int adaptB)
1119 int32_t predictionA, predictionB, sign;
1121 p->buf[delayA] = p->lastA[filter];
1122 p->buf[adaptA] = APESIGN(p->buf[delayA]);
1123 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
1124 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1126 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
1127 p->buf[delayA - 1] * p->coeffsA[filter][1] +
1128 p->buf[delayA - 2] * p->coeffsA[filter][2] +
1129 p->buf[delayA - 3] * p->coeffsA[filter][3];
1131 /* Apply a scaled first-order filter compression */
1132 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
1133 p->buf[adaptB] = APESIGN(p->buf[delayB]);
1134 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
1135 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1136 p->filterB[filter] = p->filterA[filter ^ 1];
1138 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
1139 p->buf[delayB - 1] * p->coeffsB[filter][1] +
1140 p->buf[delayB - 2] * p->coeffsB[filter][2] +
1141 p->buf[delayB - 3] * p->coeffsB[filter][3] +
1142 p->buf[delayB - 4] * p->coeffsB[filter][4];
1144 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
1145 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1147 sign = APESIGN(decoded);
1148 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
1149 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1150 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1151 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1152 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
1153 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1154 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1155 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1156 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1158 return p->filterA[filter];
1161 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1163 APEPredictor *p = &ctx->predictor;
1164 int32_t *decoded0 = ctx->decoded[0];
1165 int32_t *decoded1 = ctx->decoded[1];
1167 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1171 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1172 YADAPTCOEFFSA, YADAPTCOEFFSB);
1174 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1175 XADAPTCOEFFSA, XADAPTCOEFFSB);
1181 /* Have we filled the history buffer? */
1182 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1183 memmove(p->historybuffer, p->buf,
1184 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1185 p->buf = p->historybuffer;
1190 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1192 APEPredictor *p = &ctx->predictor;
1193 int32_t *decoded0 = ctx->decoded[0];
1194 int32_t predictionA, currentA, A, sign;
1196 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1198 currentA = p->lastA[0];
1203 p->buf[YDELAYA] = currentA;
1204 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
1206 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
1207 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1208 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1209 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1211 currentA = A + (predictionA >> 10);
1213 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
1214 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1217 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
1218 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1219 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1220 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1224 /* Have we filled the history buffer? */
1225 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1226 memmove(p->historybuffer, p->buf,
1227 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1228 p->buf = p->historybuffer;
1231 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
1232 *(decoded0++) = p->filterA[0];
1235 p->lastA[0] = currentA;
1238 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1241 f->historybuffer = buf + order;
1242 f->delay = f->historybuffer + order * 2;
1243 f->adaptcoeffs = f->historybuffer + order;
1245 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1246 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1250 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1252 do_init_filter(&f[0], buf, order);
1253 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1256 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1257 int32_t *data, int count, int order, int fracbits)
1263 /* round fixedpoint scalar product */
1264 res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
1265 f->adaptcoeffs - order,
1266 order, APESIGN(*data));
1267 res = (res + (1 << (fracbits - 1))) >> fracbits;
1271 /* Update the output history */
1272 *f->delay++ = av_clip_int16(res);
1274 if (version < 3980) {
1275 /* Version ??? to < 3.98 files (untested) */
1276 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1277 f->adaptcoeffs[-4] >>= 1;
1278 f->adaptcoeffs[-8] >>= 1;
1280 /* Version 3.98 and later files */
1282 /* Update the adaption coefficients */
1283 absres = FFABS(res);
1285 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
1286 (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
1288 *f->adaptcoeffs = 0;
1290 f->avg += (absres - f->avg) / 16;
1292 f->adaptcoeffs[-1] >>= 1;
1293 f->adaptcoeffs[-2] >>= 1;
1294 f->adaptcoeffs[-8] >>= 1;
1299 /* Have we filled the history buffer? */
1300 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1301 memmove(f->historybuffer, f->delay - (order * 2),
1302 (order * 2) * sizeof(*f->historybuffer));
1303 f->delay = f->historybuffer + order * 2;
1304 f->adaptcoeffs = f->historybuffer + order;
1309 static void apply_filter(APEContext *ctx, APEFilter *f,
1310 int32_t *data0, int32_t *data1,
1311 int count, int order, int fracbits)
1313 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1315 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1318 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1319 int32_t *decoded1, int count)
1323 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1324 if (!ape_filter_orders[ctx->fset][i])
1326 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1327 ape_filter_orders[ctx->fset][i],
1328 ape_filter_fracbits[ctx->fset][i]);
1332 static int init_frame_decoder(APEContext *ctx)
1335 if ((ret = init_entropy_decoder(ctx)) < 0)
1337 init_predictor_decoder(ctx);
1339 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1340 if (!ape_filter_orders[ctx->fset][i])
1342 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1343 ape_filter_orders[ctx->fset][i]);
1348 static void ape_unpack_mono(APEContext *ctx, int count)
1350 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1351 /* We are pure silence, so we're done. */
1352 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1356 ctx->entropy_decode_mono(ctx, count);
1358 /* Now apply the predictor decoding */
1359 ctx->predictor_decode_mono(ctx, count);
1361 /* Pseudo-stereo - just copy left channel to right channel */
1362 if (ctx->channels == 2) {
1363 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1367 static void ape_unpack_stereo(APEContext *ctx, int count)
1369 int32_t left, right;
1370 int32_t *decoded0 = ctx->decoded[0];
1371 int32_t *decoded1 = ctx->decoded[1];
1373 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1374 /* We are pure silence, so we're done. */
1375 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1379 ctx->entropy_decode_stereo(ctx, count);
1381 /* Now apply the predictor decoding */
1382 ctx->predictor_decode_stereo(ctx, count);
1384 /* Decorrelate and scale to output depth */
1386 left = *decoded1 - (*decoded0 / 2);
1387 right = left + *decoded0;
1389 *(decoded0++) = left;
1390 *(decoded1++) = right;
1394 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1395 int *got_frame_ptr, AVPacket *avpkt)
1397 AVFrame *frame = data;
1398 const uint8_t *buf = avpkt->data;
1399 APEContext *s = avctx->priv_data;
1407 /* this should never be negative, but bad things will happen if it is, so
1408 check it just to make sure. */
1409 av_assert0(s->samples >= 0);
1412 uint32_t nblocks, offset;
1419 if (avpkt->size < 8) {
1420 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1421 return AVERROR_INVALIDDATA;
1423 buf_size = avpkt->size & ~3;
1424 if (buf_size != avpkt->size) {
1425 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1426 "extra bytes at the end will be skipped.\n");
1428 if (s->fileversion < 3950) // previous versions overread two bytes
1430 av_fast_malloc(&s->data, &s->data_size, buf_size);
1432 return AVERROR(ENOMEM);
1433 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
1434 memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1436 s->data_end = s->data + buf_size;
1438 nblocks = bytestream_get_be32(&s->ptr);
1439 offset = bytestream_get_be32(&s->ptr);
1440 if (s->fileversion >= 3900) {
1442 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1444 return AVERROR_INVALIDDATA;
1446 if (s->data_end - s->ptr < offset) {
1447 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1448 return AVERROR_INVALIDDATA;
1452 init_get_bits(&s->gb, s->ptr, (s->data_end - s->ptr) * 8);
1453 if (s->fileversion > 3800)
1454 skip_bits_long(&s->gb, offset * 8);
1456 skip_bits_long(&s->gb, offset);
1459 if (!nblocks || nblocks > INT_MAX) {
1460 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
1461 return AVERROR_INVALIDDATA;
1463 s->samples = nblocks;
1465 /* Initialize the frame decoder */
1466 if (init_frame_decoder(s) < 0) {
1467 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1468 return AVERROR_INVALIDDATA;
1471 bytes_used = avpkt->size;
1479 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1480 // for old files coefficients were not interleaved,
1481 // so we need to decode all of them at once
1482 if (s->fileversion < 3930)
1483 blockstodecode = s->samples;
1485 /* reallocate decoded sample buffer if needed */
1486 av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
1487 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
1488 if (!s->decoded_buffer)
1489 return AVERROR(ENOMEM);
1490 memset(s->decoded_buffer, 0, s->decoded_size);
1491 s->decoded[0] = s->decoded_buffer;
1492 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1494 /* get output buffer */
1495 frame->nb_samples = blockstodecode;
1496 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1497 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1503 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1504 ape_unpack_mono(s, blockstodecode);
1506 ape_unpack_stereo(s, blockstodecode);
1511 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1512 return AVERROR_INVALIDDATA;
1517 for (ch = 0; ch < s->channels; ch++) {
1518 sample8 = (uint8_t *)frame->data[ch];
1519 for (i = 0; i < blockstodecode; i++)
1520 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1524 for (ch = 0; ch < s->channels; ch++) {
1525 sample16 = (int16_t *)frame->data[ch];
1526 for (i = 0; i < blockstodecode; i++)
1527 *sample16++ = s->decoded[ch][i];
1531 for (ch = 0; ch < s->channels; ch++) {
1532 sample24 = (int32_t *)frame->data[ch];
1533 for (i = 0; i < blockstodecode; i++)
1534 *sample24++ = s->decoded[ch][i] << 8;
1539 s->samples -= blockstodecode;
1546 static void ape_flush(AVCodecContext *avctx)
1548 APEContext *s = avctx->priv_data;
1552 #define OFFSET(x) offsetof(APEContext, x)
1553 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1554 static const AVOption options[] = {
1555 { "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" },
1556 { "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" },
1560 static const AVClass ape_decoder_class = {
1561 .class_name = "APE decoder",
1562 .item_name = av_default_item_name,
1564 .version = LIBAVUTIL_VERSION_INT,
1567 AVCodec ff_ape_decoder = {
1569 .type = AVMEDIA_TYPE_AUDIO,
1570 .id = AV_CODEC_ID_APE,
1571 .priv_data_size = sizeof(APEContext),
1572 .init = ape_decode_init,
1573 .close = ape_decode_close,
1574 .decode = ape_decode_frame,
1575 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
1577 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1578 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1581 AV_SAMPLE_FMT_NONE },
1582 .priv_class = &ape_decoder_class,