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.

1592 lines
50KB

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