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.

937 lines
29KB

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