FFmpeg
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 <inttypes.h>
24 
25 #include "libavutil/avassert.h"
27 #include "libavutil/crc.h"
28 #include "libavutil/opt.h"
29 #include "lossless_audiodsp.h"
30 #include "avcodec.h"
31 #include "bswapdsp.h"
32 #include "bytestream.h"
33 #include "internal.h"
34 #include "get_bits.h"
35 #include "unary.h"
36 
37 /**
38  * @file
39  * Monkey's Audio lossless audio decoder
40  */
41 
42 #define MAX_CHANNELS 2
43 #define MAX_BYTESPERSAMPLE 3
44 
45 #define APE_FRAMECODE_MONO_SILENCE 1
46 #define APE_FRAMECODE_STEREO_SILENCE 3
47 #define APE_FRAMECODE_PSEUDO_STEREO 4
48 
49 #define HISTORY_SIZE 512
50 #define PREDICTOR_ORDER 8
51 /** Total size of all predictor histories */
52 #define PREDICTOR_SIZE 50
53 
54 #define YDELAYA (18 + PREDICTOR_ORDER*4)
55 #define YDELAYB (18 + PREDICTOR_ORDER*3)
56 #define XDELAYA (18 + PREDICTOR_ORDER*2)
57 #define XDELAYB (18 + PREDICTOR_ORDER)
58 
59 #define YADAPTCOEFFSA 18
60 #define XADAPTCOEFFSA 14
61 #define YADAPTCOEFFSB 10
62 #define XADAPTCOEFFSB 5
63 
64 /**
65  * Possible compression levels
66  * @{
67  */
74 };
75 /** @} */
76 
77 #define APE_FILTER_LEVELS 3
78 
79 /** Filter orders depending on compression level */
80 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
81  { 0, 0, 0 },
82  { 16, 0, 0 },
83  { 64, 0, 0 },
84  { 32, 256, 0 },
85  { 16, 256, 1280 }
86 };
87 
88 /** Filter fraction bits depending on compression level */
90  { 0, 0, 0 },
91  { 11, 0, 0 },
92  { 11, 0, 0 },
93  { 10, 13, 0 },
94  { 11, 13, 15 }
95 };
96 
97 
98 /** Filters applied to the decoded data */
99 typedef struct APEFilter {
100  int16_t *coeffs; ///< actual coefficients used in filtering
101  int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
102  int16_t *historybuffer; ///< filter memory
103  int16_t *delay; ///< filtered values
104 
105  int avg;
106 } APEFilter;
107 
108 typedef struct APERice {
109  uint32_t k;
110  uint32_t ksum;
111 } APERice;
112 
113 typedef struct APERangecoder {
114  uint32_t low; ///< low end of interval
115  uint32_t range; ///< length of interval
116  uint32_t help; ///< bytes_to_follow resp. intermediate value
117  unsigned int buffer; ///< buffer for input/output
118 } APERangecoder;
119 
120 /** Filter histories */
121 typedef struct APEPredictor {
123 
124  int32_t lastA[2];
125 
126  int32_t filterA[2];
127  int32_t filterB[2];
128 
129  uint32_t coeffsA[2][4]; ///< adaption coefficients
130  uint32_t coeffsB[2][5]; ///< adaption coefficients
132 
133  unsigned int sample_pos;
134 } APEPredictor;
135 
136 typedef struct APEPredictor64 {
137  int64_t *buf;
138 
139  int64_t lastA[2];
140 
141  int64_t filterA[2];
142  int64_t filterB[2];
143 
144  uint64_t coeffsA[2][4]; ///< adaption coefficients
145  uint64_t coeffsB[2][5]; ///< adaption coefficients
147 
148  unsigned int sample_pos;
150 
151 /** Decoder context */
152 typedef struct APEContext {
153  AVClass *class; ///< class for AVOptions
157  int channels;
158  int samples; ///< samples left to decode in current frame
159  int bps;
160 
161  int fileversion; ///< codec version, very important in decoding process
162  int compression_level; ///< compression levels
163  int fset; ///< which filter set to use (calculated from compression level)
164  int flags; ///< global decoder flags
165 
166  uint32_t CRC; ///< signalled frame CRC
167  uint32_t CRC_state; ///< accumulated CRC
168  int frameflags; ///< frame flags
169  APEPredictor predictor; ///< predictor used for final reconstruction
170  APEPredictor64 predictor64; ///< 64bit predictor used for final reconstruction
171 
174  int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
175  int blocks_per_loop; ///< maximum number of samples to decode for each call
176 
177  int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
178 
179  APERangecoder rc; ///< rangecoder used to decode actual values
180  APERice riceX; ///< rice code parameters for the second channel
181  APERice riceY; ///< rice code parameters for the first channel
182  APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
184 
185  uint8_t *data; ///< current frame data
186  uint8_t *data_end; ///< frame data end
187  int data_size; ///< frame data allocated size
188  const uint8_t *ptr; ///< current position in frame data
189 
190  int error;
191 
192  void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
193  void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
196 } APEContext;
197 
198 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
199  int32_t *decoded1, int count);
200 
201 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
202 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
203 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
204 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
205 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
206 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
207 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
208 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
209 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
210 
217 
219 {
220  APEContext *s = avctx->priv_data;
221  int i;
222 
223  for (i = 0; i < APE_FILTER_LEVELS; i++)
224  av_freep(&s->filterbuf[i]);
225 
227  av_freep(&s->data);
228  s->decoded_size = s->data_size = 0;
229 
230  return 0;
231 }
232 
234 {
235  APEContext *s = avctx->priv_data;
236  int i;
237 
238  if (avctx->extradata_size != 6) {
239  av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
240  return AVERROR(EINVAL);
241  }
242  if (avctx->channels > 2) {
243  av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
244  return AVERROR(EINVAL);
245  }
246  s->bps = avctx->bits_per_coded_sample;
247  switch (s->bps) {
248  case 8:
249  avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
250  break;
251  case 16:
253  break;
254  case 24:
256  break;
257  default:
258  avpriv_request_sample(avctx,
259  "%d bits per coded sample", s->bps);
260  return AVERROR_PATCHWELCOME;
261  }
262  s->avctx = avctx;
263  s->channels = avctx->channels;
264  s->fileversion = AV_RL16(avctx->extradata);
265  s->compression_level = AV_RL16(avctx->extradata + 2);
266  s->flags = AV_RL16(avctx->extradata + 4);
267 
268  av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
269  s->compression_level, s->flags);
271  !s->compression_level ||
273  av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
274  s->compression_level);
275  return AVERROR_INVALIDDATA;
276  }
277  s->fset = s->compression_level / 1000 - 1;
278  for (i = 0; i < APE_FILTER_LEVELS; i++) {
279  if (!ape_filter_orders[s->fset][i])
280  break;
281  if (!(s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4)))
282  return AVERROR(ENOMEM);
283  }
284 
285  if (s->fileversion < 3860) {
288  } else if (s->fileversion < 3900) {
291  } else if (s->fileversion < 3930) {
294  } else if (s->fileversion < 3990) {
297  } else {
300  }
301 
302  if (s->fileversion < 3930) {
305  } else if (s->fileversion < 3950) {
308  } else {
311  }
312 
313  ff_bswapdsp_init(&s->bdsp);
314  ff_llauddsp_init(&s->adsp);
316 
317  return 0;
318 }
319 
320 /**
321  * @name APE range decoding functions
322  * @{
323  */
324 
325 #define CODE_BITS 32
326 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
327 #define SHIFT_BITS (CODE_BITS - 9)
328 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
329 #define BOTTOM_VALUE (TOP_VALUE >> 8)
330 
331 /** Start the decoder */
332 static inline void range_start_decoding(APEContext *ctx)
333 {
334  ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
335  ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
336  ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
337 }
338 
339 /** Perform normalization */
340 static inline void range_dec_normalize(APEContext *ctx)
341 {
342  while (ctx->rc.range <= BOTTOM_VALUE) {
343  ctx->rc.buffer <<= 8;
344  if(ctx->ptr < ctx->data_end) {
345  ctx->rc.buffer += *ctx->ptr;
346  ctx->ptr++;
347  } else {
348  ctx->error = 1;
349  }
350  ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
351  ctx->rc.range <<= 8;
352  }
353 }
354 
355 /**
356  * Calculate cumulative frequency for next symbol. Does NO update!
357  * @param ctx decoder context
358  * @param tot_f is the total frequency or (code_value)1<<shift
359  * @return the cumulative frequency
360  */
361 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
362 {
363  range_dec_normalize(ctx);
364  ctx->rc.help = ctx->rc.range / tot_f;
365  return ctx->rc.low / ctx->rc.help;
366 }
367 
368 /**
369  * Decode value with given size in bits
370  * @param ctx decoder context
371  * @param shift number of bits to decode
372  */
373 static inline int range_decode_culshift(APEContext *ctx, int shift)
374 {
375  range_dec_normalize(ctx);
376  ctx->rc.help = ctx->rc.range >> shift;
377  return ctx->rc.low / ctx->rc.help;
378 }
379 
380 
381 /**
382  * Update decoding state
383  * @param ctx decoder context
384  * @param sy_f the interval length (frequency of the symbol)
385  * @param lt_f the lower end (frequency sum of < symbols)
386  */
387 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
388 {
389  ctx->rc.low -= ctx->rc.help * lt_f;
390  ctx->rc.range = ctx->rc.help * sy_f;
391 }
392 
393 /** Decode n bits (n <= 16) without modelling */
394 static inline int range_decode_bits(APEContext *ctx, int n)
395 {
396  int sym = range_decode_culshift(ctx, n);
397  range_decode_update(ctx, 1, sym);
398  return sym;
399 }
400 
401 
402 #define MODEL_ELEMENTS 64
403 
404 /**
405  * Fixed probabilities for symbols in Monkey Audio version 3.97
406  */
407 static const uint16_t counts_3970[22] = {
408  0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
409  62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
410  65450, 65469, 65480, 65487, 65491, 65493,
411 };
412 
413 /**
414  * Probability ranges for symbols in Monkey Audio version 3.97
415  */
416 static const uint16_t counts_diff_3970[21] = {
417  14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
418  1104, 677, 415, 248, 150, 89, 54, 31,
419  19, 11, 7, 4, 2,
420 };
421 
422 /**
423  * Fixed probabilities for symbols in Monkey Audio version 3.98
424  */
425 static const uint16_t counts_3980[22] = {
426  0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
427  64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
428  65485, 65488, 65490, 65491, 65492, 65493,
429 };
430 
431 /**
432  * Probability ranges for symbols in Monkey Audio version 3.98
433  */
434 static const uint16_t counts_diff_3980[21] = {
435  19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
436  261, 119, 65, 31, 19, 10, 6, 3,
437  3, 2, 1, 1, 1,
438 };
439 
440 /**
441  * Decode symbol
442  * @param ctx decoder context
443  * @param counts probability range start position
444  * @param counts_diff probability range widths
445  */
446 static inline int range_get_symbol(APEContext *ctx,
447  const uint16_t counts[],
448  const uint16_t counts_diff[])
449 {
450  int symbol, cf;
451 
452  cf = range_decode_culshift(ctx, 16);
453 
454  if(cf > 65492){
455  symbol= cf - 65535 + 63;
456  range_decode_update(ctx, 1, cf);
457  if(cf > 65535)
458  ctx->error=1;
459  return symbol;
460  }
461  /* figure out the symbol inefficiently; a binary search would be much better */
462  for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
463 
464  range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
465 
466  return symbol;
467 }
468 /** @} */ // group rangecoder
469 
470 static inline void update_rice(APERice *rice, unsigned int x)
471 {
472  int lim = rice->k ? (1 << (rice->k + 4)) : 0;
473  rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
474 
475  if (rice->ksum < lim)
476  rice->k--;
477  else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
478  rice->k++;
479 }
480 
481 static inline int get_rice_ook(GetBitContext *gb, int k)
482 {
483  unsigned int x;
484 
485  x = get_unary(gb, 1, get_bits_left(gb));
486 
487  if (k)
488  x = (x << k) | get_bits(gb, k);
489 
490  return x;
491 }
492 
494  APERice *rice)
495 {
496  unsigned int x, overflow;
497 
498  overflow = get_unary(gb, 1, get_bits_left(gb));
499 
500  if (ctx->fileversion > 3880) {
501  while (overflow >= 16) {
502  overflow -= 16;
503  rice->k += 4;
504  }
505  }
506 
507  if (!rice->k)
508  x = overflow;
509  else if(rice->k <= MIN_CACHE_BITS) {
510  x = (overflow << rice->k) + get_bits(gb, rice->k);
511  } else {
512  av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
513  ctx->error = 1;
514  return AVERROR_INVALIDDATA;
515  }
516  rice->ksum += x - (rice->ksum + 8 >> 4);
517  if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
518  rice->k--;
519  else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
520  rice->k++;
521 
522  /* Convert to signed */
523  return ((x >> 1) ^ ((x & 1) - 1)) + 1;
524 }
525 
526 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
527 {
528  unsigned int x, overflow;
529  int tmpk;
530 
532 
533  if (overflow == (MODEL_ELEMENTS - 1)) {
534  tmpk = range_decode_bits(ctx, 5);
535  overflow = 0;
536  } else
537  tmpk = (rice->k < 1) ? 0 : rice->k - 1;
538 
539  if (tmpk <= 16 || ctx->fileversion < 3910) {
540  if (tmpk > 23) {
541  av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
542  return AVERROR_INVALIDDATA;
543  }
544  x = range_decode_bits(ctx, tmpk);
545  } else if (tmpk <= 31) {
546  x = range_decode_bits(ctx, 16);
547  x |= (range_decode_bits(ctx, tmpk - 16) << 16);
548  } else {
549  av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
550  return AVERROR_INVALIDDATA;
551  }
552  x += overflow << tmpk;
553 
554  update_rice(rice, x);
555 
556  /* Convert to signed */
557  return ((x >> 1) ^ ((x & 1) - 1)) + 1;
558 }
559 
560 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
561 {
562  unsigned int x, overflow, pivot;
563  int base;
564 
565  pivot = FFMAX(rice->ksum >> 5, 1);
566 
568 
569  if (overflow == (MODEL_ELEMENTS - 1)) {
570  overflow = (unsigned)range_decode_bits(ctx, 16) << 16;
571  overflow |= range_decode_bits(ctx, 16);
572  }
573 
574  if (pivot < 0x10000) {
575  base = range_decode_culfreq(ctx, pivot);
576  range_decode_update(ctx, 1, base);
577  } else {
578  int base_hi = pivot, base_lo;
579  int bbits = 0;
580 
581  while (base_hi & ~0xFFFF) {
582  base_hi >>= 1;
583  bbits++;
584  }
585  base_hi = range_decode_culfreq(ctx, base_hi + 1);
586  range_decode_update(ctx, 1, base_hi);
587  base_lo = range_decode_culfreq(ctx, 1 << bbits);
588  range_decode_update(ctx, 1, base_lo);
589 
590  base = (base_hi << bbits) + base_lo;
591  }
592 
593  x = base + overflow * pivot;
594 
595  update_rice(rice, x);
596 
597  /* Convert to signed */
598  return ((x >> 1) ^ ((x & 1) - 1)) + 1;
599 }
600 
601 static int get_k(int ksum)
602 {
603  return av_log2(ksum) + !!ksum;
604 }
605 
607  int32_t *out, APERice *rice, int blockstodecode)
608 {
609  int i;
610  unsigned ksummax, ksummin;
611 
612  rice->ksum = 0;
613  for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
614  out[i] = get_rice_ook(&ctx->gb, 10);
615  rice->ksum += out[i];
616  }
617 
618  if (blockstodecode <= 5)
619  goto end;
620 
621  rice->k = get_k(rice->ksum / 10);
622  if (rice->k >= 24)
623  return;
624  for (; i < FFMIN(blockstodecode, 64); i++) {
625  out[i] = get_rice_ook(&ctx->gb, rice->k);
626  rice->ksum += out[i];
627  rice->k = get_k(rice->ksum / ((i + 1) * 2));
628  if (rice->k >= 24)
629  return;
630  }
631 
632  if (blockstodecode <= 64)
633  goto end;
634 
635  rice->k = get_k(rice->ksum >> 7);
636  ksummax = 1 << rice->k + 7;
637  ksummin = rice->k ? (1 << rice->k + 6) : 0;
638  for (; i < blockstodecode; i++) {
639  if (get_bits_left(&ctx->gb) < 1) {
640  ctx->error = 1;
641  return;
642  }
643  out[i] = get_rice_ook(&ctx->gb, rice->k);
644  rice->ksum += out[i] - (unsigned)out[i - 64];
645  while (rice->ksum < ksummin) {
646  rice->k--;
647  ksummin = rice->k ? ksummin >> 1 : 0;
648  ksummax >>= 1;
649  }
650  while (rice->ksum >= ksummax) {
651  rice->k++;
652  if (rice->k > 24)
653  return;
654  ksummax <<= 1;
655  ksummin = ksummin ? ksummin << 1 : 128;
656  }
657  }
658 
659 end:
660  for (i = 0; i < blockstodecode; i++)
661  out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
662 }
663 
664 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
665 {
666  decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
667  blockstodecode);
668 }
669 
670 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
671 {
672  decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
673  blockstodecode);
674  decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
675  blockstodecode);
676 }
677 
678 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
679 {
680  int32_t *decoded0 = ctx->decoded[0];
681 
682  while (blockstodecode--)
683  *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
684 }
685 
686 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
687 {
688  int32_t *decoded0 = ctx->decoded[0];
689  int32_t *decoded1 = ctx->decoded[1];
690  int blocks = blockstodecode;
691 
692  while (blockstodecode--)
693  *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
694  while (blocks--)
695  *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
696 }
697 
698 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
699 {
700  int32_t *decoded0 = ctx->decoded[0];
701 
702  while (blockstodecode--)
703  *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
704 }
705 
706 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
707 {
708  int32_t *decoded0 = ctx->decoded[0];
709  int32_t *decoded1 = ctx->decoded[1];
710  int blocks = blockstodecode;
711 
712  while (blockstodecode--)
713  *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
714  range_dec_normalize(ctx);
715  // because of some implementation peculiarities we need to backpedal here
716  ctx->ptr -= 1;
718  while (blocks--)
719  *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
720 }
721 
722 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
723 {
724  int32_t *decoded0 = ctx->decoded[0];
725  int32_t *decoded1 = ctx->decoded[1];
726 
727  while (blockstodecode--) {
728  *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
729  *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
730  }
731 }
732 
733 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
734 {
735  int32_t *decoded0 = ctx->decoded[0];
736 
737  while (blockstodecode--)
738  *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
739 }
740 
741 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
742 {
743  int32_t *decoded0 = ctx->decoded[0];
744  int32_t *decoded1 = ctx->decoded[1];
745 
746  while (blockstodecode--) {
747  *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
748  *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
749  }
750 }
751 
753 {
754  /* Read the CRC */
755  if (ctx->fileversion >= 3900) {
756  if (ctx->data_end - ctx->ptr < 6)
757  return AVERROR_INVALIDDATA;
758  ctx->CRC = bytestream_get_be32(&ctx->ptr);
759  } else {
760  ctx->CRC = get_bits_long(&ctx->gb, 32);
761  }
762 
763  /* Read the frame flags if they exist */
764  ctx->frameflags = 0;
765  ctx->CRC_state = UINT32_MAX;
766  if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
767  ctx->CRC &= ~0x80000000;
768 
769  if (ctx->data_end - ctx->ptr < 6)
770  return AVERROR_INVALIDDATA;
771  ctx->frameflags = bytestream_get_be32(&ctx->ptr);
772  }
773 
774  /* Initialize the rice structs */
775  ctx->riceX.k = 10;
776  ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
777  ctx->riceY.k = 10;
778  ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
779 
780  if (ctx->fileversion >= 3900) {
781  /* The first 8 bits of input are ignored. */
782  ctx->ptr++;
783 
785  }
786 
787  return 0;
788 }
789 
791  375,
792 };
793 
794 static const int32_t initial_coeffs_a_3800[3] = {
795  64, 115, 64,
796 };
797 
798 static const int32_t initial_coeffs_b_3800[2] = {
799  740, 0
800 };
801 
802 static const int32_t initial_coeffs_3930[4] = {
803  360, 317, -109, 98
804 };
805 
806 static const int64_t initial_coeffs_3930_64bit[4] = {
807  360, 317, -109, 98
808 };
809 
811 {
812  APEPredictor *p = &ctx->predictor;
813  APEPredictor64 *p64 = &ctx->predictor64;
814 
815  /* Zero the history buffers */
816  memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
817  memset(p64->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p64->historybuffer));
818  p->buf = p->historybuffer;
819  p64->buf = p64->historybuffer;
820 
821  /* Initialize and zero the coefficients */
822  if (ctx->fileversion < 3930) {
824  memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
825  sizeof(initial_coeffs_fast_3320));
826  memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
827  sizeof(initial_coeffs_fast_3320));
828  } else {
829  memcpy(p->coeffsA[0], initial_coeffs_a_3800,
830  sizeof(initial_coeffs_a_3800));
831  memcpy(p->coeffsA[1], initial_coeffs_a_3800,
832  sizeof(initial_coeffs_a_3800));
833  }
834  } else {
835  memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
836  memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
839  }
840  memset(p->coeffsB, 0, sizeof(p->coeffsB));
841  memset(p64->coeffsB, 0, sizeof(p64->coeffsB));
842  if (ctx->fileversion < 3930) {
843  memcpy(p->coeffsB[0], initial_coeffs_b_3800,
844  sizeof(initial_coeffs_b_3800));
845  memcpy(p->coeffsB[1], initial_coeffs_b_3800,
846  sizeof(initial_coeffs_b_3800));
847  }
848 
849  p->filterA[0] = p->filterA[1] = 0;
850  p->filterB[0] = p->filterB[1] = 0;
851  p->lastA[0] = p->lastA[1] = 0;
852 
853  p64->filterA[0] = p64->filterA[1] = 0;
854  p64->filterB[0] = p64->filterB[1] = 0;
855  p64->lastA[0] = p64->lastA[1] = 0;
856 
857  p->sample_pos = 0;
858 
859  p64->sample_pos = 0;
860 }
861 
862 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
863 static inline int APESIGN(int32_t x) {
864  return (x < 0) - (x > 0);
865 }
866 
868  const int decoded, const int filter,
869  const int delayA)
870 {
871  int32_t predictionA;
872 
873  p->buf[delayA] = p->lastA[filter];
874  if (p->sample_pos < 3) {
875  p->lastA[filter] = decoded;
876  p->filterA[filter] = decoded;
877  return decoded;
878  }
879 
880  predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
881  p->lastA[filter] = decoded + ((int32_t)(predictionA * p->coeffsA[filter][0]) >> 9);
882 
883  if ((decoded ^ predictionA) > 0)
884  p->coeffsA[filter][0]++;
885  else
886  p->coeffsA[filter][0]--;
887 
888  p->filterA[filter] += (unsigned)p->lastA[filter];
889 
890  return p->filterA[filter];
891 }
892 
894  const unsigned decoded, const int filter,
895  const int delayA, const int delayB,
896  const int start, const int shift)
897 {
898  int32_t predictionA, predictionB, sign;
899  int32_t d0, d1, d2, d3, d4;
900 
901  p->buf[delayA] = p->lastA[filter];
902  p->buf[delayB] = p->filterB[filter];
903  if (p->sample_pos < start) {
904  predictionA = decoded + p->filterA[filter];
905  p->lastA[filter] = decoded;
906  p->filterB[filter] = decoded;
907  p->filterA[filter] = predictionA;
908  return predictionA;
909  }
910  d2 = p->buf[delayA];
911  d1 = (p->buf[delayA] - p->buf[delayA - 1]) * 2U;
912  d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) * 8U);
913  d3 = p->buf[delayB] * 2U - p->buf[delayB - 1];
914  d4 = p->buf[delayB];
915 
916  predictionA = d0 * p->coeffsA[filter][0] +
917  d1 * p->coeffsA[filter][1] +
918  d2 * p->coeffsA[filter][2];
919 
920  sign = APESIGN(decoded);
921  p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
922  p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
923  p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
924 
925  predictionB = d3 * p->coeffsB[filter][0] -
926  d4 * p->coeffsB[filter][1];
927  p->lastA[filter] = decoded + (predictionA >> 11);
928  sign = APESIGN(p->lastA[filter]);
929  p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
930  p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
931 
932  p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
933  p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
934 
935  return p->filterA[filter];
936 }
937 
938 static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
939 {
940  int i, j;
941  int32_t dotprod, sign;
942  int32_t coeffs[256], delay[256];
943 
944  if (order >= length)
945  return;
946 
947  memset(coeffs, 0, order * sizeof(*coeffs));
948  for (i = 0; i < order; i++)
949  delay[i] = buffer[i];
950  for (i = order; i < length; i++) {
951  dotprod = 0;
952  sign = APESIGN(buffer[i]);
953  for (j = 0; j < order; j++) {
954  dotprod += delay[j] * (unsigned)coeffs[j];
955  coeffs[j] += ((delay[j] >> 31) | 1) * sign;
956  }
957  buffer[i] -= dotprod >> shift;
958  for (j = 0; j < order - 1; j++)
959  delay[j] = delay[j + 1];
960  delay[order - 1] = buffer[i];
961  }
962 }
963 
965 {
966  int i, j;
967  int32_t dotprod, sign;
968  int32_t delay[8] = { 0 };
969  uint32_t coeffs[8] = { 0 };
970 
971  for (i = 0; i < length; i++) {
972  dotprod = 0;
973  sign = APESIGN(buffer[i]);
974  for (j = 7; j >= 0; j--) {
975  dotprod += delay[j] * coeffs[j];
976  coeffs[j] += ((delay[j] >> 31) | 1) * sign;
977  }
978  for (j = 7; j > 0; j--)
979  delay[j] = delay[j - 1];
980  delay[0] = buffer[i];
981  buffer[i] -= dotprod >> 9;
982  }
983 }
984 
986 {
987  APEPredictor *p = &ctx->predictor;
988  int32_t *decoded0 = ctx->decoded[0];
989  int32_t *decoded1 = ctx->decoded[1];
990  int start = 4, shift = 10;
991 
993  start = 16;
994  long_filter_high_3800(decoded0, 16, 9, count);
995  long_filter_high_3800(decoded1, 16, 9, count);
996  } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
997  int order = 128, shift2 = 11;
998 
999  if (ctx->fileversion >= 3830) {
1000  order <<= 1;
1001  shift++;
1002  shift2++;
1003  long_filter_ehigh_3830(decoded0 + order, count - order);
1004  long_filter_ehigh_3830(decoded1 + order, count - order);
1005  }
1006  start = order;
1007  long_filter_high_3800(decoded0, order, shift2, count);
1008  long_filter_high_3800(decoded1, order, shift2, count);
1009  }
1010 
1011  while (count--) {
1012  int X = *decoded0, Y = *decoded1;
1014  *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
1015  decoded0++;
1016  *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
1017  decoded1++;
1018  } else {
1019  *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
1020  start, shift);
1021  decoded0++;
1022  *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
1023  start, shift);
1024  decoded1++;
1025  }
1026 
1027  /* Combined */
1028  p->buf++;
1029  p->sample_pos++;
1030 
1031  /* Have we filled the history buffer? */
1032  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1033  memmove(p->historybuffer, p->buf,
1034  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1035  p->buf = p->historybuffer;
1036  }
1037  }
1038 }
1039 
1041 {
1042  APEPredictor *p = &ctx->predictor;
1043  int32_t *decoded0 = ctx->decoded[0];
1044  int start = 4, shift = 10;
1045 
1047  start = 16;
1048  long_filter_high_3800(decoded0, 16, 9, count);
1049  } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1050  int order = 128, shift2 = 11;
1051 
1052  if (ctx->fileversion >= 3830) {
1053  order <<= 1;
1054  shift++;
1055  shift2++;
1056  long_filter_ehigh_3830(decoded0 + order, count - order);
1057  }
1058  start = order;
1059  long_filter_high_3800(decoded0, order, shift2, count);
1060  }
1061 
1062  while (count--) {
1064  *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1065  decoded0++;
1066  } else {
1067  *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1068  start, shift);
1069  decoded0++;
1070  }
1071 
1072  /* Combined */
1073  p->buf++;
1074  p->sample_pos++;
1075 
1076  /* Have we filled the history buffer? */
1077  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1078  memmove(p->historybuffer, p->buf,
1079  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1080  p->buf = p->historybuffer;
1081  }
1082  }
1083 }
1084 
1086  const int decoded, const int filter,
1087  const int delayA)
1088 {
1089  int32_t predictionA, sign;
1090  int32_t d0, d1, d2, d3;
1091 
1092  p->buf[delayA] = p->lastA[filter];
1093  d0 = p->buf[delayA ];
1094  d1 = p->buf[delayA ] - p->buf[delayA - 1];
1095  d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1096  d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1097 
1098  predictionA = d0 * p->coeffsA[filter][0] +
1099  d1 * p->coeffsA[filter][1] +
1100  d2 * p->coeffsA[filter][2] +
1101  d3 * p->coeffsA[filter][3];
1102 
1103  p->lastA[filter] = decoded + (predictionA >> 9);
1104  p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1105 
1106  sign = APESIGN(decoded);
1107  p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1108  p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1109  p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1110  p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1111 
1112  return p->filterA[filter];
1113 }
1114 
1116 {
1117  APEPredictor *p = &ctx->predictor;
1118  int32_t *decoded0 = ctx->decoded[0];
1119  int32_t *decoded1 = ctx->decoded[1];
1120 
1121  ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1122 
1123  while (count--) {
1124  /* Predictor Y */
1125  int Y = *decoded1, X = *decoded0;
1126  *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1127  decoded0++;
1128  *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1129  decoded1++;
1130 
1131  /* Combined */
1132  p->buf++;
1133 
1134  /* Have we filled the history buffer? */
1135  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1136  memmove(p->historybuffer, p->buf,
1137  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1138  p->buf = p->historybuffer;
1139  }
1140  }
1141 }
1142 
1144 {
1145  APEPredictor *p = &ctx->predictor;
1146  int32_t *decoded0 = ctx->decoded[0];
1147 
1148  ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1149 
1150  while (count--) {
1151  *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1152  decoded0++;
1153 
1154  p->buf++;
1155 
1156  /* Have we filled the history buffer? */
1157  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1158  memmove(p->historybuffer, p->buf,
1159  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1160  p->buf = p->historybuffer;
1161  }
1162  }
1163 }
1164 
1166  const int decoded, const int filter,
1167  const int delayA, const int delayB,
1168  const int adaptA, const int adaptB)
1169 {
1170  int64_t predictionA, predictionB;
1171  int32_t sign;
1172 
1173  p->buf[delayA] = p->lastA[filter];
1174  p->buf[adaptA] = APESIGN(p->buf[delayA]);
1175  p->buf[delayA - 1] = p->buf[delayA] - (uint64_t)p->buf[delayA - 1];
1176  p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1177 
1178  predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
1179  p->buf[delayA - 1] * p->coeffsA[filter][1] +
1180  p->buf[delayA - 2] * p->coeffsA[filter][2] +
1181  p->buf[delayA - 3] * p->coeffsA[filter][3];
1182 
1183  /* Apply a scaled first-order filter compression */
1184  p->buf[delayB] = p->filterA[filter ^ 1] - ((int64_t)(p->filterB[filter] * 31ULL) >> 5);
1185  p->buf[adaptB] = APESIGN(p->buf[delayB]);
1186  p->buf[delayB - 1] = p->buf[delayB] - (uint64_t)p->buf[delayB - 1];
1187  p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1188  p->filterB[filter] = p->filterA[filter ^ 1];
1189 
1190  predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
1191  p->buf[delayB - 1] * p->coeffsB[filter][1] +
1192  p->buf[delayB - 2] * p->coeffsB[filter][2] +
1193  p->buf[delayB - 3] * p->coeffsB[filter][3] +
1194  p->buf[delayB - 4] * p->coeffsB[filter][4];
1195 
1196  p->lastA[filter] = decoded + ((int64_t)((uint64_t)predictionA + (predictionB >> 1)) >> 10);
1197  p->filterA[filter] = p->lastA[filter] + ((int64_t)(p->filterA[filter] * 31ULL) >> 5);
1198 
1199  sign = APESIGN(decoded);
1200  p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
1201  p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1202  p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1203  p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1204  p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
1205  p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1206  p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1207  p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1208  p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1209 
1210  return p->filterA[filter];
1211 }
1212 
1214 {
1215  APEPredictor64 *p = &ctx->predictor64;
1216  int32_t *decoded0 = ctx->decoded[0];
1217  int32_t *decoded1 = ctx->decoded[1];
1218 
1219  ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1220 
1221  while (count--) {
1222  /* Predictor Y */
1223  *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1225  decoded0++;
1226  *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1228  decoded1++;
1229 
1230  /* Combined */
1231  p->buf++;
1232 
1233  /* Have we filled the history buffer? */
1234  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1235  memmove(p->historybuffer, p->buf,
1236  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1237  p->buf = p->historybuffer;
1238  }
1239  }
1240 }
1241 
1243 {
1244  APEPredictor64 *p = &ctx->predictor64;
1245  int32_t *decoded0 = ctx->decoded[0];
1246  int32_t predictionA, currentA, A, sign;
1247 
1248  ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1249 
1250  currentA = p->lastA[0];
1251 
1252  while (count--) {
1253  A = *decoded0;
1254 
1255  p->buf[YDELAYA] = currentA;
1256  p->buf[YDELAYA - 1] = p->buf[YDELAYA] - (uint64_t)p->buf[YDELAYA - 1];
1257 
1258  predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
1259  p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1260  p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1261  p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1262 
1263  currentA = A + (uint64_t)(predictionA >> 10);
1264 
1265  p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
1266  p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1267 
1268  sign = APESIGN(A);
1269  p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
1270  p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1271  p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1272  p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1273 
1274  p->buf++;
1275 
1276  /* Have we filled the history buffer? */
1277  if (p->buf == p->historybuffer + HISTORY_SIZE) {
1278  memmove(p->historybuffer, p->buf,
1279  PREDICTOR_SIZE * sizeof(*p->historybuffer));
1280  p->buf = p->historybuffer;
1281  }
1282 
1283  p->filterA[0] = currentA + (uint64_t)((int64_t)(p->filterA[0] * 31U) >> 5);
1284  *(decoded0++) = p->filterA[0];
1285  }
1286 
1287  p->lastA[0] = currentA;
1288 }
1289 
1290 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1291 {
1292  f->coeffs = buf;
1293  f->historybuffer = buf + order;
1294  f->delay = f->historybuffer + order * 2;
1295  f->adaptcoeffs = f->historybuffer + order;
1296 
1297  memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1298  memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1299  f->avg = 0;
1300 }
1301 
1302 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1303 {
1304  do_init_filter(&f[0], buf, order);
1305  do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1306 }
1307 
1309  int32_t *data, int count, int order, int fracbits)
1310 {
1311  int res;
1312  unsigned absres;
1313 
1314  while (count--) {
1315  /* round fixedpoint scalar product */
1317  f->delay - order,
1318  f->adaptcoeffs - order,
1319  order, APESIGN(*data));
1320  res = (int64_t)(res + (1LL << (fracbits - 1))) >> fracbits;
1321  res += (unsigned)*data;
1322  *data++ = res;
1323 
1324  /* Update the output history */
1325  *f->delay++ = av_clip_int16(res);
1326 
1327  if (version < 3980) {
1328  /* Version ??? to < 3.98 files (untested) */
1329  f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1330  f->adaptcoeffs[-4] >>= 1;
1331  f->adaptcoeffs[-8] >>= 1;
1332  } else {
1333  /* Version 3.98 and later files */
1334 
1335  /* Update the adaption coefficients */
1336  absres = FFABS(res);
1337  if (absres)
1338  *f->adaptcoeffs = APESIGN(res) *
1339  (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1340  /* equivalent to the following code
1341  if (absres <= f->avg * 4 / 3)
1342  *f->adaptcoeffs = APESIGN(res) * 8;
1343  else if (absres <= f->avg * 3)
1344  *f->adaptcoeffs = APESIGN(res) * 16;
1345  else
1346  *f->adaptcoeffs = APESIGN(res) * 32;
1347  */
1348  else
1349  *f->adaptcoeffs = 0;
1350 
1351  f->avg += (int)(absres - (unsigned)f->avg) / 16;
1352 
1353  f->adaptcoeffs[-1] >>= 1;
1354  f->adaptcoeffs[-2] >>= 1;
1355  f->adaptcoeffs[-8] >>= 1;
1356  }
1357 
1358  f->adaptcoeffs++;
1359 
1360  /* Have we filled the history buffer? */
1361  if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1362  memmove(f->historybuffer, f->delay - (order * 2),
1363  (order * 2) * sizeof(*f->historybuffer));
1364  f->delay = f->historybuffer + order * 2;
1365  f->adaptcoeffs = f->historybuffer + order;
1366  }
1367  }
1368 }
1369 
1371  int32_t *data0, int32_t *data1,
1372  int count, int order, int fracbits)
1373 {
1374  do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1375  if (data1)
1376  do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1377 }
1378 
1379 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1380  int32_t *decoded1, int count)
1381 {
1382  int i;
1383 
1384  for (i = 0; i < APE_FILTER_LEVELS; i++) {
1385  if (!ape_filter_orders[ctx->fset][i])
1386  break;
1387  apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1388  ape_filter_orders[ctx->fset][i],
1389  ape_filter_fracbits[ctx->fset][i]);
1390  }
1391 }
1392 
1394 {
1395  int i, ret;
1396  if ((ret = init_entropy_decoder(ctx)) < 0)
1397  return ret;
1399 
1400  for (i = 0; i < APE_FILTER_LEVELS; i++) {
1401  if (!ape_filter_orders[ctx->fset][i])
1402  break;
1403  init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1404  ape_filter_orders[ctx->fset][i]);
1405  }
1406  return 0;
1407 }
1408 
1410 {
1412  /* We are pure silence, so we're done. */
1413  av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1414  return;
1415  }
1416 
1417  ctx->entropy_decode_mono(ctx, count);
1418  if (ctx->error)
1419  return;
1420 
1421  /* Now apply the predictor decoding */
1422  ctx->predictor_decode_mono(ctx, count);
1423 
1424  /* Pseudo-stereo - just copy left channel to right channel */
1425  if (ctx->channels == 2) {
1426  memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1427  }
1428 }
1429 
1431 {
1432  unsigned left, right;
1433  int32_t *decoded0 = ctx->decoded[0];
1434  int32_t *decoded1 = ctx->decoded[1];
1435 
1437  /* We are pure silence, so we're done. */
1438  av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1439  return;
1440  }
1441 
1442  ctx->entropy_decode_stereo(ctx, count);
1443  if (ctx->error)
1444  return;
1445 
1446  /* Now apply the predictor decoding */
1447  ctx->predictor_decode_stereo(ctx, count);
1448 
1449  /* Decorrelate and scale to output depth */
1450  while (count--) {
1451  left = *decoded1 - (unsigned)(*decoded0 / 2);
1452  right = left + *decoded0;
1453 
1454  *(decoded0++) = left;
1455  *(decoded1++) = right;
1456  }
1457 }
1458 
1460  int *got_frame_ptr, AVPacket *avpkt)
1461 {
1462  AVFrame *frame = data;
1463  const uint8_t *buf = avpkt->data;
1464  APEContext *s = avctx->priv_data;
1465  uint8_t *sample8;
1466  int16_t *sample16;
1467  int32_t *sample24;
1468  int i, ch, ret;
1469  int blockstodecode;
1470  uint64_t decoded_buffer_size;
1471 
1472  /* this should never be negative, but bad things will happen if it is, so
1473  check it just to make sure. */
1474  av_assert0(s->samples >= 0);
1475 
1476  if(!s->samples){
1477  uint32_t nblocks, offset;
1478  int buf_size;
1479 
1480  if (!avpkt->size) {
1481  *got_frame_ptr = 0;
1482  return 0;
1483  }
1484  if (avpkt->size < 8) {
1485  av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1486  return AVERROR_INVALIDDATA;
1487  }
1488  buf_size = avpkt->size & ~3;
1489  if (buf_size != avpkt->size) {
1490  av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1491  "extra bytes at the end will be skipped.\n");
1492  }
1493  if (s->fileversion < 3950) // previous versions overread two bytes
1494  buf_size += 2;
1495  av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1496  if (!s->data)
1497  return AVERROR(ENOMEM);
1498  s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1499  buf_size >> 2);
1500  memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1501  s->ptr = s->data;
1502  s->data_end = s->data + buf_size;
1503 
1504  nblocks = bytestream_get_be32(&s->ptr);
1505  offset = bytestream_get_be32(&s->ptr);
1506  if (s->fileversion >= 3900) {
1507  if (offset > 3) {
1508  av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1509  av_freep(&s->data);
1510  s->data_size = 0;
1511  return AVERROR_INVALIDDATA;
1512  }
1513  if (s->data_end - s->ptr < offset) {
1514  av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1515  return AVERROR_INVALIDDATA;
1516  }
1517  s->ptr += offset;
1518  } else {
1519  if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1520  return ret;
1521  if (s->fileversion > 3800)
1522  skip_bits_long(&s->gb, offset * 8);
1523  else
1524  skip_bits_long(&s->gb, offset);
1525  }
1526 
1527  if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1528  av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1529  nblocks);
1530  return AVERROR_INVALIDDATA;
1531  }
1532 
1533  /* Initialize the frame decoder */
1534  if (init_frame_decoder(s) < 0) {
1535  av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1536  return AVERROR_INVALIDDATA;
1537  }
1538  s->samples = nblocks;
1539  }
1540 
1541  if (!s->data) {
1542  *got_frame_ptr = 0;
1543  return avpkt->size;
1544  }
1545 
1546  blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1547  // for old files coefficients were not interleaved,
1548  // so we need to decode all of them at once
1549  if (s->fileversion < 3930)
1550  blockstodecode = s->samples;
1551 
1552  /* reallocate decoded sample buffer if needed */
1553  decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1554  av_assert0(decoded_buffer_size <= INT_MAX);
1555 
1556  /* get output buffer */
1557  frame->nb_samples = blockstodecode;
1558  if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1559  s->samples=0;
1560  return ret;
1561  }
1562 
1563  av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1564  if (!s->decoded_buffer)
1565  return AVERROR(ENOMEM);
1566  memset(s->decoded_buffer, 0, decoded_buffer_size);
1567  s->decoded[0] = s->decoded_buffer;
1568  s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1569 
1570  s->error=0;
1571 
1572  if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1573  ape_unpack_mono(s, blockstodecode);
1574  else
1575  ape_unpack_stereo(s, blockstodecode);
1576  emms_c();
1577 
1578  if (s->error) {
1579  s->samples=0;
1580  av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1581  return AVERROR_INVALIDDATA;
1582  }
1583 
1584  switch (s->bps) {
1585  case 8:
1586  for (ch = 0; ch < s->channels; ch++) {
1587  sample8 = (uint8_t *)frame->data[ch];
1588  for (i = 0; i < blockstodecode; i++)
1589  *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1590  }
1591  break;
1592  case 16:
1593  for (ch = 0; ch < s->channels; ch++) {
1594  sample16 = (int16_t *)frame->data[ch];
1595  for (i = 0; i < blockstodecode; i++)
1596  *sample16++ = s->decoded[ch][i];
1597  }
1598  break;
1599  case 24:
1600  for (ch = 0; ch < s->channels; ch++) {
1601  sample24 = (int32_t *)frame->data[ch];
1602  for (i = 0; i < blockstodecode; i++)
1603  *sample24++ = s->decoded[ch][i] * 256U;
1604  }
1605  break;
1606  }
1607 
1608  s->samples -= blockstodecode;
1609 
1610  if (avctx->err_recognition & AV_EF_CRCCHECK &&
1611  s->fileversion >= 3900 && s->bps < 24) {
1612  uint32_t crc = s->CRC_state;
1613  const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1614  for (i = 0; i < blockstodecode; i++) {
1615  for (ch = 0; ch < s->channels; ch++) {
1616  uint8_t *smp = frame->data[ch] + (i*(s->bps >> 3));
1617  crc = av_crc(crc_tab, crc, smp, s->bps >> 3);
1618  }
1619  }
1620 
1621  if (!s->samples && (~crc >> 1) ^ s->CRC) {
1622  av_log(avctx, AV_LOG_ERROR, "CRC mismatch! Previously decoded "
1623  "frames may have been affected as well.\n");
1624  if (avctx->err_recognition & AV_EF_EXPLODE)
1625  return AVERROR_INVALIDDATA;
1626  }
1627 
1628  s->CRC_state = crc;
1629  }
1630 
1631  *got_frame_ptr = 1;
1632 
1633  return !s->samples ? avpkt->size : 0;
1634 }
1635 
1637 {
1638  APEContext *s = avctx->priv_data;
1639  s->samples= 0;
1640 }
1641 
1642 #define OFFSET(x) offsetof(APEContext, x)
1643 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1644 static const AVOption options[] = {
1645  { "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" },
1646  { "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" },
1647  { NULL},
1648 };
1649 
1650 static const AVClass ape_decoder_class = {
1651  .class_name = "APE decoder",
1652  .item_name = av_default_item_name,
1653  .option = options,
1654  .version = LIBAVUTIL_VERSION_INT,
1655 };
1656 
1658  .name = "ape",
1659  .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1660  .type = AVMEDIA_TYPE_AUDIO,
1661  .id = AV_CODEC_ID_APE,
1662  .priv_data_size = sizeof(APEContext),
1663  .init = ape_decode_init,
1664  .close = ape_decode_close,
1666  .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1668  .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1669  .flush = ape_flush,
1670  .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1674  .priv_class = &ape_decoder_class,
1675 };
static int init_frame_decoder(APEContext *ctx)
Definition: apedec.c:1393
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
Definition: internal.h:48
static const int32_t initial_coeffs_3930[4]
Definition: apedec.c:802
int64_t * buf
Definition: apedec.c:137
uint64_t coeffsB[2][5]
adaption coefficients
Definition: apedec.c:145
static void decode_array_0000(APEContext *ctx, GetBitContext *gb, int32_t *out, APERice *rice, int blockstodecode)
Definition: apedec.c:606
int compression_level
compression levels
Definition: apedec.c:162
AVCodec ff_ape_decoder
Definition: apedec.c:1657
#define MODEL_ELEMENTS
Definition: apedec.c:402
#define NULL
Definition: coverity.c:32
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int decoded_size
Definition: apedec.c:173
#define YADAPTCOEFFSB
Definition: apedec.c:61
version
Definition: libkvazaar.c:317
static int shift(int a, int b)
Definition: sonic.c:82
This structure describes decoded (raw) audio or video data.
Definition: frame.h:308
static void range_start_decoding(APEContext *ctx)
Start the decoder.
Definition: apedec.c:332
AVOption.
Definition: opt.h:248
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:100
static void flush(AVCodecContext *avctx)
#define XDELAYA
Definition: apedec.c:56
static void apply_filter(APEContext *ctx, APEFilter *f, int32_t *data0, int32_t *data1, int count, int order, int fracbits)
Definition: apedec.c:1370
int fileversion
codec version, very important in decoding process
Definition: apedec.c:161
uint64_t coeffsA[2][4]
adaption coefficients
Definition: apedec.c:144
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
Definition: apedec.c:670
int32_t filterA[2]
Definition: apedec.c:126
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:379
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
static void skip_bits_long(GetBitContext *s, int n)
Skips the specified number of bits.
Definition: get_bits.h:291
void(* entropy_decode_mono)(struct APEContext *ctx, int blockstodecode)
Definition: apedec.c:192
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
#define avpriv_request_sample(...)
void(* entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode)
Definition: apedec.c:193
static int APESIGN(int32_t x)
Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero)
Definition: apedec.c:863
static void update_rice(APERice *rice, unsigned int x)
Definition: apedec.c:470
int size
Definition: packet.h:364
APEPredictor64 predictor64
64bit predictor used for final reconstruction
Definition: apedec.c:170
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
Definition: apedec.c:706
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
static av_cold int ape_decode_init(AVCodecContext *avctx)
Definition: apedec.c:233
unsigned int buffer
buffer for input/output
Definition: apedec.c:117
int av_log2(unsigned v)
Definition: intmath.c:26
static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
Definition: apedec.c:938
static int init_entropy_decoder(APEContext *ctx)
Definition: apedec.c:752
static void ape_flush(AVCodecContext *avctx)
Definition: apedec.c:1636
void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
Same behaviour av_fast_malloc but the buffer has additional AV_INPUT_BUFFER_PADDING_SIZE at the end w...
Definition: utils.c:72
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
Definition: apedec.c:722
static int get_k(int ksum)
Definition: apedec.c:601
static av_always_inline int predictor_update_3930(APEPredictor *p, const int decoded, const int filter, const int delayA)
Definition: apedec.c:1085
#define AV_CH_LAYOUT_STEREO
#define OFFSET(x)
Definition: apedec.c:1642
#define XADAPTCOEFFSA
Definition: apedec.c:60
AVCodec.
Definition: codec.h:190
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_RL16
Definition: bytestream.h:91
Undefined Behavior In the C some operations are like signed integer overflow
Definition: undefined.txt:3
static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile)
Definition: decode_audio.c:71
int16_t * filterbuf[APE_FILTER_LEVELS]
filter memory
Definition: apedec.c:177
static void predictor_decode_mono_3800(APEContext *ctx, int count)
Definition: apedec.c:1040
uint8_t base
Definition: vp3data.h:202
uint32_t CRC_state
accumulated CRC
Definition: apedec.c:167
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: codec.h:75
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static int ape_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt)
Definition: apedec.c:1459
Filter histories.
Definition: apedec.c:121
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1194
uint8_t
#define av_cold
Definition: attributes.h:88
#define av_malloc(s)
int16_t * delay
filtered values
Definition: apedec.c:103
AVOptions.
void(* bswap_buf)(uint32_t *dst, const uint32_t *src, int w)
Definition: bswapdsp.h:25
static void do_init_filter(APEFilter *f, int16_t *buf, int order)
Definition: apedec.c:1290
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf offset
#define f(width, name)
Definition: cbs_vp9.c:255
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:92
static const int32_t initial_coeffs_a_3800[3]
Definition: apedec.c:794
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
Definition: apedec.c:686
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
Definition: apedec.c:733
static void ape_unpack_mono(APEContext *ctx, int count)
Definition: apedec.c:1409
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:627
APERangecoder rc
rangecoder used to decode actual values
Definition: apedec.c:179
#define YDELAYB
Definition: apedec.c:55
int64_t lastA[2]
Definition: apedec.c:139
Public header for CRC hash function implementation.
static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS]
Filter fraction bits depending on compression level.
Definition: apedec.c:89
uint8_t * data
Definition: packet.h:363
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0, int32_t *decoded1, int count)
Definition: apedec.c:1379
bitstream reader API header.
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:1750
Decoder context.
Definition: apedec.c:152
#define A(x)
Definition: vp56_arith.h:28
#define FFALIGN(x, a)
Definition: macros.h:48
static const int64_t initial_coeffs_3930_64bit[4]
Definition: apedec.c:806
#define av_log(a,...)
static const uint16_t counts_3970[22]
Fixed probabilities for symbols in Monkey Audio version 3.97.
Definition: apedec.c:407
static void range_dec_normalize(APEContext *ctx)
Perform normalization.
Definition: apedec.c:340
#define U(x)
Definition: vp56_arith.h:37
static int get_bits_left(GetBitContext *gb)
Definition: get_bits.h:849
static const uint16_t counts_diff_3980[21]
Probability ranges for symbols in Monkey Audio version 3.98.
Definition: apedec.c:434
int bps
Definition: apedec.c:159
void(* predictor_decode_mono)(struct APEContext *ctx, int count)
Definition: apedec.c:194
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
#define YDELAYA
Definition: apedec.c:54
int32_t lastA[2]
Definition: apedec.c:124
filter_frame For filters that do not use the this method is called when a frame is pushed to the filter s input It can be called at any time except in a reentrant way If the input frame is enough to produce then the filter should push the output frames on the output link immediately As an exception to the previous rule if the input frame is enough to produce several output frames then the filter needs output only at least one per link The additional frames can be left buffered in the filter
static av_cold int ape_decode_close(AVCodecContext *avctx)
Definition: apedec.c:218
static av_always_inline int predictor_update_filter(APEPredictor64 *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
Definition: apedec.c:1165
static int ape_decode_value_3900(APEContext *ctx, APERice *rice)
Definition: apedec.c:526
int32_t historybuffer[HISTORY_SIZE+PREDICTOR_SIZE]
Definition: apedec.c:131
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:153
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define XDELAYB
Definition: apedec.c:57
int32_t * decoded_buffer
Definition: apedec.c:172
simple assert() macros that are a bit more flexible than ISO C assert().
GLsizei GLsizei * length
Definition: opengl_enc.c:114
int avg
Definition: apedec.c:105
const char * name
Name of the codec implementation.
Definition: codec.h:197
static int range_decode_culshift(APEContext *ctx, int shift)
Decode value with given size in bits.
Definition: apedec.c:373
#define APE_FILTER_LEVELS
Definition: apedec.c:77
GLsizei count
Definition: opengl_enc.c:108
int error
Definition: apedec.c:190
#define FFMAX(a, b)
Definition: common.h:94
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1237
static int range_decode_bits(APEContext *ctx, int n)
Decode n bits (n <= 16) without modelling.
Definition: apedec.c:394
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition: mem.c:502
int64_t filterB[2]
Definition: apedec.c:142
audio channel layout utility functions
#define Y
Definition: boxblur.h:38
static void predictor_decode_mono_3930(APEContext *ctx, int count)
Definition: apedec.c:1143
uint8_t * data
current frame data
Definition: apedec.c:185
int err_recognition
Error recognition; may misdetect some more or less valid parts as errors.
Definition: avcodec.h:1655
static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS]
Filter orders depending on compression level.
Definition: apedec.c:80
#define FFMIN(a, b)
Definition: common.h:96
signed 32 bits, planar
Definition: samplefmt.h:68
static int get_rice_ook(GetBitContext *gb, int k)
Definition: apedec.c:481
typedef void(APIENTRY *FF_PFNGLACTIVETEXTUREPROC)(GLenum texture)
static av_always_inline int filter_fast_3320(APEPredictor *p, const int decoded, const int filter, const int delayA)
Definition: apedec.c:867
AVCodecContext * avctx
Definition: apedec.c:154
static void ape_unpack_stereo(APEContext *ctx, int count)
Definition: apedec.c:1430
const uint8_t * ptr
current position in frame data
Definition: apedec.c:188
int32_t
static int range_decode_culfreq(APEContext *ctx, int tot_f)
Calculate cumulative frequency for next symbol.
Definition: apedec.c:361
AVFormatContext * ctx
Definition: movenc.c:48
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:392
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:72
#define s(width, name)
Definition: cbs_vp9.c:257
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition: avcodec.h:1666
int32_t(* scalarproduct_and_madd_int16)(int16_t *v1, const int16_t *v2, const int16_t *v3, int len, int mul)
Calculate scalar product of v1 and v2, and v1[i] += v3[i] * mul.
unsigned 8 bits, planar
Definition: samplefmt.h:66
static void predictor_decode_stereo_3930(APEContext *ctx, int count)
Definition: apedec.c:1115
uint32_t ksum
Definition: apedec.c:110
av_cold void ff_llauddsp_init(LLAudDSPContext *c)
uint32_t help
bytes_to_follow resp. intermediate value
Definition: apedec.c:116
uint32_t coeffsA[2][4]
adaption coefficients
Definition: apedec.c:129
int64_t historybuffer[HISTORY_SIZE+PREDICTOR_SIZE]
Definition: apedec.c:146
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
Definition: apedec.c:741
#define APE_FRAMECODE_PSEUDO_STEREO
Definition: apedec.c:47
unsigned int sample_pos
Definition: apedec.c:148
uint32_t range
length of interval
Definition: apedec.c:115
if(ret)
int samples
samples left to decode in current frame
Definition: apedec.c:158
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
int fset
which filter set to use (calculated from compression level)
Definition: apedec.c:163
static int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb, APERice *rice)
Definition: apedec.c:493
int64_t filterA[2]
Definition: apedec.c:141
APERice riceX
rice code parameters for the second channel
Definition: apedec.c:180
Libavcodec external API header.
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:58
static void predictor_decode_stereo_3950(APEContext *ctx, int count)
Definition: apedec.c:1213
static void predictor_decode_stereo_3800(APEContext *ctx, int count)
Definition: apedec.c:985
LLAudDSPContext adsp
Definition: apedec.c:156
static int init_get_bits8(GetBitContext *s, const uint8_t *buffer, int byte_size)
Initialize GetBitContext.
Definition: get_bits.h:677
#define APE_FRAMECODE_STEREO_SILENCE
Definition: apedec.c:46
static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
Definition: apedec.c:1302
int frameflags
frame flags
Definition: apedec.c:168
main external API structure.
Definition: avcodec.h:526
static av_always_inline int filter_3800(APEPredictor *p, const unsigned decoded, const int filter, const int delayA, const int delayB, const int start, const int shift)
Definition: apedec.c:893
static int ape_decode_value_3990(APEContext *ctx, APERice *rice)
Definition: apedec.c:560
uint32_t CRC
signalled frame CRC
Definition: apedec.c:166
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
Definition: decode.c:1879
Tag MUST be and< 10hcoeff half pel interpolation filter coefficients, hcoeff[0] are the 2 middle coefficients[1] are the next outer ones and so on, resulting in a filter like:...eff[2], hcoeff[1], hcoeff[0], hcoeff[0], hcoeff[1], hcoeff[2]...the sign of the coefficients is not explicitly stored but alternates after each coeff and coeff[0] is positive, so...,+,-,+,-,+,+,-,+,-,+,...hcoeff[0] is not explicitly stored but found by subtracting the sum of all stored coefficients with signs from 32 hcoeff[0]=32-hcoeff[1]-hcoeff[2]-...a good choice for hcoeff and htaps is htaps=6 hcoeff={40,-10, 2}an alternative which requires more computations at both encoder and decoder side and may or may not be better is htaps=8 hcoeff={42,-14, 6,-2}ref_frames minimum of the number of available reference frames and max_ref_frames for example the first frame after a key frame always has ref_frames=1spatial_decomposition_type wavelet type 0 is a 9/7 symmetric compact integer wavelet 1 is a 5/3 symmetric compact integer wavelet others are reserved stored as delta from last, last is reset to 0 if always_reset||keyframeqlog quality(logarithmic quantizer scale) stored as delta from last, last is reset to 0 if always_reset||keyframemv_scale stored as delta from last, last is reset to 0 if always_reset||keyframe FIXME check that everything works fine if this changes between framesqbias dequantization bias stored as delta from last, last is reset to 0 if always_reset||keyframeblock_max_depth maximum depth of the block tree stored as delta from last, last is reset to 0 if always_reset||keyframequant_table quantization tableHighlevel bitstream structure:==============================--------------------------------------------|Header|--------------------------------------------|------------------------------------|||Block0||||split?||||yes no||||.........intra?||||:Block01:yes no||||:Block02:.................||||:Block03::y DC::ref index:||||:Block04::cb DC::motion x:||||.........:cr DC::motion y:||||.................|||------------------------------------||------------------------------------|||Block1|||...|--------------------------------------------|------------------------------------|||Y subbands||Cb subbands||Cr subbands||||------||------||------|||||LL0||HL0||||LL0||HL0||||LL0||HL0|||||------||------||------||||------||------||------|||||LH0||HH0||||LH0||HH0||||LH0||HH0|||||------||------||------||||------||------||------|||||HL1||LH1||||HL1||LH1||||HL1||LH1|||||------||------||------||||------||------||------|||||HH1||HL2||||HH1||HL2||||HH1||HL2|||||...||...||...|||------------------------------------|--------------------------------------------Decoding process:=================------------|||Subbands|------------||||------------|Intra DC||||LL0 subband prediction------------|\Dequantization-------------------\||Reference frames|\IDWT|--------------|Motion\|||Frame 0||Frame 1||Compensation.OBMC v-------|--------------|--------------.\------> Frame n output Frame Frame<----------------------------------/|...|-------------------Range Coder:============Binary Range Coder:-------------------The implemented range coder is an adapted version based upon"Range encoding: an algorithm for removing redundancy from a digitised message."by G.N.N.Martin.The symbols encoded by the Snow range coder are bits(0|1).The associated probabilities are not fix but change depending on the symbol mix seen so far.bit seen|new state---------+-----------------------------------------------0|256-state_transition_table[256-old_state];1|state_transition_table[old_state];state_transition_table={0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 190, 191, 192, 194, 194, 195, 196, 197, 198, 199, 200, 201, 202, 202, 204, 205, 206, 207, 208, 209, 209, 210, 211, 212, 213, 215, 215, 216, 217, 218, 219, 220, 220, 222, 223, 224, 225, 226, 227, 227, 229, 229, 230, 231, 232, 234, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 0, 0, 0, 0, 0, 0, 0};FIXME Range Coding of integers:-------------------------FIXME Neighboring Blocks:===================left and top are set to the respective blocks unless they are outside of the image in which case they are set to the Null block top-left is set to the top left block unless it is outside of the image in which case it is set to the left block if this block has no larger parent block or it is at the left side of its parent block and the top right block is not outside of the image then the top right block is used for top-right else the top-left block is used Null block y, cb, cr are 128 level, ref, mx and my are 0 Motion Vector Prediction:=========================1.the motion vectors of all the neighboring blocks are scaled to compensate for the difference of reference frames scaled_mv=(mv *(256 *(current_reference+1)/(mv.reference+1))+128)> the median of the scaled left
Definition: snow.txt:206
BswapDSPContext bdsp
Definition: apedec.c:155
unsigned int sample_pos
Definition: apedec.c:133
int extradata_size
Definition: avcodec.h:628
static const uint16_t counts_3980[22]
Fixed probabilities for symbols in Monkey Audio version 3.98.
Definition: apedec.c:425
static int range_get_symbol(APEContext *ctx, const uint16_t counts[], const uint16_t counts_diff[])
Decode symbol.
Definition: apedec.c:446
Describe the class of an AVClass context structure.
Definition: log.h:67
#define AV_CODEC_CAP_SUBFRAMES
Codec can output multiple frames per AVPacket Normally demuxers return one frame at a time...
Definition: codec.h:93
uint32_t low
low end of interval
Definition: apedec.c:114
int flags
global decoder flags
Definition: apedec.c:164
APECompressionLevel
Possible compression levels.
Definition: apedec.c:68
#define AV_EF_CRCCHECK
Verify checksums embedded in the bitstream (could be of either encoded or decoded data...
Definition: avcodec.h:1663
void(* predictor_decode_stereo)(struct APEContext *ctx, int count)
Definition: apedec.c:195
#define EXTRA_BITS
Definition: apedec.c:328
static void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
Update decoding state.
Definition: apedec.c:387
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
Definition: apedec.c:698
uint32_t k
Definition: apedec.c:109
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition: get_bits.h:546
#define MAX_CHANNELS
Definition: apedec.c:42
static const int32_t initial_coeffs_fast_3320[1]
Definition: apedec.c:790
Definition: vf_addroi.c:26
#define MIN_CACHE_BITS
Definition: get_bits.h:128
static void do_apply_filter(APEContext *ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
Definition: apedec.c:1308
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:322
#define PREDICTOR_SIZE
Total size of all predictor histories.
Definition: apedec.c:52
static const uint16_t counts_diff_3970[21]
Probability ranges for symbols in Monkey Audio version 3.97.
Definition: apedec.c:416
int blocks_per_loop
maximum number of samples to decode for each call
Definition: apedec.c:175
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:374
int
uint8_t * data_end
frame data end
Definition: apedec.c:186
common internal api header.
APERice riceY
rice code parameters for the first channel
Definition: apedec.c:181
static const int shift2[6]
Definition: dxa.c:51
static int get_unary(GetBitContext *gb, int stop, int len)
Get unary code of limited length.
Definition: unary.h:46
APEFilter filters[APE_FILTER_LEVELS][2]
filters used for reconstruction
Definition: apedec.c:182
int16_t * coeffs
actual coefficients used in filtering
Definition: apedec.c:100
int32_t filterB[2]
Definition: apedec.c:127
#define YADAPTCOEFFSA
Definition: apedec.c:59
#define PAR
Definition: apedec.c:1643
static void init_predictor_decoder(APEContext *ctx)
Definition: apedec.c:810
av_cold void ff_bswapdsp_init(BswapDSPContext *c)
Definition: bswapdsp.c:49
void * priv_data
Definition: avcodec.h:553
static const int32_t initial_coeffs_b_3800[2]
Definition: apedec.c:798
APEPredictor predictor
predictor used for final reconstruction
Definition: apedec.c:169
static const AVClass ape_decoder_class
Definition: apedec.c:1650
int channels
number of audio channels
Definition: avcodec.h:1187
static void long_filter_ehigh_3830(int32_t *buffer, int length)
Definition: apedec.c:964
static void predictor_decode_mono_3950(APEContext *ctx, int count)
Definition: apedec.c:1242
GetBitContext gb
Definition: apedec.c:183
Filters applied to the decoded data.
Definition: apedec.c:99
static const struct PPFilter filters[]
Definition: postprocess.c:134
uint32_t coeffsB[2][5]
adaption coefficients
Definition: apedec.c:130
#define XADAPTCOEFFSB
Definition: apedec.c:62
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a it should return
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:846
int32_t * decoded[MAX_CHANNELS]
decoded data for each channel
Definition: apedec.c:174
int32_t * buf
Definition: apedec.c:122
FILE * out
Definition: movenc.c:54
#define av_freep(p)
signed 16 bits, planar
Definition: samplefmt.h:67
#define HISTORY_SIZE
Definition: apedec.c:49
#define av_always_inline
Definition: attributes.h:45
int data_size
frame data allocated size
Definition: apedec.c:187
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Frame references ownership and permissions
static const AVOption options[]
Definition: apedec.c:1644
#define AV_CH_LAYOUT_MONO
int16_t * adaptcoeffs
adaptive filter coefficients used for correcting of actual filter coefficients
Definition: apedec.c:101
int channels
Definition: apedec.c:157
#define BOTTOM_VALUE
Definition: apedec.c:329
This structure stores compressed data.
Definition: packet.h:340
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:374
uint32_t AVCRC
Definition: crc.h:47
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() for allocating buffers and supports custom allocators.
Definition: codec.h:50
for(j=16;j >0;--j)
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
Definition: apedec.c:664
int i
Definition: input.c:407
GLuint buffer
Definition: opengl_enc.c:101
int16_t * historybuffer
filter memory
Definition: apedec.c:102
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
Definition: apedec.c:678