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.

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