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.

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