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.

941 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 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. AVFrame frame;
  112. DSPContext dsp;
  113. int channels;
  114. int samples; ///< samples left to decode in current frame
  115. int fileversion; ///< codec version, very important in decoding process
  116. int compression_level; ///< compression levels
  117. int fset; ///< which filter set to use (calculated from compression level)
  118. int flags; ///< global decoder flags
  119. uint32_t CRC; ///< frame CRC
  120. int frameflags; ///< frame flags
  121. APEPredictor predictor; ///< predictor used for final reconstruction
  122. int32_t decoded0[BLOCKS_PER_LOOP]; ///< decoded data for the first channel
  123. int32_t decoded1[BLOCKS_PER_LOOP]; ///< decoded data for the second channel
  124. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  125. APERangecoder rc; ///< rangecoder used to decode actual values
  126. APERice riceX; ///< rice code parameters for the second channel
  127. APERice riceY; ///< rice code parameters for the first channel
  128. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  129. uint8_t *data; ///< current frame data
  130. uint8_t *data_end; ///< frame data end
  131. const uint8_t *ptr; ///< current position in frame data
  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. avcodec_get_frame_defaults(&s->frame);
  184. avctx->coded_frame = &s->frame;
  185. return 0;
  186. filter_alloc_fail:
  187. ape_decode_close(avctx);
  188. return AVERROR(ENOMEM);
  189. }
  190. /**
  191. * @name APE range decoding functions
  192. * @{
  193. */
  194. #define CODE_BITS 32
  195. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  196. #define SHIFT_BITS (CODE_BITS - 9)
  197. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  198. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  199. /** Start the decoder */
  200. static inline void range_start_decoding(APEContext *ctx)
  201. {
  202. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  203. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  204. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  205. }
  206. /** Perform normalization */
  207. static inline void range_dec_normalize(APEContext *ctx)
  208. {
  209. while (ctx->rc.range <= BOTTOM_VALUE) {
  210. ctx->rc.buffer <<= 8;
  211. if(ctx->ptr < ctx->data_end) {
  212. ctx->rc.buffer += *ctx->ptr;
  213. ctx->ptr++;
  214. } else {
  215. ctx->error = 1;
  216. }
  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 ctx decoder context
  224. * @param tot_f is the total frequency or (code_value)1<<shift
  225. * @return the culmulative frequency
  226. */
  227. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  228. {
  229. range_dec_normalize(ctx);
  230. ctx->rc.help = ctx->rc.range / tot_f;
  231. return ctx->rc.low / ctx->rc.help;
  232. }
  233. /**
  234. * Decode value with given size in bits
  235. * @param ctx decoder context
  236. * @param shift number of bits to decode
  237. */
  238. static inline int range_decode_culshift(APEContext *ctx, int shift)
  239. {
  240. range_dec_normalize(ctx);
  241. ctx->rc.help = ctx->rc.range >> shift;
  242. return ctx->rc.low / ctx->rc.help;
  243. }
  244. /**
  245. * Update decoding state
  246. * @param ctx decoder context
  247. * @param sy_f the interval length (frequency of the symbol)
  248. * @param lt_f the lower end (frequency sum of < symbols)
  249. */
  250. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  251. {
  252. ctx->rc.low -= ctx->rc.help * lt_f;
  253. ctx->rc.range = ctx->rc.help * sy_f;
  254. }
  255. /** Decode n bits (n <= 16) without modelling */
  256. static inline int range_decode_bits(APEContext *ctx, int n)
  257. {
  258. int sym = range_decode_culshift(ctx, n);
  259. range_decode_update(ctx, 1, sym);
  260. return sym;
  261. }
  262. #define MODEL_ELEMENTS 64
  263. /**
  264. * Fixed probabilities for symbols in Monkey Audio version 3.97
  265. */
  266. static const uint16_t counts_3970[22] = {
  267. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  268. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  269. 65450, 65469, 65480, 65487, 65491, 65493,
  270. };
  271. /**
  272. * Probability ranges for symbols in Monkey Audio version 3.97
  273. */
  274. static const uint16_t counts_diff_3970[21] = {
  275. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  276. 1104, 677, 415, 248, 150, 89, 54, 31,
  277. 19, 11, 7, 4, 2,
  278. };
  279. /**
  280. * Fixed probabilities for symbols in Monkey Audio version 3.98
  281. */
  282. static const uint16_t counts_3980[22] = {
  283. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  284. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  285. 65485, 65488, 65490, 65491, 65492, 65493,
  286. };
  287. /**
  288. * Probability ranges for symbols in Monkey Audio version 3.98
  289. */
  290. static const uint16_t counts_diff_3980[21] = {
  291. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  292. 261, 119, 65, 31, 19, 10, 6, 3,
  293. 3, 2, 1, 1, 1,
  294. };
  295. /**
  296. * Decode symbol
  297. * @param ctx decoder context
  298. * @param counts probability range start position
  299. * @param counts_diff probability range widths
  300. */
  301. static inline int range_get_symbol(APEContext *ctx,
  302. const uint16_t counts[],
  303. const uint16_t counts_diff[])
  304. {
  305. int symbol, cf;
  306. cf = range_decode_culshift(ctx, 16);
  307. if(cf > 65492){
  308. symbol= cf - 65535 + 63;
  309. range_decode_update(ctx, 1, cf);
  310. if(cf > 65535)
  311. ctx->error=1;
  312. return symbol;
  313. }
  314. /* figure out the symbol inefficiently; a binary search would be much better */
  315. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  316. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  317. return symbol;
  318. }
  319. /** @} */ // group rangecoder
  320. static inline void update_rice(APERice *rice, int x)
  321. {
  322. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  323. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  324. if (rice->ksum < lim)
  325. rice->k--;
  326. else if (rice->ksum >= (1 << (rice->k + 5)))
  327. rice->k++;
  328. }
  329. static inline int ape_decode_value(APEContext *ctx, APERice *rice)
  330. {
  331. int x, overflow;
  332. if (ctx->fileversion < 3990) {
  333. int tmpk;
  334. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  335. if (overflow == (MODEL_ELEMENTS - 1)) {
  336. tmpk = range_decode_bits(ctx, 5);
  337. overflow = 0;
  338. } else
  339. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  340. if (tmpk <= 16)
  341. x = range_decode_bits(ctx, tmpk);
  342. else {
  343. x = range_decode_bits(ctx, 16);
  344. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  345. }
  346. x += overflow << tmpk;
  347. } else {
  348. int base, pivot;
  349. pivot = rice->ksum >> 5;
  350. if (pivot == 0)
  351. pivot = 1;
  352. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  353. if (overflow == (MODEL_ELEMENTS - 1)) {
  354. overflow = range_decode_bits(ctx, 16) << 16;
  355. overflow |= range_decode_bits(ctx, 16);
  356. }
  357. if (pivot < 0x10000) {
  358. base = range_decode_culfreq(ctx, pivot);
  359. range_decode_update(ctx, 1, base);
  360. } else {
  361. int base_hi = pivot, base_lo;
  362. int bbits = 0;
  363. while (base_hi & ~0xFFFF) {
  364. base_hi >>= 1;
  365. bbits++;
  366. }
  367. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  368. range_decode_update(ctx, 1, base_hi);
  369. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  370. range_decode_update(ctx, 1, base_lo);
  371. base = (base_hi << bbits) + base_lo;
  372. }
  373. x = base + overflow * pivot;
  374. }
  375. update_rice(rice, x);
  376. /* Convert to signed */
  377. if (x & 1)
  378. return (x >> 1) + 1;
  379. else
  380. return -(x >> 1);
  381. }
  382. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  383. {
  384. int32_t *decoded0 = ctx->decoded0;
  385. int32_t *decoded1 = ctx->decoded1;
  386. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  387. /* We are pure silence, just memset the output buffer. */
  388. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  389. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  390. } else {
  391. while (blockstodecode--) {
  392. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  393. if (stereo)
  394. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  395. }
  396. }
  397. }
  398. static int init_entropy_decoder(APEContext *ctx)
  399. {
  400. /* Read the CRC */
  401. if (ctx->data_end - ctx->ptr < 6)
  402. return AVERROR_INVALIDDATA;
  403. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  404. /* Read the frame flags if they exist */
  405. ctx->frameflags = 0;
  406. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  407. ctx->CRC &= ~0x80000000;
  408. if (ctx->data_end - ctx->ptr < 6)
  409. return AVERROR_INVALIDDATA;
  410. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  411. }
  412. /* Initialize the rice structs */
  413. ctx->riceX.k = 10;
  414. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  415. ctx->riceY.k = 10;
  416. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  417. /* The first 8 bits of input are ignored. */
  418. ctx->ptr++;
  419. range_start_decoding(ctx);
  420. return 0;
  421. }
  422. static const int32_t initial_coeffs[4] = {
  423. 360, 317, -109, 98
  424. };
  425. static void init_predictor_decoder(APEContext *ctx)
  426. {
  427. APEPredictor *p = &ctx->predictor;
  428. /* Zero the history buffers */
  429. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
  430. p->buf = p->historybuffer;
  431. /* Initialize and zero the coefficients */
  432. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  433. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  434. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  435. p->filterA[0] = p->filterA[1] = 0;
  436. p->filterB[0] = p->filterB[1] = 0;
  437. p->lastA[0] = p->lastA[1] = 0;
  438. }
  439. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  440. static inline int APESIGN(int32_t x) {
  441. return (x < 0) - (x > 0);
  442. }
  443. static av_always_inline int predictor_update_filter(APEPredictor *p,
  444. const int decoded, const int filter,
  445. const int delayA, const int delayB,
  446. const int adaptA, const int adaptB)
  447. {
  448. int32_t predictionA, predictionB, sign;
  449. p->buf[delayA] = p->lastA[filter];
  450. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  451. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  452. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  453. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  454. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  455. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  456. p->buf[delayA - 3] * p->coeffsA[filter][3];
  457. /* Apply a scaled first-order filter compression */
  458. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  459. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  460. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  461. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  462. p->filterB[filter] = p->filterA[filter ^ 1];
  463. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  464. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  465. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  466. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  467. p->buf[delayB - 4] * p->coeffsB[filter][4];
  468. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  469. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  470. sign = APESIGN(decoded);
  471. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  472. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  473. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  474. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  475. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  476. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  477. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  478. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  479. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  480. return p->filterA[filter];
  481. }
  482. static void predictor_decode_stereo(APEContext *ctx, int count)
  483. {
  484. APEPredictor *p = &ctx->predictor;
  485. int32_t *decoded0 = ctx->decoded0;
  486. int32_t *decoded1 = ctx->decoded1;
  487. while (count--) {
  488. /* Predictor Y */
  489. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  490. YADAPTCOEFFSA, YADAPTCOEFFSB);
  491. decoded0++;
  492. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  493. XADAPTCOEFFSA, XADAPTCOEFFSB);
  494. decoded1++;
  495. /* Combined */
  496. p->buf++;
  497. /* Have we filled the history buffer? */
  498. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  499. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  500. p->buf = p->historybuffer;
  501. }
  502. }
  503. }
  504. static void predictor_decode_mono(APEContext *ctx, int count)
  505. {
  506. APEPredictor *p = &ctx->predictor;
  507. int32_t *decoded0 = ctx->decoded0;
  508. int32_t predictionA, currentA, A, sign;
  509. currentA = p->lastA[0];
  510. while (count--) {
  511. A = *decoded0;
  512. p->buf[YDELAYA] = currentA;
  513. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  514. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  515. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  516. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  517. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  518. currentA = A + (predictionA >> 10);
  519. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  520. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  521. sign = APESIGN(A);
  522. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  523. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  524. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  525. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  526. p->buf++;
  527. /* Have we filled the history buffer? */
  528. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  529. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  530. p->buf = p->historybuffer;
  531. }
  532. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  533. *(decoded0++) = p->filterA[0];
  534. }
  535. p->lastA[0] = currentA;
  536. }
  537. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  538. {
  539. f->coeffs = buf;
  540. f->historybuffer = buf + order;
  541. f->delay = f->historybuffer + order * 2;
  542. f->adaptcoeffs = f->historybuffer + order;
  543. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  544. memset(f->coeffs, 0, order * sizeof(int16_t));
  545. f->avg = 0;
  546. }
  547. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  548. {
  549. do_init_filter(&f[0], buf, order);
  550. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  551. }
  552. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  553. int32_t *data, int count, int order, int fracbits)
  554. {
  555. int res;
  556. int absres;
  557. while (count--) {
  558. /* round fixedpoint scalar product */
  559. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  560. f->adaptcoeffs - order,
  561. order, APESIGN(*data));
  562. res = (res + (1 << (fracbits - 1))) >> fracbits;
  563. res += *data;
  564. *data++ = res;
  565. /* Update the output history */
  566. *f->delay++ = av_clip_int16(res);
  567. if (version < 3980) {
  568. /* Version ??? to < 3.98 files (untested) */
  569. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  570. f->adaptcoeffs[-4] >>= 1;
  571. f->adaptcoeffs[-8] >>= 1;
  572. } else {
  573. /* Version 3.98 and later files */
  574. /* Update the adaption coefficients */
  575. absres = FFABS(res);
  576. if (absres)
  577. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  578. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  579. else
  580. *f->adaptcoeffs = 0;
  581. f->avg += (absres - f->avg) / 16;
  582. f->adaptcoeffs[-1] >>= 1;
  583. f->adaptcoeffs[-2] >>= 1;
  584. f->adaptcoeffs[-8] >>= 1;
  585. }
  586. f->adaptcoeffs++;
  587. /* Have we filled the history buffer? */
  588. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  589. memmove(f->historybuffer, f->delay - (order * 2),
  590. (order * 2) * sizeof(int16_t));
  591. f->delay = f->historybuffer + order * 2;
  592. f->adaptcoeffs = f->historybuffer + order;
  593. }
  594. }
  595. }
  596. static void apply_filter(APEContext *ctx, APEFilter *f,
  597. int32_t *data0, int32_t *data1,
  598. int count, int order, int fracbits)
  599. {
  600. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  601. if (data1)
  602. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  603. }
  604. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  605. int32_t *decoded1, int count)
  606. {
  607. int i;
  608. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  609. if (!ape_filter_orders[ctx->fset][i])
  610. break;
  611. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  612. ape_filter_orders[ctx->fset][i],
  613. ape_filter_fracbits[ctx->fset][i]);
  614. }
  615. }
  616. static int init_frame_decoder(APEContext *ctx)
  617. {
  618. int i, ret;
  619. if ((ret = init_entropy_decoder(ctx)) < 0)
  620. return ret;
  621. init_predictor_decoder(ctx);
  622. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  623. if (!ape_filter_orders[ctx->fset][i])
  624. break;
  625. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  626. ape_filter_orders[ctx->fset][i]);
  627. }
  628. return 0;
  629. }
  630. static void ape_unpack_mono(APEContext *ctx, int count)
  631. {
  632. int32_t *decoded0 = ctx->decoded0;
  633. int32_t *decoded1 = ctx->decoded1;
  634. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  635. entropy_decode(ctx, count, 0);
  636. /* We are pure silence, so we're done. */
  637. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  638. return;
  639. }
  640. entropy_decode(ctx, count, 0);
  641. ape_apply_filters(ctx, decoded0, NULL, count);
  642. /* Now apply the predictor decoding */
  643. predictor_decode_mono(ctx, count);
  644. /* Pseudo-stereo - just copy left channel to right channel */
  645. if (ctx->channels == 2) {
  646. memcpy(decoded1, decoded0, count * sizeof(*decoded1));
  647. }
  648. }
  649. static void ape_unpack_stereo(APEContext *ctx, int count)
  650. {
  651. int32_t left, right;
  652. int32_t *decoded0 = ctx->decoded0;
  653. int32_t *decoded1 = ctx->decoded1;
  654. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  655. /* We are pure silence, so we're done. */
  656. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  657. return;
  658. }
  659. entropy_decode(ctx, count, 1);
  660. ape_apply_filters(ctx, decoded0, decoded1, count);
  661. /* Now apply the predictor decoding */
  662. predictor_decode_stereo(ctx, count);
  663. /* Decorrelate and scale to output depth */
  664. while (count--) {
  665. left = *decoded1 - (*decoded0 / 2);
  666. right = left + *decoded0;
  667. *(decoded0++) = left;
  668. *(decoded1++) = right;
  669. }
  670. }
  671. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  672. int *got_frame_ptr, AVPacket *avpkt)
  673. {
  674. const uint8_t *buf = avpkt->data;
  675. int buf_size = avpkt->size;
  676. APEContext *s = avctx->priv_data;
  677. int16_t *samples;
  678. int i, ret;
  679. int blockstodecode;
  680. int bytes_used = 0;
  681. /* this should never be negative, but bad things will happen if it is, so
  682. check it just to make sure. */
  683. av_assert0(s->samples >= 0);
  684. if(!s->samples){
  685. uint32_t nblocks, offset;
  686. void *tmp_data;
  687. if (!buf_size) {
  688. *got_frame_ptr = 0;
  689. return 0;
  690. }
  691. if (buf_size < 8) {
  692. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  693. return AVERROR_INVALIDDATA;
  694. }
  695. tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
  696. if (!tmp_data)
  697. return AVERROR(ENOMEM);
  698. s->data = tmp_data;
  699. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  700. s->ptr = s->data;
  701. s->data_end = s->data + buf_size;
  702. nblocks = bytestream_get_be32(&s->ptr);
  703. offset = bytestream_get_be32(&s->ptr);
  704. if (offset > 3) {
  705. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  706. s->data = NULL;
  707. return AVERROR_INVALIDDATA;
  708. }
  709. if (s->data_end - s->ptr < offset) {
  710. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  711. return AVERROR_INVALIDDATA;
  712. }
  713. s->ptr += offset;
  714. if (!nblocks || nblocks > INT_MAX) {
  715. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  716. return AVERROR_INVALIDDATA;
  717. }
  718. s->samples = nblocks;
  719. memset(s->decoded0, 0, sizeof(s->decoded0));
  720. memset(s->decoded1, 0, sizeof(s->decoded1));
  721. /* Initialize the frame decoder */
  722. if (init_frame_decoder(s) < 0) {
  723. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  724. return AVERROR_INVALIDDATA;
  725. }
  726. bytes_used = buf_size;
  727. }
  728. if (!s->data) {
  729. *got_frame_ptr = 0;
  730. return buf_size;
  731. }
  732. blockstodecode = FFMIN(BLOCKS_PER_LOOP, s->samples);
  733. /* get output buffer */
  734. s->frame.nb_samples = blockstodecode;
  735. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  736. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  737. return ret;
  738. }
  739. samples = (int16_t *)s->frame.data[0];
  740. s->error=0;
  741. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  742. ape_unpack_mono(s, blockstodecode);
  743. else
  744. ape_unpack_stereo(s, blockstodecode);
  745. emms_c();
  746. if (s->error) {
  747. s->samples=0;
  748. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  749. return AVERROR_INVALIDDATA;
  750. }
  751. for (i = 0; i < blockstodecode; i++) {
  752. *samples++ = s->decoded0[i];
  753. if(s->channels == 2)
  754. *samples++ = s->decoded1[i];
  755. }
  756. s->samples -= blockstodecode;
  757. *got_frame_ptr = 1;
  758. *(AVFrame *)data = s->frame;
  759. return bytes_used;
  760. }
  761. static void ape_flush(AVCodecContext *avctx)
  762. {
  763. APEContext *s = avctx->priv_data;
  764. s->samples= 0;
  765. }
  766. AVCodec ff_ape_decoder = {
  767. .name = "ape",
  768. .type = AVMEDIA_TYPE_AUDIO,
  769. .id = CODEC_ID_APE,
  770. .priv_data_size = sizeof(APEContext),
  771. .init = ape_decode_init,
  772. .close = ape_decode_close,
  773. .decode = ape_decode_frame,
  774. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  775. .flush = ape_flush,
  776. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  777. };