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