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.

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