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.

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