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.

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