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.

1062 lines
33KB

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