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.

998 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 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 "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. DSPContext dsp;
  112. int channels;
  113. int samples; ///< samples left to decode in current frame
  114. int bps;
  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 *decoded_buffer;
  123. int decoded_size;
  124. int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
  125. int blocks_per_loop; ///< maximum number of samples to decode for each call
  126. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  127. APERangecoder rc; ///< rangecoder used to decode actual values
  128. APERice riceX; ///< rice code parameters for the second channel
  129. APERice riceY; ///< rice code parameters for the first channel
  130. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  131. uint8_t *data; ///< current frame data
  132. uint8_t *data_end; ///< frame data end
  133. int data_size; ///< frame data allocated size
  134. const uint8_t *ptr; ///< current position in frame data
  135. int error;
  136. } APEContext;
  137. // TODO: dsputilize
  138. static av_cold int ape_decode_close(AVCodecContext *avctx)
  139. {
  140. APEContext *s = avctx->priv_data;
  141. int i;
  142. for (i = 0; i < APE_FILTER_LEVELS; i++)
  143. av_freep(&s->filterbuf[i]);
  144. av_freep(&s->decoded_buffer);
  145. av_freep(&s->data);
  146. s->decoded_size = s->data_size = 0;
  147. return 0;
  148. }
  149. static av_cold int ape_decode_init(AVCodecContext *avctx)
  150. {
  151. APEContext *s = avctx->priv_data;
  152. int i;
  153. if (avctx->extradata_size != 6) {
  154. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  155. return AVERROR(EINVAL);
  156. }
  157. if (avctx->channels > 2) {
  158. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  159. return AVERROR(EINVAL);
  160. }
  161. s->bps = avctx->bits_per_coded_sample;
  162. switch (s->bps) {
  163. case 8:
  164. avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
  165. break;
  166. case 16:
  167. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  168. break;
  169. case 24:
  170. avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  171. break;
  172. default:
  173. av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",
  174. s->bps);
  175. return AVERROR_PATCHWELCOME;
  176. }
  177. s->avctx = avctx;
  178. s->channels = avctx->channels;
  179. s->fileversion = AV_RL16(avctx->extradata);
  180. s->compression_level = AV_RL16(avctx->extradata + 2);
  181. s->flags = AV_RL16(avctx->extradata + 4);
  182. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
  183. s->compression_level, s->flags);
  184. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
  185. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  186. s->compression_level);
  187. return AVERROR_INVALIDDATA;
  188. }
  189. s->fset = s->compression_level / 1000 - 1;
  190. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  191. if (!ape_filter_orders[s->fset][i])
  192. break;
  193. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  194. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  195. filter_alloc_fail);
  196. }
  197. ff_dsputil_init(&s->dsp, avctx);
  198. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  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, unsigned 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. unsigned 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 if (tmpk <= 32) {
  357. x = range_decode_bits(ctx, 16);
  358. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  359. } else {
  360. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  361. return AVERROR_INVALIDDATA;
  362. }
  363. x += overflow << tmpk;
  364. } else {
  365. int base, pivot;
  366. pivot = rice->ksum >> 5;
  367. if (pivot == 0)
  368. pivot = 1;
  369. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  370. if (overflow == (MODEL_ELEMENTS - 1)) {
  371. overflow = range_decode_bits(ctx, 16) << 16;
  372. overflow |= range_decode_bits(ctx, 16);
  373. }
  374. if (pivot < 0x10000) {
  375. base = range_decode_culfreq(ctx, pivot);
  376. range_decode_update(ctx, 1, base);
  377. } else {
  378. int base_hi = pivot, base_lo;
  379. int bbits = 0;
  380. while (base_hi & ~0xFFFF) {
  381. base_hi >>= 1;
  382. bbits++;
  383. }
  384. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  385. range_decode_update(ctx, 1, base_hi);
  386. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  387. range_decode_update(ctx, 1, base_lo);
  388. base = (base_hi << bbits) + base_lo;
  389. }
  390. x = base + overflow * pivot;
  391. }
  392. update_rice(rice, x);
  393. /* Convert to signed */
  394. if (x & 1)
  395. return (x >> 1) + 1;
  396. else
  397. return -(x >> 1);
  398. }
  399. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  400. {
  401. int32_t *decoded0 = ctx->decoded[0];
  402. int32_t *decoded1 = ctx->decoded[1];
  403. while (blockstodecode--) {
  404. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  405. if (stereo)
  406. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  407. }
  408. }
  409. static int init_entropy_decoder(APEContext *ctx)
  410. {
  411. /* Read the CRC */
  412. if (ctx->data_end - ctx->ptr < 6)
  413. return AVERROR_INVALIDDATA;
  414. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  415. /* Read the frame flags if they exist */
  416. ctx->frameflags = 0;
  417. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  418. ctx->CRC &= ~0x80000000;
  419. if (ctx->data_end - ctx->ptr < 6)
  420. return AVERROR_INVALIDDATA;
  421. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  422. }
  423. /* Initialize the rice structs */
  424. ctx->riceX.k = 10;
  425. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  426. ctx->riceY.k = 10;
  427. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  428. /* The first 8 bits of input are ignored. */
  429. ctx->ptr++;
  430. range_start_decoding(ctx);
  431. return 0;
  432. }
  433. static const int32_t initial_coeffs[4] = {
  434. 360, 317, -109, 98
  435. };
  436. static void init_predictor_decoder(APEContext *ctx)
  437. {
  438. APEPredictor *p = &ctx->predictor;
  439. /* Zero the history buffers */
  440. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
  441. p->buf = p->historybuffer;
  442. /* Initialize and zero the coefficients */
  443. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  444. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  445. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  446. p->filterA[0] = p->filterA[1] = 0;
  447. p->filterB[0] = p->filterB[1] = 0;
  448. p->lastA[0] = p->lastA[1] = 0;
  449. }
  450. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  451. static inline int APESIGN(int32_t x) {
  452. return (x < 0) - (x > 0);
  453. }
  454. static av_always_inline int predictor_update_filter(APEPredictor *p,
  455. const int decoded, const int filter,
  456. const int delayA, const int delayB,
  457. const int adaptA, const int adaptB)
  458. {
  459. int32_t predictionA, predictionB, sign;
  460. p->buf[delayA] = p->lastA[filter];
  461. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  462. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  463. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  464. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  465. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  466. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  467. p->buf[delayA - 3] * p->coeffsA[filter][3];
  468. /* Apply a scaled first-order filter compression */
  469. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  470. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  471. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  472. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  473. p->filterB[filter] = p->filterA[filter ^ 1];
  474. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  475. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  476. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  477. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  478. p->buf[delayB - 4] * p->coeffsB[filter][4];
  479. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  480. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  481. sign = APESIGN(decoded);
  482. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  483. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  484. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  485. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  486. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  487. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  488. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  489. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  490. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  491. return p->filterA[filter];
  492. }
  493. static void predictor_decode_stereo(APEContext *ctx, int count)
  494. {
  495. APEPredictor *p = &ctx->predictor;
  496. int32_t *decoded0 = ctx->decoded[0];
  497. int32_t *decoded1 = ctx->decoded[1];
  498. while (count--) {
  499. /* Predictor Y */
  500. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  501. YADAPTCOEFFSA, YADAPTCOEFFSB);
  502. decoded0++;
  503. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  504. XADAPTCOEFFSA, XADAPTCOEFFSB);
  505. decoded1++;
  506. /* Combined */
  507. p->buf++;
  508. /* Have we filled the history buffer? */
  509. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  510. memmove(p->historybuffer, p->buf,
  511. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  512. p->buf = p->historybuffer;
  513. }
  514. }
  515. }
  516. static void predictor_decode_mono(APEContext *ctx, int count)
  517. {
  518. APEPredictor *p = &ctx->predictor;
  519. int32_t *decoded0 = ctx->decoded[0];
  520. int32_t predictionA, currentA, A, sign;
  521. currentA = p->lastA[0];
  522. while (count--) {
  523. A = *decoded0;
  524. p->buf[YDELAYA] = currentA;
  525. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  526. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  527. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  528. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  529. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  530. currentA = A + (predictionA >> 10);
  531. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  532. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  533. sign = APESIGN(A);
  534. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  535. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  536. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  537. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  538. p->buf++;
  539. /* Have we filled the history buffer? */
  540. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  541. memmove(p->historybuffer, p->buf,
  542. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  543. p->buf = p->historybuffer;
  544. }
  545. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  546. *(decoded0++) = p->filterA[0];
  547. }
  548. p->lastA[0] = currentA;
  549. }
  550. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  551. {
  552. f->coeffs = buf;
  553. f->historybuffer = buf + order;
  554. f->delay = f->historybuffer + order * 2;
  555. f->adaptcoeffs = f->historybuffer + order;
  556. memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
  557. memset(f->coeffs, 0, order * sizeof(*f->coeffs));
  558. f->avg = 0;
  559. }
  560. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  561. {
  562. do_init_filter(&f[0], buf, order);
  563. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  564. }
  565. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  566. int32_t *data, int count, int order, int fracbits)
  567. {
  568. int res;
  569. int absres;
  570. while (count--) {
  571. /* round fixedpoint scalar product */
  572. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  573. f->adaptcoeffs - order,
  574. order, APESIGN(*data));
  575. res = (res + (1 << (fracbits - 1))) >> fracbits;
  576. res += *data;
  577. *data++ = res;
  578. /* Update the output history */
  579. *f->delay++ = av_clip_int16(res);
  580. if (version < 3980) {
  581. /* Version ??? to < 3.98 files (untested) */
  582. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  583. f->adaptcoeffs[-4] >>= 1;
  584. f->adaptcoeffs[-8] >>= 1;
  585. } else {
  586. /* Version 3.98 and later files */
  587. /* Update the adaption coefficients */
  588. absres = FFABS(res);
  589. if (absres)
  590. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  591. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  592. else
  593. *f->adaptcoeffs = 0;
  594. f->avg += (absres - f->avg) / 16;
  595. f->adaptcoeffs[-1] >>= 1;
  596. f->adaptcoeffs[-2] >>= 1;
  597. f->adaptcoeffs[-8] >>= 1;
  598. }
  599. f->adaptcoeffs++;
  600. /* Have we filled the history buffer? */
  601. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  602. memmove(f->historybuffer, f->delay - (order * 2),
  603. (order * 2) * sizeof(*f->historybuffer));
  604. f->delay = f->historybuffer + order * 2;
  605. f->adaptcoeffs = f->historybuffer + order;
  606. }
  607. }
  608. }
  609. static void apply_filter(APEContext *ctx, APEFilter *f,
  610. int32_t *data0, int32_t *data1,
  611. int count, int order, int fracbits)
  612. {
  613. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  614. if (data1)
  615. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  616. }
  617. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  618. int32_t *decoded1, int count)
  619. {
  620. int i;
  621. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  622. if (!ape_filter_orders[ctx->fset][i])
  623. break;
  624. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  625. ape_filter_orders[ctx->fset][i],
  626. ape_filter_fracbits[ctx->fset][i]);
  627. }
  628. }
  629. static int init_frame_decoder(APEContext *ctx)
  630. {
  631. int i, ret;
  632. if ((ret = init_entropy_decoder(ctx)) < 0)
  633. return ret;
  634. init_predictor_decoder(ctx);
  635. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  636. if (!ape_filter_orders[ctx->fset][i])
  637. break;
  638. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  639. ape_filter_orders[ctx->fset][i]);
  640. }
  641. return 0;
  642. }
  643. static void ape_unpack_mono(APEContext *ctx, int count)
  644. {
  645. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  646. /* We are pure silence, so we're done. */
  647. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  648. return;
  649. }
  650. entropy_decode(ctx, count, 0);
  651. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  652. /* Now apply the predictor decoding */
  653. predictor_decode_mono(ctx, count);
  654. /* Pseudo-stereo - just copy left channel to right channel */
  655. if (ctx->channels == 2) {
  656. memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
  657. }
  658. }
  659. static void ape_unpack_stereo(APEContext *ctx, int count)
  660. {
  661. int32_t left, right;
  662. int32_t *decoded0 = ctx->decoded[0];
  663. int32_t *decoded1 = ctx->decoded[1];
  664. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  665. /* We are pure silence, so we're done. */
  666. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  667. return;
  668. }
  669. entropy_decode(ctx, count, 1);
  670. ape_apply_filters(ctx, decoded0, decoded1, count);
  671. /* Now apply the predictor decoding */
  672. predictor_decode_stereo(ctx, count);
  673. /* Decorrelate and scale to output depth */
  674. while (count--) {
  675. left = *decoded1 - (*decoded0 / 2);
  676. right = left + *decoded0;
  677. *(decoded0++) = left;
  678. *(decoded1++) = right;
  679. }
  680. }
  681. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  682. int *got_frame_ptr, AVPacket *avpkt)
  683. {
  684. AVFrame *frame = data;
  685. const uint8_t *buf = avpkt->data;
  686. APEContext *s = avctx->priv_data;
  687. uint8_t *sample8;
  688. int16_t *sample16;
  689. int32_t *sample24;
  690. int i, ch, ret;
  691. int blockstodecode;
  692. int bytes_used = 0;
  693. /* this should never be negative, but bad things will happen if it is, so
  694. check it just to make sure. */
  695. av_assert0(s->samples >= 0);
  696. if(!s->samples){
  697. uint32_t nblocks, offset;
  698. int buf_size;
  699. if (!avpkt->size) {
  700. *got_frame_ptr = 0;
  701. return 0;
  702. }
  703. if (avpkt->size < 8) {
  704. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  705. return AVERROR_INVALIDDATA;
  706. }
  707. buf_size = avpkt->size & ~3;
  708. if (buf_size != avpkt->size) {
  709. av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
  710. "extra bytes at the end will be skipped.\n");
  711. }
  712. av_fast_malloc(&s->data, &s->data_size, buf_size);
  713. if (!s->data)
  714. return AVERROR(ENOMEM);
  715. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  716. s->ptr = s->data;
  717. s->data_end = s->data + buf_size;
  718. nblocks = bytestream_get_be32(&s->ptr);
  719. offset = bytestream_get_be32(&s->ptr);
  720. if (offset > 3) {
  721. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  722. s->data = NULL;
  723. return AVERROR_INVALIDDATA;
  724. }
  725. if (s->data_end - s->ptr < offset) {
  726. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  727. return AVERROR_INVALIDDATA;
  728. }
  729. s->ptr += offset;
  730. if (!nblocks || nblocks > INT_MAX) {
  731. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  732. return AVERROR_INVALIDDATA;
  733. }
  734. s->samples = nblocks;
  735. /* Initialize the frame decoder */
  736. if (init_frame_decoder(s) < 0) {
  737. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  738. return AVERROR_INVALIDDATA;
  739. }
  740. bytes_used = avpkt->size;
  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. frame->nb_samples = blockstodecode;
  757. if ((ret = ff_get_buffer(avctx, frame, 0)) < 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 *)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 *)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 *)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. return bytes_used;
  798. }
  799. static void ape_flush(AVCodecContext *avctx)
  800. {
  801. APEContext *s = avctx->priv_data;
  802. s->samples= 0;
  803. }
  804. #define OFFSET(x) offsetof(APEContext, x)
  805. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  806. static const AVOption options[] = {
  807. { "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" },
  808. { "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" },
  809. { NULL},
  810. };
  811. static const AVClass ape_decoder_class = {
  812. .class_name = "APE decoder",
  813. .item_name = av_default_item_name,
  814. .option = options,
  815. .version = LIBAVUTIL_VERSION_INT,
  816. };
  817. AVCodec ff_ape_decoder = {
  818. .name = "ape",
  819. .type = AVMEDIA_TYPE_AUDIO,
  820. .id = AV_CODEC_ID_APE,
  821. .priv_data_size = sizeof(APEContext),
  822. .init = ape_decode_init,
  823. .close = ape_decode_close,
  824. .decode = ape_decode_frame,
  825. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  826. .flush = ape_flush,
  827. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  828. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
  829. AV_SAMPLE_FMT_S16P,
  830. AV_SAMPLE_FMT_S32P,
  831. AV_SAMPLE_FMT_NONE },
  832. .priv_class = &ape_decoder_class,
  833. };