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.

899 lines
27KB

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