apedec.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. /*
  2. * Monkey's Audio lossless audio decoder
  3. * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
  4. * based upon libdemac from Dave Chapman.
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "avcodec.h"
  23. #include "dsputil.h"
  24. #include "bytestream.h"
  25. #include "libavutil/audioconvert.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/opt.h"
  28. /**
  29. * @file
  30. * Monkey's Audio lossless audio decoder
  31. */
  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. AVClass *class; ///< class for AVOptions
  109. AVCodecContext *avctx;
  110. AVFrame frame;
  111. DSPContext dsp;
  112. int channels;
  113. int samples; ///< samples left to decode in current frame
  114. int bps;
  115. int fileversion; ///< codec version, very important in decoding process
  116. int compression_level; ///< compression levels
  117. int fset; ///< which filter set to use (calculated from compression level)
  118. int flags; ///< global decoder flags
  119. uint32_t CRC; ///< frame CRC
  120. int frameflags; ///< frame flags
  121. APEPredictor predictor; ///< predictor used for final reconstruction
  122. int32_t *decoded_buffer;
  123. int decoded_size;
  124. int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
  125. int blocks_per_loop; ///< maximum number of samples to decode for each call
  126. int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
  127. APERangecoder rc; ///< rangecoder used to decode actual values
  128. APERice riceX; ///< rice code parameters for the second channel
  129. APERice riceY; ///< rice code parameters for the first channel
  130. APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
  131. uint8_t *data; ///< current frame data
  132. uint8_t *data_end; ///< frame data end
  133. int data_size; ///< frame data allocated size
  134. const uint8_t *ptr; ///< current position in frame data
  135. int error;
  136. } APEContext;
  137. // TODO: dsputilize
  138. static av_cold int ape_decode_close(AVCodecContext *avctx)
  139. {
  140. APEContext *s = avctx->priv_data;
  141. int i;
  142. for (i = 0; i < APE_FILTER_LEVELS; i++)
  143. av_freep(&s->filterbuf[i]);
  144. av_freep(&s->decoded_buffer);
  145. av_freep(&s->data);
  146. s->decoded_size = s->data_size = 0;
  147. return 0;
  148. }
  149. static av_cold int ape_decode_init(AVCodecContext *avctx)
  150. {
  151. APEContext *s = avctx->priv_data;
  152. int i;
  153. if (avctx->extradata_size != 6) {
  154. av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
  155. return AVERROR(EINVAL);
  156. }
  157. if (avctx->channels > 2) {
  158. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
  159. return AVERROR(EINVAL);
  160. }
  161. s->bps = avctx->bits_per_coded_sample;
  162. switch (s->bps) {
  163. case 8:
  164. avctx->sample_fmt = AV_SAMPLE_FMT_U8;
  165. break;
  166. case 16:
  167. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  168. break;
  169. case 24:
  170. avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  171. break;
  172. default:
  173. av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",
  174. s->bps);
  175. return AVERROR_PATCHWELCOME;
  176. }
  177. s->avctx = avctx;
  178. s->channels = avctx->channels;
  179. s->fileversion = AV_RL16(avctx->extradata);
  180. s->compression_level = AV_RL16(avctx->extradata + 2);
  181. s->flags = AV_RL16(avctx->extradata + 4);
  182. av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
  183. s->compression_level, s->flags);
  184. if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE || !s->compression_level) {
  185. av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
  186. s->compression_level);
  187. return AVERROR_INVALIDDATA;
  188. }
  189. s->fset = s->compression_level / 1000 - 1;
  190. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  191. if (!ape_filter_orders[s->fset][i])
  192. break;
  193. FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
  194. (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
  195. filter_alloc_fail);
  196. }
  197. ff_dsputil_init(&s->dsp, avctx);
  198. avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
  199. avcodec_get_frame_defaults(&s->frame);
  200. avctx->coded_frame = &s->frame;
  201. return 0;
  202. filter_alloc_fail:
  203. ape_decode_close(avctx);
  204. return AVERROR(ENOMEM);
  205. }
  206. /**
  207. * @name APE range decoding functions
  208. * @{
  209. */
  210. #define CODE_BITS 32
  211. #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
  212. #define SHIFT_BITS (CODE_BITS - 9)
  213. #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
  214. #define BOTTOM_VALUE (TOP_VALUE >> 8)
  215. /** Start the decoder */
  216. static inline void range_start_decoding(APEContext *ctx)
  217. {
  218. ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
  219. ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
  220. ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
  221. }
  222. /** Perform normalization */
  223. static inline void range_dec_normalize(APEContext *ctx)
  224. {
  225. while (ctx->rc.range <= BOTTOM_VALUE) {
  226. ctx->rc.buffer <<= 8;
  227. if(ctx->ptr < ctx->data_end) {
  228. ctx->rc.buffer += *ctx->ptr;
  229. ctx->ptr++;
  230. } else {
  231. ctx->error = 1;
  232. }
  233. ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
  234. ctx->rc.range <<= 8;
  235. }
  236. }
  237. /**
  238. * Calculate culmulative frequency for next symbol. Does NO update!
  239. * @param ctx decoder context
  240. * @param tot_f is the total frequency or (code_value)1<<shift
  241. * @return the culmulative frequency
  242. */
  243. static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
  244. {
  245. range_dec_normalize(ctx);
  246. ctx->rc.help = ctx->rc.range / tot_f;
  247. return ctx->rc.low / ctx->rc.help;
  248. }
  249. /**
  250. * Decode value with given size in bits
  251. * @param ctx decoder context
  252. * @param shift number of bits to decode
  253. */
  254. static inline int range_decode_culshift(APEContext *ctx, int shift)
  255. {
  256. range_dec_normalize(ctx);
  257. ctx->rc.help = ctx->rc.range >> shift;
  258. return ctx->rc.low / ctx->rc.help;
  259. }
  260. /**
  261. * Update decoding state
  262. * @param ctx decoder context
  263. * @param sy_f the interval length (frequency of the symbol)
  264. * @param lt_f the lower end (frequency sum of < symbols)
  265. */
  266. static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
  267. {
  268. ctx->rc.low -= ctx->rc.help * lt_f;
  269. ctx->rc.range = ctx->rc.help * sy_f;
  270. }
  271. /** Decode n bits (n <= 16) without modelling */
  272. static inline int range_decode_bits(APEContext *ctx, int n)
  273. {
  274. int sym = range_decode_culshift(ctx, n);
  275. range_decode_update(ctx, 1, sym);
  276. return sym;
  277. }
  278. #define MODEL_ELEMENTS 64
  279. /**
  280. * Fixed probabilities for symbols in Monkey Audio version 3.97
  281. */
  282. static const uint16_t counts_3970[22] = {
  283. 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
  284. 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
  285. 65450, 65469, 65480, 65487, 65491, 65493,
  286. };
  287. /**
  288. * Probability ranges for symbols in Monkey Audio version 3.97
  289. */
  290. static const uint16_t counts_diff_3970[21] = {
  291. 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
  292. 1104, 677, 415, 248, 150, 89, 54, 31,
  293. 19, 11, 7, 4, 2,
  294. };
  295. /**
  296. * Fixed probabilities for symbols in Monkey Audio version 3.98
  297. */
  298. static const uint16_t counts_3980[22] = {
  299. 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
  300. 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
  301. 65485, 65488, 65490, 65491, 65492, 65493,
  302. };
  303. /**
  304. * Probability ranges for symbols in Monkey Audio version 3.98
  305. */
  306. static const uint16_t counts_diff_3980[21] = {
  307. 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
  308. 261, 119, 65, 31, 19, 10, 6, 3,
  309. 3, 2, 1, 1, 1,
  310. };
  311. /**
  312. * Decode symbol
  313. * @param ctx decoder context
  314. * @param counts probability range start position
  315. * @param counts_diff probability range widths
  316. */
  317. static inline int range_get_symbol(APEContext *ctx,
  318. const uint16_t counts[],
  319. const uint16_t counts_diff[])
  320. {
  321. int symbol, cf;
  322. cf = range_decode_culshift(ctx, 16);
  323. if(cf > 65492){
  324. symbol= cf - 65535 + 63;
  325. range_decode_update(ctx, 1, cf);
  326. if(cf > 65535)
  327. ctx->error=1;
  328. return symbol;
  329. }
  330. /* figure out the symbol inefficiently; a binary search would be much better */
  331. for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
  332. range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
  333. return symbol;
  334. }
  335. /** @} */ // group rangecoder
  336. static inline void update_rice(APERice *rice, unsigned int x)
  337. {
  338. int lim = rice->k ? (1 << (rice->k + 4)) : 0;
  339. rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
  340. if (rice->ksum < lim)
  341. rice->k--;
  342. else if (rice->ksum >= (1 << (rice->k + 5)))
  343. rice->k++;
  344. }
  345. static inline int ape_decode_value(APEContext *ctx, APERice *rice)
  346. {
  347. unsigned int x, overflow;
  348. if (ctx->fileversion < 3990) {
  349. int tmpk;
  350. overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
  351. if (overflow == (MODEL_ELEMENTS - 1)) {
  352. tmpk = range_decode_bits(ctx, 5);
  353. overflow = 0;
  354. } else
  355. tmpk = (rice->k < 1) ? 0 : rice->k - 1;
  356. if (tmpk <= 16)
  357. x = range_decode_bits(ctx, tmpk);
  358. else if (tmpk <= 32) {
  359. x = range_decode_bits(ctx, 16);
  360. x |= (range_decode_bits(ctx, tmpk - 16) << 16);
  361. } else {
  362. av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
  363. return AVERROR_INVALIDDATA;
  364. }
  365. x += overflow << tmpk;
  366. } else {
  367. int base, pivot;
  368. pivot = rice->ksum >> 5;
  369. if (pivot == 0)
  370. pivot = 1;
  371. overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
  372. if (overflow == (MODEL_ELEMENTS - 1)) {
  373. overflow = range_decode_bits(ctx, 16) << 16;
  374. overflow |= range_decode_bits(ctx, 16);
  375. }
  376. if (pivot < 0x10000) {
  377. base = range_decode_culfreq(ctx, pivot);
  378. range_decode_update(ctx, 1, base);
  379. } else {
  380. int base_hi = pivot, base_lo;
  381. int bbits = 0;
  382. while (base_hi & ~0xFFFF) {
  383. base_hi >>= 1;
  384. bbits++;
  385. }
  386. base_hi = range_decode_culfreq(ctx, base_hi + 1);
  387. range_decode_update(ctx, 1, base_hi);
  388. base_lo = range_decode_culfreq(ctx, 1 << bbits);
  389. range_decode_update(ctx, 1, base_lo);
  390. base = (base_hi << bbits) + base_lo;
  391. }
  392. x = base + overflow * pivot;
  393. }
  394. update_rice(rice, x);
  395. /* Convert to signed */
  396. if (x & 1)
  397. return (x >> 1) + 1;
  398. else
  399. return -(x >> 1);
  400. }
  401. static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
  402. {
  403. int32_t *decoded0 = ctx->decoded[0];
  404. int32_t *decoded1 = ctx->decoded[1];
  405. while (blockstodecode--) {
  406. *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
  407. if (stereo)
  408. *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
  409. }
  410. }
  411. static int init_entropy_decoder(APEContext *ctx)
  412. {
  413. /* Read the CRC */
  414. if (ctx->data_end - ctx->ptr < 6)
  415. return AVERROR_INVALIDDATA;
  416. ctx->CRC = bytestream_get_be32(&ctx->ptr);
  417. /* Read the frame flags if they exist */
  418. ctx->frameflags = 0;
  419. if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
  420. ctx->CRC &= ~0x80000000;
  421. if (ctx->data_end - ctx->ptr < 6)
  422. return AVERROR_INVALIDDATA;
  423. ctx->frameflags = bytestream_get_be32(&ctx->ptr);
  424. }
  425. /* Initialize the rice structs */
  426. ctx->riceX.k = 10;
  427. ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
  428. ctx->riceY.k = 10;
  429. ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
  430. /* The first 8 bits of input are ignored. */
  431. ctx->ptr++;
  432. range_start_decoding(ctx);
  433. return 0;
  434. }
  435. static const int32_t initial_coeffs[4] = {
  436. 360, 317, -109, 98
  437. };
  438. static void init_predictor_decoder(APEContext *ctx)
  439. {
  440. APEPredictor *p = &ctx->predictor;
  441. /* Zero the history buffers */
  442. memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
  443. p->buf = p->historybuffer;
  444. /* Initialize and zero the coefficients */
  445. memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
  446. memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
  447. memset(p->coeffsB, 0, sizeof(p->coeffsB));
  448. p->filterA[0] = p->filterA[1] = 0;
  449. p->filterB[0] = p->filterB[1] = 0;
  450. p->lastA[0] = p->lastA[1] = 0;
  451. }
  452. /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
  453. static inline int APESIGN(int32_t x) {
  454. return (x < 0) - (x > 0);
  455. }
  456. static av_always_inline int predictor_update_filter(APEPredictor *p,
  457. const int decoded, const int filter,
  458. const int delayA, const int delayB,
  459. const int adaptA, const int adaptB)
  460. {
  461. int32_t predictionA, predictionB, sign;
  462. p->buf[delayA] = p->lastA[filter];
  463. p->buf[adaptA] = APESIGN(p->buf[delayA]);
  464. p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
  465. p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
  466. predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
  467. p->buf[delayA - 1] * p->coeffsA[filter][1] +
  468. p->buf[delayA - 2] * p->coeffsA[filter][2] +
  469. p->buf[delayA - 3] * p->coeffsA[filter][3];
  470. /* Apply a scaled first-order filter compression */
  471. p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
  472. p->buf[adaptB] = APESIGN(p->buf[delayB]);
  473. p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
  474. p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
  475. p->filterB[filter] = p->filterA[filter ^ 1];
  476. predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
  477. p->buf[delayB - 1] * p->coeffsB[filter][1] +
  478. p->buf[delayB - 2] * p->coeffsB[filter][2] +
  479. p->buf[delayB - 3] * p->coeffsB[filter][3] +
  480. p->buf[delayB - 4] * p->coeffsB[filter][4];
  481. p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
  482. p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
  483. sign = APESIGN(decoded);
  484. p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
  485. p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
  486. p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
  487. p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
  488. p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
  489. p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
  490. p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
  491. p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
  492. p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
  493. return p->filterA[filter];
  494. }
  495. static void predictor_decode_stereo(APEContext *ctx, int count)
  496. {
  497. APEPredictor *p = &ctx->predictor;
  498. int32_t *decoded0 = ctx->decoded[0];
  499. int32_t *decoded1 = ctx->decoded[1];
  500. while (count--) {
  501. /* Predictor Y */
  502. *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
  503. YADAPTCOEFFSA, YADAPTCOEFFSB);
  504. decoded0++;
  505. *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
  506. XADAPTCOEFFSA, XADAPTCOEFFSB);
  507. decoded1++;
  508. /* Combined */
  509. p->buf++;
  510. /* Have we filled the history buffer? */
  511. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  512. memmove(p->historybuffer, p->buf,
  513. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  514. p->buf = p->historybuffer;
  515. }
  516. }
  517. }
  518. static void predictor_decode_mono(APEContext *ctx, int count)
  519. {
  520. APEPredictor *p = &ctx->predictor;
  521. int32_t *decoded0 = ctx->decoded[0];
  522. int32_t predictionA, currentA, A, sign;
  523. currentA = p->lastA[0];
  524. while (count--) {
  525. A = *decoded0;
  526. p->buf[YDELAYA] = currentA;
  527. p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
  528. predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
  529. p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
  530. p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
  531. p->buf[YDELAYA - 3] * p->coeffsA[0][3];
  532. currentA = A + (predictionA >> 10);
  533. p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
  534. p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
  535. sign = APESIGN(A);
  536. p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
  537. p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
  538. p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
  539. p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
  540. p->buf++;
  541. /* Have we filled the history buffer? */
  542. if (p->buf == p->historybuffer + HISTORY_SIZE) {
  543. memmove(p->historybuffer, p->buf,
  544. PREDICTOR_SIZE * sizeof(*p->historybuffer));
  545. p->buf = p->historybuffer;
  546. }
  547. p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
  548. *(decoded0++) = p->filterA[0];
  549. }
  550. p->lastA[0] = currentA;
  551. }
  552. static void do_init_filter(APEFilter *f, int16_t *buf, int order)
  553. {
  554. f->coeffs = buf;
  555. f->historybuffer = buf + order;
  556. f->delay = f->historybuffer + order * 2;
  557. f->adaptcoeffs = f->historybuffer + order;
  558. memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
  559. memset(f->coeffs, 0, order * sizeof(*f->coeffs));
  560. f->avg = 0;
  561. }
  562. static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
  563. {
  564. do_init_filter(&f[0], buf, order);
  565. do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
  566. }
  567. static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
  568. int32_t *data, int count, int order, int fracbits)
  569. {
  570. int res;
  571. int absres;
  572. while (count--) {
  573. /* round fixedpoint scalar product */
  574. res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
  575. f->adaptcoeffs - order,
  576. order, APESIGN(*data));
  577. res = (res + (1 << (fracbits - 1))) >> fracbits;
  578. res += *data;
  579. *data++ = res;
  580. /* Update the output history */
  581. *f->delay++ = av_clip_int16(res);
  582. if (version < 3980) {
  583. /* Version ??? to < 3.98 files (untested) */
  584. f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
  585. f->adaptcoeffs[-4] >>= 1;
  586. f->adaptcoeffs[-8] >>= 1;
  587. } else {
  588. /* Version 3.98 and later files */
  589. /* Update the adaption coefficients */
  590. absres = FFABS(res);
  591. if (absres)
  592. *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
  593. (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
  594. else
  595. *f->adaptcoeffs = 0;
  596. f->avg += (absres - f->avg) / 16;
  597. f->adaptcoeffs[-1] >>= 1;
  598. f->adaptcoeffs[-2] >>= 1;
  599. f->adaptcoeffs[-8] >>= 1;
  600. }
  601. f->adaptcoeffs++;
  602. /* Have we filled the history buffer? */
  603. if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
  604. memmove(f->historybuffer, f->delay - (order * 2),
  605. (order * 2) * sizeof(*f->historybuffer));
  606. f->delay = f->historybuffer + order * 2;
  607. f->adaptcoeffs = f->historybuffer + order;
  608. }
  609. }
  610. }
  611. static void apply_filter(APEContext *ctx, APEFilter *f,
  612. int32_t *data0, int32_t *data1,
  613. int count, int order, int fracbits)
  614. {
  615. do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
  616. if (data1)
  617. do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
  618. }
  619. static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
  620. int32_t *decoded1, int count)
  621. {
  622. int i;
  623. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  624. if (!ape_filter_orders[ctx->fset][i])
  625. break;
  626. apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
  627. ape_filter_orders[ctx->fset][i],
  628. ape_filter_fracbits[ctx->fset][i]);
  629. }
  630. }
  631. static int init_frame_decoder(APEContext *ctx)
  632. {
  633. int i, ret;
  634. if ((ret = init_entropy_decoder(ctx)) < 0)
  635. return ret;
  636. init_predictor_decoder(ctx);
  637. for (i = 0; i < APE_FILTER_LEVELS; i++) {
  638. if (!ape_filter_orders[ctx->fset][i])
  639. break;
  640. init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
  641. ape_filter_orders[ctx->fset][i]);
  642. }
  643. return 0;
  644. }
  645. static void ape_unpack_mono(APEContext *ctx, int count)
  646. {
  647. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  648. /* We are pure silence, so we're done. */
  649. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
  650. return;
  651. }
  652. entropy_decode(ctx, count, 0);
  653. ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
  654. /* Now apply the predictor decoding */
  655. predictor_decode_mono(ctx, count);
  656. /* Pseudo-stereo - just copy left channel to right channel */
  657. if (ctx->channels == 2) {
  658. memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
  659. }
  660. }
  661. static void ape_unpack_stereo(APEContext *ctx, int count)
  662. {
  663. int32_t left, right;
  664. int32_t *decoded0 = ctx->decoded[0];
  665. int32_t *decoded1 = ctx->decoded[1];
  666. if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
  667. /* We are pure silence, so we're done. */
  668. av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
  669. return;
  670. }
  671. entropy_decode(ctx, count, 1);
  672. ape_apply_filters(ctx, decoded0, decoded1, count);
  673. /* Now apply the predictor decoding */
  674. predictor_decode_stereo(ctx, count);
  675. /* Decorrelate and scale to output depth */
  676. while (count--) {
  677. left = *decoded1 - (*decoded0 / 2);
  678. right = left + *decoded0;
  679. *(decoded0++) = left;
  680. *(decoded1++) = right;
  681. }
  682. }
  683. static int ape_decode_frame(AVCodecContext *avctx, void *data,
  684. int *got_frame_ptr, AVPacket *avpkt)
  685. {
  686. const uint8_t *buf = avpkt->data;
  687. APEContext *s = avctx->priv_data;
  688. uint8_t *sample8;
  689. int16_t *sample16;
  690. int32_t *sample24;
  691. int i, ret;
  692. int blockstodecode;
  693. int bytes_used = 0;
  694. /* this should never be negative, but bad things will happen if it is, so
  695. check it just to make sure. */
  696. av_assert0(s->samples >= 0);
  697. if(!s->samples){
  698. uint32_t nblocks, offset;
  699. int buf_size;
  700. if (!avpkt->size) {
  701. *got_frame_ptr = 0;
  702. return 0;
  703. }
  704. if (avpkt->size < 8) {
  705. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  706. return AVERROR_INVALIDDATA;
  707. }
  708. buf_size = avpkt->size & ~3;
  709. if (buf_size != avpkt->size) {
  710. av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
  711. "extra bytes at the end will be skipped.\n");
  712. }
  713. av_fast_malloc(&s->data, &s->data_size, buf_size);
  714. if (!s->data)
  715. return AVERROR(ENOMEM);
  716. s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
  717. s->ptr = s->data;
  718. s->data_end = s->data + buf_size;
  719. nblocks = bytestream_get_be32(&s->ptr);
  720. offset = bytestream_get_be32(&s->ptr);
  721. if (offset > 3) {
  722. av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
  723. s->data = NULL;
  724. return AVERROR_INVALIDDATA;
  725. }
  726. if (s->data_end - s->ptr < offset) {
  727. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  728. return AVERROR_INVALIDDATA;
  729. }
  730. s->ptr += offset;
  731. if (!nblocks || nblocks > INT_MAX) {
  732. av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
  733. return AVERROR_INVALIDDATA;
  734. }
  735. s->samples = nblocks;
  736. /* Initialize the frame decoder */
  737. if (init_frame_decoder(s) < 0) {
  738. av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
  739. return AVERROR_INVALIDDATA;
  740. }
  741. bytes_used = avpkt->size;
  742. }
  743. if (!s->data) {
  744. *got_frame_ptr = 0;
  745. return avpkt->size;
  746. }
  747. blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
  748. /* reallocate decoded sample buffer if needed */
  749. av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
  750. 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
  751. if (!s->decoded_buffer)
  752. return AVERROR(ENOMEM);
  753. memset(s->decoded_buffer, 0, s->decoded_size);
  754. s->decoded[0] = s->decoded_buffer;
  755. s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
  756. /* get output buffer */
  757. s->frame.nb_samples = blockstodecode;
  758. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  759. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  760. return ret;
  761. }
  762. s->error=0;
  763. if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
  764. ape_unpack_mono(s, blockstodecode);
  765. else
  766. ape_unpack_stereo(s, blockstodecode);
  767. emms_c();
  768. if (s->error) {
  769. s->samples=0;
  770. av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
  771. return AVERROR_INVALIDDATA;
  772. }
  773. switch (s->bps) {
  774. case 8:
  775. sample8 = (uint8_t *)s->frame.data[0];
  776. for (i = 0; i < blockstodecode; i++) {
  777. *sample8++ = (s->decoded[0][i] + 0x80) & 0xff;
  778. if (s->channels == 2)
  779. *sample8++ = (s->decoded[1][i] + 0x80) & 0xff;
  780. }
  781. break;
  782. case 16:
  783. sample16 = (int16_t *)s->frame.data[0];
  784. for (i = 0; i < blockstodecode; i++) {
  785. *sample16++ = s->decoded[0][i];
  786. if (s->channels == 2)
  787. *sample16++ = s->decoded[1][i];
  788. }
  789. break;
  790. case 24:
  791. sample24 = (int32_t *)s->frame.data[0];
  792. for (i = 0; i < blockstodecode; i++) {
  793. *sample24++ = s->decoded[0][i] << 8;
  794. if (s->channels == 2)
  795. *sample24++ = s->decoded[1][i] << 8;
  796. }
  797. break;
  798. }
  799. s->samples -= blockstodecode;
  800. *got_frame_ptr = 1;
  801. *(AVFrame *)data = s->frame;
  802. return bytes_used;
  803. }
  804. static void ape_flush(AVCodecContext *avctx)
  805. {
  806. APEContext *s = avctx->priv_data;
  807. s->samples= 0;
  808. }
  809. #define OFFSET(x) offsetof(APEContext, x)
  810. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  811. static const AVOption options[] = {
  812. { "max_samples", "maximum number of samples decoded per call", OFFSET(blocks_per_loop), AV_OPT_TYPE_INT, { 4608 }, 1, INT_MAX, PAR, "max_samples" },
  813. { "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" },
  814. { NULL},
  815. };
  816. static const AVClass ape_decoder_class = {
  817. .class_name = "APE decoder",
  818. .item_name = av_default_item_name,
  819. .option = options,
  820. .version = LIBAVUTIL_VERSION_INT,
  821. };
  822. AVCodec ff_ape_decoder = {
  823. .name = "ape",
  824. .type = AVMEDIA_TYPE_AUDIO,
  825. .id = AV_CODEC_ID_APE,
  826. .priv_data_size = sizeof(APEContext),
  827. .init = ape_decode_init,
  828. .close = ape_decode_close,
  829. .decode = ape_decode_frame,
  830. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
  831. .flush = ape_flush,
  832. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  833. .priv_class = &ape_decoder_class,
  834. };