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.

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