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.

1676 lines
53KB

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