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.

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