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