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.

979 lines
30KB

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