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.

1648 lines
52KB

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