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.

944 lines
29KB

  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 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 if (tmpk <= 32) {
  343. x = range_decode_bits(ctx, 16);
  344. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  345. } else {
  346. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  347. return AVERROR_INVALIDDATA;
  348. }
  349. x += overflow << tmpk;
  350. } else {
  351. int base, pivot;
  352. pivot = rice->ksum >> 5;
  353. if (pivot == 0)
  354. pivot = 1;
  355. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  356. if (overflow == (MODEL_ELEMENTS - 1)) {
  357. overflow = range_decode_bits(ctx, 16) << 16;
  358. overflow |= range_decode_bits(ctx, 16);
  359. }
  360. if (pivot < 0x10000) {
  361. base = range_decode_culfreq(ctx, pivot);
  362. range_decode_update(ctx, 1, base);
  363. } else {
  364. int base_hi = pivot, base_lo;
  365. int bbits = 0;
  366. while (base_hi & ~0xFFFF) {
  367. base_hi >>= 1;
  368. bbits++;
  369. }
  370. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  371. range_decode_update(ctx, 1, base_hi);
  372. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  373. range_decode_update(ctx, 1, base_lo);
  374. base = (base_hi << bbits) + base_lo;
  375. }
  376. x = base + overflow * pivot;
  377. }
  378. update_rice(rice, x);
  379. /* Convert to signed */
  380. if (x & 1)
  381. return (x >> 1) + 1;
  382. else
  383. return -(x >> 1);
  384. }
  385. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  386. {
  387. int32_t *decoded0 = ctx->decoded0;
  388. int32_t *decoded1 = ctx->decoded1;
  389. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  390. /* We are pure silence, just memset the output buffer. */
  391. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  392. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  393. } else {
  394. while (blockstodecode--) {
  395. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  396. if (stereo)
  397. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  398. }
  399. }
  400. }
  401. static int init_entropy_decoder(APEContext *ctx)
  402. {
  403. /* Read the CRC */
  404. if (ctx->data_end - ctx->ptr < 6)
  405. return AVERROR_INVALIDDATA;
  406. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  407. /* Read the frame flags if they exist */
  408. ctx->frameflags = 0;
  409. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  410. ctx->CRC &= ~0x80000000;
  411. if (ctx->data_end - ctx->ptr < 6)
  412. return AVERROR_INVALIDDATA;
  413. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  414. }
  415. /* Initialize the rice structs */
  416. ctx->riceX.k = 10;
  417. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  418. ctx->riceY.k = 10;
  419. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  420. /* The first 8 bits of input are ignored. */
  421. ctx->ptr++;
  422. range_start_decoding(ctx);
  423. return 0;
  424. }
  425. static const int32_t initial_coeffs[4] = {
  426. 360, 317, -109, 98
  427. };
  428. static void init_predictor_decoder(APEContext *ctx)
  429. {
  430. APEPredictor *p = &ctx->predictor;
  431. /* Zero the history buffers */
  432. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
  433. p->buf = p->historybuffer;
  434. /* Initialize and zero the coefficients */
  435. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  436. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  437. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  438. p->filterA[0] = p->filterA[1] = 0;
  439. p->filterB[0] = p->filterB[1] = 0;
  440. p->lastA[0] = p->lastA[1] = 0;
  441. }
  442. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  443. static inline int APESIGN(int32_t x) {
  444. return (x < 0) - (x > 0);
  445. }
  446. static av_always_inline int predictor_update_filter(APEPredictor *p,
  447. const int decoded, const int filter,
  448. const int delayA, const int delayB,
  449. const int adaptA, const int adaptB)
  450. {
  451. int32_t predictionA, predictionB, sign;
  452. p->buf[delayA] = p->lastA[filter];
  453. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  454. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  455. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  456. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  457. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  458. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  459. p->buf[delayA - 3] * p->coeffsA[filter][3];
  460. /* Apply a scaled first-order filter compression */
  461. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  462. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  463. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  464. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  465. p->filterB[filter] = p->filterA[filter ^ 1];
  466. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  467. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  468. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  469. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  470. p->buf[delayB - 4] * p->coeffsB[filter][4];
  471. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  472. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  473. sign = APESIGN(decoded);
  474. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  475. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  476. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  477. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  478. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  479. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  480. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  481. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  482. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  483. return p->filterA[filter];
  484. }
  485. static void predictor_decode_stereo(APEContext *ctx, int count)
  486. {
  487. APEPredictor *p = &ctx->predictor;
  488. int32_t *decoded0 = ctx->decoded0;
  489. int32_t *decoded1 = ctx->decoded1;
  490. while (count--) {
  491. /* Predictor Y */
  492. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  493. YADAPTCOEFFSA, YADAPTCOEFFSB);
  494. decoded0++;
  495. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  496. XADAPTCOEFFSA, XADAPTCOEFFSB);
  497. decoded1++;
  498. /* Combined */
  499. p->buf++;
  500. /* Have we filled the history buffer? */
  501. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  502. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  503. p->buf = p->historybuffer;
  504. }
  505. }
  506. }
  507. static void predictor_decode_mono(APEContext *ctx, int count)
  508. {
  509. APEPredictor *p = &ctx->predictor;
  510. int32_t *decoded0 = ctx->decoded0;
  511. int32_t predictionA, currentA, A, sign;
  512. currentA = p->lastA[0];
  513. while (count--) {
  514. A = *decoded0;
  515. p->buf[YDELAYA] = currentA;
  516. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  517. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  518. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  519. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  520. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  521. currentA = A + (predictionA >> 10);
  522. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  523. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  524. sign = APESIGN(A);
  525. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  526. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  527. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  528. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  529. p->buf++;
  530. /* Have we filled the history buffer? */
  531. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  532. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  533. p->buf = p->historybuffer;
  534. }
  535. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  536. *(decoded0++) = p->filterA[0];
  537. }
  538. p->lastA[0] = currentA;
  539. }
  540. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  541. {
  542. f->coeffs = buf;
  543. f->historybuffer = buf + order;
  544. f->delay = f->historybuffer + order * 2;
  545. f->adaptcoeffs = f->historybuffer + order;
  546. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  547. memset(f->coeffs, 0, order * sizeof(int16_t));
  548. f->avg = 0;
  549. }
  550. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  551. {
  552. do_init_filter(&f[0], buf, order);
  553. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  554. }
  555. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  556. int32_t *data, int count, int order, int fracbits)
  557. {
  558. int res;
  559. int absres;
  560. while (count--) {
  561. /* round fixedpoint scalar product */
  562. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  563. f->adaptcoeffs - order,
  564. order, APESIGN(*data));
  565. res = (res + (1 << (fracbits - 1))) >> fracbits;
  566. res += *data;
  567. *data++ = res;
  568. /* Update the output history */
  569. *f->delay++ = av_clip_int16(res);
  570. if (version < 3980) {
  571. /* Version ??? to < 3.98 files (untested) */
  572. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  573. f->adaptcoeffs[-4] >>= 1;
  574. f->adaptcoeffs[-8] >>= 1;
  575. } else {
  576. /* Version 3.98 and later files */
  577. /* Update the adaption coefficients */
  578. absres = FFABS(res);
  579. if (absres)
  580. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  581. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  582. else
  583. *f->adaptcoeffs = 0;
  584. f->avg += (absres - f->avg) / 16;
  585. f->adaptcoeffs[-1] >>= 1;
  586. f->adaptcoeffs[-2] >>= 1;
  587. f->adaptcoeffs[-8] >>= 1;
  588. }
  589. f->adaptcoeffs++;
  590. /* Have we filled the history buffer? */
  591. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  592. memmove(f->historybuffer, f->delay - (order * 2),
  593. (order * 2) * sizeof(int16_t));
  594. f->delay = f->historybuffer + order * 2;
  595. f->adaptcoeffs = f->historybuffer + order;
  596. }
  597. }
  598. }
  599. static void apply_filter(APEContext *ctx, APEFilter *f,
  600. int32_t *data0, int32_t *data1,
  601. int count, int order, int fracbits)
  602. {
  603. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  604. if (data1)
  605. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  606. }
  607. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  608. int32_t *decoded1, int count)
  609. {
  610. int i;
  611. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  612. if (!ape_filter_orders[ctx->fset][i])
  613. break;
  614. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  615. ape_filter_orders[ctx->fset][i],
  616. ape_filter_fracbits[ctx->fset][i]);
  617. }
  618. }
  619. static int init_frame_decoder(APEContext *ctx)
  620. {
  621. int i, ret;
  622. if ((ret = init_entropy_decoder(ctx)) < 0)
  623. return ret;
  624. init_predictor_decoder(ctx);
  625. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  626. if (!ape_filter_orders[ctx->fset][i])
  627. break;
  628. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  629. ape_filter_orders[ctx->fset][i]);
  630. }
  631. return 0;
  632. }
  633. static void ape_unpack_mono(APEContext *ctx, int count)
  634. {
  635. int32_t *decoded0 = ctx->decoded0;
  636. int32_t *decoded1 = ctx->decoded1;
  637. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  638. entropy_decode(ctx, count, 0);
  639. /* We are pure silence, so we're done. */
  640. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  641. return;
  642. }
  643. entropy_decode(ctx, count, 0);
  644. ape_apply_filters(ctx, decoded0, NULL, count);
  645. /* Now apply the predictor decoding */
  646. predictor_decode_mono(ctx, count);
  647. /* Pseudo-stereo - just copy left channel to right channel */
  648. if (ctx->channels == 2) {
  649. memcpy(decoded1, decoded0, count * sizeof(*decoded1));
  650. }
  651. }
  652. static void ape_unpack_stereo(APEContext *ctx, int count)
  653. {
  654. int32_t left, right;
  655. int32_t *decoded0 = ctx->decoded0;
  656. int32_t *decoded1 = ctx->decoded1;
  657. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  658. /* We are pure silence, so we're done. */
  659. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  660. return;
  661. }
  662. entropy_decode(ctx, count, 1);
  663. ape_apply_filters(ctx, decoded0, decoded1, count);
  664. /* Now apply the predictor decoding */
  665. predictor_decode_stereo(ctx, count);
  666. /* Decorrelate and scale to output depth */
  667. while (count--) {
  668. left = *decoded1 - (*decoded0 / 2);
  669. right = left + *decoded0;
  670. *(decoded0++) = left;
  671. *(decoded1++) = right;
  672. }
  673. }
  674. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  675. int *got_frame_ptr, AVPacket *avpkt)
  676. {
  677. const uint8_t *buf = avpkt->data;
  678. int buf_size = avpkt->size;
  679. APEContext *s = avctx->priv_data;
  680. int16_t *samples;
  681. int i, ret;
  682. int blockstodecode;
  683. int bytes_used = 0;
  684. /* this should never be negative, but bad things will happen if it is, so
  685. check it just to make sure. */
  686. av_assert0(s->samples >= 0);
  687. if(!s->samples){
  688. uint32_t nblocks, offset;
  689. void *tmp_data;
  690. if (!buf_size) {
  691. *got_frame_ptr = 0;
  692. return 0;
  693. }
  694. if (buf_size < 8) {
  695. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  696. return AVERROR_INVALIDDATA;
  697. }
  698. tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
  699. if (!tmp_data)
  700. return AVERROR(ENOMEM);
  701. s->data = tmp_data;
  702. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  703. s->ptr = s->data;
  704. s->data_end = s->data + buf_size;
  705. nblocks = bytestream_get_be32(&s->ptr);
  706. offset = bytestream_get_be32(&s->ptr);
  707. if (offset > 3) {
  708. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  709. s->data = NULL;
  710. return AVERROR_INVALIDDATA;
  711. }
  712. if (s->data_end - s->ptr < offset) {
  713. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  714. return AVERROR_INVALIDDATA;
  715. }
  716. s->ptr += offset;
  717. if (!nblocks || nblocks > INT_MAX) {
  718. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  719. return AVERROR_INVALIDDATA;
  720. }
  721. s->samples = nblocks;
  722. memset(s->decoded0, 0, sizeof(s->decoded0));
  723. memset(s->decoded1, 0, sizeof(s->decoded1));
  724. /* Initialize the frame decoder */
  725. if (init_frame_decoder(s) < 0) {
  726. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  727. return AVERROR_INVALIDDATA;
  728. }
  729. bytes_used = buf_size;
  730. }
  731. if (!s->data) {
  732. *got_frame_ptr = 0;
  733. return buf_size;
  734. }
  735. blockstodecode = FFMIN(BLOCKS_PER_LOOP, s->samples);
  736. /* get output buffer */
  737. s->frame.nb_samples = blockstodecode;
  738. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  739. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  740. return ret;
  741. }
  742. samples = (int16_t *)s->frame.data[0];
  743. s->error=0;
  744. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  745. ape_unpack_mono(s, blockstodecode);
  746. else
  747. ape_unpack_stereo(s, blockstodecode);
  748. emms_c();
  749. if (s->error) {
  750. s->samples=0;
  751. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  752. return AVERROR_INVALIDDATA;
  753. }
  754. for (i = 0; i < blockstodecode; i++) {
  755. *samples++ = s->decoded0[i];
  756. if(s->channels == 2)
  757. *samples++ = s->decoded1[i];
  758. }
  759. s->samples -= blockstodecode;
  760. *got_frame_ptr = 1;
  761. *(AVFrame *)data = s->frame;
  762. return bytes_used;
  763. }
  764. static void ape_flush(AVCodecContext *avctx)
  765. {
  766. APEContext *s = avctx->priv_data;
  767. s->samples= 0;
  768. }
  769. AVCodec ff_ape_decoder = {
  770. .name = "ape",
  771. .type = AVMEDIA_TYPE_AUDIO,
  772. .id = CODEC_ID_APE,
  773. .priv_data_size = sizeof(APEContext),
  774. .init = ape_decode_init,
  775. .close = ape_decode_close,
  776. .decode = ape_decode_frame,
  777. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  778. .flush = ape_flush,
  779. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  780. };