Libav 0.7.1
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 ALT_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 
00035 #define BLOCKS_PER_LOOP     4608
00036 #define MAX_CHANNELS        2
00037 #define MAX_BYTESPERSAMPLE  3
00038 
00039 #define APE_FRAMECODE_MONO_SILENCE    1
00040 #define APE_FRAMECODE_STEREO_SILENCE  3
00041 #define APE_FRAMECODE_PSEUDO_STEREO   4
00042 
00043 #define HISTORY_SIZE 512
00044 #define PREDICTOR_ORDER 8
00045 
00046 #define PREDICTOR_SIZE 50
00047 
00048 #define YDELAYA (18 + PREDICTOR_ORDER*4)
00049 #define YDELAYB (18 + PREDICTOR_ORDER*3)
00050 #define XDELAYA (18 + PREDICTOR_ORDER*2)
00051 #define XDELAYB (18 + PREDICTOR_ORDER)
00052 
00053 #define YADAPTCOEFFSA 18
00054 #define XADAPTCOEFFSA 14
00055 #define YADAPTCOEFFSB 10
00056 #define XADAPTCOEFFSB 5
00057 
00062 enum APECompressionLevel {
00063     COMPRESSION_LEVEL_FAST       = 1000,
00064     COMPRESSION_LEVEL_NORMAL     = 2000,
00065     COMPRESSION_LEVEL_HIGH       = 3000,
00066     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
00067     COMPRESSION_LEVEL_INSANE     = 5000
00068 };
00071 #define APE_FILTER_LEVELS 3
00072 
00074 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
00075     {  0,   0,    0 },
00076     { 16,   0,    0 },
00077     { 64,   0,    0 },
00078     { 32, 256,    0 },
00079     { 16, 256, 1280 }
00080 };
00081 
00083 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
00084     {  0,  0,  0 },
00085     { 11,  0,  0 },
00086     { 11,  0,  0 },
00087     { 10, 13,  0 },
00088     { 11, 13, 15 }
00089 };
00090 
00091 
00093 typedef struct APEFilter {
00094     int16_t *coeffs;        
00095     int16_t *adaptcoeffs;   
00096     int16_t *historybuffer; 
00097     int16_t *delay;         
00098 
00099     int avg;
00100 } APEFilter;
00101 
00102 typedef struct APERice {
00103     uint32_t k;
00104     uint32_t ksum;
00105 } APERice;
00106 
00107 typedef struct APERangecoder {
00108     uint32_t low;           
00109     uint32_t range;         
00110     uint32_t help;          
00111     unsigned int buffer;    
00112 } APERangecoder;
00113 
00115 typedef struct APEPredictor {
00116     int32_t *buf;
00117 
00118     int32_t lastA[2];
00119 
00120     int32_t filterA[2];
00121     int32_t filterB[2];
00122 
00123     int32_t coeffsA[2][4];  
00124     int32_t coeffsB[2][5];  
00125     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
00126 } APEPredictor;
00127 
00129 typedef struct APEContext {
00130     AVCodecContext *avctx;
00131     DSPContext dsp;
00132     int channels;
00133     int samples;                             
00134 
00135     int fileversion;                         
00136     int compression_level;                   
00137     int fset;                                
00138     int flags;                               
00139 
00140     uint32_t CRC;                            
00141     int frameflags;                          
00142     int currentframeblocks;                  
00143     int blocksdecoded;                       
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     const uint8_t *last_ptr;                 
00160 
00161     int error;
00162 } APEContext;
00163 
00164 // TODO: dsputilize
00165 
00166 static av_cold int ape_decode_init(AVCodecContext * avctx)
00167 {
00168     APEContext *s = avctx->priv_data;
00169     int i;
00170 
00171     if (avctx->extradata_size != 6) {
00172         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
00173         return -1;
00174     }
00175     if (avctx->bits_per_coded_sample != 16) {
00176         av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
00177         return -1;
00178     }
00179     if (avctx->channels > 2) {
00180         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
00181         return -1;
00182     }
00183     s->avctx             = avctx;
00184     s->channels          = avctx->channels;
00185     s->fileversion       = AV_RL16(avctx->extradata);
00186     s->compression_level = AV_RL16(avctx->extradata + 2);
00187     s->flags             = AV_RL16(avctx->extradata + 4);
00188 
00189     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);
00190     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
00191         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);
00192         return -1;
00193     }
00194     s->fset = s->compression_level / 1000 - 1;
00195     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00196         if (!ape_filter_orders[s->fset][i])
00197             break;
00198         s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);
00199     }
00200 
00201     dsputil_init(&s->dsp, avctx);
00202     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00203     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
00204     return 0;
00205 }
00206 
00207 static av_cold int ape_decode_close(AVCodecContext * avctx)
00208 {
00209     APEContext *s = avctx->priv_data;
00210     int i;
00211 
00212     for (i = 0; i < APE_FILTER_LEVELS; i++)
00213         av_freep(&s->filterbuf[i]);
00214 
00215     av_freep(&s->data);
00216     return 0;
00217 }
00218 
00224 #define CODE_BITS    32
00225 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
00226 #define SHIFT_BITS   (CODE_BITS - 9)
00227 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
00228 #define BOTTOM_VALUE (TOP_VALUE >> 8)
00229 
00231 static inline void range_start_decoding(APEContext * ctx)
00232 {
00233     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
00234     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
00235     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
00236 }
00237 
00239 static inline void range_dec_normalize(APEContext * ctx)
00240 {
00241     while (ctx->rc.range <= BOTTOM_VALUE) {
00242         ctx->rc.buffer <<= 8;
00243         if(ctx->ptr < ctx->data_end)
00244             ctx->rc.buffer += *ctx->ptr;
00245         ctx->ptr++;
00246         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
00247         ctx->rc.range  <<= 8;
00248     }
00249 }
00250 
00257 static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
00258 {
00259     range_dec_normalize(ctx);
00260     ctx->rc.help = ctx->rc.range / tot_f;
00261     return ctx->rc.low / ctx->rc.help;
00262 }
00263 
00269 static inline int range_decode_culshift(APEContext * ctx, int shift)
00270 {
00271     range_dec_normalize(ctx);
00272     ctx->rc.help = ctx->rc.range >> shift;
00273     return ctx->rc.low / ctx->rc.help;
00274 }
00275 
00276 
00283 static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
00284 {
00285     ctx->rc.low  -= ctx->rc.help * lt_f;
00286     ctx->rc.range = ctx->rc.help * sy_f;
00287 }
00288 
00290 static inline int range_decode_bits(APEContext * ctx, int n)
00291 {
00292     int sym = range_decode_culshift(ctx, n);
00293     range_decode_update(ctx, 1, sym);
00294     return sym;
00295 }
00296 
00297 
00298 #define MODEL_ELEMENTS 64
00299 
00303 static const uint16_t counts_3970[22] = {
00304         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
00305     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
00306     65450, 65469, 65480, 65487, 65491, 65493,
00307 };
00308 
00312 static const uint16_t counts_diff_3970[21] = {
00313     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
00314     1104, 677, 415, 248, 150, 89, 54, 31,
00315     19, 11, 7, 4, 2,
00316 };
00317 
00321 static const uint16_t counts_3980[22] = {
00322         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
00323     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
00324     65485, 65488, 65490, 65491, 65492, 65493,
00325 };
00326 
00330 static const uint16_t counts_diff_3980[21] = {
00331     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
00332     261, 119, 65, 31, 19, 10, 6, 3,
00333     3, 2, 1, 1, 1,
00334 };
00335 
00342 static inline int range_get_symbol(APEContext * ctx,
00343                                    const uint16_t counts[],
00344                                    const uint16_t counts_diff[])
00345 {
00346     int symbol, cf;
00347 
00348     cf = range_decode_culshift(ctx, 16);
00349 
00350     if(cf > 65492){
00351         symbol= cf - 65535 + 63;
00352         range_decode_update(ctx, 1, cf);
00353         if(cf > 65535)
00354             ctx->error=1;
00355         return symbol;
00356     }
00357     /* figure out the symbol inefficiently; a binary search would be much better */
00358     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
00359 
00360     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
00361 
00362     return symbol;
00363 } // group rangecoder
00365 
00366 static inline void update_rice(APERice *rice, int x)
00367 {
00368     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
00369     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
00370 
00371     if (rice->ksum < lim)
00372         rice->k--;
00373     else if (rice->ksum >= (1 << (rice->k + 5)))
00374         rice->k++;
00375 }
00376 
00377 static inline int ape_decode_value(APEContext * ctx, APERice *rice)
00378 {
00379     int x, overflow;
00380 
00381     if (ctx->fileversion < 3990) {
00382         int tmpk;
00383 
00384         overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
00385 
00386         if (overflow == (MODEL_ELEMENTS - 1)) {
00387             tmpk = range_decode_bits(ctx, 5);
00388             overflow = 0;
00389         } else
00390             tmpk = (rice->k < 1) ? 0 : rice->k - 1;
00391 
00392         if (tmpk <= 16)
00393             x = range_decode_bits(ctx, tmpk);
00394         else {
00395             x = range_decode_bits(ctx, 16);
00396             x |= (range_decode_bits(ctx, tmpk - 16) << 16);
00397         }
00398         x += overflow << tmpk;
00399     } else {
00400         int base, pivot;
00401 
00402         pivot = rice->ksum >> 5;
00403         if (pivot == 0)
00404             pivot = 1;
00405 
00406         overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
00407 
00408         if (overflow == (MODEL_ELEMENTS - 1)) {
00409             overflow  = range_decode_bits(ctx, 16) << 16;
00410             overflow |= range_decode_bits(ctx, 16);
00411         }
00412 
00413         if (pivot < 0x10000) {
00414             base = range_decode_culfreq(ctx, pivot);
00415             range_decode_update(ctx, 1, base);
00416         } else {
00417             int base_hi = pivot, base_lo;
00418             int bbits = 0;
00419 
00420             while (base_hi & ~0xFFFF) {
00421                 base_hi >>= 1;
00422                 bbits++;
00423             }
00424             base_hi = range_decode_culfreq(ctx, base_hi + 1);
00425             range_decode_update(ctx, 1, base_hi);
00426             base_lo = range_decode_culfreq(ctx, 1 << bbits);
00427             range_decode_update(ctx, 1, base_lo);
00428 
00429             base = (base_hi << bbits) + base_lo;
00430         }
00431 
00432         x = base + overflow * pivot;
00433     }
00434 
00435     update_rice(rice, x);
00436 
00437     /* Convert to signed */
00438     if (x & 1)
00439         return (x >> 1) + 1;
00440     else
00441         return -(x >> 1);
00442 }
00443 
00444 static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
00445 {
00446     int32_t *decoded0 = ctx->decoded0;
00447     int32_t *decoded1 = ctx->decoded1;
00448 
00449     ctx->blocksdecoded = blockstodecode;
00450 
00451     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00452         /* We are pure silence, just memset the output buffer. */
00453         memset(decoded0, 0, blockstodecode * sizeof(int32_t));
00454         memset(decoded1, 0, blockstodecode * sizeof(int32_t));
00455     } else {
00456         while (blockstodecode--) {
00457             *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
00458             if (stereo)
00459                 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
00460         }
00461     }
00462 
00463     if (ctx->blocksdecoded == ctx->currentframeblocks)
00464         range_dec_normalize(ctx);   /* normalize to use up all bytes */
00465 }
00466 
00467 static void init_entropy_decoder(APEContext * ctx)
00468 {
00469     /* Read the CRC */
00470     ctx->CRC = bytestream_get_be32(&ctx->ptr);
00471 
00472     /* Read the frame flags if they exist */
00473     ctx->frameflags = 0;
00474     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
00475         ctx->CRC &= ~0x80000000;
00476 
00477         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
00478     }
00479 
00480     /* Keep a count of the blocks decoded in this frame */
00481     ctx->blocksdecoded = 0;
00482 
00483     /* Initialize the rice structs */
00484     ctx->riceX.k = 10;
00485     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
00486     ctx->riceY.k = 10;
00487     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
00488 
00489     /* The first 8 bits of input are ignored. */
00490     ctx->ptr++;
00491 
00492     range_start_decoding(ctx);
00493 }
00494 
00495 static const int32_t initial_coeffs[4] = {
00496     360, 317, -109, 98
00497 };
00498 
00499 static void init_predictor_decoder(APEContext * ctx)
00500 {
00501     APEPredictor *p = &ctx->predictor;
00502 
00503     /* Zero the history buffers */
00504     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
00505     p->buf = p->historybuffer;
00506 
00507     /* Initialize and zero the coefficients */
00508     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
00509     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
00510     memset(p->coeffsB, 0, sizeof(p->coeffsB));
00511 
00512     p->filterA[0] = p->filterA[1] = 0;
00513     p->filterB[0] = p->filterB[1] = 0;
00514     p->lastA[0]   = p->lastA[1]   = 0;
00515 }
00516 
00518 static inline int APESIGN(int32_t x) {
00519     return (x < 0) - (x > 0);
00520 }
00521 
00522 static av_always_inline int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
00523 {
00524     int32_t predictionA, predictionB, sign;
00525 
00526     p->buf[delayA]     = p->lastA[filter];
00527     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
00528     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
00529     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
00530 
00531     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
00532                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
00533                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
00534                   p->buf[delayA - 3] * p->coeffsA[filter][3];
00535 
00536     /*  Apply a scaled first-order filter compression */
00537     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
00538     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
00539     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
00540     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
00541     p->filterB[filter] = p->filterA[filter ^ 1];
00542 
00543     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
00544                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
00545                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
00546                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
00547                   p->buf[delayB - 4] * p->coeffsB[filter][4];
00548 
00549     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
00550     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
00551 
00552     sign = APESIGN(decoded);
00553     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
00554     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
00555     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
00556     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
00557     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
00558     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
00559     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
00560     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
00561     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
00562 
00563     return p->filterA[filter];
00564 }
00565 
00566 static void predictor_decode_stereo(APEContext * ctx, int count)
00567 {
00568     APEPredictor *p = &ctx->predictor;
00569     int32_t *decoded0 = ctx->decoded0;
00570     int32_t *decoded1 = ctx->decoded1;
00571 
00572     while (count--) {
00573         /* Predictor Y */
00574         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
00575         decoded0++;
00576         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
00577         decoded1++;
00578 
00579         /* Combined */
00580         p->buf++;
00581 
00582         /* Have we filled the history buffer? */
00583         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00584             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
00585             p->buf = p->historybuffer;
00586         }
00587     }
00588 }
00589 
00590 static void predictor_decode_mono(APEContext * ctx, int count)
00591 {
00592     APEPredictor *p = &ctx->predictor;
00593     int32_t *decoded0 = ctx->decoded0;
00594     int32_t predictionA, currentA, A, sign;
00595 
00596     currentA = p->lastA[0];
00597 
00598     while (count--) {
00599         A = *decoded0;
00600 
00601         p->buf[YDELAYA] = currentA;
00602         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
00603 
00604         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
00605                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
00606                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
00607                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
00608 
00609         currentA = A + (predictionA >> 10);
00610 
00611         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
00612         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
00613 
00614         sign = APESIGN(A);
00615         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
00616         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
00617         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
00618         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
00619 
00620         p->buf++;
00621 
00622         /* Have we filled the history buffer? */
00623         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00624             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
00625             p->buf = p->historybuffer;
00626         }
00627 
00628         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
00629         *(decoded0++) = p->filterA[0];
00630     }
00631 
00632     p->lastA[0] = currentA;
00633 }
00634 
00635 static void do_init_filter(APEFilter *f, int16_t * buf, int order)
00636 {
00637     f->coeffs = buf;
00638     f->historybuffer = buf + order;
00639     f->delay       = f->historybuffer + order * 2;
00640     f->adaptcoeffs = f->historybuffer + order;
00641 
00642     memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
00643     memset(f->coeffs, 0, order * sizeof(int16_t));
00644     f->avg = 0;
00645 }
00646 
00647 static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
00648 {
00649     do_init_filter(&f[0], buf, order);
00650     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
00651 }
00652 
00653 static void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
00654 {
00655     int res;
00656     int absres;
00657 
00658     while (count--) {
00659         /* round fixedpoint scalar product */
00660         res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order, f->adaptcoeffs - order, order, APESIGN(*data));
00661         res = (res + (1 << (fracbits - 1))) >> fracbits;
00662         res += *data;
00663         *data++ = res;
00664 
00665         /* Update the output history */
00666         *f->delay++ = av_clip_int16(res);
00667 
00668         if (version < 3980) {
00669             /* Version ??? to < 3.98 files (untested) */
00670             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
00671             f->adaptcoeffs[-4] >>= 1;
00672             f->adaptcoeffs[-8] >>= 1;
00673         } else {
00674             /* Version 3.98 and later files */
00675 
00676             /* Update the adaption coefficients */
00677             absres = FFABS(res);
00678             if (absres)
00679                 *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >> (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
00680             else
00681                 *f->adaptcoeffs = 0;
00682 
00683             f->avg += (absres - f->avg) / 16;
00684 
00685             f->adaptcoeffs[-1] >>= 1;
00686             f->adaptcoeffs[-2] >>= 1;
00687             f->adaptcoeffs[-8] >>= 1;
00688         }
00689 
00690         f->adaptcoeffs++;
00691 
00692         /* Have we filled the history buffer? */
00693         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
00694             memmove(f->historybuffer, f->delay - (order * 2),
00695                     (order * 2) * sizeof(int16_t));
00696             f->delay = f->historybuffer + order * 2;
00697             f->adaptcoeffs = f->historybuffer + order;
00698         }
00699     }
00700 }
00701 
00702 static void apply_filter(APEContext * ctx, APEFilter *f,
00703                          int32_t * data0, int32_t * data1,
00704                          int count, int order, int fracbits)
00705 {
00706     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
00707     if (data1)
00708         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
00709 }
00710 
00711 static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
00712                               int32_t * decoded1, int count)
00713 {
00714     int i;
00715 
00716     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00717         if (!ape_filter_orders[ctx->fset][i])
00718             break;
00719         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
00720     }
00721 }
00722 
00723 static void init_frame_decoder(APEContext * ctx)
00724 {
00725     int i;
00726     init_entropy_decoder(ctx);
00727     init_predictor_decoder(ctx);
00728 
00729     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00730         if (!ape_filter_orders[ctx->fset][i])
00731             break;
00732         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
00733     }
00734 }
00735 
00736 static void ape_unpack_mono(APEContext * ctx, int count)
00737 {
00738     int32_t left;
00739     int32_t *decoded0 = ctx->decoded0;
00740     int32_t *decoded1 = ctx->decoded1;
00741 
00742     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00743         entropy_decode(ctx, count, 0);
00744         /* We are pure silence, so we're done. */
00745         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
00746         return;
00747     }
00748 
00749     entropy_decode(ctx, count, 0);
00750     ape_apply_filters(ctx, decoded0, NULL, count);
00751 
00752     /* Now apply the predictor decoding */
00753     predictor_decode_mono(ctx, count);
00754 
00755     /* Pseudo-stereo - just copy left channel to right channel */
00756     if (ctx->channels == 2) {
00757         while (count--) {
00758             left = *decoded0;
00759             *(decoded1++) = *(decoded0++) = left;
00760         }
00761     }
00762 }
00763 
00764 static void ape_unpack_stereo(APEContext * ctx, int count)
00765 {
00766     int32_t left, right;
00767     int32_t *decoded0 = ctx->decoded0;
00768     int32_t *decoded1 = ctx->decoded1;
00769 
00770     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00771         /* We are pure silence, so we're done. */
00772         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
00773         return;
00774     }
00775 
00776     entropy_decode(ctx, count, 1);
00777     ape_apply_filters(ctx, decoded0, decoded1, count);
00778 
00779     /* Now apply the predictor decoding */
00780     predictor_decode_stereo(ctx, count);
00781 
00782     /* Decorrelate and scale to output depth */
00783     while (count--) {
00784         left = *decoded1 - (*decoded0 / 2);
00785         right = left + *decoded0;
00786 
00787         *(decoded0++) = left;
00788         *(decoded1++) = right;
00789     }
00790 }
00791 
00792 static int ape_decode_frame(AVCodecContext * avctx,
00793                             void *data, int *data_size,
00794                             AVPacket *avpkt)
00795 {
00796     const uint8_t *buf = avpkt->data;
00797     int buf_size = avpkt->size;
00798     APEContext *s = avctx->priv_data;
00799     int16_t *samples = data;
00800     int nblocks;
00801     int i, n;
00802     int blockstodecode;
00803     int bytes_used;
00804 
00805     if (buf_size == 0 && !s->samples) {
00806         *data_size = 0;
00807         return 0;
00808     }
00809 
00810     /* should not happen but who knows */
00811     if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
00812         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);
00813         return -1;
00814     }
00815 
00816     if(!s->samples){
00817         s->data = av_realloc(s->data, (buf_size + 3) & ~3);
00818         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
00819         s->ptr = s->last_ptr = s->data;
00820         s->data_end = s->data + buf_size;
00821 
00822         nblocks = s->samples = bytestream_get_be32(&s->ptr);
00823         n =  bytestream_get_be32(&s->ptr);
00824         if(n < 0 || n > 3){
00825             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
00826             s->data = NULL;
00827             return -1;
00828         }
00829         s->ptr += n;
00830 
00831         s->currentframeblocks = nblocks;
00832         buf += 4;
00833         if (s->samples <= 0) {
00834             *data_size = 0;
00835             return buf_size;
00836         }
00837 
00838         memset(s->decoded0,  0, sizeof(s->decoded0));
00839         memset(s->decoded1,  0, sizeof(s->decoded1));
00840 
00841         /* Initialize the frame decoder */
00842         init_frame_decoder(s);
00843     }
00844 
00845     if (!s->data) {
00846         *data_size = 0;
00847         return buf_size;
00848     }
00849 
00850     nblocks = s->samples;
00851     blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
00852 
00853     s->error=0;
00854 
00855     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
00856         ape_unpack_mono(s, blockstodecode);
00857     else
00858         ape_unpack_stereo(s, blockstodecode);
00859     emms_c();
00860 
00861     if(s->error || s->ptr > s->data_end){
00862         s->samples=0;
00863         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
00864         return -1;
00865     }
00866 
00867     for (i = 0; i < blockstodecode; i++) {
00868         *samples++ = s->decoded0[i];
00869         if(s->channels == 2)
00870             *samples++ = s->decoded1[i];
00871     }
00872 
00873     s->samples -= blockstodecode;
00874 
00875     *data_size = blockstodecode * 2 * s->channels;
00876     bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
00877     s->last_ptr = s->ptr;
00878     return bytes_used;
00879 }
00880 
00881 static void ape_flush(AVCodecContext *avctx)
00882 {
00883     APEContext *s = avctx->priv_data;
00884     s->samples= 0;
00885 }
00886 
00887 AVCodec ff_ape_decoder = {
00888     "ape",
00889     AVMEDIA_TYPE_AUDIO,
00890     CODEC_ID_APE,
00891     sizeof(APEContext),
00892     ape_decode_init,
00893     NULL,
00894     ape_decode_close,
00895     ape_decode_frame,
00896     .capabilities = CODEC_CAP_SUBFRAMES,
00897     .flush = ape_flush,
00898     .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
00899 };