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.

1151 lines
36KB

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