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