e9069031ada691e69e5c074ee6d0fffdc3ac000d
[libav.git] / libavcodec / apedec.c
1 /*
2 * Monkey's Audio lossless audio decoder
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
5 *
6 * This file is part of Libav.
7 *
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.
12 *
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.
17 *
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
21 */
22
23 #define ALT_BITSTREAM_READER_LE
24 #include "avcodec.h"
25 #include "dsputil.h"
26 #include "get_bits.h"
27 #include "bytestream.h"
28 #include "libavutil/audioconvert.h"
29 #include "libavutil/avassert.h"
30
31 /**
32 * @file
33 * Monkey's Audio lossless audio decoder
34 */
35
36 #define BLOCKS_PER_LOOP 4608
37 #define MAX_CHANNELS 2
38 #define MAX_BYTESPERSAMPLE 3
39
40 #define APE_FRAMECODE_MONO_SILENCE 1
41 #define APE_FRAMECODE_STEREO_SILENCE 3
42 #define APE_FRAMECODE_PSEUDO_STEREO 4
43
44 #define HISTORY_SIZE 512
45 #define PREDICTOR_ORDER 8
46 /** Total size of all predictor histories */
47 #define PREDICTOR_SIZE 50
48
49 #define YDELAYA (18 + PREDICTOR_ORDER*4)
50 #define YDELAYB (18 + PREDICTOR_ORDER*3)
51 #define XDELAYA (18 + PREDICTOR_ORDER*2)
52 #define XDELAYB (18 + PREDICTOR_ORDER)
53
54 #define YADAPTCOEFFSA 18
55 #define XADAPTCOEFFSA 14
56 #define YADAPTCOEFFSB 10
57 #define XADAPTCOEFFSB 5
58
59 /**
60 * Possible compression levels
61 * @{
62 */
63 enum APECompressionLevel {
64 COMPRESSION_LEVEL_FAST = 1000,
65 COMPRESSION_LEVEL_NORMAL = 2000,
66 COMPRESSION_LEVEL_HIGH = 3000,
67 COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
68 COMPRESSION_LEVEL_INSANE = 5000
69 };
70 /** @} */
71
72 #define APE_FILTER_LEVELS 3
73
74 /** Filter orders depending on compression level */
75 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
76 { 0, 0, 0 },
77 { 16, 0, 0 },
78 { 64, 0, 0 },
79 { 32, 256, 0 },
80 { 16, 256, 1280 }
81 };
82
83 /** Filter fraction bits depending on compression level */
84 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
85 { 0, 0, 0 },
86 { 11, 0, 0 },
87 { 11, 0, 0 },
88 { 10, 13, 0 },
89 { 11, 13, 15 }
90 };
91
92
93 /** Filters applied to the decoded data */
94 typedef struct APEFilter {
95 int16_t *coeffs; ///< actual coefficients used in filtering
96 int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
97 int16_t *historybuffer; ///< filter memory
98 int16_t *delay; ///< filtered values
99
100 int avg;
101 } APEFilter;
102
103 typedef struct APERice {
104 uint32_t k;
105 uint32_t ksum;
106 } APERice;
107
108 typedef struct APERangecoder {
109 uint32_t low; ///< low end of interval
110 uint32_t range; ///< length of interval
111 uint32_t help; ///< bytes_to_follow resp. intermediate value
112 unsigned int buffer; ///< buffer for input/output
113 } APERangecoder;
114
115 /** Filter histories */
116 typedef struct APEPredictor {
117 int32_t *buf;
118
119 int32_t lastA[2];
120
121 int32_t filterA[2];
122 int32_t filterB[2];
123
124 int32_t coeffsA[2][4]; ///< adaption coefficients
125 int32_t coeffsB[2][5]; ///< adaption coefficients
126 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
127 } APEPredictor;
128
129 /** Decoder context */
130 typedef struct APEContext {
131 AVCodecContext *avctx;
132 DSPContext dsp;
133 int channels;
134 int samples; ///< samples left to decode in current frame
135
136 int fileversion; ///< codec version, very important in decoding process
137 int compression_level; ///< compression levels
138 int fset; ///< which filter set to use (calculated from compression level)
139 int flags; ///< global decoder flags
140
141 uint32_t CRC; ///< frame CRC
142 int frameflags; ///< frame flags
143 int currentframeblocks; ///< samples (per channel) in current frame
144 int blocksdecoded; ///< count of decoded samples in current frame
145 APEPredictor predictor; ///< predictor used for final reconstruction
146
147 int32_t decoded0[BLOCKS_PER_LOOP]; ///< decoded data for the first channel
148 int32_t decoded1[BLOCKS_PER_LOOP]; ///< decoded data for the second channel
149
150 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
151
152 APERangecoder rc; ///< rangecoder used to decode actual values
153 APERice riceX; ///< rice code parameters for the second channel
154 APERice riceY; ///< rice code parameters for the first channel
155 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
156
157 uint8_t *data; ///< current frame data
158 uint8_t *data_end; ///< frame data end
159 const uint8_t *ptr; ///< current position in frame data
160 const uint8_t *last_ptr; ///< position where last 4608-sample block ended
161
162 int error;
163 } APEContext;
164
165 // TODO: dsputilize
166
167 static av_cold int ape_decode_close(AVCodecContext *avctx)
168 {
169 APEContext *s = avctx->priv_data;
170 int i;
171
172 for (i = 0; i < APE_FILTER_LEVELS; i++)
173 av_freep(&s->filterbuf[i]);
174
175 av_freep(&s->data);
176 return 0;
177 }
178
179 static av_cold int ape_decode_init(AVCodecContext *avctx)
180 {
181 APEContext *s = avctx->priv_data;
182 int i;
183
184 if (avctx->extradata_size != 6) {
185 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
186 return AVERROR(EINVAL);
187 }
188 if (avctx->bits_per_coded_sample != 16) {
189 av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
190 return AVERROR(EINVAL);
191 }
192 if (avctx->channels > 2) {
193 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
194 return AVERROR(EINVAL);
195 }
196 s->avctx = avctx;
197 s->channels = avctx->channels;
198 s->fileversion = AV_RL16(avctx->extradata);
199 s->compression_level = AV_RL16(avctx->extradata + 2);
200 s->flags = AV_RL16(avctx->extradata + 4);
201
202 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
203 s->compression_level, s->flags);
204 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
205 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
206 s->compression_level);
207 return AVERROR_INVALIDDATA;
208 }
209 s->fset = s->compression_level / 1000 - 1;
210 for (i = 0; i < APE_FILTER_LEVELS; i++) {
211 if (!ape_filter_orders[s->fset][i])
212 break;
213 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
214 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
215 filter_alloc_fail);
216 }
217
218 dsputil_init(&s->dsp, avctx);
219 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
220 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
221 return 0;
222 filter_alloc_fail:
223 ape_decode_close(avctx);
224 return AVERROR(ENOMEM);
225 }
226
227 /**
228 * @name APE range decoding functions
229 * @{
230 */
231
232 #define CODE_BITS 32
233 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
234 #define SHIFT_BITS (CODE_BITS - 9)
235 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
236 #define BOTTOM_VALUE (TOP_VALUE >> 8)
237
238 /** Start the decoder */
239 static inline void range_start_decoding(APEContext *ctx)
240 {
241 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
242 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
243 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
244 }
245
246 /** Perform normalization */
247 static inline void range_dec_normalize(APEContext *ctx)
248 {
249 while (ctx->rc.range <= BOTTOM_VALUE) {
250 ctx->rc.buffer <<= 8;
251 if(ctx->ptr < ctx->data_end) {
252 ctx->rc.buffer += *ctx->ptr;
253 ctx->ptr++;
254 } else {
255 ctx->error = 1;
256 }
257 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
258 ctx->rc.range <<= 8;
259 }
260 }
261
262 /**
263 * Calculate culmulative frequency for next symbol. Does NO update!
264 * @param ctx decoder context
265 * @param tot_f is the total frequency or (code_value)1<<shift
266 * @return the culmulative frequency
267 */
268 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
269 {
270 range_dec_normalize(ctx);
271 ctx->rc.help = ctx->rc.range / tot_f;
272 return ctx->rc.low / ctx->rc.help;
273 }
274
275 /**
276 * Decode value with given size in bits
277 * @param ctx decoder context
278 * @param shift number of bits to decode
279 */
280 static inline int range_decode_culshift(APEContext *ctx, int shift)
281 {
282 range_dec_normalize(ctx);
283 ctx->rc.help = ctx->rc.range >> shift;
284 return ctx->rc.low / ctx->rc.help;
285 }
286
287
288 /**
289 * Update decoding state
290 * @param ctx decoder context
291 * @param sy_f the interval length (frequency of the symbol)
292 * @param lt_f the lower end (frequency sum of < symbols)
293 */
294 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
295 {
296 ctx->rc.low -= ctx->rc.help * lt_f;
297 ctx->rc.range = ctx->rc.help * sy_f;
298 }
299
300 /** Decode n bits (n <= 16) without modelling */
301 static inline int range_decode_bits(APEContext *ctx, int n)
302 {
303 int sym = range_decode_culshift(ctx, n);
304 range_decode_update(ctx, 1, sym);
305 return sym;
306 }
307
308
309 #define MODEL_ELEMENTS 64
310
311 /**
312 * Fixed probabilities for symbols in Monkey Audio version 3.97
313 */
314 static const uint16_t counts_3970[22] = {
315 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
316 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
317 65450, 65469, 65480, 65487, 65491, 65493,
318 };
319
320 /**
321 * Probability ranges for symbols in Monkey Audio version 3.97
322 */
323 static const uint16_t counts_diff_3970[21] = {
324 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
325 1104, 677, 415, 248, 150, 89, 54, 31,
326 19, 11, 7, 4, 2,
327 };
328
329 /**
330 * Fixed probabilities for symbols in Monkey Audio version 3.98
331 */
332 static const uint16_t counts_3980[22] = {
333 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
334 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
335 65485, 65488, 65490, 65491, 65492, 65493,
336 };
337
338 /**
339 * Probability ranges for symbols in Monkey Audio version 3.98
340 */
341 static const uint16_t counts_diff_3980[21] = {
342 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
343 261, 119, 65, 31, 19, 10, 6, 3,
344 3, 2, 1, 1, 1,
345 };
346
347 /**
348 * Decode symbol
349 * @param ctx decoder context
350 * @param counts probability range start position
351 * @param counts_diff probability range widths
352 */
353 static inline int range_get_symbol(APEContext *ctx,
354 const uint16_t counts[],
355 const uint16_t counts_diff[])
356 {
357 int symbol, cf;
358
359 cf = range_decode_culshift(ctx, 16);
360
361 if(cf > 65492){
362 symbol= cf - 65535 + 63;
363 range_decode_update(ctx, 1, cf);
364 if(cf > 65535)
365 ctx->error=1;
366 return symbol;
367 }
368 /* figure out the symbol inefficiently; a binary search would be much better */
369 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
370
371 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
372
373 return symbol;
374 }
375 /** @} */ // group rangecoder
376
377 static inline void update_rice(APERice *rice, int x)
378 {
379 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
380 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
381
382 if (rice->ksum < lim)
383 rice->k--;
384 else if (rice->ksum >= (1 << (rice->k + 5)))
385 rice->k++;
386 }
387
388 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
389 {
390 int x, overflow;
391
392 if (ctx->fileversion < 3990) {
393 int tmpk;
394
395 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
396
397 if (overflow == (MODEL_ELEMENTS - 1)) {
398 tmpk = range_decode_bits(ctx, 5);
399 overflow = 0;
400 } else
401 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
402
403 if (tmpk <= 16)
404 x = range_decode_bits(ctx, tmpk);
405 else {
406 x = range_decode_bits(ctx, 16);
407 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
408 }
409 x += overflow << tmpk;
410 } else {
411 int base, pivot;
412
413 pivot = rice->ksum >> 5;
414 if (pivot == 0)
415 pivot = 1;
416
417 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
418
419 if (overflow == (MODEL_ELEMENTS - 1)) {
420 overflow = range_decode_bits(ctx, 16) << 16;
421 overflow |= range_decode_bits(ctx, 16);
422 }
423
424 if (pivot < 0x10000) {
425 base = range_decode_culfreq(ctx, pivot);
426 range_decode_update(ctx, 1, base);
427 } else {
428 int base_hi = pivot, base_lo;
429 int bbits = 0;
430
431 while (base_hi & ~0xFFFF) {
432 base_hi >>= 1;
433 bbits++;
434 }
435 base_hi = range_decode_culfreq(ctx, base_hi + 1);
436 range_decode_update(ctx, 1, base_hi);
437 base_lo = range_decode_culfreq(ctx, 1 << bbits);
438 range_decode_update(ctx, 1, base_lo);
439
440 base = (base_hi << bbits) + base_lo;
441 }
442
443 x = base + overflow * pivot;
444 }
445
446 update_rice(rice, x);
447
448 /* Convert to signed */
449 if (x & 1)
450 return (x >> 1) + 1;
451 else
452 return -(x >> 1);
453 }
454
455 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
456 {
457 int32_t *decoded0 = ctx->decoded0;
458 int32_t *decoded1 = ctx->decoded1;
459
460 ctx->blocksdecoded = blockstodecode;
461
462 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
463 /* We are pure silence, just memset the output buffer. */
464 memset(decoded0, 0, blockstodecode * sizeof(int32_t));
465 memset(decoded1, 0, blockstodecode * sizeof(int32_t));
466 } else {
467 while (blockstodecode--) {
468 *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
469 if (stereo)
470 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
471 }
472 }
473
474 if (ctx->blocksdecoded == ctx->currentframeblocks)
475 range_dec_normalize(ctx); /* normalize to use up all bytes */
476 }
477
478 static int init_entropy_decoder(APEContext *ctx)
479 {
480 /* Read the CRC */
481 if (ctx->data_end - ctx->ptr < 6)
482 return AVERROR_INVALIDDATA;
483 ctx->CRC = bytestream_get_be32(&ctx->ptr);
484
485 /* Read the frame flags if they exist */
486 ctx->frameflags = 0;
487 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
488 ctx->CRC &= ~0x80000000;
489
490 if (ctx->data_end - ctx->ptr < 6)
491 return AVERROR_INVALIDDATA;
492 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
493 }
494
495 /* Keep a count of the blocks decoded in this frame */
496 ctx->blocksdecoded = 0;
497
498 /* Initialize the rice structs */
499 ctx->riceX.k = 10;
500 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
501 ctx->riceY.k = 10;
502 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
503
504 /* The first 8 bits of input are ignored. */
505 ctx->ptr++;
506
507 range_start_decoding(ctx);
508
509 return 0;
510 }
511
512 static const int32_t initial_coeffs[4] = {
513 360, 317, -109, 98
514 };
515
516 static void init_predictor_decoder(APEContext *ctx)
517 {
518 APEPredictor *p = &ctx->predictor;
519
520 /* Zero the history buffers */
521 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
522 p->buf = p->historybuffer;
523
524 /* Initialize and zero the coefficients */
525 memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
526 memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
527 memset(p->coeffsB, 0, sizeof(p->coeffsB));
528
529 p->filterA[0] = p->filterA[1] = 0;
530 p->filterB[0] = p->filterB[1] = 0;
531 p->lastA[0] = p->lastA[1] = 0;
532 }
533
534 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
535 static inline int APESIGN(int32_t x) {
536 return (x < 0) - (x > 0);
537 }
538
539 static av_always_inline int predictor_update_filter(APEPredictor *p,
540 const int decoded, const int filter,
541 const int delayA, const int delayB,
542 const int adaptA, const int adaptB)
543 {
544 int32_t predictionA, predictionB, sign;
545
546 p->buf[delayA] = p->lastA[filter];
547 p->buf[adaptA] = APESIGN(p->buf[delayA]);
548 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
549 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
550
551 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
552 p->buf[delayA - 1] * p->coeffsA[filter][1] +
553 p->buf[delayA - 2] * p->coeffsA[filter][2] +
554 p->buf[delayA - 3] * p->coeffsA[filter][3];
555
556 /* Apply a scaled first-order filter compression */
557 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
558 p->buf[adaptB] = APESIGN(p->buf[delayB]);
559 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
560 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
561 p->filterB[filter] = p->filterA[filter ^ 1];
562
563 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
564 p->buf[delayB - 1] * p->coeffsB[filter][1] +
565 p->buf[delayB - 2] * p->coeffsB[filter][2] +
566 p->buf[delayB - 3] * p->coeffsB[filter][3] +
567 p->buf[delayB - 4] * p->coeffsB[filter][4];
568
569 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
570 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
571
572 sign = APESIGN(decoded);
573 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
574 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
575 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
576 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
577 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
578 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
579 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
580 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
581 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
582
583 return p->filterA[filter];
584 }
585
586 static void predictor_decode_stereo(APEContext *ctx, int count)
587 {
588 APEPredictor *p = &ctx->predictor;
589 int32_t *decoded0 = ctx->decoded0;
590 int32_t *decoded1 = ctx->decoded1;
591
592 while (count--) {
593 /* Predictor Y */
594 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
595 YADAPTCOEFFSA, YADAPTCOEFFSB);
596 decoded0++;
597 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
598 XADAPTCOEFFSA, XADAPTCOEFFSB);
599 decoded1++;
600
601 /* Combined */
602 p->buf++;
603
604 /* Have we filled the history buffer? */
605 if (p->buf == p->historybuffer + HISTORY_SIZE) {
606 memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
607 p->buf = p->historybuffer;
608 }
609 }
610 }
611
612 static void predictor_decode_mono(APEContext *ctx, int count)
613 {
614 APEPredictor *p = &ctx->predictor;
615 int32_t *decoded0 = ctx->decoded0;
616 int32_t predictionA, currentA, A, sign;
617
618 currentA = p->lastA[0];
619
620 while (count--) {
621 A = *decoded0;
622
623 p->buf[YDELAYA] = currentA;
624 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
625
626 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
627 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
628 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
629 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
630
631 currentA = A + (predictionA >> 10);
632
633 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
634 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
635
636 sign = APESIGN(A);
637 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
638 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
639 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
640 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
641
642 p->buf++;
643
644 /* Have we filled the history buffer? */
645 if (p->buf == p->historybuffer + HISTORY_SIZE) {
646 memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
647 p->buf = p->historybuffer;
648 }
649
650 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
651 *(decoded0++) = p->filterA[0];
652 }
653
654 p->lastA[0] = currentA;
655 }
656
657 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
658 {
659 f->coeffs = buf;
660 f->historybuffer = buf + order;
661 f->delay = f->historybuffer + order * 2;
662 f->adaptcoeffs = f->historybuffer + order;
663
664 memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
665 memset(f->coeffs, 0, order * sizeof(int16_t));
666 f->avg = 0;
667 }
668
669 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
670 {
671 do_init_filter(&f[0], buf, order);
672 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
673 }
674
675 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
676 int32_t *data, int count, int order, int fracbits)
677 {
678 int res;
679 int absres;
680
681 while (count--) {
682 /* round fixedpoint scalar product */
683 res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
684 f->adaptcoeffs - order,
685 order, APESIGN(*data));
686 res = (res + (1 << (fracbits - 1))) >> fracbits;
687 res += *data;
688 *data++ = res;
689
690 /* Update the output history */
691 *f->delay++ = av_clip_int16(res);
692
693 if (version < 3980) {
694 /* Version ??? to < 3.98 files (untested) */
695 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
696 f->adaptcoeffs[-4] >>= 1;
697 f->adaptcoeffs[-8] >>= 1;
698 } else {
699 /* Version 3.98 and later files */
700
701 /* Update the adaption coefficients */
702 absres = FFABS(res);
703 if (absres)
704 *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >>
705 (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
706 else
707 *f->adaptcoeffs = 0;
708
709 f->avg += (absres - f->avg) / 16;
710
711 f->adaptcoeffs[-1] >>= 1;
712 f->adaptcoeffs[-2] >>= 1;
713 f->adaptcoeffs[-8] >>= 1;
714 }
715
716 f->adaptcoeffs++;
717
718 /* Have we filled the history buffer? */
719 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
720 memmove(f->historybuffer, f->delay - (order * 2),
721 (order * 2) * sizeof(int16_t));
722 f->delay = f->historybuffer + order * 2;
723 f->adaptcoeffs = f->historybuffer + order;
724 }
725 }
726 }
727
728 static void apply_filter(APEContext *ctx, APEFilter *f,
729 int32_t *data0, int32_t *data1,
730 int count, int order, int fracbits)
731 {
732 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
733 if (data1)
734 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
735 }
736
737 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
738 int32_t *decoded1, int count)
739 {
740 int i;
741
742 for (i = 0; i < APE_FILTER_LEVELS; i++) {
743 if (!ape_filter_orders[ctx->fset][i])
744 break;
745 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
746 ape_filter_orders[ctx->fset][i],
747 ape_filter_fracbits[ctx->fset][i]);
748 }
749 }
750
751 static int init_frame_decoder(APEContext *ctx)
752 {
753 int i, ret;
754 if ((ret = init_entropy_decoder(ctx)) < 0)
755 return ret;
756 init_predictor_decoder(ctx);
757
758 for (i = 0; i < APE_FILTER_LEVELS; i++) {
759 if (!ape_filter_orders[ctx->fset][i])
760 break;
761 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
762 ape_filter_orders[ctx->fset][i]);
763 }
764 return 0;
765 }
766
767 static void ape_unpack_mono(APEContext *ctx, int count)
768 {
769 int32_t *decoded0 = ctx->decoded0;
770 int32_t *decoded1 = ctx->decoded1;
771
772 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
773 entropy_decode(ctx, count, 0);
774 /* We are pure silence, so we're done. */
775 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
776 return;
777 }
778
779 entropy_decode(ctx, count, 0);
780 ape_apply_filters(ctx, decoded0, NULL, count);
781
782 /* Now apply the predictor decoding */
783 predictor_decode_mono(ctx, count);
784
785 /* Pseudo-stereo - just copy left channel to right channel */
786 if (ctx->channels == 2) {
787 memcpy(decoded1, decoded0, count * sizeof(*decoded1));
788 }
789 }
790
791 static void ape_unpack_stereo(APEContext *ctx, int count)
792 {
793 int32_t left, right;
794 int32_t *decoded0 = ctx->decoded0;
795 int32_t *decoded1 = ctx->decoded1;
796
797 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
798 /* We are pure silence, so we're done. */
799 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
800 return;
801 }
802
803 entropy_decode(ctx, count, 1);
804 ape_apply_filters(ctx, decoded0, decoded1, count);
805
806 /* Now apply the predictor decoding */
807 predictor_decode_stereo(ctx, count);
808
809 /* Decorrelate and scale to output depth */
810 while (count--) {
811 left = *decoded1 - (*decoded0 / 2);
812 right = left + *decoded0;
813
814 *(decoded0++) = left;
815 *(decoded1++) = right;
816 }
817 }
818
819 static int ape_decode_frame(AVCodecContext *avctx,
820 void *data, int *data_size,
821 AVPacket *avpkt)
822 {
823 const uint8_t *buf = avpkt->data;
824 int buf_size = avpkt->size;
825 APEContext *s = avctx->priv_data;
826 int16_t *samples = data;
827 uint32_t nblocks;
828 int i;
829 int blockstodecode;
830 int bytes_used;
831
832 /* should not happen but who knows */
833 if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
834 av_log (avctx, AV_LOG_ERROR, "Output buffer is too small.\n");
835 return AVERROR(EINVAL);
836 }
837
838 /* this should never be negative, but bad things will happen if it is, so
839 check it just to make sure. */
840 av_assert0(s->samples >= 0);
841
842 if(!s->samples){
843 uint32_t offset;
844 void *tmp_data;
845
846 if (buf_size < 8) {
847 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
848 return AVERROR_INVALIDDATA;
849 }
850
851 tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
852 if (!tmp_data)
853 return AVERROR(ENOMEM);
854 s->data = tmp_data;
855 s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
856 s->ptr = s->last_ptr = s->data;
857 s->data_end = s->data + buf_size;
858
859 nblocks = bytestream_get_be32(&s->ptr);
860 offset = bytestream_get_be32(&s->ptr);
861 if (offset > 3) {
862 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
863 s->data = NULL;
864 return AVERROR_INVALIDDATA;
865 }
866 if (s->data_end - s->ptr < offset) {
867 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
868 return AVERROR_INVALIDDATA;
869 }
870 s->ptr += offset;
871
872 if (!nblocks || nblocks > INT_MAX) {
873 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
874 return AVERROR_INVALIDDATA;
875 }
876 s->currentframeblocks = s->samples = nblocks;
877
878 memset(s->decoded0, 0, sizeof(s->decoded0));
879 memset(s->decoded1, 0, sizeof(s->decoded1));
880
881 /* Initialize the frame decoder */
882 if (init_frame_decoder(s) < 0) {
883 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
884 return AVERROR_INVALIDDATA;
885 }
886 }
887
888 if (!s->data) {
889 *data_size = 0;
890 return buf_size;
891 }
892
893 nblocks = s->samples;
894 blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
895
896 s->error=0;
897
898 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
899 ape_unpack_mono(s, blockstodecode);
900 else
901 ape_unpack_stereo(s, blockstodecode);
902 emms_c();
903
904 if (s->error) {
905 s->samples=0;
906 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
907 return AVERROR_INVALIDDATA;
908 }
909
910 for (i = 0; i < blockstodecode; i++) {
911 *samples++ = s->decoded0[i];
912 if(s->channels == 2)
913 *samples++ = s->decoded1[i];
914 }
915
916 s->samples -= blockstodecode;
917
918 *data_size = blockstodecode * 2 * s->channels;
919 bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
920 s->last_ptr = s->ptr;
921 return bytes_used;
922 }
923
924 static void ape_flush(AVCodecContext *avctx)
925 {
926 APEContext *s = avctx->priv_data;
927 s->samples= 0;
928 }
929
930 AVCodec ff_ape_decoder = {
931 .name = "ape",
932 .type = AVMEDIA_TYPE_AUDIO,
933 .id = CODEC_ID_APE,
934 .priv_data_size = sizeof(APEContext),
935 .init = ape_decode_init,
936 .close = ape_decode_close,
937 .decode = ape_decode_frame,
938 .capabilities = CODEC_CAP_SUBFRAMES,
939 .flush = ape_flush,
940 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
941 };