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