You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

909 lines
28KB

  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. #define ALT_BITSTREAM_READER_LE
  23. #include "avcodec.h"
  24. #include "dsputil.h"
  25. #include "get_bits.h"
  26. #include "bytestream.h"
  27. #include "libavutil/audioconvert.h"
  28. /**
  29. * @file
  30. * Monkey's Audio lossless audio decoder
  31. */
  32. #define BLOCKS_PER_LOOP 4608
  33. #define MAX_CHANNELS 2
  34. #define MAX_BYTESPERSAMPLE 3
  35. #define APE_FRAMECODE_MONO_SILENCE 1
  36. #define APE_FRAMECODE_STEREO_SILENCE 3
  37. #define APE_FRAMECODE_PSEUDO_STEREO 4
  38. #define HISTORY_SIZE 512
  39. #define PREDICTOR_ORDER 8
  40. /** Total size of all predictor histories */
  41. #define PREDICTOR_SIZE 50
  42. #define YDELAYA (18 + PREDICTOR_ORDER*4)
  43. #define YDELAYB (18 + PREDICTOR_ORDER*3)
  44. #define XDELAYA (18 + PREDICTOR_ORDER*2)
  45. #define XDELAYB (18 + PREDICTOR_ORDER)
  46. #define YADAPTCOEFFSA 18
  47. #define XADAPTCOEFFSA 14
  48. #define YADAPTCOEFFSB 10
  49. #define XADAPTCOEFFSB 5
  50. /**
  51. * Possible compression levels
  52. * @{
  53. */
  54. enum APECompressionLevel {
  55. COMPRESSION_LEVEL_FAST = 1000,
  56. COMPRESSION_LEVEL_NORMAL = 2000,
  57. COMPRESSION_LEVEL_HIGH = 3000,
  58. COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
  59. COMPRESSION_LEVEL_INSANE = 5000
  60. };
  61. /** @} */
  62. #define APE_FILTER_LEVELS 3
  63. /** Filter orders depending on compression level */
  64. static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
  65. { 0, 0, 0 },
  66. { 16, 0, 0 },
  67. { 64, 0, 0 },
  68. { 32, 256, 0 },
  69. { 16, 256, 1280 }
  70. };
  71. /** Filter fraction bits depending on compression level */
  72. static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
  73. { 0, 0, 0 },
  74. { 11, 0, 0 },
  75. { 11, 0, 0 },
  76. { 10, 13, 0 },
  77. { 11, 13, 15 }
  78. };
  79. /** Filters applied to the decoded data */
  80. typedef struct APEFilter {
  81. int16_t *coeffs; ///< actual coefficients used in filtering
  82. int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
  83. int16_t *historybuffer; ///< filter memory
  84. int16_t *delay; ///< filtered values
  85. int avg;
  86. } APEFilter;
  87. typedef struct APERice {
  88. uint32_t k;
  89. uint32_t ksum;
  90. } APERice;
  91. typedef struct APERangecoder {
  92. uint32_t low; ///< low end of interval
  93. uint32_t range; ///< length of interval
  94. uint32_t help; ///< bytes_to_follow resp. intermediate value
  95. unsigned int buffer; ///< buffer for input/output
  96. } APERangecoder;
  97. /** Filter histories */
  98. typedef struct APEPredictor {
  99. int32_t *buf;
  100. int32_t lastA[2];
  101. int32_t filterA[2];
  102. int32_t filterB[2];
  103. int32_t coeffsA[2][4]; ///< adaption coefficients
  104. int32_t coeffsB[2][5]; ///< adaption coefficients
  105. int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
  106. } APEPredictor;
  107. /** Decoder context */
  108. typedef struct APEContext {
  109. AVCodecContext *avctx;
  110. DSPContext dsp;
  111. int channels;
  112. int samples; ///< samples left to decode in current frame
  113. int fileversion; ///< codec version, very important in decoding process
  114. int compression_level; ///< compression levels
  115. int fset; ///< which filter set to use (calculated from compression level)
  116. int flags; ///< global decoder flags
  117. uint32_t CRC; ///< frame CRC
  118. int frameflags; ///< frame flags
  119. int currentframeblocks; ///< samples (per channel) in current frame
  120. int blocksdecoded; ///< count of decoded samples in current frame
  121. APEPredictor predictor; ///< predictor used for final reconstruction
  122. int32_t decoded0[BLOCKS_PER_LOOP]; ///< decoded data for the first channel
  123. int32_t decoded1[BLOCKS_PER_LOOP]; ///< decoded data for the second channel
  124. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  125. APERangecoder rc; ///< rangecoder used to decode actual values
  126. APERice riceX; ///< rice code parameters for the second channel
  127. APERice riceY; ///< rice code parameters for the first channel
  128. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  129. uint8_t *data; ///< current frame data
  130. uint8_t *data_end; ///< frame data end
  131. const uint8_t *ptr; ///< current position in frame data
  132. const uint8_t *last_ptr; ///< position where last 4608-sample block ended
  133. int error;
  134. } APEContext;
  135. // TODO: dsputilize
  136. static av_cold int ape_decode_close(AVCodecContext * avctx)
  137. {
  138. APEContext *s = avctx->priv_data;
  139. int i;
  140. for (i = 0; i < APE_FILTER_LEVELS; i++)
  141. av_freep(&s->filterbuf[i]);
  142. av_freep(&s->data);
  143. return 0;
  144. }
  145. static av_cold int ape_decode_init(AVCodecContext * avctx)
  146. {
  147. APEContext *s = avctx->priv_data;
  148. int i;
  149. if (avctx->extradata_size != 6) {
  150. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  151. return -1;
  152. }
  153. if (avctx->bits_per_coded_sample != 16) {
  154. av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
  155. return -1;
  156. }
  157. if (avctx->channels > 2) {
  158. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  159. return -1;
  160. }
  161. s->avctx = avctx;
  162. s->channels = avctx->channels;
  163. s->fileversion = AV_RL16(avctx->extradata);
  164. s->compression_level = AV_RL16(avctx->extradata + 2);
  165. s->flags = AV_RL16(avctx->extradata + 4);
  166. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);
  167. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
  168. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);
  169. return -1;
  170. }
  171. s->fset = s->compression_level / 1000 - 1;
  172. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  173. if (!ape_filter_orders[s->fset][i])
  174. break;
  175. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  176. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  177. filter_alloc_fail);
  178. }
  179. dsputil_init(&s->dsp, avctx);
  180. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  181. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  182. return 0;
  183. filter_alloc_fail:
  184. ape_decode_close(avctx);
  185. return AVERROR(ENOMEM);
  186. }
  187. /**
  188. * @name APE range decoding functions
  189. * @{
  190. */
  191. #define CODE_BITS 32
  192. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  193. #define SHIFT_BITS (CODE_BITS - 9)
  194. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  195. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  196. /** Start the decoder */
  197. static inline void range_start_decoding(APEContext * ctx)
  198. {
  199. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  200. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  201. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  202. }
  203. /** Perform normalization */
  204. static inline void range_dec_normalize(APEContext * ctx)
  205. {
  206. while (ctx->rc.range <= BOTTOM_VALUE) {
  207. ctx->rc.buffer <<= 8;
  208. if(ctx->ptr < ctx->data_end)
  209. ctx->rc.buffer += *ctx->ptr;
  210. ctx->ptr++;
  211. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  212. ctx->rc.range <<= 8;
  213. }
  214. }
  215. /**
  216. * Calculate culmulative frequency for next symbol. Does NO update!
  217. * @param ctx decoder context
  218. * @param tot_f is the total frequency or (code_value)1<<shift
  219. * @return the culmulative frequency
  220. */
  221. static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
  222. {
  223. range_dec_normalize(ctx);
  224. ctx->rc.help = ctx->rc.range / tot_f;
  225. return ctx->rc.low / ctx->rc.help;
  226. }
  227. /**
  228. * Decode value with given size in bits
  229. * @param ctx decoder context
  230. * @param shift number of bits to decode
  231. */
  232. static inline int range_decode_culshift(APEContext * ctx, int shift)
  233. {
  234. range_dec_normalize(ctx);
  235. ctx->rc.help = ctx->rc.range >> shift;
  236. return ctx->rc.low / ctx->rc.help;
  237. }
  238. /**
  239. * Update decoding state
  240. * @param ctx decoder context
  241. * @param sy_f the interval length (frequency of the symbol)
  242. * @param lt_f the lower end (frequency sum of < symbols)
  243. */
  244. static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
  245. {
  246. ctx->rc.low -= ctx->rc.help * lt_f;
  247. ctx->rc.range = ctx->rc.help * sy_f;
  248. }
  249. /** Decode n bits (n <= 16) without modelling */
  250. static inline int range_decode_bits(APEContext * ctx, int n)
  251. {
  252. int sym = range_decode_culshift(ctx, n);
  253. range_decode_update(ctx, 1, sym);
  254. return sym;
  255. }
  256. #define MODEL_ELEMENTS 64
  257. /**
  258. * Fixed probabilities for symbols in Monkey Audio version 3.97
  259. */
  260. static const uint16_t counts_3970[22] = {
  261. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  262. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  263. 65450, 65469, 65480, 65487, 65491, 65493,
  264. };
  265. /**
  266. * Probability ranges for symbols in Monkey Audio version 3.97
  267. */
  268. static const uint16_t counts_diff_3970[21] = {
  269. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  270. 1104, 677, 415, 248, 150, 89, 54, 31,
  271. 19, 11, 7, 4, 2,
  272. };
  273. /**
  274. * Fixed probabilities for symbols in Monkey Audio version 3.98
  275. */
  276. static const uint16_t counts_3980[22] = {
  277. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  278. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  279. 65485, 65488, 65490, 65491, 65492, 65493,
  280. };
  281. /**
  282. * Probability ranges for symbols in Monkey Audio version 3.98
  283. */
  284. static const uint16_t counts_diff_3980[21] = {
  285. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  286. 261, 119, 65, 31, 19, 10, 6, 3,
  287. 3, 2, 1, 1, 1,
  288. };
  289. /**
  290. * Decode symbol
  291. * @param ctx decoder context
  292. * @param counts probability range start position
  293. * @param counts_diff probability range widths
  294. */
  295. static inline int range_get_symbol(APEContext * ctx,
  296. const uint16_t counts[],
  297. const uint16_t counts_diff[])
  298. {
  299. int symbol, cf;
  300. cf = range_decode_culshift(ctx, 16);
  301. if(cf > 65492){
  302. symbol= cf - 65535 + 63;
  303. range_decode_update(ctx, 1, cf);
  304. if(cf > 65535)
  305. ctx->error=1;
  306. return symbol;
  307. }
  308. /* figure out the symbol inefficiently; a binary search would be much better */
  309. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  310. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  311. return symbol;
  312. }
  313. /** @} */ // group rangecoder
  314. static inline void update_rice(APERice *rice, int x)
  315. {
  316. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  317. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  318. if (rice->ksum < lim)
  319. rice->k--;
  320. else if (rice->ksum >= (1 << (rice->k + 5)))
  321. rice->k++;
  322. }
  323. static inline int ape_decode_value(APEContext * ctx, APERice *rice)
  324. {
  325. int x, overflow;
  326. if (ctx->fileversion < 3990) {
  327. int tmpk;
  328. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  329. if (overflow == (MODEL_ELEMENTS - 1)) {
  330. tmpk = range_decode_bits(ctx, 5);
  331. overflow = 0;
  332. } else
  333. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  334. if (tmpk <= 16)
  335. x = range_decode_bits(ctx, tmpk);
  336. else {
  337. x = range_decode_bits(ctx, 16);
  338. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  339. }
  340. x += overflow << tmpk;
  341. } else {
  342. int base, pivot;
  343. pivot = rice->ksum >> 5;
  344. if (pivot == 0)
  345. pivot = 1;
  346. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  347. if (overflow == (MODEL_ELEMENTS - 1)) {
  348. overflow = range_decode_bits(ctx, 16) << 16;
  349. overflow |= range_decode_bits(ctx, 16);
  350. }
  351. if (pivot < 0x10000) {
  352. base = range_decode_culfreq(ctx, pivot);
  353. range_decode_update(ctx, 1, base);
  354. } else {
  355. int base_hi = pivot, base_lo;
  356. int bbits = 0;
  357. while (base_hi & ~0xFFFF) {
  358. base_hi >>= 1;
  359. bbits++;
  360. }
  361. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  362. range_decode_update(ctx, 1, base_hi);
  363. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  364. range_decode_update(ctx, 1, base_lo);
  365. base = (base_hi << bbits) + base_lo;
  366. }
  367. x = base + overflow * pivot;
  368. }
  369. update_rice(rice, x);
  370. /* Convert to signed */
  371. if (x & 1)
  372. return (x >> 1) + 1;
  373. else
  374. return -(x >> 1);
  375. }
  376. static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
  377. {
  378. int32_t *decoded0 = ctx->decoded0;
  379. int32_t *decoded1 = ctx->decoded1;
  380. ctx->blocksdecoded = blockstodecode;
  381. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  382. /* We are pure silence, just memset the output buffer. */
  383. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  384. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  385. } else {
  386. while (blockstodecode--) {
  387. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  388. if (stereo)
  389. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  390. }
  391. }
  392. if (ctx->blocksdecoded == ctx->currentframeblocks)
  393. range_dec_normalize(ctx); /* normalize to use up all bytes */
  394. }
  395. static void init_entropy_decoder(APEContext * ctx)
  396. {
  397. /* Read the CRC */
  398. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  399. /* Read the frame flags if they exist */
  400. ctx->frameflags = 0;
  401. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  402. ctx->CRC &= ~0x80000000;
  403. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  404. }
  405. /* Keep a count of the blocks decoded in this frame */
  406. ctx->blocksdecoded = 0;
  407. /* Initialize the rice structs */
  408. ctx->riceX.k = 10;
  409. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  410. ctx->riceY.k = 10;
  411. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  412. /* The first 8 bits of input are ignored. */
  413. ctx->ptr++;
  414. range_start_decoding(ctx);
  415. }
  416. static const int32_t initial_coeffs[4] = {
  417. 360, 317, -109, 98
  418. };
  419. static void init_predictor_decoder(APEContext * ctx)
  420. {
  421. APEPredictor *p = &ctx->predictor;
  422. /* Zero the history buffers */
  423. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
  424. p->buf = p->historybuffer;
  425. /* Initialize and zero the coefficients */
  426. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  427. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  428. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  429. p->filterA[0] = p->filterA[1] = 0;
  430. p->filterB[0] = p->filterB[1] = 0;
  431. p->lastA[0] = p->lastA[1] = 0;
  432. }
  433. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  434. static inline int APESIGN(int32_t x) {
  435. return (x < 0) - (x > 0);
  436. }
  437. static av_always_inline int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
  438. {
  439. int32_t predictionA, predictionB, sign;
  440. p->buf[delayA] = p->lastA[filter];
  441. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  442. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  443. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  444. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  445. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  446. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  447. p->buf[delayA - 3] * p->coeffsA[filter][3];
  448. /* Apply a scaled first-order filter compression */
  449. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  450. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  451. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  452. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  453. p->filterB[filter] = p->filterA[filter ^ 1];
  454. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  455. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  456. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  457. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  458. p->buf[delayB - 4] * p->coeffsB[filter][4];
  459. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  460. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  461. sign = APESIGN(decoded);
  462. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  463. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  464. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  465. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  466. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  467. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  468. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  469. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  470. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  471. return p->filterA[filter];
  472. }
  473. static void predictor_decode_stereo(APEContext * ctx, int count)
  474. {
  475. APEPredictor *p = &ctx->predictor;
  476. int32_t *decoded0 = ctx->decoded0;
  477. int32_t *decoded1 = ctx->decoded1;
  478. while (count--) {
  479. /* Predictor Y */
  480. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
  481. decoded0++;
  482. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
  483. decoded1++;
  484. /* Combined */
  485. p->buf++;
  486. /* Have we filled the history buffer? */
  487. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  488. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  489. p->buf = p->historybuffer;
  490. }
  491. }
  492. }
  493. static void predictor_decode_mono(APEContext * ctx, int count)
  494. {
  495. APEPredictor *p = &ctx->predictor;
  496. int32_t *decoded0 = ctx->decoded0;
  497. int32_t predictionA, currentA, A, sign;
  498. currentA = p->lastA[0];
  499. while (count--) {
  500. A = *decoded0;
  501. p->buf[YDELAYA] = currentA;
  502. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  503. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  504. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  505. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  506. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  507. currentA = A + (predictionA >> 10);
  508. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  509. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  510. sign = APESIGN(A);
  511. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  512. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  513. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  514. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  515. p->buf++;
  516. /* Have we filled the history buffer? */
  517. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  518. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  519. p->buf = p->historybuffer;
  520. }
  521. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  522. *(decoded0++) = p->filterA[0];
  523. }
  524. p->lastA[0] = currentA;
  525. }
  526. static void do_init_filter(APEFilter *f, int16_t * buf, int order)
  527. {
  528. f->coeffs = buf;
  529. f->historybuffer = buf + order;
  530. f->delay = f->historybuffer + order * 2;
  531. f->adaptcoeffs = f->historybuffer + order;
  532. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  533. memset(f->coeffs, 0, order * sizeof(int16_t));
  534. f->avg = 0;
  535. }
  536. static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
  537. {
  538. do_init_filter(&f[0], buf, order);
  539. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  540. }
  541. static void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
  542. {
  543. int res;
  544. int absres;
  545. while (count--) {
  546. /* round fixedpoint scalar product */
  547. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order, f->adaptcoeffs - order, order, APESIGN(*data));
  548. res = (res + (1 << (fracbits - 1))) >> fracbits;
  549. res += *data;
  550. *data++ = res;
  551. /* Update the output history */
  552. *f->delay++ = av_clip_int16(res);
  553. if (version < 3980) {
  554. /* Version ??? to < 3.98 files (untested) */
  555. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  556. f->adaptcoeffs[-4] >>= 1;
  557. f->adaptcoeffs[-8] >>= 1;
  558. } else {
  559. /* Version 3.98 and later files */
  560. /* Update the adaption coefficients */
  561. absres = FFABS(res);
  562. if (absres)
  563. *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >> (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  564. else
  565. *f->adaptcoeffs = 0;
  566. f->avg += (absres - f->avg) / 16;
  567. f->adaptcoeffs[-1] >>= 1;
  568. f->adaptcoeffs[-2] >>= 1;
  569. f->adaptcoeffs[-8] >>= 1;
  570. }
  571. f->adaptcoeffs++;
  572. /* Have we filled the history buffer? */
  573. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  574. memmove(f->historybuffer, f->delay - (order * 2),
  575. (order * 2) * sizeof(int16_t));
  576. f->delay = f->historybuffer + order * 2;
  577. f->adaptcoeffs = f->historybuffer + order;
  578. }
  579. }
  580. }
  581. static void apply_filter(APEContext * ctx, APEFilter *f,
  582. int32_t * data0, int32_t * data1,
  583. int count, int order, int fracbits)
  584. {
  585. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  586. if (data1)
  587. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  588. }
  589. static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
  590. int32_t * decoded1, int count)
  591. {
  592. int i;
  593. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  594. if (!ape_filter_orders[ctx->fset][i])
  595. break;
  596. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
  597. }
  598. }
  599. static void init_frame_decoder(APEContext * ctx)
  600. {
  601. int i;
  602. init_entropy_decoder(ctx);
  603. init_predictor_decoder(ctx);
  604. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  605. if (!ape_filter_orders[ctx->fset][i])
  606. break;
  607. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
  608. }
  609. }
  610. static void ape_unpack_mono(APEContext * ctx, int count)
  611. {
  612. int32_t left;
  613. int32_t *decoded0 = ctx->decoded0;
  614. int32_t *decoded1 = ctx->decoded1;
  615. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  616. entropy_decode(ctx, count, 0);
  617. /* We are pure silence, so we're done. */
  618. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  619. return;
  620. }
  621. entropy_decode(ctx, count, 0);
  622. ape_apply_filters(ctx, decoded0, NULL, count);
  623. /* Now apply the predictor decoding */
  624. predictor_decode_mono(ctx, count);
  625. /* Pseudo-stereo - just copy left channel to right channel */
  626. if (ctx->channels == 2) {
  627. while (count--) {
  628. left = *decoded0;
  629. *(decoded1++) = *(decoded0++) = left;
  630. }
  631. }
  632. }
  633. static void ape_unpack_stereo(APEContext * ctx, int count)
  634. {
  635. int32_t left, right;
  636. int32_t *decoded0 = ctx->decoded0;
  637. int32_t *decoded1 = ctx->decoded1;
  638. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  639. /* We are pure silence, so we're done. */
  640. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  641. return;
  642. }
  643. entropy_decode(ctx, count, 1);
  644. ape_apply_filters(ctx, decoded0, decoded1, count);
  645. /* Now apply the predictor decoding */
  646. predictor_decode_stereo(ctx, count);
  647. /* Decorrelate and scale to output depth */
  648. while (count--) {
  649. left = *decoded1 - (*decoded0 / 2);
  650. right = left + *decoded0;
  651. *(decoded0++) = left;
  652. *(decoded1++) = right;
  653. }
  654. }
  655. static int ape_decode_frame(AVCodecContext * avctx,
  656. void *data, int *data_size,
  657. AVPacket *avpkt)
  658. {
  659. const uint8_t *buf = avpkt->data;
  660. int buf_size = avpkt->size;
  661. APEContext *s = avctx->priv_data;
  662. int16_t *samples = data;
  663. uint32_t nblocks;
  664. int i, n;
  665. int blockstodecode;
  666. int bytes_used;
  667. if (buf_size == 0 && !s->samples) {
  668. *data_size = 0;
  669. return 0;
  670. }
  671. /* should not happen but who knows */
  672. if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
  673. av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);
  674. return -1;
  675. }
  676. if(!s->samples){
  677. void *tmp_data = av_realloc(s->data, (buf_size + 3) & ~3);
  678. if (!tmp_data)
  679. return AVERROR(ENOMEM);
  680. s->data = tmp_data;
  681. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  682. s->ptr = s->last_ptr = s->data;
  683. s->data_end = s->data + buf_size;
  684. nblocks = bytestream_get_be32(&s->ptr);
  685. n = bytestream_get_be32(&s->ptr);
  686. if(n < 0 || n > 3){
  687. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  688. s->data = NULL;
  689. return -1;
  690. }
  691. s->ptr += n;
  692. buf += 4;
  693. if (!nblocks || nblocks > INT_MAX) {
  694. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  695. *data_size = 0;
  696. return AVERROR_INVALIDDATA;
  697. }
  698. s->currentframeblocks = s->samples = nblocks;
  699. memset(s->decoded0, 0, sizeof(s->decoded0));
  700. memset(s->decoded1, 0, sizeof(s->decoded1));
  701. /* Initialize the frame decoder */
  702. init_frame_decoder(s);
  703. }
  704. if (!s->data) {
  705. *data_size = 0;
  706. return buf_size;
  707. }
  708. nblocks = s->samples;
  709. blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
  710. s->error=0;
  711. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  712. ape_unpack_mono(s, blockstodecode);
  713. else
  714. ape_unpack_stereo(s, blockstodecode);
  715. emms_c();
  716. if(s->error || s->ptr > s->data_end){
  717. s->samples=0;
  718. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  719. return -1;
  720. }
  721. for (i = 0; i < blockstodecode; i++) {
  722. *samples++ = s->decoded0[i];
  723. if(s->channels == 2)
  724. *samples++ = s->decoded1[i];
  725. }
  726. s->samples -= blockstodecode;
  727. *data_size = blockstodecode * 2 * s->channels;
  728. bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
  729. s->last_ptr = s->ptr;
  730. return bytes_used;
  731. }
  732. static void ape_flush(AVCodecContext *avctx)
  733. {
  734. APEContext *s = avctx->priv_data;
  735. s->samples= 0;
  736. }
  737. AVCodec ff_ape_decoder = {
  738. "ape",
  739. AVMEDIA_TYPE_AUDIO,
  740. CODEC_ID_APE,
  741. sizeof(APEContext),
  742. ape_decode_init,
  743. NULL,
  744. ape_decode_close,
  745. ape_decode_frame,
  746. .capabilities = CODEC_CAP_SUBFRAMES,
  747. .flush = ape_flush,
  748. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  749. };