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.

1587 lines
50KB

  1. /*
  2. * Monkey's Audio lossless audio decoder
  3. * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
  4. * based upon libdemac from Dave Chapman.
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/channel_layout.h"
  24. #include "libavutil/opt.h"
  25. #include "avcodec.h"
  26. #include "dsputil.h"
  27. #include "bytestream.h"
  28. #include "internal.h"
  29. #include "get_bits.h"
  30. #include "unary.h"
  31. /**
  32. * @file
  33. * Monkey's Audio lossless audio decoder
  34. */
  35. #define MAX_CHANNELS 2
  36. #define MAX_BYTESPERSAMPLE 3
  37. #define APE_FRAMECODE_MONO_SILENCE 1
  38. #define APE_FRAMECODE_STEREO_SILENCE 3
  39. #define APE_FRAMECODE_PSEUDO_STEREO 4
  40. #define HISTORY_SIZE 512
  41. #define PREDICTOR_ORDER 8
  42. /** Total size of all predictor histories */
  43. #define PREDICTOR_SIZE 50
  44. #define YDELAYA (18 + PREDICTOR_ORDER*4)
  45. #define YDELAYB (18 + PREDICTOR_ORDER*3)
  46. #define XDELAYA (18 + PREDICTOR_ORDER*2)
  47. #define XDELAYB (18 + PREDICTOR_ORDER)
  48. #define YADAPTCOEFFSA 18
  49. #define XADAPTCOEFFSA 14
  50. #define YADAPTCOEFFSB 10
  51. #define XADAPTCOEFFSB 5
  52. /**
  53. * Possible compression levels
  54. * @{
  55. */
  56. enum APECompressionLevel {
  57. COMPRESSION_LEVEL_FAST = 1000,
  58. COMPRESSION_LEVEL_NORMAL = 2000,
  59. COMPRESSION_LEVEL_HIGH = 3000,
  60. COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
  61. COMPRESSION_LEVEL_INSANE = 5000
  62. };
  63. /** @} */
  64. #define APE_FILTER_LEVELS 3
  65. /** Filter orders depending on compression level */
  66. static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
  67. { 0, 0, 0 },
  68. { 16, 0, 0 },
  69. { 64, 0, 0 },
  70. { 32, 256, 0 },
  71. { 16, 256, 1280 }
  72. };
  73. /** Filter fraction bits depending on compression level */
  74. static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
  75. { 0, 0, 0 },
  76. { 11, 0, 0 },
  77. { 11, 0, 0 },
  78. { 10, 13, 0 },
  79. { 11, 13, 15 }
  80. };
  81. /** Filters applied to the decoded data */
  82. typedef struct APEFilter {
  83. int16_t *coeffs; ///< actual coefficients used in filtering
  84. int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
  85. int16_t *historybuffer; ///< filter memory
  86. int16_t *delay; ///< filtered values
  87. int avg;
  88. } APEFilter;
  89. typedef struct APERice {
  90. uint32_t k;
  91. uint32_t ksum;
  92. } APERice;
  93. typedef struct APERangecoder {
  94. uint32_t low; ///< low end of interval
  95. uint32_t range; ///< length of interval
  96. uint32_t help; ///< bytes_to_follow resp. intermediate value
  97. unsigned int buffer; ///< buffer for input/output
  98. } APERangecoder;
  99. /** Filter histories */
  100. typedef struct APEPredictor {
  101. int32_t *buf;
  102. int32_t lastA[2];
  103. int32_t filterA[2];
  104. int32_t filterB[2];
  105. int32_t coeffsA[2][4]; ///< adaption coefficients
  106. int32_t coeffsB[2][5]; ///< adaption coefficients
  107. int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
  108. unsigned int sample_pos;
  109. } APEPredictor;
  110. /** Decoder context */
  111. typedef struct APEContext {
  112. AVClass *class; ///< class for AVOptions
  113. AVCodecContext *avctx;
  114. DSPContext dsp;
  115. int channels;
  116. int samples; ///< samples left to decode in current frame
  117. int bps;
  118. int fileversion; ///< codec version, very important in decoding process
  119. int compression_level; ///< compression levels
  120. int fset; ///< which filter set to use (calculated from compression level)
  121. int flags; ///< global decoder flags
  122. uint32_t CRC; ///< frame CRC
  123. int frameflags; ///< frame flags
  124. APEPredictor predictor; ///< predictor used for final reconstruction
  125. int32_t *decoded_buffer;
  126. int decoded_size;
  127. int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
  128. int blocks_per_loop; ///< maximum number of samples to decode for each call
  129. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  130. APERangecoder rc; ///< rangecoder used to decode actual values
  131. APERice riceX; ///< rice code parameters for the second channel
  132. APERice riceY; ///< rice code parameters for the first channel
  133. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  134. GetBitContext gb;
  135. uint8_t *data; ///< current frame data
  136. uint8_t *data_end; ///< frame data end
  137. int data_size; ///< frame data allocated size
  138. const uint8_t *ptr; ///< current position in frame data
  139. int error;
  140. void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
  141. void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
  142. void (*predictor_decode_mono)(struct APEContext *ctx, int count);
  143. void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
  144. } APEContext;
  145. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  146. int32_t *decoded1, int count);
  147. static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
  148. static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
  149. static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
  150. static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
  151. static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
  152. static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
  153. static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
  154. static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
  155. static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
  156. static void predictor_decode_mono_3800(APEContext *ctx, int count);
  157. static void predictor_decode_stereo_3800(APEContext *ctx, int count);
  158. static void predictor_decode_mono_3930(APEContext *ctx, int count);
  159. static void predictor_decode_stereo_3930(APEContext *ctx, int count);
  160. static void predictor_decode_mono_3950(APEContext *ctx, int count);
  161. static void predictor_decode_stereo_3950(APEContext *ctx, int count);
  162. // TODO: dsputilize
  163. static av_cold int ape_decode_close(AVCodecContext *avctx)
  164. {
  165. APEContext *s = avctx->priv_data;
  166. int i;
  167. for (i = 0; i < APE_FILTER_LEVELS; i++)
  168. av_freep(&s->filterbuf[i]);
  169. av_freep(&s->decoded_buffer);
  170. av_freep(&s->data);
  171. s->decoded_size = s->data_size = 0;
  172. return 0;
  173. }
  174. static av_cold int ape_decode_init(AVCodecContext *avctx)
  175. {
  176. APEContext *s = avctx->priv_data;
  177. int i;
  178. if (avctx->extradata_size != 6) {
  179. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  180. return AVERROR(EINVAL);
  181. }
  182. if (avctx->channels > 2) {
  183. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  184. return AVERROR(EINVAL);
  185. }
  186. s->bps = avctx->bits_per_coded_sample;
  187. switch (s->bps) {
  188. case 8:
  189. avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
  190. break;
  191. case 16:
  192. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  193. break;
  194. case 24:
  195. avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  196. break;
  197. default:
  198. avpriv_request_sample(avctx,
  199. "%d bits per coded sample", s->bps);
  200. return AVERROR_PATCHWELCOME;
  201. }
  202. s->avctx = avctx;
  203. s->channels = avctx->channels;
  204. s->fileversion = AV_RL16(avctx->extradata);
  205. s->compression_level = AV_RL16(avctx->extradata + 2);
  206. s->flags = AV_RL16(avctx->extradata + 4);
  207. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
  208. s->compression_level, s->flags);
  209. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
  210. !s->compression_level ||
  211. (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
  212. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  213. s->compression_level);
  214. return AVERROR_INVALIDDATA;
  215. }
  216. s->fset = s->compression_level / 1000 - 1;
  217. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  218. if (!ape_filter_orders[s->fset][i])
  219. break;
  220. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  221. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  222. filter_alloc_fail);
  223. }
  224. if (s->fileversion < 3860) {
  225. s->entropy_decode_mono = entropy_decode_mono_0000;
  226. s->entropy_decode_stereo = entropy_decode_stereo_0000;
  227. } else if (s->fileversion < 3900) {
  228. s->entropy_decode_mono = entropy_decode_mono_3860;
  229. s->entropy_decode_stereo = entropy_decode_stereo_3860;
  230. } else if (s->fileversion < 3930) {
  231. s->entropy_decode_mono = entropy_decode_mono_3900;
  232. s->entropy_decode_stereo = entropy_decode_stereo_3900;
  233. } else if (s->fileversion < 3990) {
  234. s->entropy_decode_mono = entropy_decode_mono_3900;
  235. s->entropy_decode_stereo = entropy_decode_stereo_3930;
  236. } else {
  237. s->entropy_decode_mono = entropy_decode_mono_3990;
  238. s->entropy_decode_stereo = entropy_decode_stereo_3990;
  239. }
  240. if (s->fileversion < 3930) {
  241. s->predictor_decode_mono = predictor_decode_mono_3800;
  242. s->predictor_decode_stereo = predictor_decode_stereo_3800;
  243. } else if (s->fileversion < 3950) {
  244. s->predictor_decode_mono = predictor_decode_mono_3930;
  245. s->predictor_decode_stereo = predictor_decode_stereo_3930;
  246. } else {
  247. s->predictor_decode_mono = predictor_decode_mono_3950;
  248. s->predictor_decode_stereo = predictor_decode_stereo_3950;
  249. }
  250. ff_dsputil_init(&s->dsp, avctx);
  251. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  252. return 0;
  253. filter_alloc_fail:
  254. ape_decode_close(avctx);
  255. return AVERROR(ENOMEM);
  256. }
  257. /**
  258. * @name APE range decoding functions
  259. * @{
  260. */
  261. #define CODE_BITS 32
  262. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  263. #define SHIFT_BITS (CODE_BITS - 9)
  264. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  265. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  266. /** Start the decoder */
  267. static inline void range_start_decoding(APEContext *ctx)
  268. {
  269. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  270. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  271. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  272. }
  273. /** Perform normalization */
  274. static inline void range_dec_normalize(APEContext *ctx)
  275. {
  276. while (ctx->rc.range <= BOTTOM_VALUE) {
  277. ctx->rc.buffer <<= 8;
  278. if(ctx->ptr < ctx->data_end) {
  279. ctx->rc.buffer += *ctx->ptr;
  280. ctx->ptr++;
  281. } else {
  282. ctx->error = 1;
  283. }
  284. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  285. ctx->rc.range <<= 8;
  286. }
  287. }
  288. /**
  289. * Calculate culmulative frequency for next symbol. Does NO update!
  290. * @param ctx decoder context
  291. * @param tot_f is the total frequency or (code_value)1<<shift
  292. * @return the culmulative frequency
  293. */
  294. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  295. {
  296. range_dec_normalize(ctx);
  297. ctx->rc.help = ctx->rc.range / tot_f;
  298. return ctx->rc.low / ctx->rc.help;
  299. }
  300. /**
  301. * Decode value with given size in bits
  302. * @param ctx decoder context
  303. * @param shift number of bits to decode
  304. */
  305. static inline int range_decode_culshift(APEContext *ctx, int shift)
  306. {
  307. range_dec_normalize(ctx);
  308. ctx->rc.help = ctx->rc.range >> shift;
  309. return ctx->rc.low / ctx->rc.help;
  310. }
  311. /**
  312. * Update decoding state
  313. * @param ctx decoder context
  314. * @param sy_f the interval length (frequency of the symbol)
  315. * @param lt_f the lower end (frequency sum of < symbols)
  316. */
  317. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  318. {
  319. ctx->rc.low -= ctx->rc.help * lt_f;
  320. ctx->rc.range = ctx->rc.help * sy_f;
  321. }
  322. /** Decode n bits (n <= 16) without modelling */
  323. static inline int range_decode_bits(APEContext *ctx, int n)
  324. {
  325. int sym = range_decode_culshift(ctx, n);
  326. range_decode_update(ctx, 1, sym);
  327. return sym;
  328. }
  329. #define MODEL_ELEMENTS 64
  330. /**
  331. * Fixed probabilities for symbols in Monkey Audio version 3.97
  332. */
  333. static const uint16_t counts_3970[22] = {
  334. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  335. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  336. 65450, 65469, 65480, 65487, 65491, 65493,
  337. };
  338. /**
  339. * Probability ranges for symbols in Monkey Audio version 3.97
  340. */
  341. static const uint16_t counts_diff_3970[21] = {
  342. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  343. 1104, 677, 415, 248, 150, 89, 54, 31,
  344. 19, 11, 7, 4, 2,
  345. };
  346. /**
  347. * Fixed probabilities for symbols in Monkey Audio version 3.98
  348. */
  349. static const uint16_t counts_3980[22] = {
  350. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  351. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  352. 65485, 65488, 65490, 65491, 65492, 65493,
  353. };
  354. /**
  355. * Probability ranges for symbols in Monkey Audio version 3.98
  356. */
  357. static const uint16_t counts_diff_3980[21] = {
  358. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  359. 261, 119, 65, 31, 19, 10, 6, 3,
  360. 3, 2, 1, 1, 1,
  361. };
  362. /**
  363. * Decode symbol
  364. * @param ctx decoder context
  365. * @param counts probability range start position
  366. * @param counts_diff probability range widths
  367. */
  368. static inline int range_get_symbol(APEContext *ctx,
  369. const uint16_t counts[],
  370. const uint16_t counts_diff[])
  371. {
  372. int symbol, cf;
  373. cf = range_decode_culshift(ctx, 16);
  374. if(cf > 65492){
  375. symbol= cf - 65535 + 63;
  376. range_decode_update(ctx, 1, cf);
  377. if(cf > 65535)
  378. ctx->error=1;
  379. return symbol;
  380. }
  381. /* figure out the symbol inefficiently; a binary search would be much better */
  382. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  383. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  384. return symbol;
  385. }
  386. /** @} */ // group rangecoder
  387. static inline void update_rice(APERice *rice, unsigned int x)
  388. {
  389. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  390. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  391. if (rice->ksum < lim)
  392. rice->k--;
  393. else if (rice->ksum >= (1 << (rice->k + 5)))
  394. rice->k++;
  395. }
  396. static inline int get_rice_ook(GetBitContext *gb, int k)
  397. {
  398. unsigned int x;
  399. x = get_unary(gb, 1, get_bits_left(gb));
  400. if (k)
  401. x = (x << k) | get_bits(gb, k);
  402. return x;
  403. }
  404. static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
  405. APERice *rice)
  406. {
  407. unsigned int x, overflow;
  408. overflow = get_unary(gb, 1, get_bits_left(gb));
  409. if (ctx->fileversion > 3880) {
  410. while (overflow >= 16) {
  411. overflow -= 16;
  412. rice->k += 4;
  413. }
  414. }
  415. if (!rice->k)
  416. x = overflow;
  417. else if(rice->k <= MIN_CACHE_BITS) {
  418. x = (overflow << rice->k) + get_bits(gb, rice->k);
  419. } else {
  420. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", rice->k);
  421. return AVERROR_INVALIDDATA;
  422. }
  423. rice->ksum += x - (rice->ksum + 8 >> 4);
  424. if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
  425. rice->k--;
  426. else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
  427. rice->k++;
  428. /* Convert to signed */
  429. if (x & 1)
  430. return (x >> 1) + 1;
  431. else
  432. return -(x >> 1);
  433. }
  434. static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
  435. {
  436. unsigned int x, overflow;
  437. int tmpk;
  438. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  439. if (overflow == (MODEL_ELEMENTS - 1)) {
  440. tmpk = range_decode_bits(ctx, 5);
  441. overflow = 0;
  442. } else
  443. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  444. if (tmpk <= 16 || ctx->fileversion < 3910) {
  445. if (tmpk > 23) {
  446. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  447. return AVERROR_INVALIDDATA;
  448. }
  449. x = range_decode_bits(ctx, tmpk);
  450. } else if (tmpk <= 32) {
  451. x = range_decode_bits(ctx, 16);
  452. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  453. } else {
  454. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  455. return AVERROR_INVALIDDATA;
  456. }
  457. x += overflow << tmpk;
  458. update_rice(rice, x);
  459. /* Convert to signed */
  460. if (x & 1)
  461. return (x >> 1) + 1;
  462. else
  463. return -(x >> 1);
  464. }
  465. static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
  466. {
  467. unsigned int x, overflow;
  468. int base, pivot;
  469. pivot = rice->ksum >> 5;
  470. if (pivot == 0)
  471. pivot = 1;
  472. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  473. if (overflow == (MODEL_ELEMENTS - 1)) {
  474. overflow = range_decode_bits(ctx, 16) << 16;
  475. overflow |= range_decode_bits(ctx, 16);
  476. }
  477. if (pivot < 0x10000) {
  478. base = range_decode_culfreq(ctx, pivot);
  479. range_decode_update(ctx, 1, base);
  480. } else {
  481. int base_hi = pivot, base_lo;
  482. int bbits = 0;
  483. while (base_hi & ~0xFFFF) {
  484. base_hi >>= 1;
  485. bbits++;
  486. }
  487. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  488. range_decode_update(ctx, 1, base_hi);
  489. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  490. range_decode_update(ctx, 1, base_lo);
  491. base = (base_hi << bbits) + base_lo;
  492. }
  493. x = base + overflow * pivot;
  494. update_rice(rice, x);
  495. /* Convert to signed */
  496. if (x & 1)
  497. return (x >> 1) + 1;
  498. else
  499. return -(x >> 1);
  500. }
  501. static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
  502. int32_t *out, APERice *rice, int blockstodecode)
  503. {
  504. int i;
  505. int ksummax, ksummin;
  506. rice->ksum = 0;
  507. for (i = 0; i < 5; i++) {
  508. out[i] = get_rice_ook(&ctx->gb, 10);
  509. rice->ksum += out[i];
  510. }
  511. rice->k = av_log2(rice->ksum / 10) + 1;
  512. for (; i < 64; i++) {
  513. out[i] = get_rice_ook(&ctx->gb, rice->k);
  514. rice->ksum += out[i];
  515. rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
  516. }
  517. ksummax = 1 << rice->k + 7;
  518. ksummin = rice->k ? (1 << rice->k + 6) : 0;
  519. for (; i < blockstodecode; i++) {
  520. out[i] = get_rice_ook(&ctx->gb, rice->k);
  521. rice->ksum += out[i] - out[i - 64];
  522. while (rice->ksum < ksummin) {
  523. rice->k--;
  524. ksummin = rice->k ? ksummin >> 1 : 0;
  525. ksummax >>= 1;
  526. }
  527. while (rice->ksum >= ksummax) {
  528. rice->k++;
  529. if (rice->k > 24)
  530. return;
  531. ksummax <<= 1;
  532. ksummin = ksummin ? ksummin << 1 : 128;
  533. }
  534. }
  535. for (i = 0; i < blockstodecode; i++) {
  536. if (out[i] & 1)
  537. out[i] = (out[i] >> 1) + 1;
  538. else
  539. out[i] = -(out[i] >> 1);
  540. }
  541. }
  542. static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
  543. {
  544. decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
  545. blockstodecode);
  546. }
  547. static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
  548. {
  549. decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
  550. blockstodecode);
  551. decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
  552. blockstodecode);
  553. }
  554. static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
  555. {
  556. int32_t *decoded0 = ctx->decoded[0];
  557. while (blockstodecode--)
  558. *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
  559. }
  560. static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
  561. {
  562. int32_t *decoded0 = ctx->decoded[0];
  563. int32_t *decoded1 = ctx->decoded[1];
  564. int blocks = blockstodecode;
  565. while (blockstodecode--)
  566. *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
  567. while (blocks--)
  568. *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
  569. }
  570. static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
  571. {
  572. int32_t *decoded0 = ctx->decoded[0];
  573. while (blockstodecode--)
  574. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  575. }
  576. static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
  577. {
  578. int32_t *decoded0 = ctx->decoded[0];
  579. int32_t *decoded1 = ctx->decoded[1];
  580. int blocks = blockstodecode;
  581. while (blockstodecode--)
  582. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  583. range_dec_normalize(ctx);
  584. // because of some implementation peculiarities we need to backpedal here
  585. ctx->ptr -= 1;
  586. range_start_decoding(ctx);
  587. while (blocks--)
  588. *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
  589. }
  590. static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
  591. {
  592. int32_t *decoded0 = ctx->decoded[0];
  593. int32_t *decoded1 = ctx->decoded[1];
  594. while (blockstodecode--) {
  595. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  596. *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
  597. }
  598. }
  599. static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
  600. {
  601. int32_t *decoded0 = ctx->decoded[0];
  602. while (blockstodecode--)
  603. *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
  604. }
  605. static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
  606. {
  607. int32_t *decoded0 = ctx->decoded[0];
  608. int32_t *decoded1 = ctx->decoded[1];
  609. while (blockstodecode--) {
  610. *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
  611. *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
  612. }
  613. }
  614. static int init_entropy_decoder(APEContext *ctx)
  615. {
  616. /* Read the CRC */
  617. if (ctx->fileversion >= 3900) {
  618. if (ctx->data_end - ctx->ptr < 6)
  619. return AVERROR_INVALIDDATA;
  620. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  621. } else {
  622. ctx->CRC = get_bits_long(&ctx->gb, 32);
  623. }
  624. /* Read the frame flags if they exist */
  625. ctx->frameflags = 0;
  626. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  627. ctx->CRC &= ~0x80000000;
  628. if (ctx->data_end - ctx->ptr < 6)
  629. return AVERROR_INVALIDDATA;
  630. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  631. }
  632. /* Initialize the rice structs */
  633. ctx->riceX.k = 10;
  634. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  635. ctx->riceY.k = 10;
  636. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  637. if (ctx->fileversion >= 3900) {
  638. /* The first 8 bits of input are ignored. */
  639. ctx->ptr++;
  640. range_start_decoding(ctx);
  641. }
  642. return 0;
  643. }
  644. static const int32_t initial_coeffs_fast_3320[1] = {
  645. 375,
  646. };
  647. static const int32_t initial_coeffs_a_3800[3] = {
  648. 64, 115, 64,
  649. };
  650. static const int32_t initial_coeffs_b_3800[2] = {
  651. 740, 0
  652. };
  653. static const int32_t initial_coeffs_3930[4] = {
  654. 360, 317, -109, 98
  655. };
  656. static void init_predictor_decoder(APEContext *ctx)
  657. {
  658. APEPredictor *p = &ctx->predictor;
  659. /* Zero the history buffers */
  660. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
  661. p->buf = p->historybuffer;
  662. /* Initialize and zero the coefficients */
  663. if (ctx->fileversion < 3930) {
  664. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  665. memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
  666. sizeof(initial_coeffs_fast_3320));
  667. memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
  668. sizeof(initial_coeffs_fast_3320));
  669. } else {
  670. memcpy(p->coeffsA[0], initial_coeffs_a_3800,
  671. sizeof(initial_coeffs_a_3800));
  672. memcpy(p->coeffsA[1], initial_coeffs_a_3800,
  673. sizeof(initial_coeffs_a_3800));
  674. }
  675. } else {
  676. memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
  677. memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
  678. }
  679. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  680. if (ctx->fileversion < 3930) {
  681. memcpy(p->coeffsB[0], initial_coeffs_b_3800,
  682. sizeof(initial_coeffs_b_3800));
  683. memcpy(p->coeffsB[1], initial_coeffs_b_3800,
  684. sizeof(initial_coeffs_b_3800));
  685. }
  686. p->filterA[0] = p->filterA[1] = 0;
  687. p->filterB[0] = p->filterB[1] = 0;
  688. p->lastA[0] = p->lastA[1] = 0;
  689. p->sample_pos = 0;
  690. }
  691. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  692. static inline int APESIGN(int32_t x) {
  693. return (x < 0) - (x > 0);
  694. }
  695. static av_always_inline int filter_fast_3320(APEPredictor *p,
  696. const int decoded, const int filter,
  697. const int delayA)
  698. {
  699. int32_t predictionA;
  700. p->buf[delayA] = p->lastA[filter];
  701. if (p->sample_pos < 3) {
  702. p->lastA[filter] = decoded;
  703. p->filterA[filter] = decoded;
  704. return decoded;
  705. }
  706. predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
  707. p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9);
  708. if ((decoded ^ predictionA) > 0)
  709. p->coeffsA[filter][0]++;
  710. else
  711. p->coeffsA[filter][0]--;
  712. p->filterA[filter] += p->lastA[filter];
  713. return p->filterA[filter];
  714. }
  715. static av_always_inline int filter_3800(APEPredictor *p,
  716. const int decoded, const int filter,
  717. const int delayA, const int delayB,
  718. const int start, const int shift)
  719. {
  720. int32_t predictionA, predictionB, sign;
  721. int32_t d0, d1, d2, d3, d4;
  722. p->buf[delayA] = p->lastA[filter];
  723. p->buf[delayB] = p->filterB[filter];
  724. if (p->sample_pos < start) {
  725. predictionA = decoded + p->filterA[filter];
  726. p->lastA[filter] = decoded;
  727. p->filterB[filter] = decoded;
  728. p->filterA[filter] = predictionA;
  729. return predictionA;
  730. }
  731. d2 = p->buf[delayA];
  732. d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
  733. d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
  734. d3 = p->buf[delayB] * 2 - p->buf[delayB - 1];
  735. d4 = p->buf[delayB];
  736. predictionA = d0 * p->coeffsA[filter][0] +
  737. d1 * p->coeffsA[filter][1] +
  738. d2 * p->coeffsA[filter][2];
  739. sign = APESIGN(decoded);
  740. p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
  741. p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
  742. p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
  743. predictionB = d3 * p->coeffsB[filter][0] -
  744. d4 * p->coeffsB[filter][1];
  745. p->lastA[filter] = decoded + (predictionA >> 11);
  746. sign = APESIGN(p->lastA[filter]);
  747. p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
  748. p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
  749. p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
  750. p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
  751. return p->filterA[filter];
  752. }
  753. static void long_filter_high_3800(int32_t *buffer, int order, int shift,
  754. int32_t *coeffs, int32_t *delay, int length)
  755. {
  756. int i, j;
  757. int32_t dotprod, sign;
  758. memset(coeffs, 0, order * sizeof(*coeffs));
  759. for (i = 0; i < order; i++)
  760. delay[i] = buffer[i];
  761. for (i = order; i < length; i++) {
  762. dotprod = 0;
  763. sign = APESIGN(buffer[i]);
  764. for (j = 0; j < order; j++) {
  765. dotprod += delay[j] * coeffs[j];
  766. coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
  767. }
  768. buffer[i] -= dotprod >> shift;
  769. for (j = 0; j < order - 1; j++)
  770. delay[j] = delay[j + 1];
  771. delay[order - 1] = buffer[i];
  772. }
  773. }
  774. static void long_filter_ehigh_3830(int32_t *buffer, int length)
  775. {
  776. int i, j;
  777. int32_t dotprod, sign;
  778. int32_t coeffs[8], delay[8];
  779. memset(coeffs, 0, sizeof(coeffs));
  780. memset(delay, 0, sizeof(delay));
  781. for (i = 0; i < length; i++) {
  782. dotprod = 0;
  783. sign = APESIGN(buffer[i]);
  784. for (j = 7; j >= 0; j--) {
  785. dotprod += delay[j] * coeffs[j];
  786. coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
  787. }
  788. for (j = 7; j > 0; j--)
  789. delay[j] = delay[j - 1];
  790. delay[0] = buffer[i];
  791. buffer[i] -= dotprod >> 9;
  792. }
  793. }
  794. static void predictor_decode_stereo_3800(APEContext *ctx, int count)
  795. {
  796. APEPredictor *p = &ctx->predictor;
  797. int32_t *decoded0 = ctx->decoded[0];
  798. int32_t *decoded1 = ctx->decoded[1];
  799. int32_t coeffs[256], delay[256];
  800. int start = 4, shift = 10;
  801. if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
  802. start = 16;
  803. long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
  804. long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
  805. } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
  806. int order = 128, shift2 = 11;
  807. if (ctx->fileversion >= 3830) {
  808. order <<= 1;
  809. shift++;
  810. shift2++;
  811. long_filter_ehigh_3830(decoded0 + order, count - order);
  812. long_filter_ehigh_3830(decoded1 + order, count - order);
  813. }
  814. start = order;
  815. long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
  816. long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
  817. }
  818. while (count--) {
  819. int X = *decoded0, Y = *decoded1;
  820. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  821. *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
  822. decoded0++;
  823. *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
  824. decoded1++;
  825. } else {
  826. *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
  827. start, shift);
  828. decoded0++;
  829. *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
  830. start, shift);
  831. decoded1++;
  832. }
  833. /* Combined */
  834. p->buf++;
  835. p->sample_pos++;
  836. /* Have we filled the history buffer? */
  837. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  838. memmove(p->historybuffer, p->buf,
  839. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  840. p->buf = p->historybuffer;
  841. }
  842. }
  843. }
  844. static void predictor_decode_mono_3800(APEContext *ctx, int count)
  845. {
  846. APEPredictor *p = &ctx->predictor;
  847. int32_t *decoded0 = ctx->decoded[0];
  848. int32_t coeffs[256], delay[256];
  849. int start = 4, shift = 10;
  850. if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
  851. start = 16;
  852. long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
  853. } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
  854. int order = 128, shift2 = 11;
  855. if (ctx->fileversion >= 3830) {
  856. order <<= 1;
  857. shift++;
  858. shift2++;
  859. long_filter_ehigh_3830(decoded0 + order, count - order);
  860. }
  861. start = order;
  862. long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
  863. }
  864. while (count--) {
  865. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  866. *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
  867. decoded0++;
  868. } else {
  869. *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
  870. start, shift);
  871. decoded0++;
  872. }
  873. /* Combined */
  874. p->buf++;
  875. p->sample_pos++;
  876. /* Have we filled the history buffer? */
  877. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  878. memmove(p->historybuffer, p->buf,
  879. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  880. p->buf = p->historybuffer;
  881. }
  882. }
  883. }
  884. static av_always_inline int predictor_update_3930(APEPredictor *p,
  885. const int decoded, const int filter,
  886. const int delayA)
  887. {
  888. int32_t predictionA, sign;
  889. int32_t d0, d1, d2, d3;
  890. p->buf[delayA] = p->lastA[filter];
  891. d0 = p->buf[delayA ];
  892. d1 = p->buf[delayA ] - p->buf[delayA - 1];
  893. d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
  894. d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
  895. predictionA = d0 * p->coeffsA[filter][0] +
  896. d1 * p->coeffsA[filter][1] +
  897. d2 * p->coeffsA[filter][2] +
  898. d3 * p->coeffsA[filter][3];
  899. p->lastA[filter] = decoded + (predictionA >> 9);
  900. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  901. sign = APESIGN(decoded);
  902. p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
  903. p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
  904. p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
  905. p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
  906. return p->filterA[filter];
  907. }
  908. static void predictor_decode_stereo_3930(APEContext *ctx, int count)
  909. {
  910. APEPredictor *p = &ctx->predictor;
  911. int32_t *decoded0 = ctx->decoded[0];
  912. int32_t *decoded1 = ctx->decoded[1];
  913. ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
  914. while (count--) {
  915. /* Predictor Y */
  916. int Y = *decoded1, X = *decoded0;
  917. *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
  918. decoded0++;
  919. *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
  920. decoded1++;
  921. /* Combined */
  922. p->buf++;
  923. /* Have we filled the history buffer? */
  924. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  925. memmove(p->historybuffer, p->buf,
  926. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  927. p->buf = p->historybuffer;
  928. }
  929. }
  930. }
  931. static void predictor_decode_mono_3930(APEContext *ctx, int count)
  932. {
  933. APEPredictor *p = &ctx->predictor;
  934. int32_t *decoded0 = ctx->decoded[0];
  935. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  936. while (count--) {
  937. *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
  938. decoded0++;
  939. p->buf++;
  940. /* Have we filled the history buffer? */
  941. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  942. memmove(p->historybuffer, p->buf,
  943. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  944. p->buf = p->historybuffer;
  945. }
  946. }
  947. }
  948. static av_always_inline int predictor_update_filter(APEPredictor *p,
  949. const int decoded, const int filter,
  950. const int delayA, const int delayB,
  951. const int adaptA, const int adaptB)
  952. {
  953. int32_t predictionA, predictionB, sign;
  954. p->buf[delayA] = p->lastA[filter];
  955. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  956. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  957. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  958. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  959. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  960. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  961. p->buf[delayA - 3] * p->coeffsA[filter][3];
  962. /* Apply a scaled first-order filter compression */
  963. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  964. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  965. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  966. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  967. p->filterB[filter] = p->filterA[filter ^ 1];
  968. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  969. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  970. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  971. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  972. p->buf[delayB - 4] * p->coeffsB[filter][4];
  973. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  974. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  975. sign = APESIGN(decoded);
  976. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  977. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  978. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  979. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  980. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  981. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  982. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  983. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  984. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  985. return p->filterA[filter];
  986. }
  987. static void predictor_decode_stereo_3950(APEContext *ctx, int count)
  988. {
  989. APEPredictor *p = &ctx->predictor;
  990. int32_t *decoded0 = ctx->decoded[0];
  991. int32_t *decoded1 = ctx->decoded[1];
  992. ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
  993. while (count--) {
  994. /* Predictor Y */
  995. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  996. YADAPTCOEFFSA, YADAPTCOEFFSB);
  997. decoded0++;
  998. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  999. XADAPTCOEFFSA, XADAPTCOEFFSB);
  1000. decoded1++;
  1001. /* Combined */
  1002. p->buf++;
  1003. /* Have we filled the history buffer? */
  1004. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  1005. memmove(p->historybuffer, p->buf,
  1006. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  1007. p->buf = p->historybuffer;
  1008. }
  1009. }
  1010. }
  1011. static void predictor_decode_mono_3950(APEContext *ctx, int count)
  1012. {
  1013. APEPredictor *p = &ctx->predictor;
  1014. int32_t *decoded0 = ctx->decoded[0];
  1015. int32_t predictionA, currentA, A, sign;
  1016. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  1017. currentA = p->lastA[0];
  1018. while (count--) {
  1019. A = *decoded0;
  1020. p->buf[YDELAYA] = currentA;
  1021. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  1022. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  1023. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  1024. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  1025. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  1026. currentA = A + (predictionA >> 10);
  1027. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  1028. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  1029. sign = APESIGN(A);
  1030. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  1031. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  1032. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  1033. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  1034. p->buf++;
  1035. /* Have we filled the history buffer? */
  1036. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  1037. memmove(p->historybuffer, p->buf,
  1038. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  1039. p->buf = p->historybuffer;
  1040. }
  1041. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  1042. *(decoded0++) = p->filterA[0];
  1043. }
  1044. p->lastA[0] = currentA;
  1045. }
  1046. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  1047. {
  1048. f->coeffs = buf;
  1049. f->historybuffer = buf + order;
  1050. f->delay = f->historybuffer + order * 2;
  1051. f->adaptcoeffs = f->historybuffer + order;
  1052. memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
  1053. memset(f->coeffs, 0, order * sizeof(*f->coeffs));
  1054. f->avg = 0;
  1055. }
  1056. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  1057. {
  1058. do_init_filter(&f[0], buf, order);
  1059. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  1060. }
  1061. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  1062. int32_t *data, int count, int order, int fracbits)
  1063. {
  1064. int res;
  1065. int absres;
  1066. while (count--) {
  1067. /* round fixedpoint scalar product */
  1068. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  1069. f->adaptcoeffs - order,
  1070. order, APESIGN(*data));
  1071. res = (res + (1 << (fracbits - 1))) >> fracbits;
  1072. res += *data;
  1073. *data++ = res;
  1074. /* Update the output history */
  1075. *f->delay++ = av_clip_int16(res);
  1076. if (version < 3980) {
  1077. /* Version ??? to < 3.98 files (untested) */
  1078. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  1079. f->adaptcoeffs[-4] >>= 1;
  1080. f->adaptcoeffs[-8] >>= 1;
  1081. } else {
  1082. /* Version 3.98 and later files */
  1083. /* Update the adaption coefficients */
  1084. absres = FFABS(res);
  1085. if (absres)
  1086. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  1087. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  1088. else
  1089. *f->adaptcoeffs = 0;
  1090. f->avg += (absres - f->avg) / 16;
  1091. f->adaptcoeffs[-1] >>= 1;
  1092. f->adaptcoeffs[-2] >>= 1;
  1093. f->adaptcoeffs[-8] >>= 1;
  1094. }
  1095. f->adaptcoeffs++;
  1096. /* Have we filled the history buffer? */
  1097. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  1098. memmove(f->historybuffer, f->delay - (order * 2),
  1099. (order * 2) * sizeof(*f->historybuffer));
  1100. f->delay = f->historybuffer + order * 2;
  1101. f->adaptcoeffs = f->historybuffer + order;
  1102. }
  1103. }
  1104. }
  1105. static void apply_filter(APEContext *ctx, APEFilter *f,
  1106. int32_t *data0, int32_t *data1,
  1107. int count, int order, int fracbits)
  1108. {
  1109. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  1110. if (data1)
  1111. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  1112. }
  1113. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  1114. int32_t *decoded1, int count)
  1115. {
  1116. int i;
  1117. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  1118. if (!ape_filter_orders[ctx->fset][i])
  1119. break;
  1120. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  1121. ape_filter_orders[ctx->fset][i],
  1122. ape_filter_fracbits[ctx->fset][i]);
  1123. }
  1124. }
  1125. static int init_frame_decoder(APEContext *ctx)
  1126. {
  1127. int i, ret;
  1128. if ((ret = init_entropy_decoder(ctx)) < 0)
  1129. return ret;
  1130. init_predictor_decoder(ctx);
  1131. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  1132. if (!ape_filter_orders[ctx->fset][i])
  1133. break;
  1134. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  1135. ape_filter_orders[ctx->fset][i]);
  1136. }
  1137. return 0;
  1138. }
  1139. static void ape_unpack_mono(APEContext *ctx, int count)
  1140. {
  1141. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  1142. /* We are pure silence, so we're done. */
  1143. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  1144. return;
  1145. }
  1146. ctx->entropy_decode_mono(ctx, count);
  1147. /* Now apply the predictor decoding */
  1148. ctx->predictor_decode_mono(ctx, count);
  1149. /* Pseudo-stereo - just copy left channel to right channel */
  1150. if (ctx->channels == 2) {
  1151. memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
  1152. }
  1153. }
  1154. static void ape_unpack_stereo(APEContext *ctx, int count)
  1155. {
  1156. int32_t left, right;
  1157. int32_t *decoded0 = ctx->decoded[0];
  1158. int32_t *decoded1 = ctx->decoded[1];
  1159. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  1160. /* We are pure silence, so we're done. */
  1161. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  1162. return;
  1163. }
  1164. ctx->entropy_decode_stereo(ctx, count);
  1165. /* Now apply the predictor decoding */
  1166. ctx->predictor_decode_stereo(ctx, count);
  1167. /* Decorrelate and scale to output depth */
  1168. while (count--) {
  1169. left = *decoded1 - (*decoded0 / 2);
  1170. right = left + *decoded0;
  1171. *(decoded0++) = left;
  1172. *(decoded1++) = right;
  1173. }
  1174. }
  1175. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  1176. int *got_frame_ptr, AVPacket *avpkt)
  1177. {
  1178. AVFrame *frame = data;
  1179. const uint8_t *buf = avpkt->data;
  1180. APEContext *s = avctx->priv_data;
  1181. uint8_t *sample8;
  1182. int16_t *sample16;
  1183. int32_t *sample24;
  1184. int i, ch, ret;
  1185. int blockstodecode;
  1186. /* this should never be negative, but bad things will happen if it is, so
  1187. check it just to make sure. */
  1188. av_assert0(s->samples >= 0);
  1189. if(!s->samples){
  1190. uint32_t nblocks, offset;
  1191. int buf_size;
  1192. if (!avpkt->size) {
  1193. *got_frame_ptr = 0;
  1194. return 0;
  1195. }
  1196. if (avpkt->size < 8) {
  1197. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  1198. return AVERROR_INVALIDDATA;
  1199. }
  1200. buf_size = avpkt->size & ~3;
  1201. if (buf_size != avpkt->size) {
  1202. av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
  1203. "extra bytes at the end will be skipped.\n");
  1204. }
  1205. if (s->fileversion < 3950) // previous versions overread two bytes
  1206. buf_size += 2;
  1207. av_fast_malloc(&s->data, &s->data_size, buf_size);
  1208. if (!s->data)
  1209. return AVERROR(ENOMEM);
  1210. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  1211. memset(s->data + (buf_size & ~3), 0, buf_size & 3);
  1212. s->ptr = s->data;
  1213. s->data_end = s->data + buf_size;
  1214. nblocks = bytestream_get_be32(&s->ptr);
  1215. offset = bytestream_get_be32(&s->ptr);
  1216. if (s->fileversion >= 3900) {
  1217. if (offset > 3) {
  1218. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  1219. s->data = NULL;
  1220. return AVERROR_INVALIDDATA;
  1221. }
  1222. if (s->data_end - s->ptr < offset) {
  1223. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  1224. return AVERROR_INVALIDDATA;
  1225. }
  1226. s->ptr += offset;
  1227. } else {
  1228. init_get_bits(&s->gb, s->ptr, (s->data_end - s->ptr) * 8);
  1229. if (s->fileversion > 3800)
  1230. skip_bits_long(&s->gb, offset * 8);
  1231. else
  1232. skip_bits_long(&s->gb, offset);
  1233. }
  1234. if (!nblocks || nblocks > INT_MAX) {
  1235. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  1236. return AVERROR_INVALIDDATA;
  1237. }
  1238. s->samples = nblocks;
  1239. /* Initialize the frame decoder */
  1240. if (init_frame_decoder(s) < 0) {
  1241. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  1242. return AVERROR_INVALIDDATA;
  1243. }
  1244. }
  1245. if (!s->data) {
  1246. *got_frame_ptr = 0;
  1247. return avpkt->size;
  1248. }
  1249. blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
  1250. // for old files coefficients were not interleaved,
  1251. // so we need to decode all of them at once
  1252. if (s->fileversion < 3930)
  1253. blockstodecode = s->samples;
  1254. /* reallocate decoded sample buffer if needed */
  1255. av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
  1256. 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
  1257. if (!s->decoded_buffer)
  1258. return AVERROR(ENOMEM);
  1259. memset(s->decoded_buffer, 0, s->decoded_size);
  1260. s->decoded[0] = s->decoded_buffer;
  1261. s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
  1262. /* get output buffer */
  1263. frame->nb_samples = blockstodecode;
  1264. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  1265. return ret;
  1266. s->error=0;
  1267. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  1268. ape_unpack_mono(s, blockstodecode);
  1269. else
  1270. ape_unpack_stereo(s, blockstodecode);
  1271. emms_c();
  1272. if (s->error) {
  1273. s->samples=0;
  1274. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  1275. return AVERROR_INVALIDDATA;
  1276. }
  1277. switch (s->bps) {
  1278. case 8:
  1279. for (ch = 0; ch < s->channels; ch++) {
  1280. sample8 = (uint8_t *)frame->data[ch];
  1281. for (i = 0; i < blockstodecode; i++)
  1282. *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
  1283. }
  1284. break;
  1285. case 16:
  1286. for (ch = 0; ch < s->channels; ch++) {
  1287. sample16 = (int16_t *)frame->data[ch];
  1288. for (i = 0; i < blockstodecode; i++)
  1289. *sample16++ = s->decoded[ch][i];
  1290. }
  1291. break;
  1292. case 24:
  1293. for (ch = 0; ch < s->channels; ch++) {
  1294. sample24 = (int32_t *)frame->data[ch];
  1295. for (i = 0; i < blockstodecode; i++)
  1296. *sample24++ = s->decoded[ch][i] << 8;
  1297. }
  1298. break;
  1299. }
  1300. s->samples -= blockstodecode;
  1301. *got_frame_ptr = 1;
  1302. return !s->samples ? avpkt->size : 0;
  1303. }
  1304. static void ape_flush(AVCodecContext *avctx)
  1305. {
  1306. APEContext *s = avctx->priv_data;
  1307. s->samples= 0;
  1308. }
  1309. #define OFFSET(x) offsetof(APEContext, x)
  1310. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  1311. static const AVOption options[] = {
  1312. { "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" },
  1313. { "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" },
  1314. { NULL},
  1315. };
  1316. static const AVClass ape_decoder_class = {
  1317. .class_name = "APE decoder",
  1318. .item_name = av_default_item_name,
  1319. .option = options,
  1320. .version = LIBAVUTIL_VERSION_INT,
  1321. };
  1322. AVCodec ff_ape_decoder = {
  1323. .name = "ape",
  1324. .type = AVMEDIA_TYPE_AUDIO,
  1325. .id = AV_CODEC_ID_APE,
  1326. .priv_data_size = sizeof(APEContext),
  1327. .init = ape_decode_init,
  1328. .close = ape_decode_close,
  1329. .decode = ape_decode_frame,
  1330. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  1331. .flush = ape_flush,
  1332. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  1333. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
  1334. AV_SAMPLE_FMT_S16P,
  1335. AV_SAMPLE_FMT_S32P,
  1336. AV_SAMPLE_FMT_NONE },
  1337. .priv_class = &ape_decoder_class,
  1338. };