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.

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