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.

1624 lines
51KB

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