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