libavcodec/apedec.c
Go to the documentation of this file.
00001 /*
00002  * Monkey's Audio lossless audio decoder
00003  * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
00004  *  based upon libdemac from Dave Chapman.
00005  *
00006  * This file is part of Libav.
00007  *
00008  * Libav is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * Libav is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00023 #define BITSTREAM_READER_LE
00024 #include "avcodec.h"
00025 #include "dsputil.h"
00026 #include "get_bits.h"
00027 #include "bytestream.h"
00028 #include "libavutil/audioconvert.h"
00029 #include "libavutil/avassert.h"
00030 
00036 #define BLOCKS_PER_LOOP     4608
00037 #define MAX_CHANNELS        2
00038 #define MAX_BYTESPERSAMPLE  3
00039 
00040 #define APE_FRAMECODE_MONO_SILENCE    1
00041 #define APE_FRAMECODE_STEREO_SILENCE  3
00042 #define APE_FRAMECODE_PSEUDO_STEREO   4
00043 
00044 #define HISTORY_SIZE 512
00045 #define PREDICTOR_ORDER 8
00046 
00047 #define PREDICTOR_SIZE 50
00048 
00049 #define YDELAYA (18 + PREDICTOR_ORDER*4)
00050 #define YDELAYB (18 + PREDICTOR_ORDER*3)
00051 #define XDELAYA (18 + PREDICTOR_ORDER*2)
00052 #define XDELAYB (18 + PREDICTOR_ORDER)
00053 
00054 #define YADAPTCOEFFSA 18
00055 #define XADAPTCOEFFSA 14
00056 #define YADAPTCOEFFSB 10
00057 #define XADAPTCOEFFSB 5
00058 
00063 enum APECompressionLevel {
00064     COMPRESSION_LEVEL_FAST       = 1000,
00065     COMPRESSION_LEVEL_NORMAL     = 2000,
00066     COMPRESSION_LEVEL_HIGH       = 3000,
00067     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
00068     COMPRESSION_LEVEL_INSANE     = 5000
00069 };
00072 #define APE_FILTER_LEVELS 3
00073 
00075 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
00076     {  0,   0,    0 },
00077     { 16,   0,    0 },
00078     { 64,   0,    0 },
00079     { 32, 256,    0 },
00080     { 16, 256, 1280 }
00081 };
00082 
00084 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
00085     {  0,  0,  0 },
00086     { 11,  0,  0 },
00087     { 11,  0,  0 },
00088     { 10, 13,  0 },
00089     { 11, 13, 15 }
00090 };
00091 
00092 
00094 typedef struct APEFilter {
00095     int16_t *coeffs;        
00096     int16_t *adaptcoeffs;   
00097     int16_t *historybuffer; 
00098     int16_t *delay;         
00099 
00100     int avg;
00101 } APEFilter;
00102 
00103 typedef struct APERice {
00104     uint32_t k;
00105     uint32_t ksum;
00106 } APERice;
00107 
00108 typedef struct APERangecoder {
00109     uint32_t low;           
00110     uint32_t range;         
00111     uint32_t help;          
00112     unsigned int buffer;    
00113 } APERangecoder;
00114 
00116 typedef struct APEPredictor {
00117     int32_t *buf;
00118 
00119     int32_t lastA[2];
00120 
00121     int32_t filterA[2];
00122     int32_t filterB[2];
00123 
00124     int32_t coeffsA[2][4];  
00125     int32_t coeffsB[2][5];  
00126     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
00127 } APEPredictor;
00128 
00130 typedef struct APEContext {
00131     AVCodecContext *avctx;
00132     AVFrame frame;
00133     DSPContext dsp;
00134     int channels;
00135     int samples;                             
00136 
00137     int fileversion;                         
00138     int compression_level;                   
00139     int fset;                                
00140     int flags;                               
00141 
00142     uint32_t CRC;                            
00143     int frameflags;                          
00144     APEPredictor predictor;                  
00145 
00146     int32_t decoded0[BLOCKS_PER_LOOP];       
00147     int32_t decoded1[BLOCKS_PER_LOOP];       
00148 
00149     int16_t* filterbuf[APE_FILTER_LEVELS];   
00150 
00151     APERangecoder rc;                        
00152     APERice riceX;                           
00153     APERice riceY;                           
00154     APEFilter filters[APE_FILTER_LEVELS][2]; 
00155 
00156     uint8_t *data;                           
00157     uint8_t *data_end;                       
00158     const uint8_t *ptr;                      
00159 
00160     int error;
00161 } APEContext;
00162 
00163 // TODO: dsputilize
00164 
00165 static av_cold int ape_decode_close(AVCodecContext *avctx)
00166 {
00167     APEContext *s = avctx->priv_data;
00168     int i;
00169 
00170     for (i = 0; i < APE_FILTER_LEVELS; i++)
00171         av_freep(&s->filterbuf[i]);
00172 
00173     av_freep(&s->data);
00174     return 0;
00175 }
00176 
00177 static av_cold int ape_decode_init(AVCodecContext *avctx)
00178 {
00179     APEContext *s = avctx->priv_data;
00180     int i;
00181 
00182     if (avctx->extradata_size != 6) {
00183         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
00184         return AVERROR(EINVAL);
00185     }
00186     if (avctx->bits_per_coded_sample != 16) {
00187         av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
00188         return AVERROR(EINVAL);
00189     }
00190     if (avctx->channels > 2) {
00191         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
00192         return AVERROR(EINVAL);
00193     }
00194     s->avctx             = avctx;
00195     s->channels          = avctx->channels;
00196     s->fileversion       = AV_RL16(avctx->extradata);
00197     s->compression_level = AV_RL16(avctx->extradata + 2);
00198     s->flags             = AV_RL16(avctx->extradata + 4);
00199 
00200     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
00201            s->compression_level, s->flags);
00202     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
00203         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
00204                s->compression_level);
00205         return AVERROR_INVALIDDATA;
00206     }
00207     s->fset = s->compression_level / 1000 - 1;
00208     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00209         if (!ape_filter_orders[s->fset][i])
00210             break;
00211         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
00212                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
00213                          filter_alloc_fail);
00214     }
00215 
00216     dsputil_init(&s->dsp, avctx);
00217     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00218     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
00219 
00220     avcodec_get_frame_defaults(&s->frame);
00221     avctx->coded_frame = &s->frame;
00222 
00223     return 0;
00224 filter_alloc_fail:
00225     ape_decode_close(avctx);
00226     return AVERROR(ENOMEM);
00227 }
00228 
00234 #define CODE_BITS    32
00235 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
00236 #define SHIFT_BITS   (CODE_BITS - 9)
00237 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
00238 #define BOTTOM_VALUE (TOP_VALUE >> 8)
00239 
00241 static inline void range_start_decoding(APEContext *ctx)
00242 {
00243     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
00244     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
00245     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
00246 }
00247 
00249 static inline void range_dec_normalize(APEContext *ctx)
00250 {
00251     while (ctx->rc.range <= BOTTOM_VALUE) {
00252         ctx->rc.buffer <<= 8;
00253         if(ctx->ptr < ctx->data_end) {
00254             ctx->rc.buffer += *ctx->ptr;
00255             ctx->ptr++;
00256         } else {
00257             ctx->error = 1;
00258         }
00259         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
00260         ctx->rc.range  <<= 8;
00261     }
00262 }
00263 
00270 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
00271 {
00272     range_dec_normalize(ctx);
00273     ctx->rc.help = ctx->rc.range / tot_f;
00274     return ctx->rc.low / ctx->rc.help;
00275 }
00276 
00282 static inline int range_decode_culshift(APEContext *ctx, int shift)
00283 {
00284     range_dec_normalize(ctx);
00285     ctx->rc.help = ctx->rc.range >> shift;
00286     return ctx->rc.low / ctx->rc.help;
00287 }
00288 
00289 
00296 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
00297 {
00298     ctx->rc.low  -= ctx->rc.help * lt_f;
00299     ctx->rc.range = ctx->rc.help * sy_f;
00300 }
00301 
00303 static inline int range_decode_bits(APEContext *ctx, int n)
00304 {
00305     int sym = range_decode_culshift(ctx, n);
00306     range_decode_update(ctx, 1, sym);
00307     return sym;
00308 }
00309 
00310 
00311 #define MODEL_ELEMENTS 64
00312 
00316 static const uint16_t counts_3970[22] = {
00317         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
00318     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
00319     65450, 65469, 65480, 65487, 65491, 65493,
00320 };
00321 
00325 static const uint16_t counts_diff_3970[21] = {
00326     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
00327     1104, 677, 415, 248, 150, 89, 54, 31,
00328     19, 11, 7, 4, 2,
00329 };
00330 
00334 static const uint16_t counts_3980[22] = {
00335         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
00336     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
00337     65485, 65488, 65490, 65491, 65492, 65493,
00338 };
00339 
00343 static const uint16_t counts_diff_3980[21] = {
00344     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
00345     261, 119, 65, 31, 19, 10, 6, 3,
00346     3, 2, 1, 1, 1,
00347 };
00348 
00355 static inline int range_get_symbol(APEContext *ctx,
00356                                    const uint16_t counts[],
00357                                    const uint16_t counts_diff[])
00358 {
00359     int symbol, cf;
00360 
00361     cf = range_decode_culshift(ctx, 16);
00362 
00363     if(cf > 65492){
00364         symbol= cf - 65535 + 63;
00365         range_decode_update(ctx, 1, cf);
00366         if(cf > 65535)
00367             ctx->error=1;
00368         return symbol;
00369     }
00370     /* figure out the symbol inefficiently; a binary search would be much better */
00371     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
00372 
00373     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
00374 
00375     return symbol;
00376 } // group rangecoder
00378 
00379 static inline void update_rice(APERice *rice, int x)
00380 {
00381     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
00382     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
00383 
00384     if (rice->ksum < lim)
00385         rice->k--;
00386     else if (rice->ksum >= (1 << (rice->k + 5)))
00387         rice->k++;
00388 }
00389 
00390 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
00391 {
00392     int x, overflow;
00393 
00394     if (ctx->fileversion < 3990) {
00395         int tmpk;
00396 
00397         overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
00398 
00399         if (overflow == (MODEL_ELEMENTS - 1)) {
00400             tmpk = range_decode_bits(ctx, 5);
00401             overflow = 0;
00402         } else
00403             tmpk = (rice->k < 1) ? 0 : rice->k - 1;
00404 
00405         if (tmpk <= 16)
00406             x = range_decode_bits(ctx, tmpk);
00407         else {
00408             x = range_decode_bits(ctx, 16);
00409             x |= (range_decode_bits(ctx, tmpk - 16) << 16);
00410         }
00411         x += overflow << tmpk;
00412     } else {
00413         int base, pivot;
00414 
00415         pivot = rice->ksum >> 5;
00416         if (pivot == 0)
00417             pivot = 1;
00418 
00419         overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
00420 
00421         if (overflow == (MODEL_ELEMENTS - 1)) {
00422             overflow  = range_decode_bits(ctx, 16) << 16;
00423             overflow |= range_decode_bits(ctx, 16);
00424         }
00425 
00426         if (pivot < 0x10000) {
00427             base = range_decode_culfreq(ctx, pivot);
00428             range_decode_update(ctx, 1, base);
00429         } else {
00430             int base_hi = pivot, base_lo;
00431             int bbits = 0;
00432 
00433             while (base_hi & ~0xFFFF) {
00434                 base_hi >>= 1;
00435                 bbits++;
00436             }
00437             base_hi = range_decode_culfreq(ctx, base_hi + 1);
00438             range_decode_update(ctx, 1, base_hi);
00439             base_lo = range_decode_culfreq(ctx, 1 << bbits);
00440             range_decode_update(ctx, 1, base_lo);
00441 
00442             base = (base_hi << bbits) + base_lo;
00443         }
00444 
00445         x = base + overflow * pivot;
00446     }
00447 
00448     update_rice(rice, x);
00449 
00450     /* Convert to signed */
00451     if (x & 1)
00452         return (x >> 1) + 1;
00453     else
00454         return -(x >> 1);
00455 }
00456 
00457 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
00458 {
00459     int32_t *decoded0 = ctx->decoded0;
00460     int32_t *decoded1 = ctx->decoded1;
00461 
00462     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00463         /* We are pure silence, just memset the output buffer. */
00464         memset(decoded0, 0, blockstodecode * sizeof(int32_t));
00465         memset(decoded1, 0, blockstodecode * sizeof(int32_t));
00466     } else {
00467         while (blockstodecode--) {
00468             *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
00469             if (stereo)
00470                 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
00471         }
00472     }
00473 }
00474 
00475 static int init_entropy_decoder(APEContext *ctx)
00476 {
00477     /* Read the CRC */
00478     if (ctx->data_end - ctx->ptr < 6)
00479         return AVERROR_INVALIDDATA;
00480     ctx->CRC = bytestream_get_be32(&ctx->ptr);
00481 
00482     /* Read the frame flags if they exist */
00483     ctx->frameflags = 0;
00484     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
00485         ctx->CRC &= ~0x80000000;
00486 
00487         if (ctx->data_end - ctx->ptr < 6)
00488             return AVERROR_INVALIDDATA;
00489         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
00490     }
00491 
00492     /* Initialize the rice structs */
00493     ctx->riceX.k = 10;
00494     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
00495     ctx->riceY.k = 10;
00496     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
00497 
00498     /* The first 8 bits of input are ignored. */
00499     ctx->ptr++;
00500 
00501     range_start_decoding(ctx);
00502 
00503     return 0;
00504 }
00505 
00506 static const int32_t initial_coeffs[4] = {
00507     360, 317, -109, 98
00508 };
00509 
00510 static void init_predictor_decoder(APEContext *ctx)
00511 {
00512     APEPredictor *p = &ctx->predictor;
00513 
00514     /* Zero the history buffers */
00515     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
00516     p->buf = p->historybuffer;
00517 
00518     /* Initialize and zero the coefficients */
00519     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
00520     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
00521     memset(p->coeffsB, 0, sizeof(p->coeffsB));
00522 
00523     p->filterA[0] = p->filterA[1] = 0;
00524     p->filterB[0] = p->filterB[1] = 0;
00525     p->lastA[0]   = p->lastA[1]   = 0;
00526 }
00527 
00529 static inline int APESIGN(int32_t x) {
00530     return (x < 0) - (x > 0);
00531 }
00532 
00533 static av_always_inline int predictor_update_filter(APEPredictor *p,
00534                                                     const int decoded, const int filter,
00535                                                     const int delayA,  const int delayB,
00536                                                     const int adaptA,  const int adaptB)
00537 {
00538     int32_t predictionA, predictionB, sign;
00539 
00540     p->buf[delayA]     = p->lastA[filter];
00541     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
00542     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
00543     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
00544 
00545     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
00546                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
00547                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
00548                   p->buf[delayA - 3] * p->coeffsA[filter][3];
00549 
00550     /*  Apply a scaled first-order filter compression */
00551     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
00552     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
00553     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
00554     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
00555     p->filterB[filter] = p->filterA[filter ^ 1];
00556 
00557     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
00558                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
00559                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
00560                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
00561                   p->buf[delayB - 4] * p->coeffsB[filter][4];
00562 
00563     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
00564     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
00565 
00566     sign = APESIGN(decoded);
00567     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
00568     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
00569     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
00570     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
00571     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
00572     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
00573     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
00574     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
00575     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
00576 
00577     return p->filterA[filter];
00578 }
00579 
00580 static void predictor_decode_stereo(APEContext *ctx, int count)
00581 {
00582     APEPredictor *p = &ctx->predictor;
00583     int32_t *decoded0 = ctx->decoded0;
00584     int32_t *decoded1 = ctx->decoded1;
00585 
00586     while (count--) {
00587         /* Predictor Y */
00588         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
00589                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
00590         decoded0++;
00591         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
00592                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
00593         decoded1++;
00594 
00595         /* Combined */
00596         p->buf++;
00597 
00598         /* Have we filled the history buffer? */
00599         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00600             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
00601             p->buf = p->historybuffer;
00602         }
00603     }
00604 }
00605 
00606 static void predictor_decode_mono(APEContext *ctx, int count)
00607 {
00608     APEPredictor *p = &ctx->predictor;
00609     int32_t *decoded0 = ctx->decoded0;
00610     int32_t predictionA, currentA, A, sign;
00611 
00612     currentA = p->lastA[0];
00613 
00614     while (count--) {
00615         A = *decoded0;
00616 
00617         p->buf[YDELAYA] = currentA;
00618         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
00619 
00620         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
00621                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
00622                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
00623                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
00624 
00625         currentA = A + (predictionA >> 10);
00626 
00627         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
00628         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
00629 
00630         sign = APESIGN(A);
00631         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
00632         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
00633         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
00634         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
00635 
00636         p->buf++;
00637 
00638         /* Have we filled the history buffer? */
00639         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00640             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
00641             p->buf = p->historybuffer;
00642         }
00643 
00644         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
00645         *(decoded0++) = p->filterA[0];
00646     }
00647 
00648     p->lastA[0] = currentA;
00649 }
00650 
00651 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
00652 {
00653     f->coeffs = buf;
00654     f->historybuffer = buf + order;
00655     f->delay       = f->historybuffer + order * 2;
00656     f->adaptcoeffs = f->historybuffer + order;
00657 
00658     memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
00659     memset(f->coeffs, 0, order * sizeof(int16_t));
00660     f->avg = 0;
00661 }
00662 
00663 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
00664 {
00665     do_init_filter(&f[0], buf, order);
00666     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
00667 }
00668 
00669 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
00670                             int32_t *data, int count, int order, int fracbits)
00671 {
00672     int res;
00673     int absres;
00674 
00675     while (count--) {
00676         /* round fixedpoint scalar product */
00677         res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
00678                                                     f->adaptcoeffs - order,
00679                                                     order, APESIGN(*data));
00680         res = (res + (1 << (fracbits - 1))) >> fracbits;
00681         res += *data;
00682         *data++ = res;
00683 
00684         /* Update the output history */
00685         *f->delay++ = av_clip_int16(res);
00686 
00687         if (version < 3980) {
00688             /* Version ??? to < 3.98 files (untested) */
00689             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
00690             f->adaptcoeffs[-4] >>= 1;
00691             f->adaptcoeffs[-8] >>= 1;
00692         } else {
00693             /* Version 3.98 and later files */
00694 
00695             /* Update the adaption coefficients */
00696             absres = FFABS(res);
00697             if (absres)
00698                 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
00699                                   (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
00700             else
00701                 *f->adaptcoeffs = 0;
00702 
00703             f->avg += (absres - f->avg) / 16;
00704 
00705             f->adaptcoeffs[-1] >>= 1;
00706             f->adaptcoeffs[-2] >>= 1;
00707             f->adaptcoeffs[-8] >>= 1;
00708         }
00709 
00710         f->adaptcoeffs++;
00711 
00712         /* Have we filled the history buffer? */
00713         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
00714             memmove(f->historybuffer, f->delay - (order * 2),
00715                     (order * 2) * sizeof(int16_t));
00716             f->delay = f->historybuffer + order * 2;
00717             f->adaptcoeffs = f->historybuffer + order;
00718         }
00719     }
00720 }
00721 
00722 static void apply_filter(APEContext *ctx, APEFilter *f,
00723                          int32_t *data0, int32_t *data1,
00724                          int count, int order, int fracbits)
00725 {
00726     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
00727     if (data1)
00728         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
00729 }
00730 
00731 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
00732                               int32_t *decoded1, int count)
00733 {
00734     int i;
00735 
00736     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00737         if (!ape_filter_orders[ctx->fset][i])
00738             break;
00739         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
00740                      ape_filter_orders[ctx->fset][i],
00741                      ape_filter_fracbits[ctx->fset][i]);
00742     }
00743 }
00744 
00745 static int init_frame_decoder(APEContext *ctx)
00746 {
00747     int i, ret;
00748     if ((ret = init_entropy_decoder(ctx)) < 0)
00749         return ret;
00750     init_predictor_decoder(ctx);
00751 
00752     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00753         if (!ape_filter_orders[ctx->fset][i])
00754             break;
00755         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
00756                     ape_filter_orders[ctx->fset][i]);
00757     }
00758     return 0;
00759 }
00760 
00761 static void ape_unpack_mono(APEContext *ctx, int count)
00762 {
00763     int32_t *decoded0 = ctx->decoded0;
00764     int32_t *decoded1 = ctx->decoded1;
00765 
00766     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00767         entropy_decode(ctx, count, 0);
00768         /* We are pure silence, so we're done. */
00769         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
00770         return;
00771     }
00772 
00773     entropy_decode(ctx, count, 0);
00774     ape_apply_filters(ctx, decoded0, NULL, count);
00775 
00776     /* Now apply the predictor decoding */
00777     predictor_decode_mono(ctx, count);
00778 
00779     /* Pseudo-stereo - just copy left channel to right channel */
00780     if (ctx->channels == 2) {
00781         memcpy(decoded1, decoded0, count * sizeof(*decoded1));
00782     }
00783 }
00784 
00785 static void ape_unpack_stereo(APEContext *ctx, int count)
00786 {
00787     int32_t left, right;
00788     int32_t *decoded0 = ctx->decoded0;
00789     int32_t *decoded1 = ctx->decoded1;
00790 
00791     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00792         /* We are pure silence, so we're done. */
00793         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
00794         return;
00795     }
00796 
00797     entropy_decode(ctx, count, 1);
00798     ape_apply_filters(ctx, decoded0, decoded1, count);
00799 
00800     /* Now apply the predictor decoding */
00801     predictor_decode_stereo(ctx, count);
00802 
00803     /* Decorrelate and scale to output depth */
00804     while (count--) {
00805         left = *decoded1 - (*decoded0 / 2);
00806         right = left + *decoded0;
00807 
00808         *(decoded0++) = left;
00809         *(decoded1++) = right;
00810     }
00811 }
00812 
00813 static int ape_decode_frame(AVCodecContext *avctx, void *data,
00814                             int *got_frame_ptr, AVPacket *avpkt)
00815 {
00816     const uint8_t *buf = avpkt->data;
00817     int buf_size = avpkt->size;
00818     APEContext *s = avctx->priv_data;
00819     int16_t *samples;
00820     int i, ret;
00821     int blockstodecode;
00822     int bytes_used = 0;
00823 
00824     /* this should never be negative, but bad things will happen if it is, so
00825        check it just to make sure. */
00826     av_assert0(s->samples >= 0);
00827 
00828     if(!s->samples){
00829         uint32_t nblocks, offset;
00830         void *tmp_data;
00831 
00832         if (!buf_size) {
00833             *got_frame_ptr = 0;
00834             return 0;
00835         }
00836         if (buf_size < 8) {
00837             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
00838             return AVERROR_INVALIDDATA;
00839         }
00840 
00841         tmp_data = av_realloc(s->data, FFALIGN(buf_size, 4));
00842         if (!tmp_data)
00843             return AVERROR(ENOMEM);
00844         s->data = tmp_data;
00845         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
00846         s->ptr = s->data;
00847         s->data_end = s->data + buf_size;
00848 
00849         nblocks = bytestream_get_be32(&s->ptr);
00850         offset  = bytestream_get_be32(&s->ptr);
00851         if (offset > 3) {
00852             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
00853             s->data = NULL;
00854             return AVERROR_INVALIDDATA;
00855         }
00856         if (s->data_end - s->ptr < offset) {
00857             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
00858             return AVERROR_INVALIDDATA;
00859         }
00860         s->ptr += offset;
00861 
00862         if (!nblocks || nblocks > INT_MAX) {
00863             av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
00864             return AVERROR_INVALIDDATA;
00865         }
00866         s->samples = nblocks;
00867 
00868         memset(s->decoded0,  0, sizeof(s->decoded0));
00869         memset(s->decoded1,  0, sizeof(s->decoded1));
00870 
00871         /* Initialize the frame decoder */
00872         if (init_frame_decoder(s) < 0) {
00873             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
00874             return AVERROR_INVALIDDATA;
00875         }
00876 
00877         bytes_used = buf_size;
00878     }
00879 
00880     if (!s->data) {
00881         *got_frame_ptr = 0;
00882         return buf_size;
00883     }
00884 
00885     blockstodecode = FFMIN(BLOCKS_PER_LOOP, s->samples);
00886 
00887     /* get output buffer */
00888     s->frame.nb_samples = blockstodecode;
00889     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
00890         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00891         return ret;
00892     }
00893     samples = (int16_t *)s->frame.data[0];
00894 
00895     s->error=0;
00896 
00897     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
00898         ape_unpack_mono(s, blockstodecode);
00899     else
00900         ape_unpack_stereo(s, blockstodecode);
00901     emms_c();
00902 
00903     if (s->error) {
00904         s->samples=0;
00905         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
00906         return AVERROR_INVALIDDATA;
00907     }
00908 
00909     for (i = 0; i < blockstodecode; i++) {
00910         *samples++ = s->decoded0[i];
00911         if(s->channels == 2)
00912             *samples++ = s->decoded1[i];
00913     }
00914 
00915     s->samples -= blockstodecode;
00916 
00917     *got_frame_ptr   = 1;
00918     *(AVFrame *)data = s->frame;
00919 
00920     return bytes_used;
00921 }
00922 
00923 static void ape_flush(AVCodecContext *avctx)
00924 {
00925     APEContext *s = avctx->priv_data;
00926     s->samples= 0;
00927 }
00928 
00929 AVCodec ff_ape_decoder = {
00930     .name           = "ape",
00931     .type           = AVMEDIA_TYPE_AUDIO,
00932     .id             = CODEC_ID_APE,
00933     .priv_data_size = sizeof(APEContext),
00934     .init           = ape_decode_init,
00935     .close          = ape_decode_close,
00936     .decode         = ape_decode_frame,
00937     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
00938     .flush = ape_flush,
00939     .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
00940 };