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.

911 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 Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #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 AVERROR(EINVAL);
  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 AVERROR(EINVAL);
  156. }
  157. if (avctx->channels > 2) {
  158. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  159. return AVERROR(EINVAL);
  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",
  167. s->compression_level, s->flags);
  168. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
  169. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  170. s->compression_level);
  171. return AVERROR_INVALIDDATA;
  172. }
  173. s->fset = s->compression_level / 1000 - 1;
  174. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  175. if (!ape_filter_orders[s->fset][i])
  176. break;
  177. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  178. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  179. filter_alloc_fail);
  180. }
  181. dsputil_init(&s->dsp, avctx);
  182. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  183. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  184. return 0;
  185. filter_alloc_fail:
  186. ape_decode_close(avctx);
  187. return AVERROR(ENOMEM);
  188. }
  189. /**
  190. * @name APE range decoding functions
  191. * @{
  192. */
  193. #define CODE_BITS 32
  194. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  195. #define SHIFT_BITS (CODE_BITS - 9)
  196. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  197. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  198. /** Start the decoder */
  199. static inline void range_start_decoding(APEContext *ctx)
  200. {
  201. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  202. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  203. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  204. }
  205. /** Perform normalization */
  206. static inline void range_dec_normalize(APEContext *ctx)
  207. {
  208. while (ctx->rc.range <= BOTTOM_VALUE) {
  209. ctx->rc.buffer <<= 8;
  210. if(ctx->ptr < ctx->data_end)
  211. ctx->rc.buffer += *ctx->ptr;
  212. ctx->ptr++;
  213. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  214. ctx->rc.range <<= 8;
  215. }
  216. }
  217. /**
  218. * Calculate culmulative frequency for next symbol. Does NO update!
  219. * @param ctx decoder context
  220. * @param tot_f is the total frequency or (code_value)1<<shift
  221. * @return the culmulative frequency
  222. */
  223. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  224. {
  225. range_dec_normalize(ctx);
  226. ctx->rc.help = ctx->rc.range / tot_f;
  227. return ctx->rc.low / ctx->rc.help;
  228. }
  229. /**
  230. * Decode value with given size in bits
  231. * @param ctx decoder context
  232. * @param shift number of bits to decode
  233. */
  234. static inline int range_decode_culshift(APEContext *ctx, int shift)
  235. {
  236. range_dec_normalize(ctx);
  237. ctx->rc.help = ctx->rc.range >> shift;
  238. return ctx->rc.low / ctx->rc.help;
  239. }
  240. /**
  241. * Update decoding state
  242. * @param ctx decoder context
  243. * @param sy_f the interval length (frequency of the symbol)
  244. * @param lt_f the lower end (frequency sum of < symbols)
  245. */
  246. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  247. {
  248. ctx->rc.low -= ctx->rc.help * lt_f;
  249. ctx->rc.range = ctx->rc.help * sy_f;
  250. }
  251. /** Decode n bits (n <= 16) without modelling */
  252. static inline int range_decode_bits(APEContext *ctx, int n)
  253. {
  254. int sym = range_decode_culshift(ctx, n);
  255. range_decode_update(ctx, 1, sym);
  256. return sym;
  257. }
  258. #define MODEL_ELEMENTS 64
  259. /**
  260. * Fixed probabilities for symbols in Monkey Audio version 3.97
  261. */
  262. static const uint16_t counts_3970[22] = {
  263. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  264. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  265. 65450, 65469, 65480, 65487, 65491, 65493,
  266. };
  267. /**
  268. * Probability ranges for symbols in Monkey Audio version 3.97
  269. */
  270. static const uint16_t counts_diff_3970[21] = {
  271. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  272. 1104, 677, 415, 248, 150, 89, 54, 31,
  273. 19, 11, 7, 4, 2,
  274. };
  275. /**
  276. * Fixed probabilities for symbols in Monkey Audio version 3.98
  277. */
  278. static const uint16_t counts_3980[22] = {
  279. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  280. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  281. 65485, 65488, 65490, 65491, 65492, 65493,
  282. };
  283. /**
  284. * Probability ranges for symbols in Monkey Audio version 3.98
  285. */
  286. static const uint16_t counts_diff_3980[21] = {
  287. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  288. 261, 119, 65, 31, 19, 10, 6, 3,
  289. 3, 2, 1, 1, 1,
  290. };
  291. /**
  292. * Decode symbol
  293. * @param ctx decoder context
  294. * @param counts probability range start position
  295. * @param counts_diff probability range widths
  296. */
  297. static inline int range_get_symbol(APEContext *ctx,
  298. const uint16_t counts[],
  299. const uint16_t counts_diff[])
  300. {
  301. int symbol, cf;
  302. cf = range_decode_culshift(ctx, 16);
  303. if(cf > 65492){
  304. symbol= cf - 65535 + 63;
  305. range_decode_update(ctx, 1, cf);
  306. if(cf > 65535)
  307. ctx->error=1;
  308. return symbol;
  309. }
  310. /* figure out the symbol inefficiently; a binary search would be much better */
  311. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  312. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  313. return symbol;
  314. }
  315. /** @} */ // group rangecoder
  316. static inline void update_rice(APERice *rice, int x)
  317. {
  318. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  319. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  320. if (rice->ksum < lim)
  321. rice->k--;
  322. else if (rice->ksum >= (1 << (rice->k + 5)))
  323. rice->k++;
  324. }
  325. static inline int ape_decode_value(APEContext *ctx, APERice *rice)
  326. {
  327. int x, overflow;
  328. if (ctx->fileversion < 3990) {
  329. int tmpk;
  330. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  331. if (overflow == (MODEL_ELEMENTS - 1)) {
  332. tmpk = range_decode_bits(ctx, 5);
  333. overflow = 0;
  334. } else
  335. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  336. if (tmpk <= 16)
  337. x = range_decode_bits(ctx, tmpk);
  338. else {
  339. x = range_decode_bits(ctx, 16);
  340. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  341. }
  342. x += overflow << tmpk;
  343. } else {
  344. int base, pivot;
  345. pivot = rice->ksum >> 5;
  346. if (pivot == 0)
  347. pivot = 1;
  348. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  349. if (overflow == (MODEL_ELEMENTS - 1)) {
  350. overflow = range_decode_bits(ctx, 16) << 16;
  351. overflow |= range_decode_bits(ctx, 16);
  352. }
  353. if (pivot < 0x10000) {
  354. base = range_decode_culfreq(ctx, pivot);
  355. range_decode_update(ctx, 1, base);
  356. } else {
  357. int base_hi = pivot, base_lo;
  358. int bbits = 0;
  359. while (base_hi & ~0xFFFF) {
  360. base_hi >>= 1;
  361. bbits++;
  362. }
  363. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  364. range_decode_update(ctx, 1, base_hi);
  365. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  366. range_decode_update(ctx, 1, base_lo);
  367. base = (base_hi << bbits) + base_lo;
  368. }
  369. x = base + overflow * pivot;
  370. }
  371. update_rice(rice, x);
  372. /* Convert to signed */
  373. if (x & 1)
  374. return (x >> 1) + 1;
  375. else
  376. return -(x >> 1);
  377. }
  378. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  379. {
  380. int32_t *decoded0 = ctx->decoded0;
  381. int32_t *decoded1 = ctx->decoded1;
  382. ctx->blocksdecoded = blockstodecode;
  383. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  384. /* We are pure silence, just memset the output buffer. */
  385. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  386. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  387. } else {
  388. while (blockstodecode--) {
  389. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  390. if (stereo)
  391. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  392. }
  393. }
  394. if (ctx->blocksdecoded == ctx->currentframeblocks)
  395. range_dec_normalize(ctx); /* normalize to use up all bytes */
  396. }
  397. static void init_entropy_decoder(APEContext *ctx)
  398. {
  399. /* Read the CRC */
  400. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  401. /* Read the frame flags if they exist */
  402. ctx->frameflags = 0;
  403. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  404. ctx->CRC &= ~0x80000000;
  405. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  406. }
  407. /* Keep a count of the blocks decoded in this frame */
  408. ctx->blocksdecoded = 0;
  409. /* Initialize the rice structs */
  410. ctx->riceX.k = 10;
  411. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  412. ctx->riceY.k = 10;
  413. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  414. /* The first 8 bits of input are ignored. */
  415. ctx->ptr++;
  416. range_start_decoding(ctx);
  417. }
  418. static const int32_t initial_coeffs[4] = {
  419. 360, 317, -109, 98
  420. };
  421. static void init_predictor_decoder(APEContext *ctx)
  422. {
  423. APEPredictor *p = &ctx->predictor;
  424. /* Zero the history buffers */
  425. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
  426. p->buf = p->historybuffer;
  427. /* Initialize and zero the coefficients */
  428. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  429. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  430. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  431. p->filterA[0] = p->filterA[1] = 0;
  432. p->filterB[0] = p->filterB[1] = 0;
  433. p->lastA[0] = p->lastA[1] = 0;
  434. }
  435. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  436. static inline int APESIGN(int32_t x) {
  437. return (x < 0) - (x > 0);
  438. }
  439. static av_always_inline int predictor_update_filter(APEPredictor *p,
  440. const int decoded, const int filter,
  441. const int delayA, const int delayB,
  442. const int adaptA, const int adaptB)
  443. {
  444. int32_t predictionA, predictionB, sign;
  445. p->buf[delayA] = p->lastA[filter];
  446. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  447. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  448. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  449. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  450. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  451. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  452. p->buf[delayA - 3] * p->coeffsA[filter][3];
  453. /* Apply a scaled first-order filter compression */
  454. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  455. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  456. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  457. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  458. p->filterB[filter] = p->filterA[filter ^ 1];
  459. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  460. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  461. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  462. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  463. p->buf[delayB - 4] * p->coeffsB[filter][4];
  464. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  465. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  466. sign = APESIGN(decoded);
  467. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  468. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  469. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  470. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  471. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  472. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  473. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  474. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  475. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  476. return p->filterA[filter];
  477. }
  478. static void predictor_decode_stereo(APEContext *ctx, int count)
  479. {
  480. APEPredictor *p = &ctx->predictor;
  481. int32_t *decoded0 = ctx->decoded0;
  482. int32_t *decoded1 = ctx->decoded1;
  483. while (count--) {
  484. /* Predictor Y */
  485. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  486. YADAPTCOEFFSA, YADAPTCOEFFSB);
  487. decoded0++;
  488. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  489. XADAPTCOEFFSA, XADAPTCOEFFSB);
  490. decoded1++;
  491. /* Combined */
  492. p->buf++;
  493. /* Have we filled the history buffer? */
  494. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  495. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  496. p->buf = p->historybuffer;
  497. }
  498. }
  499. }
  500. static void predictor_decode_mono(APEContext *ctx, int count)
  501. {
  502. APEPredictor *p = &ctx->predictor;
  503. int32_t *decoded0 = ctx->decoded0;
  504. int32_t predictionA, currentA, A, sign;
  505. currentA = p->lastA[0];
  506. while (count--) {
  507. A = *decoded0;
  508. p->buf[YDELAYA] = currentA;
  509. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  510. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  511. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  512. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  513. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  514. currentA = A + (predictionA >> 10);
  515. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  516. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  517. sign = APESIGN(A);
  518. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  519. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  520. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  521. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  522. p->buf++;
  523. /* Have we filled the history buffer? */
  524. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  525. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  526. p->buf = p->historybuffer;
  527. }
  528. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  529. *(decoded0++) = p->filterA[0];
  530. }
  531. p->lastA[0] = currentA;
  532. }
  533. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  534. {
  535. f->coeffs = buf;
  536. f->historybuffer = buf + order;
  537. f->delay = f->historybuffer + order * 2;
  538. f->adaptcoeffs = f->historybuffer + order;
  539. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  540. memset(f->coeffs, 0, order * sizeof(int16_t));
  541. f->avg = 0;
  542. }
  543. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  544. {
  545. do_init_filter(&f[0], buf, order);
  546. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  547. }
  548. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  549. int32_t *data, int count, int order, int fracbits)
  550. {
  551. int res;
  552. int absres;
  553. while (count--) {
  554. /* round fixedpoint scalar product */
  555. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  556. f->adaptcoeffs - order,
  557. order, APESIGN(*data));
  558. res = (res + (1 << (fracbits - 1))) >> fracbits;
  559. res += *data;
  560. *data++ = res;
  561. /* Update the output history */
  562. *f->delay++ = av_clip_int16(res);
  563. if (version < 3980) {
  564. /* Version ??? to < 3.98 files (untested) */
  565. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  566. f->adaptcoeffs[-4] >>= 1;
  567. f->adaptcoeffs[-8] >>= 1;
  568. } else {
  569. /* Version 3.98 and later files */
  570. /* Update the adaption coefficients */
  571. absres = FFABS(res);
  572. if (absres)
  573. *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >>
  574. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  575. else
  576. *f->adaptcoeffs = 0;
  577. f->avg += (absres - f->avg) / 16;
  578. f->adaptcoeffs[-1] >>= 1;
  579. f->adaptcoeffs[-2] >>= 1;
  580. f->adaptcoeffs[-8] >>= 1;
  581. }
  582. f->adaptcoeffs++;
  583. /* Have we filled the history buffer? */
  584. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  585. memmove(f->historybuffer, f->delay - (order * 2),
  586. (order * 2) * sizeof(int16_t));
  587. f->delay = f->historybuffer + order * 2;
  588. f->adaptcoeffs = f->historybuffer + order;
  589. }
  590. }
  591. }
  592. static void apply_filter(APEContext *ctx, APEFilter *f,
  593. int32_t *data0, int32_t *data1,
  594. int count, int order, int fracbits)
  595. {
  596. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  597. if (data1)
  598. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  599. }
  600. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  601. int32_t *decoded1, int count)
  602. {
  603. int i;
  604. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  605. if (!ape_filter_orders[ctx->fset][i])
  606. break;
  607. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  608. ape_filter_orders[ctx->fset][i],
  609. ape_filter_fracbits[ctx->fset][i]);
  610. }
  611. }
  612. static void init_frame_decoder(APEContext *ctx)
  613. {
  614. int i;
  615. init_entropy_decoder(ctx);
  616. init_predictor_decoder(ctx);
  617. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  618. if (!ape_filter_orders[ctx->fset][i])
  619. break;
  620. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  621. ape_filter_orders[ctx->fset][i]);
  622. }
  623. }
  624. static void ape_unpack_mono(APEContext *ctx, int count)
  625. {
  626. int32_t *decoded0 = ctx->decoded0;
  627. int32_t *decoded1 = ctx->decoded1;
  628. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  629. entropy_decode(ctx, count, 0);
  630. /* We are pure silence, so we're done. */
  631. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  632. return;
  633. }
  634. entropy_decode(ctx, count, 0);
  635. ape_apply_filters(ctx, decoded0, NULL, count);
  636. /* Now apply the predictor decoding */
  637. predictor_decode_mono(ctx, count);
  638. /* Pseudo-stereo - just copy left channel to right channel */
  639. if (ctx->channels == 2) {
  640. memcpy(decoded1, decoded0, count * sizeof(*decoded1));
  641. }
  642. }
  643. static void ape_unpack_stereo(APEContext *ctx, int count)
  644. {
  645. int32_t left, right;
  646. int32_t *decoded0 = ctx->decoded0;
  647. int32_t *decoded1 = ctx->decoded1;
  648. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  649. /* We are pure silence, so we're done. */
  650. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  651. return;
  652. }
  653. entropy_decode(ctx, count, 1);
  654. ape_apply_filters(ctx, decoded0, decoded1, count);
  655. /* Now apply the predictor decoding */
  656. predictor_decode_stereo(ctx, count);
  657. /* Decorrelate and scale to output depth */
  658. while (count--) {
  659. left = *decoded1 - (*decoded0 / 2);
  660. right = left + *decoded0;
  661. *(decoded0++) = left;
  662. *(decoded1++) = right;
  663. }
  664. }
  665. static int ape_decode_frame(AVCodecContext *avctx,
  666. void *data, int *data_size,
  667. AVPacket *avpkt)
  668. {
  669. const uint8_t *buf = avpkt->data;
  670. int buf_size = avpkt->size;
  671. APEContext *s = avctx->priv_data;
  672. int16_t *samples = data;
  673. int nblocks;
  674. int i, n;
  675. int blockstodecode;
  676. int bytes_used;
  677. /* should not happen but who knows */
  678. if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
  679. av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled "
  680. "in lavc! (max is %d where you have %d)\n",
  681. *data_size, s->samples * 2 * avctx->channels);
  682. return -1;
  683. }
  684. if(!s->samples){
  685. s->data = av_realloc(s->data, (buf_size + 3) & ~3);
  686. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  687. s->ptr = s->last_ptr = s->data;
  688. s->data_end = s->data + buf_size;
  689. nblocks = s->samples = bytestream_get_be32(&s->ptr);
  690. n = bytestream_get_be32(&s->ptr);
  691. if(n < 0 || n > 3){
  692. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  693. s->data = NULL;
  694. return -1;
  695. }
  696. s->ptr += n;
  697. s->currentframeblocks = nblocks;
  698. buf += 4;
  699. if (s->samples <= 0) {
  700. *data_size = 0;
  701. return buf_size;
  702. }
  703. memset(s->decoded0, 0, sizeof(s->decoded0));
  704. memset(s->decoded1, 0, sizeof(s->decoded1));
  705. /* Initialize the frame decoder */
  706. init_frame_decoder(s);
  707. }
  708. if (!s->data) {
  709. *data_size = 0;
  710. return buf_size;
  711. }
  712. nblocks = s->samples;
  713. blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
  714. s->error=0;
  715. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  716. ape_unpack_mono(s, blockstodecode);
  717. else
  718. ape_unpack_stereo(s, blockstodecode);
  719. emms_c();
  720. if(s->error || s->ptr > s->data_end){
  721. s->samples=0;
  722. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  723. return -1;
  724. }
  725. for (i = 0; i < blockstodecode; i++) {
  726. *samples++ = s->decoded0[i];
  727. if(s->channels == 2)
  728. *samples++ = s->decoded1[i];
  729. }
  730. s->samples -= blockstodecode;
  731. *data_size = blockstodecode * 2 * s->channels;
  732. bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
  733. s->last_ptr = s->ptr;
  734. return bytes_used;
  735. }
  736. static void ape_flush(AVCodecContext *avctx)
  737. {
  738. APEContext *s = avctx->priv_data;
  739. s->samples= 0;
  740. }
  741. AVCodec ff_ape_decoder = {
  742. .name = "ape",
  743. .type = AVMEDIA_TYPE_AUDIO,
  744. .id = CODEC_ID_APE,
  745. .priv_data_size = sizeof(APEContext),
  746. .init = ape_decode_init,
  747. .close = ape_decode_close,
  748. .decode = ape_decode_frame,
  749. .capabilities = CODEC_CAP_SUBFRAMES,
  750. .flush = ape_flush,
  751. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  752. };