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.

921 lines
28KB

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