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 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 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 
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 
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 
69 };
72 #define APE_FILTER_LEVELS 3
73 
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 
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 
94 typedef struct APEFilter {
95  int16_t *coeffs;
96  int16_t *adaptcoeffs;
97  int16_t *historybuffer;
98  int16_t *delay;
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;
110  uint32_t range;
111  uint32_t help;
112  unsigned int buffer;
113 } APERangecoder;
114 
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];
125  int32_t coeffsB[2][5];
127 } APEPredictor;
128 
130 typedef struct APEContext {
134  int channels;
135  int samples;
136 
139  int fset;
140  int flags;
141 
142  uint32_t CRC;
145 
148 
150 
155 
156  uint8_t *data;
157  uint8_t *data_end;
158  const uint8_t *ptr;
159 
160  int error;
161 } APEContext;
162 
163 // TODO: dsputilize
164 
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 
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);
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;
219 
221  avctx->coded_frame = &s->frame;
222 
223  return 0;
224 filter_alloc_fail:
225  ape_decode_close(avctx);
226  return AVERROR(ENOMEM);
227 }
228 
234 #define CODE_BITS 32
235 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
236 #define SHIFT_BITS (CODE_BITS - 9)
237 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
238 #define BOTTOM_VALUE (TOP_VALUE >> 8)
239 
241 static inline void range_start_decoding(APEContext *ctx)
242 {
243  ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
244  ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
245  ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
246 }
247 
249 static inline void range_dec_normalize(APEContext *ctx)
250 {
251  while (ctx->rc.range <= BOTTOM_VALUE) {
252  ctx->rc.buffer <<= 8;
253  if(ctx->ptr < ctx->data_end) {
254  ctx->rc.buffer += *ctx->ptr;
255  ctx->ptr++;
256  } else {
257  ctx->error = 1;
258  }
259  ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
260  ctx->rc.range <<= 8;
261  }
262 }
263 
270 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
271 {
272  range_dec_normalize(ctx);
273  ctx->rc.help = ctx->rc.range / tot_f;
274  return ctx->rc.low / ctx->rc.help;
275 }
276 
282 static inline int range_decode_culshift(APEContext *ctx, int shift)
283 {
284  range_dec_normalize(ctx);
285  ctx->rc.help = ctx->rc.range >> shift;
286  return ctx->rc.low / ctx->rc.help;
287 }
288 
289 
296 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
297 {
298  ctx->rc.low -= ctx->rc.help * lt_f;
299  ctx->rc.range = ctx->rc.help * sy_f;
300 }
301 
303 static inline int range_decode_bits(APEContext *ctx, int n)
304 {
305  int sym = range_decode_culshift(ctx, n);
306  range_decode_update(ctx, 1, sym);
307  return sym;
308 }
309 
310 
311 #define MODEL_ELEMENTS 64
312 
316 static const uint16_t counts_3970[22] = {
317  0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
318  62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
319  65450, 65469, 65480, 65487, 65491, 65493,
320 };
321 
325 static const uint16_t counts_diff_3970[21] = {
326  14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
327  1104, 677, 415, 248, 150, 89, 54, 31,
328  19, 11, 7, 4, 2,
329 };
330 
334 static const uint16_t counts_3980[22] = {
335  0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
336  64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
337  65485, 65488, 65490, 65491, 65492, 65493,
338 };
339 
343 static const uint16_t counts_diff_3980[21] = {
344  19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
345  261, 119, 65, 31, 19, 10, 6, 3,
346  3, 2, 1, 1, 1,
347 };
348 
355 static inline int range_get_symbol(APEContext *ctx,
356  const uint16_t counts[],
357  const uint16_t counts_diff[])
358 {
359  int symbol, cf;
360 
361  cf = range_decode_culshift(ctx, 16);
362 
363  if(cf > 65492){
364  symbol= cf - 65535 + 63;
365  range_decode_update(ctx, 1, cf);
366  if(cf > 65535)
367  ctx->error=1;
368  return symbol;
369  }
370  /* figure out the symbol inefficiently; a binary search would be much better */
371  for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
372 
373  range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
374 
375  return symbol;
376 } // group rangecoder
378 
379 static inline void update_rice(APERice *rice, int x)
380 {
381  int lim = rice->k ? (1 << (rice->k + 4)) : 0;
382  rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
383 
384  if (rice->ksum < lim)
385  rice->k--;
386  else if (rice->ksum >= (1 << (rice->k + 5)))
387  rice->k++;
388 }
389 
390 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
391 {
392  int x, overflow;
393 
394  if (ctx->fileversion < 3990) {
395  int tmpk;
396 
398 
399  if (overflow == (MODEL_ELEMENTS - 1)) {
400  tmpk = range_decode_bits(ctx, 5);
401  overflow = 0;
402  } else
403  tmpk = (rice->k < 1) ? 0 : rice->k - 1;
404 
405  if (tmpk <= 16)
406  x = range_decode_bits(ctx, tmpk);
407  else if (tmpk <= 32) {
408  x = range_decode_bits(ctx, 16);
409  x |= (range_decode_bits(ctx, tmpk - 16) << 16);
410  } else {
411  av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
412  return AVERROR_INVALIDDATA;
413  }
414  x += overflow << tmpk;
415  } else {
416  int base, pivot;
417 
418  pivot = rice->ksum >> 5;
419  if (pivot == 0)
420  pivot = 1;
421 
423 
424  if (overflow == (MODEL_ELEMENTS - 1)) {
425  overflow = range_decode_bits(ctx, 16) << 16;
426  overflow |= range_decode_bits(ctx, 16);
427  }
428 
429  if (pivot < 0x10000) {
430  base = range_decode_culfreq(ctx, pivot);
431  range_decode_update(ctx, 1, base);
432  } else {
433  int base_hi = pivot, base_lo;
434  int bbits = 0;
435 
436  while (base_hi & ~0xFFFF) {
437  base_hi >>= 1;
438  bbits++;
439  }
440  base_hi = range_decode_culfreq(ctx, base_hi + 1);
441  range_decode_update(ctx, 1, base_hi);
442  base_lo = range_decode_culfreq(ctx, 1 << bbits);
443  range_decode_update(ctx, 1, base_lo);
444 
445  base = (base_hi << bbits) + base_lo;
446  }
447 
448  x = base + overflow * pivot;
449  }
450 
451  update_rice(rice, x);
452 
453  /* Convert to signed */
454  if (x & 1)
455  return (x >> 1) + 1;
456  else
457  return -(x >> 1);
458 }
459 
460 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
461 {
462  int32_t *decoded0 = ctx->decoded0;
463  int32_t *decoded1 = ctx->decoded1;
464 
466  /* We are pure silence, just memset the output buffer. */
467  memset(decoded0, 0, blockstodecode * sizeof(int32_t));
468  memset(decoded1, 0, blockstodecode * sizeof(int32_t));
469  } else {
470  while (blockstodecode--) {
471  *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
472  if (stereo)
473  *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
474  }
475  }
476 }
477 
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  /* Initialize the rice structs */
496  ctx->riceX.k = 10;
497  ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
498  ctx->riceY.k = 10;
499  ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
500 
501  /* The first 8 bits of input are ignored. */
502  ctx->ptr++;
503 
505 
506  return 0;
507 }
508 
509 static const int32_t initial_coeffs[4] = {
510  360, 317, -109, 98
511 };
512 
514 {
515  APEPredictor *p = &ctx->predictor;
516 
517  /* Zero the history buffers */
518  memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
519  p->buf = p->historybuffer;
520 
521  /* Initialize and zero the coefficients */
522  memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
523  memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
524  memset(p->coeffsB, 0, sizeof(p->coeffsB));
525 
526  p->filterA[0] = p->filterA[1] = 0;
527  p->filterB[0] = p->filterB[1] = 0;
528  p->lastA[0] = p->lastA[1] = 0;
529 }
530 
532 static inline int APESIGN(int32_t x) {
533  return (x < 0) - (x > 0);
534 }
535 
537  const int decoded, const int filter,
538  const int delayA, const int delayB,
539  const int adaptA, const int adaptB)
540 {
541  int32_t predictionA, predictionB, sign;
542 
543  p->buf[delayA] = p->lastA[filter];
544  p->buf[adaptA] = APESIGN(p->buf[delayA]);
545  p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
546  p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
547 
548  predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
549  p->buf[delayA - 1] * p->coeffsA[filter][1] +
550  p->buf[delayA - 2] * p->coeffsA[filter][2] +
551  p->buf[delayA - 3] * p->coeffsA[filter][3];
552 
553  /* Apply a scaled first-order filter compression */
554  p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
555  p->buf[adaptB] = APESIGN(p->buf[delayB]);
556  p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
557  p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
558  p->filterB[filter] = p->filterA[filter ^ 1];
559 
560  predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
561  p->buf[delayB - 1] * p->coeffsB[filter][1] +
562  p->buf[delayB - 2] * p->coeffsB[filter][2] +
563  p->buf[delayB - 3] * p->coeffsB[filter][3] +
564  p->buf[delayB - 4] * p->coeffsB[filter][4];
565 
566  p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
567  p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
568 
569  sign = APESIGN(decoded);
570  p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
571  p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
572  p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
573  p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
574  p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
575  p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
576  p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
577  p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
578  p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
579 
580  return p->filterA[filter];
581 }
582 
583 static void predictor_decode_stereo(APEContext *ctx, int count)
584 {
585  APEPredictor *p = &ctx->predictor;
586  int32_t *decoded0 = ctx->decoded0;
587  int32_t *decoded1 = ctx->decoded1;
588 
589  while (count--) {
590  /* Predictor Y */
591  *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
593  decoded0++;
594  *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
596  decoded1++;
597 
598  /* Combined */
599  p->buf++;
600 
601  /* Have we filled the history buffer? */
602  if (p->buf == p->historybuffer + HISTORY_SIZE) {
603  memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
604  p->buf = p->historybuffer;
605  }
606  }
607 }
608 
609 static void predictor_decode_mono(APEContext *ctx, int count)
610 {
611  APEPredictor *p = &ctx->predictor;
612  int32_t *decoded0 = ctx->decoded0;
613  int32_t predictionA, currentA, A, sign;
614 
615  currentA = p->lastA[0];
616 
617  while (count--) {
618  A = *decoded0;
619 
620  p->buf[YDELAYA] = currentA;
621  p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
622 
623  predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
624  p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
625  p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
626  p->buf[YDELAYA - 3] * p->coeffsA[0][3];
627 
628  currentA = A + (predictionA >> 10);
629 
630  p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
631  p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
632 
633  sign = APESIGN(A);
634  p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
635  p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
636  p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
637  p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
638 
639  p->buf++;
640 
641  /* Have we filled the history buffer? */
642  if (p->buf == p->historybuffer + HISTORY_SIZE) {
643  memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
644  p->buf = p->historybuffer;
645  }
646 
647  p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
648  *(decoded0++) = p->filterA[0];
649  }
650 
651  p->lastA[0] = currentA;
652 }
653 
654 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
655 {
656  f->coeffs = buf;
657  f->historybuffer = buf + order;
658  f->delay = f->historybuffer + order * 2;
659  f->adaptcoeffs = f->historybuffer + order;
660 
661  memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
662  memset(f->coeffs, 0, order * sizeof(int16_t));
663  f->avg = 0;
664 }
665 
666 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
667 {
668  do_init_filter(&f[0], buf, order);
669  do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
670 }
671 
672 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
673  int32_t *data, int count, int order, int fracbits)
674 {
675  int res;
676  int absres;
677 
678  while (count--) {
679  /* round fixedpoint scalar product */
680  res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
681  f->adaptcoeffs - order,
682  order, APESIGN(*data));
683  res = (res + (1 << (fracbits - 1))) >> fracbits;
684  res += *data;
685  *data++ = res;
686 
687  /* Update the output history */
688  *f->delay++ = av_clip_int16(res);
689 
690  if (version < 3980) {
691  /* Version ??? to < 3.98 files (untested) */
692  f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
693  f->adaptcoeffs[-4] >>= 1;
694  f->adaptcoeffs[-8] >>= 1;
695  } else {
696  /* Version 3.98 and later files */
697 
698  /* Update the adaption coefficients */
699  absres = FFABS(res);
700  if (absres)
701  *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
702  (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
703  else
704  *f->adaptcoeffs = 0;
705 
706  f->avg += (absres - f->avg) / 16;
707 
708  f->adaptcoeffs[-1] >>= 1;
709  f->adaptcoeffs[-2] >>= 1;
710  f->adaptcoeffs[-8] >>= 1;
711  }
712 
713  f->adaptcoeffs++;
714 
715  /* Have we filled the history buffer? */
716  if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
717  memmove(f->historybuffer, f->delay - (order * 2),
718  (order * 2) * sizeof(int16_t));
719  f->delay = f->historybuffer + order * 2;
720  f->adaptcoeffs = f->historybuffer + order;
721  }
722  }
723 }
724 
725 static void apply_filter(APEContext *ctx, APEFilter *f,
726  int32_t *data0, int32_t *data1,
727  int count, int order, int fracbits)
728 {
729  do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
730  if (data1)
731  do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
732 }
733 
734 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
735  int32_t *decoded1, int count)
736 {
737  int i;
738 
739  for (i = 0; i < APE_FILTER_LEVELS; i++) {
740  if (!ape_filter_orders[ctx->fset][i])
741  break;
742  apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
743  ape_filter_orders[ctx->fset][i],
744  ape_filter_fracbits[ctx->fset][i]);
745  }
746 }
747 
749 {
750  int i, ret;
751  if ((ret = init_entropy_decoder(ctx)) < 0)
752  return ret;
754 
755  for (i = 0; i < APE_FILTER_LEVELS; i++) {
756  if (!ape_filter_orders[ctx->fset][i])
757  break;
758  init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
759  ape_filter_orders[ctx->fset][i]);
760  }
761  return 0;
762 }
763 
764 static void ape_unpack_mono(APEContext *ctx, int count)
765 {
766  int32_t *decoded0 = ctx->decoded0;
767  int32_t *decoded1 = ctx->decoded1;
768 
770  entropy_decode(ctx, count, 0);
771  /* We are pure silence, so we're done. */
772  av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
773  return;
774  }
775 
776  entropy_decode(ctx, count, 0);
777  ape_apply_filters(ctx, decoded0, NULL, count);
778 
779  /* Now apply the predictor decoding */
780  predictor_decode_mono(ctx, count);
781 
782  /* Pseudo-stereo - just copy left channel to right channel */
783  if (ctx->channels == 2) {
784  memcpy(decoded1, decoded0, count * sizeof(*decoded1));
785  }
786 }
787 
788 static void ape_unpack_stereo(APEContext *ctx, int count)
789 {
790  int32_t left, right;
791  int32_t *decoded0 = ctx->decoded0;
792  int32_t *decoded1 = ctx->decoded1;
793 
795  /* We are pure silence, so we're done. */
796  av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
797  return;
798  }
799 
800  entropy_decode(ctx, count, 1);
801  ape_apply_filters(ctx, decoded0, decoded1, count);
802 
803  /* Now apply the predictor decoding */
804  predictor_decode_stereo(ctx, count);
805 
806  /* Decorrelate and scale to output depth */
807  while (count--) {
808  left = *decoded1 - (*decoded0 / 2);
809  right = left + *decoded0;
810 
811  *(decoded0++) = left;
812  *(decoded1++) = right;
813  }
814 }
815 
816 static int ape_decode_frame(AVCodecContext *avctx, void *data,
817  int *got_frame_ptr, AVPacket *avpkt)
818 {
819  const uint8_t *buf = avpkt->data;
820  int buf_size = avpkt->size;
821  APEContext *s = avctx->priv_data;
822  int16_t *samples;
823  int i, ret;
824  int blockstodecode;
825 
826  /* this should never be negative, but bad things will happen if it is, so
827  check it just to make sure. */
828  av_assert0(s->samples >= 0);
829 
830  if(!s->samples){
831  uint32_t nblocks, offset;
832  void *tmp_data;
833 
834  if (!buf_size) {
835  *got_frame_ptr = 0;
836  return 0;
837  }
838  if (buf_size < 8) {
839  av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
840  return AVERROR_INVALIDDATA;
841  }
842 
843  tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
844  if (!tmp_data)
845  return AVERROR(ENOMEM);
846  s->data = tmp_data;
847  s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
848  s->ptr = s->data;
849  s->data_end = s->data + buf_size;
850 
851  nblocks = bytestream_get_be32(&s->ptr);
852  offset = bytestream_get_be32(&s->ptr);
853  if (offset > 3) {
854  av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
855  s->data = NULL;
856  return AVERROR_INVALIDDATA;
857  }
858  if (s->data_end - s->ptr < offset) {
859  av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
860  return AVERROR_INVALIDDATA;
861  }
862  s->ptr += offset;
863 
864  if (!nblocks || nblocks > INT_MAX) {
865  av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
866  return AVERROR_INVALIDDATA;
867  }
868  s->samples = nblocks;
869 
870  memset(s->decoded0, 0, sizeof(s->decoded0));
871  memset(s->decoded1, 0, sizeof(s->decoded1));
872 
873  /* Initialize the frame decoder */
874  if (init_frame_decoder(s) < 0) {
875  av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
876  return AVERROR_INVALIDDATA;
877  }
878 
879  }
880 
881  if (!s->data) {
882  *got_frame_ptr = 0;
883  return buf_size;
884  }
885 
886  blockstodecode = FFMIN(BLOCKS_PER_LOOP, s->samples);
887 
888  /* get output buffer */
889  s->frame.nb_samples = blockstodecode;
890  if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
891  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
892  return ret;
893  }
894  samples = (int16_t *)s->frame.data[0];
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  *got_frame_ptr = 1;
919  *(AVFrame *)data = s->frame;
920 
921  return (s->samples == 0) ? buf_size : 0;
922 }
923 
924 static void ape_flush(AVCodecContext *avctx)
925 {
926  APEContext *s = avctx->priv_data;
927  s->samples= 0;
928 }
929 
931  .name = "ape",
932  .type = AVMEDIA_TYPE_AUDIO,
933  .id = CODEC_ID_APE,
934  .priv_data_size = sizeof(APEContext),
939  .flush = ape_flush,
940  .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
941 };