apedec.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. /*
  2. * Monkey's Audio lossless audio decoder
  3. * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
  4. * based upon libdemac from Dave Chapman.
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #define ALT_BITSTREAM_READER_LE
  23. #include "avcodec.h"
  24. #include "dsputil.h"
  25. #include "bitstream.h"
  26. #include "bytestream.h"
  27. /**
  28. * @file libavcodec/apedec.c
  29. * Monkey's Audio lossless audio decoder
  30. */
  31. #define BLOCKS_PER_LOOP 4608
  32. #define MAX_CHANNELS 2
  33. #define MAX_BYTESPERSAMPLE 3
  34. #define APE_FRAMECODE_MONO_SILENCE 1
  35. #define APE_FRAMECODE_STEREO_SILENCE 3
  36. #define APE_FRAMECODE_PSEUDO_STEREO 4
  37. #define HISTORY_SIZE 512
  38. #define PREDICTOR_ORDER 8
  39. /** Total size of all predictor histories */
  40. #define PREDICTOR_SIZE 50
  41. #define YDELAYA (18 + PREDICTOR_ORDER*4)
  42. #define YDELAYB (18 + PREDICTOR_ORDER*3)
  43. #define XDELAYA (18 + PREDICTOR_ORDER*2)
  44. #define XDELAYB (18 + PREDICTOR_ORDER)
  45. #define YADAPTCOEFFSA 18
  46. #define XADAPTCOEFFSA 14
  47. #define YADAPTCOEFFSB 10
  48. #define XADAPTCOEFFSB 5
  49. /**
  50. * Possible compression levels
  51. * @{
  52. */
  53. enum APECompressionLevel {
  54. COMPRESSION_LEVEL_FAST = 1000,
  55. COMPRESSION_LEVEL_NORMAL = 2000,
  56. COMPRESSION_LEVEL_HIGH = 3000,
  57. COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
  58. COMPRESSION_LEVEL_INSANE = 5000
  59. };
  60. /** @} */
  61. #define APE_FILTER_LEVELS 3
  62. /** Filter orders depending on compression level */
  63. static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
  64. { 0, 0, 0 },
  65. { 16, 0, 0 },
  66. { 64, 0, 0 },
  67. { 32, 256, 0 },
  68. { 16, 256, 1280 }
  69. };
  70. /** Filter fraction bits depending on compression level */
  71. static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
  72. { 0, 0, 0 },
  73. { 11, 0, 0 },
  74. { 11, 0, 0 },
  75. { 10, 13, 0 },
  76. { 11, 13, 15 }
  77. };
  78. /** Filters applied to the decoded data */
  79. typedef struct APEFilter {
  80. int16_t *coeffs; ///< actual coefficients used in filtering
  81. int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
  82. int16_t *historybuffer; ///< filter memory
  83. int16_t *delay; ///< filtered values
  84. int avg;
  85. } APEFilter;
  86. typedef struct APERice {
  87. uint32_t k;
  88. uint32_t ksum;
  89. } APERice;
  90. typedef struct APERangecoder {
  91. uint32_t low; ///< low end of interval
  92. uint32_t range; ///< length of interval
  93. uint32_t help; ///< bytes_to_follow resp. intermediate value
  94. unsigned int buffer; ///< buffer for input/output
  95. } APERangecoder;
  96. /** Filter histories */
  97. typedef struct APEPredictor {
  98. int32_t *buf;
  99. int32_t lastA[2];
  100. int32_t filterA[2];
  101. int32_t filterB[2];
  102. int32_t coeffsA[2][4]; ///< adaption coefficients
  103. int32_t coeffsB[2][5]; ///< adaption coefficients
  104. int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
  105. } APEPredictor;
  106. /** Decoder context */
  107. typedef struct APEContext {
  108. AVCodecContext *avctx;
  109. DSPContext dsp;
  110. int channels;
  111. int samples; ///< samples left to decode in current frame
  112. int fileversion; ///< codec version, very important in decoding process
  113. int compression_level; ///< compression levels
  114. int fset; ///< which filter set to use (calculated from compression level)
  115. int flags; ///< global decoder flags
  116. uint32_t CRC; ///< frame CRC
  117. int frameflags; ///< frame flags
  118. int currentframeblocks; ///< samples (per channel) in current frame
  119. int blocksdecoded; ///< count of decoded samples in current frame
  120. APEPredictor predictor; ///< predictor used for final reconstruction
  121. int32_t decoded0[BLOCKS_PER_LOOP]; ///< decoded data for the first channel
  122. int32_t decoded1[BLOCKS_PER_LOOP]; ///< decoded data for the second channel
  123. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  124. APERangecoder rc; ///< rangecoder used to decode actual values
  125. APERice riceX; ///< rice code parameters for the second channel
  126. APERice riceY; ///< rice code parameters for the first channel
  127. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  128. uint8_t *data; ///< current frame data
  129. uint8_t *data_end; ///< frame data end
  130. const uint8_t *ptr; ///< current position in frame data
  131. const uint8_t *last_ptr; ///< position where last 4608-sample block ended
  132. int error;
  133. } APEContext;
  134. // TODO: dsputilize
  135. static av_cold int ape_decode_init(AVCodecContext * avctx)
  136. {
  137. APEContext *s = avctx->priv_data;
  138. int i;
  139. if (avctx->extradata_size != 6) {
  140. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  141. return -1;
  142. }
  143. if (avctx->bits_per_coded_sample != 16) {
  144. av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
  145. return -1;
  146. }
  147. if (avctx->channels > 2) {
  148. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  149. return -1;
  150. }
  151. s->avctx = avctx;
  152. s->channels = avctx->channels;
  153. s->fileversion = AV_RL16(avctx->extradata);
  154. s->compression_level = AV_RL16(avctx->extradata + 2);
  155. s->flags = AV_RL16(avctx->extradata + 4);
  156. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);
  157. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
  158. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);
  159. return -1;
  160. }
  161. s->fset = s->compression_level / 1000 - 1;
  162. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  163. if (!ape_filter_orders[s->fset][i])
  164. break;
  165. s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);
  166. }
  167. dsputil_init(&s->dsp, avctx);
  168. avctx->sample_fmt = SAMPLE_FMT_S16;
  169. avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
  170. return 0;
  171. }
  172. static av_cold int ape_decode_close(AVCodecContext * avctx)
  173. {
  174. APEContext *s = avctx->priv_data;
  175. int i;
  176. for (i = 0; i < APE_FILTER_LEVELS; i++)
  177. av_freep(&s->filterbuf[i]);
  178. return 0;
  179. }
  180. /**
  181. * @defgroup rangecoder APE range decoder
  182. * @{
  183. */
  184. #define CODE_BITS 32
  185. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  186. #define SHIFT_BITS (CODE_BITS - 9)
  187. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  188. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  189. /** Start the decoder */
  190. static inline void range_start_decoding(APEContext * ctx)
  191. {
  192. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  193. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  194. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  195. }
  196. /** Perform normalization */
  197. static inline void range_dec_normalize(APEContext * ctx)
  198. {
  199. while (ctx->rc.range <= BOTTOM_VALUE) {
  200. ctx->rc.buffer <<= 8;
  201. if(ctx->ptr < ctx->data_end)
  202. ctx->rc.buffer += *ctx->ptr;
  203. ctx->ptr++;
  204. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  205. ctx->rc.range <<= 8;
  206. }
  207. }
  208. /**
  209. * Calculate culmulative frequency for next symbol. Does NO update!
  210. * @param ctx decoder context
  211. * @param tot_f is the total frequency or (code_value)1<<shift
  212. * @return the culmulative frequency
  213. */
  214. static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
  215. {
  216. range_dec_normalize(ctx);
  217. ctx->rc.help = ctx->rc.range / tot_f;
  218. return ctx->rc.low / ctx->rc.help;
  219. }
  220. /**
  221. * Decode value with given size in bits
  222. * @param ctx decoder context
  223. * @param shift number of bits to decode
  224. */
  225. static inline int range_decode_culshift(APEContext * ctx, int shift)
  226. {
  227. range_dec_normalize(ctx);
  228. ctx->rc.help = ctx->rc.range >> shift;
  229. return ctx->rc.low / ctx->rc.help;
  230. }
  231. /**
  232. * Update decoding state
  233. * @param ctx decoder context
  234. * @param sy_f the interval length (frequency of the symbol)
  235. * @param lt_f the lower end (frequency sum of < symbols)
  236. */
  237. static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
  238. {
  239. ctx->rc.low -= ctx->rc.help * lt_f;
  240. ctx->rc.range = ctx->rc.help * sy_f;
  241. }
  242. /** Decode n bits (n <= 16) without modelling */
  243. static inline int range_decode_bits(APEContext * ctx, int n)
  244. {
  245. int sym = range_decode_culshift(ctx, n);
  246. range_decode_update(ctx, 1, sym);
  247. return sym;
  248. }
  249. #define MODEL_ELEMENTS 64
  250. /**
  251. * Fixed probabilities for symbols in Monkey Audio version 3.97
  252. */
  253. static const uint16_t counts_3970[22] = {
  254. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  255. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  256. 65450, 65469, 65480, 65487, 65491, 65493,
  257. };
  258. /**
  259. * Probability ranges for symbols in Monkey Audio version 3.97
  260. */
  261. static const uint16_t counts_diff_3970[21] = {
  262. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  263. 1104, 677, 415, 248, 150, 89, 54, 31,
  264. 19, 11, 7, 4, 2,
  265. };
  266. /**
  267. * Fixed probabilities for symbols in Monkey Audio version 3.98
  268. */
  269. static const uint16_t counts_3980[22] = {
  270. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  271. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  272. 65485, 65488, 65490, 65491, 65492, 65493,
  273. };
  274. /**
  275. * Probability ranges for symbols in Monkey Audio version 3.98
  276. */
  277. static const uint16_t counts_diff_3980[21] = {
  278. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  279. 261, 119, 65, 31, 19, 10, 6, 3,
  280. 3, 2, 1, 1, 1,
  281. };
  282. /**
  283. * Decode symbol
  284. * @param ctx decoder context
  285. * @param counts probability range start position
  286. * @param counts_diff probability range widths
  287. */
  288. static inline int range_get_symbol(APEContext * ctx,
  289. const uint16_t counts[],
  290. const uint16_t counts_diff[])
  291. {
  292. int symbol, cf;
  293. cf = range_decode_culshift(ctx, 16);
  294. if(cf > 65492){
  295. symbol= cf - 65535 + 63;
  296. range_decode_update(ctx, 1, cf);
  297. if(cf > 65535)
  298. ctx->error=1;
  299. return symbol;
  300. }
  301. /* figure out the symbol inefficiently; a binary search would be much better */
  302. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  303. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  304. return symbol;
  305. }
  306. /** @} */ // group rangecoder
  307. static inline void update_rice(APERice *rice, int x)
  308. {
  309. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  310. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  311. if (rice->ksum < lim)
  312. rice->k--;
  313. else if (rice->ksum >= (1 << (rice->k + 5)))
  314. rice->k++;
  315. }
  316. static inline int ape_decode_value(APEContext * ctx, APERice *rice)
  317. {
  318. int x, overflow;
  319. if (ctx->fileversion < 3990) {
  320. int tmpk;
  321. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  322. if (overflow == (MODEL_ELEMENTS - 1)) {
  323. tmpk = range_decode_bits(ctx, 5);
  324. overflow = 0;
  325. } else
  326. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  327. if (tmpk <= 16)
  328. x = range_decode_bits(ctx, tmpk);
  329. else {
  330. x = range_decode_bits(ctx, 16);
  331. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  332. }
  333. x += overflow << tmpk;
  334. } else {
  335. int base, pivot;
  336. pivot = rice->ksum >> 5;
  337. if (pivot == 0)
  338. pivot = 1;
  339. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  340. if (overflow == (MODEL_ELEMENTS - 1)) {
  341. overflow = range_decode_bits(ctx, 16) << 16;
  342. overflow |= range_decode_bits(ctx, 16);
  343. }
  344. base = range_decode_culfreq(ctx, pivot);
  345. range_decode_update(ctx, 1, base);
  346. x = base + overflow * pivot;
  347. }
  348. update_rice(rice, x);
  349. /* Convert to signed */
  350. if (x & 1)
  351. return (x >> 1) + 1;
  352. else
  353. return -(x >> 1);
  354. }
  355. static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
  356. {
  357. int32_t *decoded0 = ctx->decoded0;
  358. int32_t *decoded1 = ctx->decoded1;
  359. ctx->blocksdecoded = blockstodecode;
  360. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  361. /* We are pure silence, just memset the output buffer. */
  362. memset(decoded0, 0, blockstodecode * sizeof(int32_t));
  363. memset(decoded1, 0, blockstodecode * sizeof(int32_t));
  364. } else {
  365. while (blockstodecode--) {
  366. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  367. if (stereo)
  368. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  369. }
  370. }
  371. if (ctx->blocksdecoded == ctx->currentframeblocks)
  372. range_dec_normalize(ctx); /* normalize to use up all bytes */
  373. }
  374. static void init_entropy_decoder(APEContext * ctx)
  375. {
  376. /* Read the CRC */
  377. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  378. /* Read the frame flags if they exist */
  379. ctx->frameflags = 0;
  380. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  381. ctx->CRC &= ~0x80000000;
  382. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  383. }
  384. /* Keep a count of the blocks decoded in this frame */
  385. ctx->blocksdecoded = 0;
  386. /* Initialize the rice structs */
  387. ctx->riceX.k = 10;
  388. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  389. ctx->riceY.k = 10;
  390. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  391. /* The first 8 bits of input are ignored. */
  392. ctx->ptr++;
  393. range_start_decoding(ctx);
  394. }
  395. static const int32_t initial_coeffs[4] = {
  396. 360, 317, -109, 98
  397. };
  398. static void init_predictor_decoder(APEContext * ctx)
  399. {
  400. APEPredictor *p = &ctx->predictor;
  401. /* Zero the history buffers */
  402. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
  403. p->buf = p->historybuffer;
  404. /* Initialize and zero the coefficients */
  405. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  406. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  407. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  408. p->filterA[0] = p->filterA[1] = 0;
  409. p->filterB[0] = p->filterB[1] = 0;
  410. p->lastA[0] = p->lastA[1] = 0;
  411. }
  412. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  413. static inline int APESIGN(int32_t x) {
  414. return (x < 0) - (x > 0);
  415. }
  416. static int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
  417. {
  418. int32_t predictionA, predictionB;
  419. p->buf[delayA] = p->lastA[filter];
  420. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  421. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  422. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  423. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  424. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  425. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  426. p->buf[delayA - 3] * p->coeffsA[filter][3];
  427. /* Apply a scaled first-order filter compression */
  428. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  429. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  430. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  431. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  432. p->filterB[filter] = p->filterA[filter ^ 1];
  433. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  434. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  435. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  436. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  437. p->buf[delayB - 4] * p->coeffsB[filter][4];
  438. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  439. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  440. if (!decoded) // no need updating filter coefficients
  441. return p->filterA[filter];
  442. if (decoded > 0) {
  443. p->coeffsA[filter][0] -= p->buf[adaptA ];
  444. p->coeffsA[filter][1] -= p->buf[adaptA - 1];
  445. p->coeffsA[filter][2] -= p->buf[adaptA - 2];
  446. p->coeffsA[filter][3] -= p->buf[adaptA - 3];
  447. p->coeffsB[filter][0] -= p->buf[adaptB ];
  448. p->coeffsB[filter][1] -= p->buf[adaptB - 1];
  449. p->coeffsB[filter][2] -= p->buf[adaptB - 2];
  450. p->coeffsB[filter][3] -= p->buf[adaptB - 3];
  451. p->coeffsB[filter][4] -= p->buf[adaptB - 4];
  452. } else {
  453. p->coeffsA[filter][0] += p->buf[adaptA ];
  454. p->coeffsA[filter][1] += p->buf[adaptA - 1];
  455. p->coeffsA[filter][2] += p->buf[adaptA - 2];
  456. p->coeffsA[filter][3] += p->buf[adaptA - 3];
  457. p->coeffsB[filter][0] += p->buf[adaptB ];
  458. p->coeffsB[filter][1] += p->buf[adaptB - 1];
  459. p->coeffsB[filter][2] += p->buf[adaptB - 2];
  460. p->coeffsB[filter][3] += p->buf[adaptB - 3];
  461. p->coeffsB[filter][4] += p->buf[adaptB - 4];
  462. }
  463. return p->filterA[filter];
  464. }
  465. static void predictor_decode_stereo(APEContext * ctx, int count)
  466. {
  467. int32_t predictionA, predictionB;
  468. APEPredictor *p = &ctx->predictor;
  469. int32_t *decoded0 = ctx->decoded0;
  470. int32_t *decoded1 = ctx->decoded1;
  471. while (count--) {
  472. /* Predictor Y */
  473. predictionA = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
  474. predictionB = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
  475. *(decoded0++) = predictionA;
  476. *(decoded1++) = predictionB;
  477. /* Combined */
  478. p->buf++;
  479. /* Have we filled the history buffer? */
  480. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  481. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  482. p->buf = p->historybuffer;
  483. }
  484. }
  485. }
  486. static void predictor_decode_mono(APEContext * ctx, int count)
  487. {
  488. APEPredictor *p = &ctx->predictor;
  489. int32_t *decoded0 = ctx->decoded0;
  490. int32_t predictionA, currentA, A;
  491. currentA = p->lastA[0];
  492. while (count--) {
  493. A = *decoded0;
  494. p->buf[YDELAYA] = currentA;
  495. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  496. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  497. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  498. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  499. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  500. currentA = A + (predictionA >> 10);
  501. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  502. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  503. if (A > 0) {
  504. p->coeffsA[0][0] -= p->buf[YADAPTCOEFFSA ];
  505. p->coeffsA[0][1] -= p->buf[YADAPTCOEFFSA - 1];
  506. p->coeffsA[0][2] -= p->buf[YADAPTCOEFFSA - 2];
  507. p->coeffsA[0][3] -= p->buf[YADAPTCOEFFSA - 3];
  508. } else if (A < 0) {
  509. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ];
  510. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1];
  511. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2];
  512. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3];
  513. }
  514. p->buf++;
  515. /* Have we filled the history buffer? */
  516. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  517. memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
  518. p->buf = p->historybuffer;
  519. }
  520. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  521. *(decoded0++) = p->filterA[0];
  522. }
  523. p->lastA[0] = currentA;
  524. }
  525. static void do_init_filter(APEFilter *f, int16_t * buf, int order)
  526. {
  527. f->coeffs = buf;
  528. f->historybuffer = buf + order;
  529. f->delay = f->historybuffer + order * 2;
  530. f->adaptcoeffs = f->historybuffer + order;
  531. memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
  532. memset(f->coeffs, 0, order * sizeof(int16_t));
  533. f->avg = 0;
  534. }
  535. static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
  536. {
  537. do_init_filter(&f[0], buf, order);
  538. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  539. }
  540. static inline void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
  541. {
  542. int res;
  543. int absres;
  544. while (count--) {
  545. /* round fixedpoint scalar product */
  546. res = (ctx->dsp.scalarproduct_int16(f->delay - order, f->coeffs, order, 0) + (1 << (fracbits - 1))) >> fracbits;
  547. if (*data < 0)
  548. ctx->dsp.add_int16(f->coeffs, f->adaptcoeffs - order, order);
  549. else if (*data > 0)
  550. ctx->dsp.sub_int16(f->coeffs, f->adaptcoeffs - order, order);
  551. res += *data;
  552. *data++ = res;
  553. /* Update the output history */
  554. *f->delay++ = av_clip_int16(res);
  555. if (version < 3980) {
  556. /* Version ??? to < 3.98 files (untested) */
  557. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  558. f->adaptcoeffs[-4] >>= 1;
  559. f->adaptcoeffs[-8] >>= 1;
  560. } else {
  561. /* Version 3.98 and later files */
  562. /* Update the adaption coefficients */
  563. absres = (res < 0 ? -res : res);
  564. if (absres > (f->avg * 3))
  565. *f->adaptcoeffs = ((res >> 25) & 64) - 32;
  566. else if (absres > (f->avg * 4) / 3)
  567. *f->adaptcoeffs = ((res >> 26) & 32) - 16;
  568. else if (absres > 0)
  569. *f->adaptcoeffs = ((res >> 27) & 16) - 8;
  570. else
  571. *f->adaptcoeffs = 0;
  572. f->avg += (absres - f->avg) / 16;
  573. f->adaptcoeffs[-1] >>= 1;
  574. f->adaptcoeffs[-2] >>= 1;
  575. f->adaptcoeffs[-8] >>= 1;
  576. }
  577. f->adaptcoeffs++;
  578. /* Have we filled the history buffer? */
  579. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  580. memmove(f->historybuffer, f->delay - (order * 2),
  581. (order * 2) * sizeof(int16_t));
  582. f->delay = f->historybuffer + order * 2;
  583. f->adaptcoeffs = f->historybuffer + order;
  584. }
  585. }
  586. }
  587. static void apply_filter(APEContext * ctx, APEFilter *f,
  588. int32_t * data0, int32_t * data1,
  589. int count, int order, int fracbits)
  590. {
  591. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  592. if (data1)
  593. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  594. }
  595. static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
  596. int32_t * decoded1, int count)
  597. {
  598. int i;
  599. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  600. if (!ape_filter_orders[ctx->fset][i])
  601. break;
  602. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
  603. }
  604. }
  605. static void init_frame_decoder(APEContext * ctx)
  606. {
  607. int i;
  608. init_entropy_decoder(ctx);
  609. init_predictor_decoder(ctx);
  610. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  611. if (!ape_filter_orders[ctx->fset][i])
  612. break;
  613. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
  614. }
  615. }
  616. static void ape_unpack_mono(APEContext * ctx, int count)
  617. {
  618. int32_t left;
  619. int32_t *decoded0 = ctx->decoded0;
  620. int32_t *decoded1 = ctx->decoded1;
  621. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  622. entropy_decode(ctx, count, 0);
  623. /* We are pure silence, so we're done. */
  624. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  625. return;
  626. }
  627. entropy_decode(ctx, count, 0);
  628. ape_apply_filters(ctx, decoded0, NULL, count);
  629. /* Now apply the predictor decoding */
  630. predictor_decode_mono(ctx, count);
  631. /* Pseudo-stereo - just copy left channel to right channel */
  632. if (ctx->channels == 2) {
  633. while (count--) {
  634. left = *decoded0;
  635. *(decoded1++) = *(decoded0++) = left;
  636. }
  637. }
  638. }
  639. static void ape_unpack_stereo(APEContext * ctx, int count)
  640. {
  641. int32_t left, right;
  642. int32_t *decoded0 = ctx->decoded0;
  643. int32_t *decoded1 = ctx->decoded1;
  644. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  645. /* We are pure silence, so we're done. */
  646. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  647. return;
  648. }
  649. entropy_decode(ctx, count, 1);
  650. ape_apply_filters(ctx, decoded0, decoded1, count);
  651. /* Now apply the predictor decoding */
  652. predictor_decode_stereo(ctx, count);
  653. /* Decorrelate and scale to output depth */
  654. while (count--) {
  655. left = *decoded1 - (*decoded0 / 2);
  656. right = left + *decoded0;
  657. *(decoded0++) = left;
  658. *(decoded1++) = right;
  659. }
  660. }
  661. static int ape_decode_frame(AVCodecContext * avctx,
  662. void *data, int *data_size,
  663. const uint8_t * buf, int buf_size)
  664. {
  665. APEContext *s = avctx->priv_data;
  666. int16_t *samples = data;
  667. int nblocks;
  668. int i, n;
  669. int blockstodecode;
  670. int bytes_used;
  671. if (buf_size == 0 && !s->samples) {
  672. *data_size = 0;
  673. return 0;
  674. }
  675. /* should not happen but who knows */
  676. if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
  677. av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);
  678. return -1;
  679. }
  680. if(!s->samples){
  681. s->data = av_realloc(s->data, (buf_size + 3) & ~3);
  682. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  683. s->ptr = s->last_ptr = s->data;
  684. s->data_end = s->data + buf_size;
  685. nblocks = s->samples = bytestream_get_be32(&s->ptr);
  686. n = bytestream_get_be32(&s->ptr);
  687. if(n < 0 || n > 3){
  688. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  689. s->data = NULL;
  690. return -1;
  691. }
  692. s->ptr += n;
  693. s->currentframeblocks = nblocks;
  694. buf += 4;
  695. if (s->samples <= 0) {
  696. *data_size = 0;
  697. return buf_size;
  698. }
  699. memset(s->decoded0, 0, sizeof(s->decoded0));
  700. memset(s->decoded1, 0, sizeof(s->decoded1));
  701. /* Initialize the frame decoder */
  702. init_frame_decoder(s);
  703. }
  704. if (!s->data) {
  705. *data_size = 0;
  706. return buf_size;
  707. }
  708. nblocks = s->samples;
  709. blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
  710. s->error=0;
  711. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  712. ape_unpack_mono(s, blockstodecode);
  713. else
  714. ape_unpack_stereo(s, blockstodecode);
  715. if(s->error || s->ptr > s->data_end){
  716. s->samples=0;
  717. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  718. return -1;
  719. }
  720. for (i = 0; i < blockstodecode; i++) {
  721. *samples++ = s->decoded0[i];
  722. if(s->channels == 2)
  723. *samples++ = s->decoded1[i];
  724. }
  725. s->samples -= blockstodecode;
  726. *data_size = blockstodecode * 2 * s->channels;
  727. bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
  728. s->last_ptr = s->ptr;
  729. return bytes_used;
  730. }
  731. AVCodec ape_decoder = {
  732. "ape",
  733. CODEC_TYPE_AUDIO,
  734. CODEC_ID_APE,
  735. sizeof(APEContext),
  736. ape_decode_init,
  737. NULL,
  738. ape_decode_close,
  739. ape_decode_frame,
  740. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  741. };