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.

932 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 Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #define ALT_BITSTREAM_READER_LE
  23. #include "avcodec.h"
  24. #include "dsputil.h"
  25. #include "get_bits.h"
  26. #include "bytestream.h"
  27. #include "libavutil/audioconvert.h"
  28. #include "libavutil/avassert.h"
  29. /**
  30. * @file
  31. * Monkey's Audio lossless audio decoder
  32. */
  33. #define BLOCKS_PER_LOOP 4608
  34. #define MAX_CHANNELS 2
  35. #define MAX_BYTESPERSAMPLE 3
  36. #define APE_FRAMECODE_MONO_SILENCE 1
  37. #define APE_FRAMECODE_STEREO_SILENCE 3
  38. #define APE_FRAMECODE_PSEUDO_STEREO 4
  39. #define HISTORY_SIZE 512
  40. #define PREDICTOR_ORDER 8
  41. /** Total size of all predictor histories */
  42. #define PREDICTOR_SIZE 50
  43. #define YDELAYA (18 + PREDICTOR_ORDER*4)
  44. #define YDELAYB (18 + PREDICTOR_ORDER*3)
  45. #define XDELAYA (18 + PREDICTOR_ORDER*2)
  46. #define XDELAYB (18 + PREDICTOR_ORDER)
  47. #define YADAPTCOEFFSA 18
  48. #define XADAPTCOEFFSA 14
  49. #define YADAPTCOEFFSB 10
  50. #define XADAPTCOEFFSB 5
  51. /**
  52. * Possible compression levels
  53. * @{
  54. */
  55. enum APECompressionLevel {
  56. COMPRESSION_LEVEL_FAST = 1000,
  57. COMPRESSION_LEVEL_NORMAL = 2000,
  58. COMPRESSION_LEVEL_HIGH = 3000,
  59. COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
  60. COMPRESSION_LEVEL_INSANE = 5000
  61. };
  62. /** @} */
  63. #define APE_FILTER_LEVELS 3
  64. /** Filter orders depending on compression level */
  65. static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
  66. { 0, 0, 0 },
  67. { 16, 0, 0 },
  68. { 64, 0, 0 },
  69. { 32, 256, 0 },
  70. { 16, 256, 1280 }
  71. };
  72. /** Filter fraction bits depending on compression level */
  73. static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
  74. { 0, 0, 0 },
  75. { 11, 0, 0 },
  76. { 11, 0, 0 },
  77. { 10, 13, 0 },
  78. { 11, 13, 15 }
  79. };
  80. /** Filters applied to the decoded data */
  81. typedef struct APEFilter {
  82. int16_t *coeffs; ///< actual coefficients used in filtering
  83. int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
  84. int16_t *historybuffer; ///< filter memory
  85. int16_t *delay; ///< filtered values
  86. int avg;
  87. } APEFilter;
  88. typedef struct APERice {
  89. uint32_t k;
  90. uint32_t ksum;
  91. } APERice;
  92. typedef struct APERangecoder {
  93. uint32_t low; ///< low end of interval
  94. uint32_t range; ///< length of interval
  95. uint32_t help; ///< bytes_to_follow resp. intermediate value
  96. unsigned int buffer; ///< buffer for input/output
  97. } APERangecoder;
  98. /** Filter histories */
  99. typedef struct APEPredictor {
  100. int32_t *buf;
  101. int32_t lastA[2];
  102. int32_t filterA[2];
  103. int32_t filterB[2];
  104. int32_t coeffsA[2][4]; ///< adaption coefficients
  105. int32_t coeffsB[2][5]; ///< adaption coefficients
  106. int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
  107. } APEPredictor;
  108. /** Decoder context */
  109. typedef struct APEContext {
  110. AVCodecContext *avctx;
  111. DSPContext dsp;
  112. int channels;
  113. int samples; ///< samples left to decode in current frame
  114. int fileversion; ///< codec version, very important in decoding process
  115. int compression_level; ///< compression levels
  116. int fset; ///< which filter set to use (calculated from compression level)
  117. int flags; ///< global decoder flags
  118. uint32_t CRC; ///< frame CRC
  119. int frameflags; ///< frame flags
  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_close(AVCodecContext *avctx)
  136. {
  137. APEContext *s = avctx->priv_data;
  138. int i;
  139. for (i = 0; i < APE_FILTER_LEVELS; i++)
  140. av_freep(&s->filterbuf[i]);
  141. av_freep(&s->data);
  142. return 0;
  143. }
  144. static av_cold int ape_decode_init(AVCodecContext *avctx)
  145. {
  146. APEContext *s = avctx->priv_data;
  147. int i;
  148. if (avctx->extradata_size != 6) {
  149. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  150. return AVERROR(EINVAL);
  151. }
  152. if (avctx->bits_per_coded_sample != 16) {
  153. av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
  154. return AVERROR(EINVAL);
  155. }
  156. if (avctx->channels > 2) {
  157. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  158. return AVERROR(EINVAL);
  159. }
  160. s->avctx = avctx;
  161. s->channels = avctx->channels;
  162. s->fileversion = AV_RL16(avctx->extradata);
  163. s->compression_level = AV_RL16(avctx->extradata + 2);
  164. s->flags = AV_RL16(avctx->extradata + 4);
  165. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
  166. s->compression_level, s->flags);
  167. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
  168. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  169. s->compression_level);
  170. return AVERROR_INVALIDDATA;
  171. }
  172. s->fset = s->compression_level / 1000 - 1;
  173. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  174. if (!ape_filter_orders[s->fset][i])
  175. break;
  176. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  177. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  178. filter_alloc_fail);
  179. }
  180. dsputil_init(&s->dsp, avctx);
  181. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  182. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  183. return 0;
  184. filter_alloc_fail:
  185. ape_decode_close(avctx);
  186. return AVERROR(ENOMEM);
  187. }
  188. /**
  189. * @name APE range decoding functions
  190. * @{
  191. */
  192. #define CODE_BITS 32
  193. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  194. #define SHIFT_BITS (CODE_BITS - 9)
  195. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  196. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  197. /** Start the decoder */
  198. static inline void range_start_decoding(APEContext *ctx)
  199. {
  200. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  201. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  202. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  203. }
  204. /** Perform normalization */
  205. static inline void range_dec_normalize(APEContext *ctx)
  206. {
  207. while (ctx->rc.range <= BOTTOM_VALUE) {
  208. ctx->rc.buffer <<= 8;
  209. if(ctx->ptr < ctx->data_end) {
  210. ctx->rc.buffer += *ctx->ptr;
  211. ctx->ptr++;
  212. } else {
  213. ctx->error = 1;
  214. }
  215. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  216. ctx->rc.range <<= 8;
  217. }
  218. }
  219. /**
  220. * Calculate culmulative frequency for next symbol. Does NO update!
  221. * @param ctx decoder context
  222. * @param tot_f is the total frequency or (code_value)1<<shift
  223. * @return the culmulative frequency
  224. */
  225. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  226. {
  227. range_dec_normalize(ctx);
  228. ctx->rc.help = ctx->rc.range / tot_f;
  229. return ctx->rc.low / ctx->rc.help;
  230. }
  231. /**
  232. * Decode value with given size in bits
  233. * @param ctx decoder context
  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 ctx decoder context
  245. * @param sy_f the interval length (frequency of the symbol)
  246. * @param lt_f the lower end (frequency sum of < symbols)
  247. */
  248. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  249. {
  250. ctx->rc.low -= ctx->rc.help * lt_f;
  251. ctx->rc.range = ctx->rc.help * sy_f;
  252. }
  253. /** Decode n bits (n <= 16) without modelling */
  254. static inline int range_decode_bits(APEContext *ctx, int n)
  255. {
  256. int sym = range_decode_culshift(ctx, n);
  257. range_decode_update(ctx, 1, sym);
  258. return sym;
  259. }
  260. #define MODEL_ELEMENTS 64
  261. /**
  262. * Fixed probabilities for symbols in Monkey Audio version 3.97
  263. */
  264. static const uint16_t counts_3970[22] = {
  265. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  266. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  267. 65450, 65469, 65480, 65487, 65491, 65493,
  268. };
  269. /**
  270. * Probability ranges for symbols in Monkey Audio version 3.97
  271. */
  272. static const uint16_t counts_diff_3970[21] = {
  273. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  274. 1104, 677, 415, 248, 150, 89, 54, 31,
  275. 19, 11, 7, 4, 2,
  276. };
  277. /**
  278. * Fixed probabilities for symbols in Monkey Audio version 3.98
  279. */
  280. static const uint16_t counts_3980[22] = {
  281. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  282. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  283. 65485, 65488, 65490, 65491, 65492, 65493,
  284. };
  285. /**
  286. * Probability ranges for symbols in Monkey Audio version 3.98
  287. */
  288. static const uint16_t counts_diff_3980[21] = {
  289. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  290. 261, 119, 65, 31, 19, 10, 6, 3,
  291. 3, 2, 1, 1, 1,
  292. };
  293. /**
  294. * Decode symbol
  295. * @param ctx decoder context
  296. * @param counts probability range start position
  297. * @param counts_diff probability range widths
  298. */
  299. static inline int range_get_symbol(APEContext *ctx,
  300. const uint16_t counts[],
  301. const uint16_t counts_diff[])
  302. {
  303. int symbol, cf;
  304. cf = range_decode_culshift(ctx, 16);
  305. if(cf > 65492){
  306. symbol= cf - 65535 + 63;
  307. range_decode_update(ctx, 1, cf);
  308. if(cf > 65535)
  309. ctx->error=1;
  310. return symbol;
  311. }
  312. /* figure out the symbol inefficiently; a binary search would be much better */
  313. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  314. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  315. return symbol;
  316. }
  317. /** @} */ // group rangecoder
  318. static inline void update_rice(APERice *rice, int x)
  319. {
  320. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  321. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  322. if (rice->ksum < lim)
  323. rice->k--;
  324. else if (rice->ksum >= (1 << (rice->k + 5)))
  325. rice->k++;
  326. }
  327. static inline int ape_decode_value(APEContext *ctx, APERice *rice)
  328. {
  329. int x, overflow;
  330. if (ctx->fileversion < 3990) {
  331. int tmpk;
  332. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  333. if (overflow == (MODEL_ELEMENTS - 1)) {
  334. tmpk = range_decode_bits(ctx, 5);
  335. overflow = 0;
  336. } else
  337. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  338. if (tmpk <= 16)
  339. x = range_decode_bits(ctx, tmpk);
  340. else {
  341. x = range_decode_bits(ctx, 16);
  342. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  343. }
  344. x += overflow << tmpk;
  345. } else {
  346. int base, pivot;
  347. pivot = rice->ksum >> 5;
  348. if (pivot == 0)
  349. pivot = 1;
  350. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  351. if (overflow == (MODEL_ELEMENTS - 1)) {
  352. overflow = range_decode_bits(ctx, 16) << 16;
  353. overflow |= range_decode_bits(ctx, 16);
  354. }
  355. if (pivot < 0x10000) {
  356. base = range_decode_culfreq(ctx, pivot);
  357. range_decode_update(ctx, 1, base);
  358. } else {
  359. int base_hi = pivot, base_lo;
  360. int bbits = 0;
  361. while (base_hi & ~0xFFFF) {
  362. base_hi >>= 1;
  363. bbits++;
  364. }
  365. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  366. range_decode_update(ctx, 1, base_hi);
  367. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  368. range_decode_update(ctx, 1, base_lo);
  369. base = (base_hi << bbits) + base_lo;
  370. }
  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. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  385. /* We are pure silence, just memset the output buffer. */
  386. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  387. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  388. } else {
  389. while (blockstodecode--) {
  390. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  391. if (stereo)
  392. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  393. }
  394. }
  395. }
  396. static int init_entropy_decoder(APEContext *ctx)
  397. {
  398. /* Read the CRC */
  399. if (ctx->data_end - ctx->ptr < 6)
  400. return AVERROR_INVALIDDATA;
  401. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  402. /* Read the frame flags if they exist */
  403. ctx->frameflags = 0;
  404. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  405. ctx->CRC &= ~0x80000000;
  406. if (ctx->data_end - ctx->ptr < 6)
  407. return AVERROR_INVALIDDATA;
  408. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  409. }
  410. /* Initialize the rice structs */
  411. ctx->riceX.k = 10;
  412. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  413. ctx->riceY.k = 10;
  414. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  415. /* The first 8 bits of input are ignored. */
  416. ctx->ptr++;
  417. range_start_decoding(ctx);
  418. return 0;
  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 av_always_inline int predictor_update_filter(APEPredictor *p,
  442. const int decoded, const int filter,
  443. const int delayA, const int delayB,
  444. const int adaptA, const int adaptB)
  445. {
  446. int32_t predictionA, predictionB, sign;
  447. p->buf[delayA] = p->lastA[filter];
  448. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  449. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  450. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  451. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  452. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  453. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  454. p->buf[delayA - 3] * p->coeffsA[filter][3];
  455. /* Apply a scaled first-order filter compression */
  456. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  457. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  458. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  459. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  460. p->filterB[filter] = p->filterA[filter ^ 1];
  461. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  462. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  463. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  464. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  465. p->buf[delayB - 4] * p->coeffsB[filter][4];
  466. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  467. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  468. sign = APESIGN(decoded);
  469. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  470. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  471. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  472. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  473. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  474. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  475. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  476. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  477. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  478. return p->filterA[filter];
  479. }
  480. static void predictor_decode_stereo(APEContext *ctx, int count)
  481. {
  482. APEPredictor *p = &ctx->predictor;
  483. int32_t *decoded0 = ctx->decoded0;
  484. int32_t *decoded1 = ctx->decoded1;
  485. while (count--) {
  486. /* Predictor Y */
  487. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  488. YADAPTCOEFFSA, YADAPTCOEFFSB);
  489. decoded0++;
  490. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  491. XADAPTCOEFFSA, XADAPTCOEFFSB);
  492. decoded1++;
  493. /* Combined */
  494. p->buf++;
  495. /* Have we filled the history buffer? */
  496. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  497. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  498. p->buf = p->historybuffer;
  499. }
  500. }
  501. }
  502. static void predictor_decode_mono(APEContext *ctx, int count)
  503. {
  504. APEPredictor *p = &ctx->predictor;
  505. int32_t *decoded0 = ctx->decoded0;
  506. int32_t predictionA, currentA, A, sign;
  507. currentA = p->lastA[0];
  508. while (count--) {
  509. A = *decoded0;
  510. p->buf[YDELAYA] = currentA;
  511. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  512. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  513. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  514. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  515. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  516. currentA = A + (predictionA >> 10);
  517. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  518. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  519. sign = APESIGN(A);
  520. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  521. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  522. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  523. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  524. p->buf++;
  525. /* Have we filled the history buffer? */
  526. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  527. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  528. p->buf = p->historybuffer;
  529. }
  530. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  531. *(decoded0++) = p->filterA[0];
  532. }
  533. p->lastA[0] = currentA;
  534. }
  535. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  536. {
  537. f->coeffs = buf;
  538. f->historybuffer = buf + order;
  539. f->delay = f->historybuffer + order * 2;
  540. f->adaptcoeffs = f->historybuffer + order;
  541. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  542. memset(f->coeffs, 0, order * sizeof(int16_t));
  543. f->avg = 0;
  544. }
  545. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  546. {
  547. do_init_filter(&f[0], buf, order);
  548. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  549. }
  550. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  551. int32_t *data, int count, int order, int fracbits)
  552. {
  553. int res;
  554. int absres;
  555. while (count--) {
  556. /* round fixedpoint scalar product */
  557. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  558. f->adaptcoeffs - order,
  559. order, APESIGN(*data));
  560. res = (res + (1 << (fracbits - 1))) >> fracbits;
  561. res += *data;
  562. *data++ = res;
  563. /* Update the output history */
  564. *f->delay++ = av_clip_int16(res);
  565. if (version < 3980) {
  566. /* Version ??? to < 3.98 files (untested) */
  567. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  568. f->adaptcoeffs[-4] >>= 1;
  569. f->adaptcoeffs[-8] >>= 1;
  570. } else {
  571. /* Version 3.98 and later files */
  572. /* Update the adaption coefficients */
  573. absres = FFABS(res);
  574. if (absres)
  575. *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >>
  576. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  577. else
  578. *f->adaptcoeffs = 0;
  579. f->avg += (absres - f->avg) / 16;
  580. f->adaptcoeffs[-1] >>= 1;
  581. f->adaptcoeffs[-2] >>= 1;
  582. f->adaptcoeffs[-8] >>= 1;
  583. }
  584. f->adaptcoeffs++;
  585. /* Have we filled the history buffer? */
  586. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  587. memmove(f->historybuffer, f->delay - (order * 2),
  588. (order * 2) * sizeof(int16_t));
  589. f->delay = f->historybuffer + order * 2;
  590. f->adaptcoeffs = f->historybuffer + order;
  591. }
  592. }
  593. }
  594. static void apply_filter(APEContext *ctx, APEFilter *f,
  595. int32_t *data0, int32_t *data1,
  596. int count, int order, int fracbits)
  597. {
  598. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  599. if (data1)
  600. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  601. }
  602. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  603. int32_t *decoded1, int count)
  604. {
  605. int i;
  606. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  607. if (!ape_filter_orders[ctx->fset][i])
  608. break;
  609. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  610. ape_filter_orders[ctx->fset][i],
  611. ape_filter_fracbits[ctx->fset][i]);
  612. }
  613. }
  614. static int init_frame_decoder(APEContext *ctx)
  615. {
  616. int i, ret;
  617. if ((ret = init_entropy_decoder(ctx)) < 0)
  618. return ret;
  619. init_predictor_decoder(ctx);
  620. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  621. if (!ape_filter_orders[ctx->fset][i])
  622. break;
  623. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  624. ape_filter_orders[ctx->fset][i]);
  625. }
  626. return 0;
  627. }
  628. static void ape_unpack_mono(APEContext *ctx, int count)
  629. {
  630. int32_t *decoded0 = ctx->decoded0;
  631. int32_t *decoded1 = ctx->decoded1;
  632. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  633. entropy_decode(ctx, count, 0);
  634. /* We are pure silence, so we're done. */
  635. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  636. return;
  637. }
  638. entropy_decode(ctx, count, 0);
  639. ape_apply_filters(ctx, decoded0, NULL, count);
  640. /* Now apply the predictor decoding */
  641. predictor_decode_mono(ctx, count);
  642. /* Pseudo-stereo - just copy left channel to right channel */
  643. if (ctx->channels == 2) {
  644. memcpy(decoded1, decoded0, count * sizeof(*decoded1));
  645. }
  646. }
  647. static void ape_unpack_stereo(APEContext *ctx, int count)
  648. {
  649. int32_t left, right;
  650. int32_t *decoded0 = ctx->decoded0;
  651. int32_t *decoded1 = ctx->decoded1;
  652. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  653. /* We are pure silence, so we're done. */
  654. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  655. return;
  656. }
  657. entropy_decode(ctx, count, 1);
  658. ape_apply_filters(ctx, decoded0, decoded1, count);
  659. /* Now apply the predictor decoding */
  660. predictor_decode_stereo(ctx, count);
  661. /* Decorrelate and scale to output depth */
  662. while (count--) {
  663. left = *decoded1 - (*decoded0 / 2);
  664. right = left + *decoded0;
  665. *(decoded0++) = left;
  666. *(decoded1++) = right;
  667. }
  668. }
  669. static int ape_decode_frame(AVCodecContext *avctx,
  670. void *data, int *data_size,
  671. AVPacket *avpkt)
  672. {
  673. const uint8_t *buf = avpkt->data;
  674. int buf_size = avpkt->size;
  675. APEContext *s = avctx->priv_data;
  676. int16_t *samples = data;
  677. int i;
  678. int blockstodecode, out_size;
  679. int bytes_used;
  680. /* this should never be negative, but bad things will happen if it is, so
  681. check it just to make sure. */
  682. av_assert0(s->samples >= 0);
  683. if(!s->samples){
  684. uint32_t nblocks, offset;
  685. void *tmp_data;
  686. if (buf_size < 8) {
  687. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  688. return AVERROR_INVALIDDATA;
  689. }
  690. tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
  691. if (!tmp_data)
  692. return AVERROR(ENOMEM);
  693. s->data = tmp_data;
  694. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  695. s->ptr = s->last_ptr = s->data;
  696. s->data_end = s->data + buf_size;
  697. nblocks = bytestream_get_be32(&s->ptr);
  698. offset = bytestream_get_be32(&s->ptr);
  699. if (offset > 3) {
  700. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  701. s->data = NULL;
  702. return AVERROR_INVALIDDATA;
  703. }
  704. if (s->data_end - s->ptr < offset) {
  705. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  706. return AVERROR_INVALIDDATA;
  707. }
  708. s->ptr += offset;
  709. if (!nblocks || nblocks > INT_MAX) {
  710. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  711. return AVERROR_INVALIDDATA;
  712. }
  713. s->samples = nblocks;
  714. memset(s->decoded0, 0, sizeof(s->decoded0));
  715. memset(s->decoded1, 0, sizeof(s->decoded1));
  716. /* Initialize the frame decoder */
  717. if (init_frame_decoder(s) < 0) {
  718. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  719. return AVERROR_INVALIDDATA;
  720. }
  721. }
  722. if (!s->data) {
  723. *data_size = 0;
  724. return buf_size;
  725. }
  726. blockstodecode = FFMIN(BLOCKS_PER_LOOP, s->samples);
  727. out_size = blockstodecode * avctx->channels *
  728. av_get_bytes_per_sample(avctx->sample_fmt);
  729. if (*data_size < out_size) {
  730. av_log(avctx, AV_LOG_ERROR, "Output buffer is too small.\n");
  731. return AVERROR(EINVAL);
  732. }
  733. s->error=0;
  734. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  735. ape_unpack_mono(s, blockstodecode);
  736. else
  737. ape_unpack_stereo(s, blockstodecode);
  738. emms_c();
  739. if (s->error) {
  740. s->samples=0;
  741. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  742. return AVERROR_INVALIDDATA;
  743. }
  744. for (i = 0; i < blockstodecode; i++) {
  745. *samples++ = s->decoded0[i];
  746. if(s->channels == 2)
  747. *samples++ = s->decoded1[i];
  748. }
  749. s->samples -= blockstodecode;
  750. bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
  751. s->last_ptr = s->ptr;
  752. *data_size = out_size;
  753. return bytes_used;
  754. }
  755. static void ape_flush(AVCodecContext *avctx)
  756. {
  757. APEContext *s = avctx->priv_data;
  758. s->samples= 0;
  759. }
  760. AVCodec ff_ape_decoder = {
  761. .name = "ape",
  762. .type = AVMEDIA_TYPE_AUDIO,
  763. .id = CODEC_ID_APE,
  764. .priv_data_size = sizeof(APEContext),
  765. .init = ape_decode_init,
  766. .close = ape_decode_close,
  767. .decode = ape_decode_frame,
  768. .capabilities = CODEC_CAP_SUBFRAMES,
  769. .flush = ape_flush,
  770. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  771. };