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.

1601 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. int32_t coeffsA[2][4]; ///< adaption coefficients
  108. int32_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_DEBUG, "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 culmulative 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 culmulative 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)))
  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: %d\n", rice->k);
  424. return AVERROR_INVALIDDATA;
  425. }
  426. rice->ksum += x - (rice->ksum + 8 >> 4);
  427. if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
  428. rice->k--;
  429. else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
  430. rice->k++;
  431. /* Convert to signed */
  432. if (x & 1)
  433. return (x >> 1) + 1;
  434. else
  435. return -(x >> 1);
  436. }
  437. static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
  438. {
  439. unsigned int x, overflow;
  440. int tmpk;
  441. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  442. if (overflow == (MODEL_ELEMENTS - 1)) {
  443. tmpk = range_decode_bits(ctx, 5);
  444. overflow = 0;
  445. } else
  446. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  447. if (tmpk <= 16 || ctx->fileversion < 3910) {
  448. if (tmpk > 23) {
  449. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  450. return AVERROR_INVALIDDATA;
  451. }
  452. x = range_decode_bits(ctx, tmpk);
  453. } else if (tmpk <= 31) {
  454. x = range_decode_bits(ctx, 16);
  455. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  456. } else {
  457. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  458. return AVERROR_INVALIDDATA;
  459. }
  460. x += overflow << tmpk;
  461. update_rice(rice, x);
  462. /* Convert to signed */
  463. if (x & 1)
  464. return (x >> 1) + 1;
  465. else
  466. return -(x >> 1);
  467. }
  468. static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
  469. {
  470. unsigned int x, overflow;
  471. int base, pivot;
  472. pivot = rice->ksum >> 5;
  473. if (pivot == 0)
  474. pivot = 1;
  475. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  476. if (overflow == (MODEL_ELEMENTS - 1)) {
  477. overflow = range_decode_bits(ctx, 16) << 16;
  478. overflow |= range_decode_bits(ctx, 16);
  479. }
  480. if (pivot < 0x10000) {
  481. base = range_decode_culfreq(ctx, pivot);
  482. range_decode_update(ctx, 1, base);
  483. } else {
  484. int base_hi = pivot, base_lo;
  485. int bbits = 0;
  486. while (base_hi & ~0xFFFF) {
  487. base_hi >>= 1;
  488. bbits++;
  489. }
  490. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  491. range_decode_update(ctx, 1, base_hi);
  492. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  493. range_decode_update(ctx, 1, base_lo);
  494. base = (base_hi << bbits) + base_lo;
  495. }
  496. x = base + overflow * pivot;
  497. update_rice(rice, x);
  498. /* Convert to signed */
  499. if (x & 1)
  500. return (x >> 1) + 1;
  501. else
  502. return -(x >> 1);
  503. }
  504. static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
  505. int32_t *out, APERice *rice, int blockstodecode)
  506. {
  507. int i;
  508. int ksummax, ksummin;
  509. rice->ksum = 0;
  510. for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
  511. out[i] = get_rice_ook(&ctx->gb, 10);
  512. rice->ksum += out[i];
  513. }
  514. rice->k = av_log2(rice->ksum / 10) + 1;
  515. if (rice->k >= 24)
  516. return;
  517. for (; i < FFMIN(blockstodecode, 64); i++) {
  518. out[i] = get_rice_ook(&ctx->gb, rice->k);
  519. rice->ksum += out[i];
  520. rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
  521. if (rice->k >= 24)
  522. return;
  523. }
  524. ksummax = 1 << rice->k + 7;
  525. ksummin = rice->k ? (1 << rice->k + 6) : 0;
  526. for (; i < blockstodecode; i++) {
  527. out[i] = get_rice_ook(&ctx->gb, rice->k);
  528. rice->ksum += out[i] - out[i - 64];
  529. while (rice->ksum < ksummin) {
  530. rice->k--;
  531. ksummin = rice->k ? ksummin >> 1 : 0;
  532. ksummax >>= 1;
  533. }
  534. while (rice->ksum >= ksummax) {
  535. rice->k++;
  536. if (rice->k > 24)
  537. return;
  538. ksummax <<= 1;
  539. ksummin = ksummin ? ksummin << 1 : 128;
  540. }
  541. }
  542. for (i = 0; i < blockstodecode; i++) {
  543. if (out[i] & 1)
  544. out[i] = (out[i] >> 1) + 1;
  545. else
  546. out[i] = -(out[i] >> 1);
  547. }
  548. }
  549. static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
  550. {
  551. decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
  552. blockstodecode);
  553. }
  554. static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
  555. {
  556. decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
  557. blockstodecode);
  558. decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
  559. blockstodecode);
  560. }
  561. static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
  562. {
  563. int32_t *decoded0 = ctx->decoded[0];
  564. while (blockstodecode--)
  565. *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
  566. }
  567. static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
  568. {
  569. int32_t *decoded0 = ctx->decoded[0];
  570. int32_t *decoded1 = ctx->decoded[1];
  571. int blocks = blockstodecode;
  572. while (blockstodecode--)
  573. *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
  574. while (blocks--)
  575. *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
  576. }
  577. static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
  578. {
  579. int32_t *decoded0 = ctx->decoded[0];
  580. while (blockstodecode--)
  581. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  582. }
  583. static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
  584. {
  585. int32_t *decoded0 = ctx->decoded[0];
  586. int32_t *decoded1 = ctx->decoded[1];
  587. int blocks = blockstodecode;
  588. while (blockstodecode--)
  589. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  590. range_dec_normalize(ctx);
  591. // because of some implementation peculiarities we need to backpedal here
  592. ctx->ptr -= 1;
  593. range_start_decoding(ctx);
  594. while (blocks--)
  595. *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
  596. }
  597. static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
  598. {
  599. int32_t *decoded0 = ctx->decoded[0];
  600. int32_t *decoded1 = ctx->decoded[1];
  601. while (blockstodecode--) {
  602. *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
  603. *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
  604. }
  605. }
  606. static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
  607. {
  608. int32_t *decoded0 = ctx->decoded[0];
  609. while (blockstodecode--)
  610. *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
  611. }
  612. static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
  613. {
  614. int32_t *decoded0 = ctx->decoded[0];
  615. int32_t *decoded1 = ctx->decoded[1];
  616. while (blockstodecode--) {
  617. *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
  618. *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
  619. }
  620. }
  621. static int init_entropy_decoder(APEContext *ctx)
  622. {
  623. /* Read the CRC */
  624. if (ctx->fileversion >= 3900) {
  625. if (ctx->data_end - ctx->ptr < 6)
  626. return AVERROR_INVALIDDATA;
  627. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  628. } else {
  629. ctx->CRC = get_bits_long(&ctx->gb, 32);
  630. }
  631. /* Read the frame flags if they exist */
  632. ctx->frameflags = 0;
  633. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  634. ctx->CRC &= ~0x80000000;
  635. if (ctx->data_end - ctx->ptr < 6)
  636. return AVERROR_INVALIDDATA;
  637. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  638. }
  639. /* Initialize the rice structs */
  640. ctx->riceX.k = 10;
  641. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  642. ctx->riceY.k = 10;
  643. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  644. if (ctx->fileversion >= 3900) {
  645. /* The first 8 bits of input are ignored. */
  646. ctx->ptr++;
  647. range_start_decoding(ctx);
  648. }
  649. return 0;
  650. }
  651. static const int32_t initial_coeffs_fast_3320[1] = {
  652. 375,
  653. };
  654. static const int32_t initial_coeffs_a_3800[3] = {
  655. 64, 115, 64,
  656. };
  657. static const int32_t initial_coeffs_b_3800[2] = {
  658. 740, 0
  659. };
  660. static const int32_t initial_coeffs_3930[4] = {
  661. 360, 317, -109, 98
  662. };
  663. static void init_predictor_decoder(APEContext *ctx)
  664. {
  665. APEPredictor *p = &ctx->predictor;
  666. /* Zero the history buffers */
  667. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
  668. p->buf = p->historybuffer;
  669. /* Initialize and zero the coefficients */
  670. if (ctx->fileversion < 3930) {
  671. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  672. memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
  673. sizeof(initial_coeffs_fast_3320));
  674. memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
  675. sizeof(initial_coeffs_fast_3320));
  676. } else {
  677. memcpy(p->coeffsA[0], initial_coeffs_a_3800,
  678. sizeof(initial_coeffs_a_3800));
  679. memcpy(p->coeffsA[1], initial_coeffs_a_3800,
  680. sizeof(initial_coeffs_a_3800));
  681. }
  682. } else {
  683. memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
  684. memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
  685. }
  686. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  687. if (ctx->fileversion < 3930) {
  688. memcpy(p->coeffsB[0], initial_coeffs_b_3800,
  689. sizeof(initial_coeffs_b_3800));
  690. memcpy(p->coeffsB[1], initial_coeffs_b_3800,
  691. sizeof(initial_coeffs_b_3800));
  692. }
  693. p->filterA[0] = p->filterA[1] = 0;
  694. p->filterB[0] = p->filterB[1] = 0;
  695. p->lastA[0] = p->lastA[1] = 0;
  696. p->sample_pos = 0;
  697. }
  698. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  699. static inline int APESIGN(int32_t x) {
  700. return (x < 0) - (x > 0);
  701. }
  702. static av_always_inline int filter_fast_3320(APEPredictor *p,
  703. const int decoded, const int filter,
  704. const int delayA)
  705. {
  706. int32_t predictionA;
  707. p->buf[delayA] = p->lastA[filter];
  708. if (p->sample_pos < 3) {
  709. p->lastA[filter] = decoded;
  710. p->filterA[filter] = decoded;
  711. return decoded;
  712. }
  713. predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
  714. p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9);
  715. if ((decoded ^ predictionA) > 0)
  716. p->coeffsA[filter][0]++;
  717. else
  718. p->coeffsA[filter][0]--;
  719. p->filterA[filter] += p->lastA[filter];
  720. return p->filterA[filter];
  721. }
  722. static av_always_inline int filter_3800(APEPredictor *p,
  723. const int decoded, const int filter,
  724. const int delayA, const int delayB,
  725. const int start, const int shift)
  726. {
  727. int32_t predictionA, predictionB, sign;
  728. int32_t d0, d1, d2, d3, d4;
  729. p->buf[delayA] = p->lastA[filter];
  730. p->buf[delayB] = p->filterB[filter];
  731. if (p->sample_pos < start) {
  732. predictionA = decoded + p->filterA[filter];
  733. p->lastA[filter] = decoded;
  734. p->filterB[filter] = decoded;
  735. p->filterA[filter] = predictionA;
  736. return predictionA;
  737. }
  738. d2 = p->buf[delayA];
  739. d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
  740. d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
  741. d3 = p->buf[delayB] * 2 - p->buf[delayB - 1];
  742. d4 = p->buf[delayB];
  743. predictionA = d0 * p->coeffsA[filter][0] +
  744. d1 * p->coeffsA[filter][1] +
  745. d2 * p->coeffsA[filter][2];
  746. sign = APESIGN(decoded);
  747. p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
  748. p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
  749. p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
  750. predictionB = d3 * p->coeffsB[filter][0] -
  751. d4 * p->coeffsB[filter][1];
  752. p->lastA[filter] = decoded + (predictionA >> 11);
  753. sign = APESIGN(p->lastA[filter]);
  754. p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
  755. p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
  756. p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
  757. p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
  758. return p->filterA[filter];
  759. }
  760. static void long_filter_high_3800(int32_t *buffer, int order, int shift,
  761. int32_t *coeffs, int32_t *delay, int length)
  762. {
  763. int i, j;
  764. int32_t dotprod, sign;
  765. if (order >= length)
  766. return;
  767. memset(coeffs, 0, order * sizeof(*coeffs));
  768. for (i = 0; i < order; i++)
  769. delay[i] = buffer[i];
  770. for (i = order; i < length; i++) {
  771. dotprod = 0;
  772. sign = APESIGN(buffer[i]);
  773. for (j = 0; j < order; j++) {
  774. dotprod += delay[j] * coeffs[j];
  775. coeffs[j] += ((delay[j] >> 31) | 1) * sign;
  776. }
  777. buffer[i] -= dotprod >> shift;
  778. for (j = 0; j < order - 1; j++)
  779. delay[j] = delay[j + 1];
  780. delay[order - 1] = buffer[i];
  781. }
  782. }
  783. static void long_filter_ehigh_3830(int32_t *buffer, int length)
  784. {
  785. int i, j;
  786. int32_t dotprod, sign;
  787. int32_t coeffs[8] = { 0 }, delay[8] = { 0 };
  788. for (i = 0; i < length; i++) {
  789. dotprod = 0;
  790. sign = APESIGN(buffer[i]);
  791. for (j = 7; j >= 0; j--) {
  792. dotprod += delay[j] * coeffs[j];
  793. coeffs[j] += ((delay[j] >> 31) | 1) * sign;
  794. }
  795. for (j = 7; j > 0; j--)
  796. delay[j] = delay[j - 1];
  797. delay[0] = buffer[i];
  798. buffer[i] -= dotprod >> 9;
  799. }
  800. }
  801. static void predictor_decode_stereo_3800(APEContext *ctx, int count)
  802. {
  803. APEPredictor *p = &ctx->predictor;
  804. int32_t *decoded0 = ctx->decoded[0];
  805. int32_t *decoded1 = ctx->decoded[1];
  806. int32_t coeffs[256], delay[256];
  807. int start = 4, shift = 10;
  808. if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
  809. start = 16;
  810. long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
  811. long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
  812. } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
  813. int order = 128, shift2 = 11;
  814. if (ctx->fileversion >= 3830) {
  815. order <<= 1;
  816. shift++;
  817. shift2++;
  818. long_filter_ehigh_3830(decoded0 + order, count - order);
  819. long_filter_ehigh_3830(decoded1 + order, count - order);
  820. }
  821. start = order;
  822. long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
  823. long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
  824. }
  825. while (count--) {
  826. int X = *decoded0, Y = *decoded1;
  827. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  828. *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
  829. decoded0++;
  830. *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
  831. decoded1++;
  832. } else {
  833. *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
  834. start, shift);
  835. decoded0++;
  836. *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
  837. start, shift);
  838. decoded1++;
  839. }
  840. /* Combined */
  841. p->buf++;
  842. p->sample_pos++;
  843. /* Have we filled the history buffer? */
  844. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  845. memmove(p->historybuffer, p->buf,
  846. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  847. p->buf = p->historybuffer;
  848. }
  849. }
  850. }
  851. static void predictor_decode_mono_3800(APEContext *ctx, int count)
  852. {
  853. APEPredictor *p = &ctx->predictor;
  854. int32_t *decoded0 = ctx->decoded[0];
  855. int32_t coeffs[256], delay[256];
  856. int start = 4, shift = 10;
  857. if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
  858. start = 16;
  859. long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
  860. } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
  861. int order = 128, shift2 = 11;
  862. if (ctx->fileversion >= 3830) {
  863. order <<= 1;
  864. shift++;
  865. shift2++;
  866. long_filter_ehigh_3830(decoded0 + order, count - order);
  867. }
  868. start = order;
  869. long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
  870. }
  871. while (count--) {
  872. if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
  873. *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
  874. decoded0++;
  875. } else {
  876. *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
  877. start, shift);
  878. decoded0++;
  879. }
  880. /* Combined */
  881. p->buf++;
  882. p->sample_pos++;
  883. /* Have we filled the history buffer? */
  884. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  885. memmove(p->historybuffer, p->buf,
  886. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  887. p->buf = p->historybuffer;
  888. }
  889. }
  890. }
  891. static av_always_inline int predictor_update_3930(APEPredictor *p,
  892. const int decoded, const int filter,
  893. const int delayA)
  894. {
  895. int32_t predictionA, sign;
  896. int32_t d0, d1, d2, d3;
  897. p->buf[delayA] = p->lastA[filter];
  898. d0 = p->buf[delayA ];
  899. d1 = p->buf[delayA ] - p->buf[delayA - 1];
  900. d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
  901. d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
  902. predictionA = d0 * p->coeffsA[filter][0] +
  903. d1 * p->coeffsA[filter][1] +
  904. d2 * p->coeffsA[filter][2] +
  905. d3 * p->coeffsA[filter][3];
  906. p->lastA[filter] = decoded + (predictionA >> 9);
  907. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  908. sign = APESIGN(decoded);
  909. p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
  910. p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
  911. p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
  912. p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
  913. return p->filterA[filter];
  914. }
  915. static void predictor_decode_stereo_3930(APEContext *ctx, int count)
  916. {
  917. APEPredictor *p = &ctx->predictor;
  918. int32_t *decoded0 = ctx->decoded[0];
  919. int32_t *decoded1 = ctx->decoded[1];
  920. ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
  921. while (count--) {
  922. /* Predictor Y */
  923. int Y = *decoded1, X = *decoded0;
  924. *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
  925. decoded0++;
  926. *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
  927. decoded1++;
  928. /* Combined */
  929. p->buf++;
  930. /* Have we filled the history buffer? */
  931. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  932. memmove(p->historybuffer, p->buf,
  933. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  934. p->buf = p->historybuffer;
  935. }
  936. }
  937. }
  938. static void predictor_decode_mono_3930(APEContext *ctx, int count)
  939. {
  940. APEPredictor *p = &ctx->predictor;
  941. int32_t *decoded0 = ctx->decoded[0];
  942. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  943. while (count--) {
  944. *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
  945. decoded0++;
  946. p->buf++;
  947. /* Have we filled the history buffer? */
  948. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  949. memmove(p->historybuffer, p->buf,
  950. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  951. p->buf = p->historybuffer;
  952. }
  953. }
  954. }
  955. static av_always_inline int predictor_update_filter(APEPredictor *p,
  956. const int decoded, const int filter,
  957. const int delayA, const int delayB,
  958. const int adaptA, const int adaptB)
  959. {
  960. int32_t predictionA, predictionB, sign;
  961. p->buf[delayA] = p->lastA[filter];
  962. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  963. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  964. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  965. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  966. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  967. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  968. p->buf[delayA - 3] * p->coeffsA[filter][3];
  969. /* Apply a scaled first-order filter compression */
  970. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  971. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  972. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  973. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  974. p->filterB[filter] = p->filterA[filter ^ 1];
  975. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  976. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  977. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  978. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  979. p->buf[delayB - 4] * p->coeffsB[filter][4];
  980. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  981. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  982. sign = APESIGN(decoded);
  983. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  984. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  985. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  986. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  987. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  988. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  989. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  990. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  991. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  992. return p->filterA[filter];
  993. }
  994. static void predictor_decode_stereo_3950(APEContext *ctx, int count)
  995. {
  996. APEPredictor *p = &ctx->predictor;
  997. int32_t *decoded0 = ctx->decoded[0];
  998. int32_t *decoded1 = ctx->decoded[1];
  999. ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
  1000. while (count--) {
  1001. /* Predictor Y */
  1002. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  1003. YADAPTCOEFFSA, YADAPTCOEFFSB);
  1004. decoded0++;
  1005. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  1006. XADAPTCOEFFSA, XADAPTCOEFFSB);
  1007. decoded1++;
  1008. /* Combined */
  1009. p->buf++;
  1010. /* Have we filled the history buffer? */
  1011. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  1012. memmove(p->historybuffer, p->buf,
  1013. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  1014. p->buf = p->historybuffer;
  1015. }
  1016. }
  1017. }
  1018. static void predictor_decode_mono_3950(APEContext *ctx, int count)
  1019. {
  1020. APEPredictor *p = &ctx->predictor;
  1021. int32_t *decoded0 = ctx->decoded[0];
  1022. int32_t predictionA, currentA, A, sign;
  1023. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  1024. currentA = p->lastA[0];
  1025. while (count--) {
  1026. A = *decoded0;
  1027. p->buf[YDELAYA] = currentA;
  1028. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  1029. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  1030. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  1031. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  1032. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  1033. currentA = A + (predictionA >> 10);
  1034. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  1035. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  1036. sign = APESIGN(A);
  1037. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  1038. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  1039. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  1040. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  1041. p->buf++;
  1042. /* Have we filled the history buffer? */
  1043. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  1044. memmove(p->historybuffer, p->buf,
  1045. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  1046. p->buf = p->historybuffer;
  1047. }
  1048. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  1049. *(decoded0++) = p->filterA[0];
  1050. }
  1051. p->lastA[0] = currentA;
  1052. }
  1053. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  1054. {
  1055. f->coeffs = buf;
  1056. f->historybuffer = buf + order;
  1057. f->delay = f->historybuffer + order * 2;
  1058. f->adaptcoeffs = f->historybuffer + order;
  1059. memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
  1060. memset(f->coeffs, 0, order * sizeof(*f->coeffs));
  1061. f->avg = 0;
  1062. }
  1063. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  1064. {
  1065. do_init_filter(&f[0], buf, order);
  1066. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  1067. }
  1068. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  1069. int32_t *data, int count, int order, int fracbits)
  1070. {
  1071. int res;
  1072. int absres;
  1073. while (count--) {
  1074. /* round fixedpoint scalar product */
  1075. res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
  1076. f->delay - order,
  1077. f->adaptcoeffs - order,
  1078. order, APESIGN(*data));
  1079. res = (res + (1 << (fracbits - 1))) >> fracbits;
  1080. res += *data;
  1081. *data++ = res;
  1082. /* Update the output history */
  1083. *f->delay++ = av_clip_int16(res);
  1084. if (version < 3980) {
  1085. /* Version ??? to < 3.98 files (untested) */
  1086. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  1087. f->adaptcoeffs[-4] >>= 1;
  1088. f->adaptcoeffs[-8] >>= 1;
  1089. } else {
  1090. /* Version 3.98 and later files */
  1091. /* Update the adaption coefficients */
  1092. absres = FFABS(res);
  1093. if (absres)
  1094. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  1095. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  1096. else
  1097. *f->adaptcoeffs = 0;
  1098. f->avg += (absres - f->avg) / 16;
  1099. f->adaptcoeffs[-1] >>= 1;
  1100. f->adaptcoeffs[-2] >>= 1;
  1101. f->adaptcoeffs[-8] >>= 1;
  1102. }
  1103. f->adaptcoeffs++;
  1104. /* Have we filled the history buffer? */
  1105. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  1106. memmove(f->historybuffer, f->delay - (order * 2),
  1107. (order * 2) * sizeof(*f->historybuffer));
  1108. f->delay = f->historybuffer + order * 2;
  1109. f->adaptcoeffs = f->historybuffer + order;
  1110. }
  1111. }
  1112. }
  1113. static void apply_filter(APEContext *ctx, APEFilter *f,
  1114. int32_t *data0, int32_t *data1,
  1115. int count, int order, int fracbits)
  1116. {
  1117. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  1118. if (data1)
  1119. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  1120. }
  1121. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  1122. int32_t *decoded1, int count)
  1123. {
  1124. int i;
  1125. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  1126. if (!ape_filter_orders[ctx->fset][i])
  1127. break;
  1128. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  1129. ape_filter_orders[ctx->fset][i],
  1130. ape_filter_fracbits[ctx->fset][i]);
  1131. }
  1132. }
  1133. static int init_frame_decoder(APEContext *ctx)
  1134. {
  1135. int i, ret;
  1136. if ((ret = init_entropy_decoder(ctx)) < 0)
  1137. return ret;
  1138. init_predictor_decoder(ctx);
  1139. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  1140. if (!ape_filter_orders[ctx->fset][i])
  1141. break;
  1142. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  1143. ape_filter_orders[ctx->fset][i]);
  1144. }
  1145. return 0;
  1146. }
  1147. static void ape_unpack_mono(APEContext *ctx, int count)
  1148. {
  1149. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  1150. /* We are pure silence, so we're done. */
  1151. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  1152. return;
  1153. }
  1154. ctx->entropy_decode_mono(ctx, count);
  1155. /* Now apply the predictor decoding */
  1156. ctx->predictor_decode_mono(ctx, count);
  1157. /* Pseudo-stereo - just copy left channel to right channel */
  1158. if (ctx->channels == 2) {
  1159. memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
  1160. }
  1161. }
  1162. static void ape_unpack_stereo(APEContext *ctx, int count)
  1163. {
  1164. int32_t left, right;
  1165. int32_t *decoded0 = ctx->decoded[0];
  1166. int32_t *decoded1 = ctx->decoded[1];
  1167. if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
  1168. /* We are pure silence, so we're done. */
  1169. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  1170. return;
  1171. }
  1172. ctx->entropy_decode_stereo(ctx, count);
  1173. /* Now apply the predictor decoding */
  1174. ctx->predictor_decode_stereo(ctx, count);
  1175. /* Decorrelate and scale to output depth */
  1176. while (count--) {
  1177. left = *decoded1 - (*decoded0 / 2);
  1178. right = left + *decoded0;
  1179. *(decoded0++) = left;
  1180. *(decoded1++) = right;
  1181. }
  1182. }
  1183. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  1184. int *got_frame_ptr, AVPacket *avpkt)
  1185. {
  1186. AVFrame *frame = data;
  1187. const uint8_t *buf = avpkt->data;
  1188. APEContext *s = avctx->priv_data;
  1189. uint8_t *sample8;
  1190. int16_t *sample16;
  1191. int32_t *sample24;
  1192. int i, ch, ret;
  1193. int blockstodecode;
  1194. uint64_t decoded_buffer_size;
  1195. /* this should never be negative, but bad things will happen if it is, so
  1196. check it just to make sure. */
  1197. av_assert0(s->samples >= 0);
  1198. if(!s->samples){
  1199. uint32_t nblocks, offset;
  1200. int buf_size;
  1201. if (!avpkt->size) {
  1202. *got_frame_ptr = 0;
  1203. return 0;
  1204. }
  1205. if (avpkt->size < 8) {
  1206. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  1207. return AVERROR_INVALIDDATA;
  1208. }
  1209. buf_size = avpkt->size & ~3;
  1210. if (buf_size != avpkt->size) {
  1211. av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
  1212. "extra bytes at the end will be skipped.\n");
  1213. }
  1214. if (s->fileversion < 3950) // previous versions overread two bytes
  1215. buf_size += 2;
  1216. av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
  1217. if (!s->data)
  1218. return AVERROR(ENOMEM);
  1219. s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
  1220. buf_size >> 2);
  1221. memset(s->data + (buf_size & ~3), 0, buf_size & 3);
  1222. s->ptr = s->data;
  1223. s->data_end = s->data + buf_size;
  1224. nblocks = bytestream_get_be32(&s->ptr);
  1225. offset = bytestream_get_be32(&s->ptr);
  1226. if (s->fileversion >= 3900) {
  1227. if (offset > 3) {
  1228. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  1229. s->data = NULL;
  1230. return AVERROR_INVALIDDATA;
  1231. }
  1232. if (s->data_end - s->ptr < offset) {
  1233. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  1234. return AVERROR_INVALIDDATA;
  1235. }
  1236. s->ptr += offset;
  1237. } else {
  1238. if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
  1239. return ret;
  1240. if (s->fileversion > 3800)
  1241. skip_bits_long(&s->gb, offset * 8);
  1242. else
  1243. skip_bits_long(&s->gb, offset);
  1244. }
  1245. if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
  1246. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
  1247. nblocks);
  1248. return AVERROR_INVALIDDATA;
  1249. }
  1250. /* Initialize the frame decoder */
  1251. if (init_frame_decoder(s) < 0) {
  1252. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  1253. return AVERROR_INVALIDDATA;
  1254. }
  1255. s->samples = nblocks;
  1256. }
  1257. if (!s->data) {
  1258. *got_frame_ptr = 0;
  1259. return avpkt->size;
  1260. }
  1261. blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
  1262. // for old files coefficients were not interleaved,
  1263. // so we need to decode all of them at once
  1264. if (s->fileversion < 3930)
  1265. blockstodecode = s->samples;
  1266. /* reallocate decoded sample buffer if needed */
  1267. decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
  1268. av_assert0(decoded_buffer_size <= INT_MAX);
  1269. av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
  1270. if (!s->decoded_buffer)
  1271. return AVERROR(ENOMEM);
  1272. memset(s->decoded_buffer, 0, s->decoded_size);
  1273. s->decoded[0] = s->decoded_buffer;
  1274. s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
  1275. /* get output buffer */
  1276. frame->nb_samples = blockstodecode;
  1277. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  1278. return ret;
  1279. s->error=0;
  1280. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  1281. ape_unpack_mono(s, blockstodecode);
  1282. else
  1283. ape_unpack_stereo(s, blockstodecode);
  1284. emms_c();
  1285. if (s->error) {
  1286. s->samples=0;
  1287. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  1288. return AVERROR_INVALIDDATA;
  1289. }
  1290. switch (s->bps) {
  1291. case 8:
  1292. for (ch = 0; ch < s->channels; ch++) {
  1293. sample8 = (uint8_t *)frame->data[ch];
  1294. for (i = 0; i < blockstodecode; i++)
  1295. *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
  1296. }
  1297. break;
  1298. case 16:
  1299. for (ch = 0; ch < s->channels; ch++) {
  1300. sample16 = (int16_t *)frame->data[ch];
  1301. for (i = 0; i < blockstodecode; i++)
  1302. *sample16++ = s->decoded[ch][i];
  1303. }
  1304. break;
  1305. case 24:
  1306. for (ch = 0; ch < s->channels; ch++) {
  1307. sample24 = (int32_t *)frame->data[ch];
  1308. for (i = 0; i < blockstodecode; i++)
  1309. *sample24++ = s->decoded[ch][i] << 8;
  1310. }
  1311. break;
  1312. }
  1313. s->samples -= blockstodecode;
  1314. *got_frame_ptr = 1;
  1315. return !s->samples ? avpkt->size : 0;
  1316. }
  1317. static void ape_flush(AVCodecContext *avctx)
  1318. {
  1319. APEContext *s = avctx->priv_data;
  1320. s->samples= 0;
  1321. }
  1322. #define OFFSET(x) offsetof(APEContext, x)
  1323. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  1324. static const AVOption options[] = {
  1325. { "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" },
  1326. { "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" },
  1327. { NULL},
  1328. };
  1329. static const AVClass ape_decoder_class = {
  1330. .class_name = "APE decoder",
  1331. .item_name = av_default_item_name,
  1332. .option = options,
  1333. .version = LIBAVUTIL_VERSION_INT,
  1334. };
  1335. AVCodec ff_ape_decoder = {
  1336. .name = "ape",
  1337. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  1338. .type = AVMEDIA_TYPE_AUDIO,
  1339. .id = AV_CODEC_ID_APE,
  1340. .priv_data_size = sizeof(APEContext),
  1341. .init = ape_decode_init,
  1342. .close = ape_decode_close,
  1343. .decode = ape_decode_frame,
  1344. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  1345. .flush = ape_flush,
  1346. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
  1347. AV_SAMPLE_FMT_S16P,
  1348. AV_SAMPLE_FMT_S32P,
  1349. AV_SAMPLE_FMT_NONE },
  1350. .priv_class = &ape_decoder_class,
  1351. };