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