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.

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