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.

999 lines
31KB

  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 "libavutil/avassert.h"
  23. #include "libavutil/channel_layout.h"
  24. #include "libavutil/opt.h"
  25. #include "avcodec.h"
  26. #include "dsputil.h"
  27. #include "bytestream.h"
  28. #include "internal.h"
  29. /**
  30. * @file
  31. * Monkey's Audio lossless audio decoder
  32. */
  33. #define MAX_CHANNELS 2
  34. #define MAX_BYTESPERSAMPLE 3
  35. #define APE_FRAMECODE_MONO_SILENCE 1
  36. #define APE_FRAMECODE_STEREO_SILENCE 3
  37. #define APE_FRAMECODE_PSEUDO_STEREO 4
  38. #define HISTORY_SIZE 512
  39. #define PREDICTOR_ORDER 8
  40. /** Total size of all predictor histories */
  41. #define PREDICTOR_SIZE 50
  42. #define YDELAYA (18 + PREDICTOR_ORDER*4)
  43. #define YDELAYB (18 + PREDICTOR_ORDER*3)
  44. #define XDELAYA (18 + PREDICTOR_ORDER*2)
  45. #define XDELAYB (18 + PREDICTOR_ORDER)
  46. #define YADAPTCOEFFSA 18
  47. #define XADAPTCOEFFSA 14
  48. #define YADAPTCOEFFSB 10
  49. #define XADAPTCOEFFSB 5
  50. /**
  51. * Possible compression levels
  52. * @{
  53. */
  54. enum APECompressionLevel {
  55. COMPRESSION_LEVEL_FAST = 1000,
  56. COMPRESSION_LEVEL_NORMAL = 2000,
  57. COMPRESSION_LEVEL_HIGH = 3000,
  58. COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
  59. COMPRESSION_LEVEL_INSANE = 5000
  60. };
  61. /** @} */
  62. #define APE_FILTER_LEVELS 3
  63. /** Filter orders depending on compression level */
  64. static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
  65. { 0, 0, 0 },
  66. { 16, 0, 0 },
  67. { 64, 0, 0 },
  68. { 32, 256, 0 },
  69. { 16, 256, 1280 }
  70. };
  71. /** Filter fraction bits depending on compression level */
  72. static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
  73. { 0, 0, 0 },
  74. { 11, 0, 0 },
  75. { 11, 0, 0 },
  76. { 10, 13, 0 },
  77. { 11, 13, 15 }
  78. };
  79. /** Filters applied to the decoded data */
  80. typedef struct APEFilter {
  81. int16_t *coeffs; ///< actual coefficients used in filtering
  82. int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
  83. int16_t *historybuffer; ///< filter memory
  84. int16_t *delay; ///< filtered values
  85. int avg;
  86. } APEFilter;
  87. typedef struct APERice {
  88. uint32_t k;
  89. uint32_t ksum;
  90. } APERice;
  91. typedef struct APERangecoder {
  92. uint32_t low; ///< low end of interval
  93. uint32_t range; ///< length of interval
  94. uint32_t help; ///< bytes_to_follow resp. intermediate value
  95. unsigned int buffer; ///< buffer for input/output
  96. } APERangecoder;
  97. /** Filter histories */
  98. typedef struct APEPredictor {
  99. int32_t *buf;
  100. int32_t lastA[2];
  101. int32_t filterA[2];
  102. int32_t filterB[2];
  103. int32_t coeffsA[2][4]; ///< adaption coefficients
  104. int32_t coeffsB[2][5]; ///< adaption coefficients
  105. int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
  106. } APEPredictor;
  107. /** Decoder context */
  108. typedef struct APEContext {
  109. AVClass *class; ///< class for AVOptions
  110. AVCodecContext *avctx;
  111. AVFrame frame;
  112. DSPContext dsp;
  113. int channels;
  114. int samples; ///< samples left to decode in current frame
  115. int bps;
  116. int fileversion; ///< codec version, very important in decoding process
  117. int compression_level; ///< compression levels
  118. int fset; ///< which filter set to use (calculated from compression level)
  119. int flags; ///< global decoder flags
  120. uint32_t CRC; ///< frame CRC
  121. int frameflags; ///< frame flags
  122. APEPredictor predictor; ///< predictor used for final reconstruction
  123. int32_t *decoded_buffer;
  124. int decoded_size;
  125. int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
  126. int blocks_per_loop; ///< maximum number of samples to decode for each call
  127. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  128. APERangecoder rc; ///< rangecoder used to decode actual values
  129. APERice riceX; ///< rice code parameters for the second channel
  130. APERice riceY; ///< rice code parameters for the first channel
  131. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  132. uint8_t *data; ///< current frame data
  133. uint8_t *data_end; ///< frame data end
  134. int data_size; ///< frame data allocated size
  135. const uint8_t *ptr; ///< current position in frame data
  136. int error;
  137. } APEContext;
  138. // TODO: dsputilize
  139. static av_cold int ape_decode_close(AVCodecContext *avctx)
  140. {
  141. APEContext *s = avctx->priv_data;
  142. int i;
  143. for (i = 0; i < APE_FILTER_LEVELS; i++)
  144. av_freep(&s->filterbuf[i]);
  145. av_freep(&s->decoded_buffer);
  146. av_freep(&s->data);
  147. s->decoded_size = s->data_size = 0;
  148. return 0;
  149. }
  150. static av_cold int ape_decode_init(AVCodecContext *avctx)
  151. {
  152. APEContext *s = avctx->priv_data;
  153. int i;
  154. if (avctx->extradata_size != 6) {
  155. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\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->bps = avctx->bits_per_coded_sample;
  163. switch (s->bps) {
  164. case 8:
  165. avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
  166. break;
  167. case 16:
  168. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  169. break;
  170. case 24:
  171. avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  172. break;
  173. default:
  174. av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",
  175. s->bps);
  176. return AVERROR_PATCHWELCOME;
  177. }
  178. s->avctx = avctx;
  179. s->channels = avctx->channels;
  180. s->fileversion = AV_RL16(avctx->extradata);
  181. s->compression_level = AV_RL16(avctx->extradata + 2);
  182. s->flags = AV_RL16(avctx->extradata + 4);
  183. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
  184. s->compression_level, s->flags);
  185. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE || !s->compression_level) {
  186. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  187. s->compression_level);
  188. return AVERROR_INVALIDDATA;
  189. }
  190. s->fset = s->compression_level / 1000 - 1;
  191. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  192. if (!ape_filter_orders[s->fset][i])
  193. break;
  194. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  195. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  196. filter_alloc_fail);
  197. }
  198. ff_dsputil_init(&s->dsp, avctx);
  199. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  200. avcodec_get_frame_defaults(&s->frame);
  201. avctx->coded_frame = &s->frame;
  202. return 0;
  203. filter_alloc_fail:
  204. ape_decode_close(avctx);
  205. return AVERROR(ENOMEM);
  206. }
  207. /**
  208. * @name APE range decoding functions
  209. * @{
  210. */
  211. #define CODE_BITS 32
  212. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  213. #define SHIFT_BITS (CODE_BITS - 9)
  214. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  215. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  216. /** Start the decoder */
  217. static inline void range_start_decoding(APEContext *ctx)
  218. {
  219. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  220. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  221. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  222. }
  223. /** Perform normalization */
  224. static inline void range_dec_normalize(APEContext *ctx)
  225. {
  226. while (ctx->rc.range <= BOTTOM_VALUE) {
  227. ctx->rc.buffer <<= 8;
  228. if(ctx->ptr < ctx->data_end) {
  229. ctx->rc.buffer += *ctx->ptr;
  230. ctx->ptr++;
  231. } else {
  232. ctx->error = 1;
  233. }
  234. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  235. ctx->rc.range <<= 8;
  236. }
  237. }
  238. /**
  239. * Calculate culmulative frequency for next symbol. Does NO update!
  240. * @param ctx decoder context
  241. * @param tot_f is the total frequency or (code_value)1<<shift
  242. * @return the culmulative frequency
  243. */
  244. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  245. {
  246. range_dec_normalize(ctx);
  247. ctx->rc.help = ctx->rc.range / tot_f;
  248. return ctx->rc.low / ctx->rc.help;
  249. }
  250. /**
  251. * Decode value with given size in bits
  252. * @param ctx decoder context
  253. * @param shift number of bits to decode
  254. */
  255. static inline int range_decode_culshift(APEContext *ctx, int shift)
  256. {
  257. range_dec_normalize(ctx);
  258. ctx->rc.help = ctx->rc.range >> shift;
  259. return ctx->rc.low / ctx->rc.help;
  260. }
  261. /**
  262. * Update decoding state
  263. * @param ctx decoder context
  264. * @param sy_f the interval length (frequency of the symbol)
  265. * @param lt_f the lower end (frequency sum of < symbols)
  266. */
  267. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  268. {
  269. ctx->rc.low -= ctx->rc.help * lt_f;
  270. ctx->rc.range = ctx->rc.help * sy_f;
  271. }
  272. /** Decode n bits (n <= 16) without modelling */
  273. static inline int range_decode_bits(APEContext *ctx, int n)
  274. {
  275. int sym = range_decode_culshift(ctx, n);
  276. range_decode_update(ctx, 1, sym);
  277. return sym;
  278. }
  279. #define MODEL_ELEMENTS 64
  280. /**
  281. * Fixed probabilities for symbols in Monkey Audio version 3.97
  282. */
  283. static const uint16_t counts_3970[22] = {
  284. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  285. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  286. 65450, 65469, 65480, 65487, 65491, 65493,
  287. };
  288. /**
  289. * Probability ranges for symbols in Monkey Audio version 3.97
  290. */
  291. static const uint16_t counts_diff_3970[21] = {
  292. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  293. 1104, 677, 415, 248, 150, 89, 54, 31,
  294. 19, 11, 7, 4, 2,
  295. };
  296. /**
  297. * Fixed probabilities for symbols in Monkey Audio version 3.98
  298. */
  299. static const uint16_t counts_3980[22] = {
  300. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  301. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  302. 65485, 65488, 65490, 65491, 65492, 65493,
  303. };
  304. /**
  305. * Probability ranges for symbols in Monkey Audio version 3.98
  306. */
  307. static const uint16_t counts_diff_3980[21] = {
  308. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  309. 261, 119, 65, 31, 19, 10, 6, 3,
  310. 3, 2, 1, 1, 1,
  311. };
  312. /**
  313. * Decode symbol
  314. * @param ctx decoder context
  315. * @param counts probability range start position
  316. * @param counts_diff probability range widths
  317. */
  318. static inline int range_get_symbol(APEContext *ctx,
  319. const uint16_t counts[],
  320. const uint16_t counts_diff[])
  321. {
  322. int symbol, cf;
  323. cf = range_decode_culshift(ctx, 16);
  324. if(cf > 65492){
  325. symbol= cf - 65535 + 63;
  326. range_decode_update(ctx, 1, cf);
  327. if(cf > 65535)
  328. ctx->error=1;
  329. return symbol;
  330. }
  331. /* figure out the symbol inefficiently; a binary search would be much better */
  332. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  333. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  334. return symbol;
  335. }
  336. /** @} */ // group rangecoder
  337. static inline void update_rice(APERice *rice, unsigned int x)
  338. {
  339. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  340. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  341. if (rice->ksum < lim)
  342. rice->k--;
  343. else if (rice->ksum >= (1 << (rice->k + 5)))
  344. rice->k++;
  345. }
  346. static inline int ape_decode_value(APEContext *ctx, APERice *rice)
  347. {
  348. unsigned int x, overflow;
  349. if (ctx->fileversion < 3990) {
  350. int tmpk;
  351. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  352. if (overflow == (MODEL_ELEMENTS - 1)) {
  353. tmpk = range_decode_bits(ctx, 5);
  354. overflow = 0;
  355. } else
  356. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  357. if (tmpk <= 16)
  358. x = range_decode_bits(ctx, tmpk);
  359. else if (tmpk <= 32) {
  360. x = range_decode_bits(ctx, 16);
  361. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  362. } else {
  363. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  364. return AVERROR_INVALIDDATA;
  365. }
  366. x += overflow << tmpk;
  367. } else {
  368. int base, pivot;
  369. pivot = rice->ksum >> 5;
  370. if (pivot == 0)
  371. pivot = 1;
  372. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  373. if (overflow == (MODEL_ELEMENTS - 1)) {
  374. overflow = range_decode_bits(ctx, 16) << 16;
  375. overflow |= range_decode_bits(ctx, 16);
  376. }
  377. if (pivot < 0x10000) {
  378. base = range_decode_culfreq(ctx, pivot);
  379. range_decode_update(ctx, 1, base);
  380. } else {
  381. int base_hi = pivot, base_lo;
  382. int bbits = 0;
  383. while (base_hi & ~0xFFFF) {
  384. base_hi >>= 1;
  385. bbits++;
  386. }
  387. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  388. range_decode_update(ctx, 1, base_hi);
  389. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  390. range_decode_update(ctx, 1, base_lo);
  391. base = (base_hi << bbits) + base_lo;
  392. }
  393. x = base + overflow * pivot;
  394. }
  395. update_rice(rice, x);
  396. /* Convert to signed */
  397. if (x & 1)
  398. return (x >> 1) + 1;
  399. else
  400. return -(x >> 1);
  401. }
  402. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  403. {
  404. int32_t *decoded0 = ctx->decoded[0];
  405. int32_t *decoded1 = ctx->decoded[1];
  406. while (blockstodecode--) {
  407. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  408. if (stereo)
  409. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  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. /* We are pure silence, so we're done. */
  650. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  651. return;
  652. }
  653. entropy_decode(ctx, count, 0);
  654. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  655. /* Now apply the predictor decoding */
  656. predictor_decode_mono(ctx, count);
  657. /* Pseudo-stereo - just copy left channel to right channel */
  658. if (ctx->channels == 2) {
  659. memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
  660. }
  661. }
  662. static void ape_unpack_stereo(APEContext *ctx, int count)
  663. {
  664. int32_t left, right;
  665. int32_t *decoded0 = ctx->decoded[0];
  666. int32_t *decoded1 = ctx->decoded[1];
  667. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  668. /* We are pure silence, so we're done. */
  669. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  670. return;
  671. }
  672. entropy_decode(ctx, count, 1);
  673. ape_apply_filters(ctx, decoded0, decoded1, count);
  674. /* Now apply the predictor decoding */
  675. predictor_decode_stereo(ctx, count);
  676. /* Decorrelate and scale to output depth */
  677. while (count--) {
  678. left = *decoded1 - (*decoded0 / 2);
  679. right = left + *decoded0;
  680. *(decoded0++) = left;
  681. *(decoded1++) = right;
  682. }
  683. }
  684. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  685. int *got_frame_ptr, AVPacket *avpkt)
  686. {
  687. const uint8_t *buf = avpkt->data;
  688. APEContext *s = avctx->priv_data;
  689. uint8_t *sample8;
  690. int16_t *sample16;
  691. int32_t *sample24;
  692. int i, ch, ret;
  693. int blockstodecode;
  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. /* Initialize the frame decoder */
  737. if (init_frame_decoder(s) < 0) {
  738. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  739. return AVERROR_INVALIDDATA;
  740. }
  741. }
  742. if (!s->data) {
  743. *got_frame_ptr = 0;
  744. return avpkt->size;
  745. }
  746. blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
  747. /* reallocate decoded sample buffer if needed */
  748. av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
  749. 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
  750. if (!s->decoded_buffer)
  751. return AVERROR(ENOMEM);
  752. memset(s->decoded_buffer, 0, s->decoded_size);
  753. s->decoded[0] = s->decoded_buffer;
  754. s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
  755. /* get output buffer */
  756. s->frame.nb_samples = blockstodecode;
  757. if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
  758. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  759. return ret;
  760. }
  761. s->error=0;
  762. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  763. ape_unpack_mono(s, blockstodecode);
  764. else
  765. ape_unpack_stereo(s, blockstodecode);
  766. emms_c();
  767. if (s->error) {
  768. s->samples=0;
  769. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  770. return AVERROR_INVALIDDATA;
  771. }
  772. switch (s->bps) {
  773. case 8:
  774. for (ch = 0; ch < s->channels; ch++) {
  775. sample8 = (uint8_t *)s->frame.data[ch];
  776. for (i = 0; i < blockstodecode; i++)
  777. *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
  778. }
  779. break;
  780. case 16:
  781. for (ch = 0; ch < s->channels; ch++) {
  782. sample16 = (int16_t *)s->frame.data[ch];
  783. for (i = 0; i < blockstodecode; i++)
  784. *sample16++ = s->decoded[ch][i];
  785. }
  786. break;
  787. case 24:
  788. for (ch = 0; ch < s->channels; ch++) {
  789. sample24 = (int32_t *)s->frame.data[ch];
  790. for (i = 0; i < blockstodecode; i++)
  791. *sample24++ = s->decoded[ch][i] << 8;
  792. }
  793. break;
  794. }
  795. s->samples -= blockstodecode;
  796. *got_frame_ptr = 1;
  797. *(AVFrame *)data = s->frame;
  798. return !s->samples ? avpkt->size : 0;
  799. }
  800. static void ape_flush(AVCodecContext *avctx)
  801. {
  802. APEContext *s = avctx->priv_data;
  803. s->samples= 0;
  804. }
  805. #define OFFSET(x) offsetof(APEContext, x)
  806. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  807. static const AVOption options[] = {
  808. { "max_samples", "maximum number of samples decoded per call", OFFSET(blocks_per_loop), AV_OPT_TYPE_INT, { .i64 = 4608 }, 1, INT_MAX, PAR, "max_samples" },
  809. { "all", "no maximum. decode all samples for each packet at once", 0, AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
  810. { NULL},
  811. };
  812. static const AVClass ape_decoder_class = {
  813. .class_name = "APE decoder",
  814. .item_name = av_default_item_name,
  815. .option = options,
  816. .version = LIBAVUTIL_VERSION_INT,
  817. };
  818. AVCodec ff_ape_decoder = {
  819. .name = "ape",
  820. .type = AVMEDIA_TYPE_AUDIO,
  821. .id = AV_CODEC_ID_APE,
  822. .priv_data_size = sizeof(APEContext),
  823. .init = ape_decode_init,
  824. .close = ape_decode_close,
  825. .decode = ape_decode_frame,
  826. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  827. .flush = ape_flush,
  828. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  829. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
  830. AV_SAMPLE_FMT_S16P,
  831. AV_SAMPLE_FMT_S32P,
  832. AV_SAMPLE_FMT_NONE },
  833. .priv_class = &ape_decoder_class,
  834. };