00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 
00018 
00019 
00020 
00021 
00022 
00023 #include "avcodec.h"
00024 #include "dsputil.h"
00025 #include "bytestream.h"
00026 #include "libavutil/audioconvert.h"
00027 #include "libavutil/avassert.h"
00028 #include "libavutil/opt.h"
00029 
00035 #define MAX_CHANNELS        2
00036 #define MAX_BYTESPERSAMPLE  3
00037 
00038 #define APE_FRAMECODE_MONO_SILENCE    1
00039 #define APE_FRAMECODE_STEREO_SILENCE  3
00040 #define APE_FRAMECODE_PSEUDO_STEREO   4
00041 
00042 #define HISTORY_SIZE 512
00043 #define PREDICTOR_ORDER 8
00044 
00045 #define PREDICTOR_SIZE 50
00046 
00047 #define YDELAYA (18 + PREDICTOR_ORDER*4)
00048 #define YDELAYB (18 + PREDICTOR_ORDER*3)
00049 #define XDELAYA (18 + PREDICTOR_ORDER*2)
00050 #define XDELAYB (18 + PREDICTOR_ORDER)
00051 
00052 #define YADAPTCOEFFSA 18
00053 #define XADAPTCOEFFSA 14
00054 #define YADAPTCOEFFSB 10
00055 #define XADAPTCOEFFSB 5
00056 
00061 enum APECompressionLevel {
00062     COMPRESSION_LEVEL_FAST       = 1000,
00063     COMPRESSION_LEVEL_NORMAL     = 2000,
00064     COMPRESSION_LEVEL_HIGH       = 3000,
00065     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
00066     COMPRESSION_LEVEL_INSANE     = 5000
00067 };
00070 #define APE_FILTER_LEVELS 3
00071 
00073 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
00074     {  0,   0,    0 },
00075     { 16,   0,    0 },
00076     { 64,   0,    0 },
00077     { 32, 256,    0 },
00078     { 16, 256, 1280 }
00079 };
00080 
00082 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
00083     {  0,  0,  0 },
00084     { 11,  0,  0 },
00085     { 11,  0,  0 },
00086     { 10, 13,  0 },
00087     { 11, 13, 15 }
00088 };
00089 
00090 
00092 typedef struct APEFilter {
00093     int16_t *coeffs;        
00094     int16_t *adaptcoeffs;   
00095     int16_t *historybuffer; 
00096     int16_t *delay;         
00097 
00098     int avg;
00099 } APEFilter;
00100 
00101 typedef struct APERice {
00102     uint32_t k;
00103     uint32_t ksum;
00104 } APERice;
00105 
00106 typedef struct APERangecoder {
00107     uint32_t low;           
00108     uint32_t range;         
00109     uint32_t help;          
00110     unsigned int buffer;    
00111 } APERangecoder;
00112 
00114 typedef struct APEPredictor {
00115     int32_t *buf;
00116 
00117     int32_t lastA[2];
00118 
00119     int32_t filterA[2];
00120     int32_t filterB[2];
00121 
00122     int32_t coeffsA[2][4];  
00123     int32_t coeffsB[2][5];  
00124     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
00125 } APEPredictor;
00126 
00128 typedef struct APEContext {
00129     AVClass *class;                          
00130     AVCodecContext *avctx;
00131     AVFrame frame;
00132     DSPContext dsp;
00133     int channels;
00134     int samples;                             
00135     int bps;
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 *decoded_buffer;
00147     int decoded_size;
00148     int32_t *decoded[MAX_CHANNELS];          
00149     int blocks_per_loop;                     
00150 
00151     int16_t* filterbuf[APE_FILTER_LEVELS];   
00152 
00153     APERangecoder rc;                        
00154     APERice riceX;                           
00155     APERice riceY;                           
00156     APEFilter filters[APE_FILTER_LEVELS][2]; 
00157 
00158     uint8_t *data;                           
00159     uint8_t *data_end;                       
00160     int data_size;                           
00161     const uint8_t *ptr;                      
00162 
00163     int error;
00164 } APEContext;
00165 
00166 
00167 
00168 static av_cold int ape_decode_close(AVCodecContext *avctx)
00169 {
00170     APEContext *s = avctx->priv_data;
00171     int i;
00172 
00173     for (i = 0; i < APE_FILTER_LEVELS; i++)
00174         av_freep(&s->filterbuf[i]);
00175 
00176     av_freep(&s->decoded_buffer);
00177     av_freep(&s->data);
00178     s->decoded_size = s->data_size = 0;
00179 
00180     return 0;
00181 }
00182 
00183 static av_cold int ape_decode_init(AVCodecContext *avctx)
00184 {
00185     APEContext *s = avctx->priv_data;
00186     int i;
00187 
00188     if (avctx->extradata_size != 6) {
00189         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
00190         return AVERROR(EINVAL);
00191     }
00192     if (avctx->channels > 2) {
00193         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
00194         return AVERROR(EINVAL);
00195     }
00196     s->bps = avctx->bits_per_coded_sample;
00197     switch (s->bps) {
00198     case 8:
00199         avctx->sample_fmt = AV_SAMPLE_FMT_U8;
00200         break;
00201     case 16:
00202         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00203         break;
00204     case 24:
00205         avctx->sample_fmt = AV_SAMPLE_FMT_S32;
00206         break;
00207     default:
00208         av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",
00209                               s->bps);
00210         return AVERROR_PATCHWELCOME;
00211     }
00212     s->avctx             = avctx;
00213     s->channels          = avctx->channels;
00214     s->fileversion       = AV_RL16(avctx->extradata);
00215     s->compression_level = AV_RL16(avctx->extradata + 2);
00216     s->flags             = AV_RL16(avctx->extradata + 4);
00217 
00218     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
00219            s->compression_level, s->flags);
00220     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE || !s->compression_level) {
00221         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
00222                s->compression_level);
00223         return AVERROR_INVALIDDATA;
00224     }
00225     s->fset = s->compression_level / 1000 - 1;
00226     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00227         if (!ape_filter_orders[s->fset][i])
00228             break;
00229         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
00230                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
00231                          filter_alloc_fail);
00232     }
00233 
00234     ff_dsputil_init(&s->dsp, avctx);
00235     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
00236 
00237     avcodec_get_frame_defaults(&s->frame);
00238     avctx->coded_frame = &s->frame;
00239 
00240     return 0;
00241 filter_alloc_fail:
00242     ape_decode_close(avctx);
00243     return AVERROR(ENOMEM);
00244 }
00245 
00251 #define CODE_BITS    32
00252 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
00253 #define SHIFT_BITS   (CODE_BITS - 9)
00254 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
00255 #define BOTTOM_VALUE (TOP_VALUE >> 8)
00256 
00258 static inline void range_start_decoding(APEContext *ctx)
00259 {
00260     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
00261     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
00262     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
00263 }
00264 
00266 static inline void range_dec_normalize(APEContext *ctx)
00267 {
00268     while (ctx->rc.range <= BOTTOM_VALUE) {
00269         ctx->rc.buffer <<= 8;
00270         if(ctx->ptr < ctx->data_end) {
00271             ctx->rc.buffer += *ctx->ptr;
00272             ctx->ptr++;
00273         } else {
00274             ctx->error = 1;
00275         }
00276         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
00277         ctx->rc.range  <<= 8;
00278     }
00279 }
00280 
00287 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
00288 {
00289     range_dec_normalize(ctx);
00290     ctx->rc.help = ctx->rc.range / tot_f;
00291     return ctx->rc.low / ctx->rc.help;
00292 }
00293 
00299 static inline int range_decode_culshift(APEContext *ctx, int shift)
00300 {
00301     range_dec_normalize(ctx);
00302     ctx->rc.help = ctx->rc.range >> shift;
00303     return ctx->rc.low / ctx->rc.help;
00304 }
00305 
00306 
00313 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
00314 {
00315     ctx->rc.low  -= ctx->rc.help * lt_f;
00316     ctx->rc.range = ctx->rc.help * sy_f;
00317 }
00318 
00320 static inline int range_decode_bits(APEContext *ctx, int n)
00321 {
00322     int sym = range_decode_culshift(ctx, n);
00323     range_decode_update(ctx, 1, sym);
00324     return sym;
00325 }
00326 
00327 
00328 #define MODEL_ELEMENTS 64
00329 
00333 static const uint16_t counts_3970[22] = {
00334         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
00335     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
00336     65450, 65469, 65480, 65487, 65491, 65493,
00337 };
00338 
00342 static const uint16_t counts_diff_3970[21] = {
00343     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
00344     1104, 677, 415, 248, 150, 89, 54, 31,
00345     19, 11, 7, 4, 2,
00346 };
00347 
00351 static const uint16_t counts_3980[22] = {
00352         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
00353     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
00354     65485, 65488, 65490, 65491, 65492, 65493,
00355 };
00356 
00360 static const uint16_t counts_diff_3980[21] = {
00361     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
00362     261, 119, 65, 31, 19, 10, 6, 3,
00363     3, 2, 1, 1, 1,
00364 };
00365 
00372 static inline int range_get_symbol(APEContext *ctx,
00373                                    const uint16_t counts[],
00374                                    const uint16_t counts_diff[])
00375 {
00376     int symbol, cf;
00377 
00378     cf = range_decode_culshift(ctx, 16);
00379 
00380     if(cf > 65492){
00381         symbol= cf - 65535 + 63;
00382         range_decode_update(ctx, 1, cf);
00383         if(cf > 65535)
00384             ctx->error=1;
00385         return symbol;
00386     }
00387     
00388     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
00389 
00390     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
00391 
00392     return symbol;
00393 } 
00395 
00396 static inline void update_rice(APERice *rice, unsigned int x)
00397 {
00398     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
00399     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
00400 
00401     if (rice->ksum < lim)
00402         rice->k--;
00403     else if (rice->ksum >= (1 << (rice->k + 5)))
00404         rice->k++;
00405 }
00406 
00407 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
00408 {
00409     unsigned int x, overflow;
00410 
00411     if (ctx->fileversion < 3990) {
00412         int tmpk;
00413 
00414         overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
00415 
00416         if (overflow == (MODEL_ELEMENTS - 1)) {
00417             tmpk = range_decode_bits(ctx, 5);
00418             overflow = 0;
00419         } else
00420             tmpk = (rice->k < 1) ? 0 : rice->k - 1;
00421 
00422         if (tmpk <= 16)
00423             x = range_decode_bits(ctx, tmpk);
00424         else if (tmpk <= 32) {
00425             x = range_decode_bits(ctx, 16);
00426             x |= (range_decode_bits(ctx, tmpk - 16) << 16);
00427         } else {
00428             av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
00429             return AVERROR_INVALIDDATA;
00430         }
00431         x += overflow << tmpk;
00432     } else {
00433         int base, pivot;
00434 
00435         pivot = rice->ksum >> 5;
00436         if (pivot == 0)
00437             pivot = 1;
00438 
00439         overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
00440 
00441         if (overflow == (MODEL_ELEMENTS - 1)) {
00442             overflow  = range_decode_bits(ctx, 16) << 16;
00443             overflow |= range_decode_bits(ctx, 16);
00444         }
00445 
00446         if (pivot < 0x10000) {
00447             base = range_decode_culfreq(ctx, pivot);
00448             range_decode_update(ctx, 1, base);
00449         } else {
00450             int base_hi = pivot, base_lo;
00451             int bbits = 0;
00452 
00453             while (base_hi & ~0xFFFF) {
00454                 base_hi >>= 1;
00455                 bbits++;
00456             }
00457             base_hi = range_decode_culfreq(ctx, base_hi + 1);
00458             range_decode_update(ctx, 1, base_hi);
00459             base_lo = range_decode_culfreq(ctx, 1 << bbits);
00460             range_decode_update(ctx, 1, base_lo);
00461 
00462             base = (base_hi << bbits) + base_lo;
00463         }
00464 
00465         x = base + overflow * pivot;
00466     }
00467 
00468     update_rice(rice, x);
00469 
00470     
00471     if (x & 1)
00472         return (x >> 1) + 1;
00473     else
00474         return -(x >> 1);
00475 }
00476 
00477 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
00478 {
00479     int32_t *decoded0 = ctx->decoded[0];
00480     int32_t *decoded1 = ctx->decoded[1];
00481 
00482     while (blockstodecode--) {
00483         *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
00484         if (stereo)
00485             *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
00486     }
00487 }
00488 
00489 static int init_entropy_decoder(APEContext *ctx)
00490 {
00491     
00492     if (ctx->data_end - ctx->ptr < 6)
00493         return AVERROR_INVALIDDATA;
00494     ctx->CRC = bytestream_get_be32(&ctx->ptr);
00495 
00496     
00497     ctx->frameflags = 0;
00498     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
00499         ctx->CRC &= ~0x80000000;
00500 
00501         if (ctx->data_end - ctx->ptr < 6)
00502             return AVERROR_INVALIDDATA;
00503         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
00504     }
00505 
00506     
00507     ctx->riceX.k = 10;
00508     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
00509     ctx->riceY.k = 10;
00510     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
00511 
00512     
00513     ctx->ptr++;
00514 
00515     range_start_decoding(ctx);
00516 
00517     return 0;
00518 }
00519 
00520 static const int32_t initial_coeffs[4] = {
00521     360, 317, -109, 98
00522 };
00523 
00524 static void init_predictor_decoder(APEContext *ctx)
00525 {
00526     APEPredictor *p = &ctx->predictor;
00527 
00528     
00529     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
00530     p->buf = p->historybuffer;
00531 
00532     
00533     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
00534     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
00535     memset(p->coeffsB, 0, sizeof(p->coeffsB));
00536 
00537     p->filterA[0] = p->filterA[1] = 0;
00538     p->filterB[0] = p->filterB[1] = 0;
00539     p->lastA[0]   = p->lastA[1]   = 0;
00540 }
00541 
00543 static inline int APESIGN(int32_t x) {
00544     return (x < 0) - (x > 0);
00545 }
00546 
00547 static av_always_inline int predictor_update_filter(APEPredictor *p,
00548                                                     const int decoded, const int filter,
00549                                                     const int delayA,  const int delayB,
00550                                                     const int adaptA,  const int adaptB)
00551 {
00552     int32_t predictionA, predictionB, sign;
00553 
00554     p->buf[delayA]     = p->lastA[filter];
00555     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
00556     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
00557     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
00558 
00559     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
00560                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
00561                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
00562                   p->buf[delayA - 3] * p->coeffsA[filter][3];
00563 
00564     
00565     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
00566     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
00567     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
00568     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
00569     p->filterB[filter] = p->filterA[filter ^ 1];
00570 
00571     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
00572                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
00573                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
00574                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
00575                   p->buf[delayB - 4] * p->coeffsB[filter][4];
00576 
00577     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
00578     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
00579 
00580     sign = APESIGN(decoded);
00581     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
00582     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
00583     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
00584     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
00585     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
00586     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
00587     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
00588     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
00589     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
00590 
00591     return p->filterA[filter];
00592 }
00593 
00594 static void predictor_decode_stereo(APEContext *ctx, int count)
00595 {
00596     APEPredictor *p = &ctx->predictor;
00597     int32_t *decoded0 = ctx->decoded[0];
00598     int32_t *decoded1 = ctx->decoded[1];
00599 
00600     while (count--) {
00601         
00602         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
00603                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
00604         decoded0++;
00605         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
00606                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
00607         decoded1++;
00608 
00609         
00610         p->buf++;
00611 
00612         
00613         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00614             memmove(p->historybuffer, p->buf,
00615                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
00616             p->buf = p->historybuffer;
00617         }
00618     }
00619 }
00620 
00621 static void predictor_decode_mono(APEContext *ctx, int count)
00622 {
00623     APEPredictor *p = &ctx->predictor;
00624     int32_t *decoded0 = ctx->decoded[0];
00625     int32_t predictionA, currentA, A, sign;
00626 
00627     currentA = p->lastA[0];
00628 
00629     while (count--) {
00630         A = *decoded0;
00631 
00632         p->buf[YDELAYA] = currentA;
00633         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
00634 
00635         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
00636                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
00637                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
00638                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
00639 
00640         currentA = A + (predictionA >> 10);
00641 
00642         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
00643         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
00644 
00645         sign = APESIGN(A);
00646         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
00647         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
00648         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
00649         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
00650 
00651         p->buf++;
00652 
00653         
00654         if (p->buf == p->historybuffer + HISTORY_SIZE) {
00655             memmove(p->historybuffer, p->buf,
00656                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
00657             p->buf = p->historybuffer;
00658         }
00659 
00660         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
00661         *(decoded0++) = p->filterA[0];
00662     }
00663 
00664     p->lastA[0] = currentA;
00665 }
00666 
00667 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
00668 {
00669     f->coeffs = buf;
00670     f->historybuffer = buf + order;
00671     f->delay       = f->historybuffer + order * 2;
00672     f->adaptcoeffs = f->historybuffer + order;
00673 
00674     memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
00675     memset(f->coeffs, 0, order * sizeof(*f->coeffs));
00676     f->avg = 0;
00677 }
00678 
00679 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
00680 {
00681     do_init_filter(&f[0], buf, order);
00682     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
00683 }
00684 
00685 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
00686                             int32_t *data, int count, int order, int fracbits)
00687 {
00688     int res;
00689     int absres;
00690 
00691     while (count--) {
00692         
00693         res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
00694                                                     f->adaptcoeffs - order,
00695                                                     order, APESIGN(*data));
00696         res = (res + (1 << (fracbits - 1))) >> fracbits;
00697         res += *data;
00698         *data++ = res;
00699 
00700         
00701         *f->delay++ = av_clip_int16(res);
00702 
00703         if (version < 3980) {
00704             
00705             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
00706             f->adaptcoeffs[-4] >>= 1;
00707             f->adaptcoeffs[-8] >>= 1;
00708         } else {
00709             
00710 
00711             
00712             absres = FFABS(res);
00713             if (absres)
00714                 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
00715                                   (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
00716             else
00717                 *f->adaptcoeffs = 0;
00718 
00719             f->avg += (absres - f->avg) / 16;
00720 
00721             f->adaptcoeffs[-1] >>= 1;
00722             f->adaptcoeffs[-2] >>= 1;
00723             f->adaptcoeffs[-8] >>= 1;
00724         }
00725 
00726         f->adaptcoeffs++;
00727 
00728         
00729         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
00730             memmove(f->historybuffer, f->delay - (order * 2),
00731                     (order * 2) * sizeof(*f->historybuffer));
00732             f->delay = f->historybuffer + order * 2;
00733             f->adaptcoeffs = f->historybuffer + order;
00734         }
00735     }
00736 }
00737 
00738 static void apply_filter(APEContext *ctx, APEFilter *f,
00739                          int32_t *data0, int32_t *data1,
00740                          int count, int order, int fracbits)
00741 {
00742     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
00743     if (data1)
00744         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
00745 }
00746 
00747 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
00748                               int32_t *decoded1, int count)
00749 {
00750     int i;
00751 
00752     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00753         if (!ape_filter_orders[ctx->fset][i])
00754             break;
00755         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
00756                      ape_filter_orders[ctx->fset][i],
00757                      ape_filter_fracbits[ctx->fset][i]);
00758     }
00759 }
00760 
00761 static int init_frame_decoder(APEContext *ctx)
00762 {
00763     int i, ret;
00764     if ((ret = init_entropy_decoder(ctx)) < 0)
00765         return ret;
00766     init_predictor_decoder(ctx);
00767 
00768     for (i = 0; i < APE_FILTER_LEVELS; i++) {
00769         if (!ape_filter_orders[ctx->fset][i])
00770             break;
00771         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
00772                     ape_filter_orders[ctx->fset][i]);
00773     }
00774     return 0;
00775 }
00776 
00777 static void ape_unpack_mono(APEContext *ctx, int count)
00778 {
00779     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00780         
00781         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
00782         return;
00783     }
00784 
00785     entropy_decode(ctx, count, 0);
00786     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
00787 
00788     
00789     predictor_decode_mono(ctx, count);
00790 
00791     
00792     if (ctx->channels == 2) {
00793         memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
00794     }
00795 }
00796 
00797 static void ape_unpack_stereo(APEContext *ctx, int count)
00798 {
00799     int32_t left, right;
00800     int32_t *decoded0 = ctx->decoded[0];
00801     int32_t *decoded1 = ctx->decoded[1];
00802 
00803     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
00804         
00805         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
00806         return;
00807     }
00808 
00809     entropy_decode(ctx, count, 1);
00810     ape_apply_filters(ctx, decoded0, decoded1, count);
00811 
00812     
00813     predictor_decode_stereo(ctx, count);
00814 
00815     
00816     while (count--) {
00817         left = *decoded1 - (*decoded0 / 2);
00818         right = left + *decoded0;
00819 
00820         *(decoded0++) = left;
00821         *(decoded1++) = right;
00822     }
00823 }
00824 
00825 static int ape_decode_frame(AVCodecContext *avctx, void *data,
00826                             int *got_frame_ptr, AVPacket *avpkt)
00827 {
00828     const uint8_t *buf = avpkt->data;
00829     APEContext *s = avctx->priv_data;
00830     uint8_t *sample8;
00831     int16_t *sample16;
00832     int32_t *sample24;
00833     int i, ret;
00834     int blockstodecode;
00835     int bytes_used = 0;
00836 
00837     
00838 
00839     av_assert0(s->samples >= 0);
00840 
00841     if(!s->samples){
00842         uint32_t nblocks, offset;
00843         int buf_size;
00844 
00845         if (!avpkt->size) {
00846             *got_frame_ptr = 0;
00847             return 0;
00848         }
00849         if (avpkt->size < 8) {
00850             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
00851             return AVERROR_INVALIDDATA;
00852         }
00853         buf_size = avpkt->size & ~3;
00854         if (buf_size != avpkt->size) {
00855             av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
00856                    "extra bytes at the end will be skipped.\n");
00857         }
00858 
00859         av_fast_malloc(&s->data, &s->data_size, buf_size);
00860         if (!s->data)
00861             return AVERROR(ENOMEM);
00862         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
00863         s->ptr = s->data;
00864         s->data_end = s->data + buf_size;
00865 
00866         nblocks = bytestream_get_be32(&s->ptr);
00867         offset  = bytestream_get_be32(&s->ptr);
00868         if (offset > 3) {
00869             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
00870             s->data = NULL;
00871             return AVERROR_INVALIDDATA;
00872         }
00873         if (s->data_end - s->ptr < offset) {
00874             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
00875             return AVERROR_INVALIDDATA;
00876         }
00877         s->ptr += offset;
00878 
00879         if (!nblocks || nblocks > INT_MAX) {
00880             av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
00881             return AVERROR_INVALIDDATA;
00882         }
00883         s->samples = nblocks;
00884 
00885         
00886         if (init_frame_decoder(s) < 0) {
00887             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
00888             return AVERROR_INVALIDDATA;
00889         }
00890 
00891         bytes_used = avpkt->size;
00892     }
00893 
00894     if (!s->data) {
00895         *got_frame_ptr = 0;
00896         return avpkt->size;
00897     }
00898 
00899     blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
00900 
00901     
00902     av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
00903                    2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
00904     if (!s->decoded_buffer)
00905         return AVERROR(ENOMEM);
00906     memset(s->decoded_buffer, 0, s->decoded_size);
00907     s->decoded[0] = s->decoded_buffer;
00908     s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
00909 
00910     
00911     s->frame.nb_samples = blockstodecode;
00912     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
00913         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00914         return ret;
00915     }
00916 
00917     s->error=0;
00918 
00919     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
00920         ape_unpack_mono(s, blockstodecode);
00921     else
00922         ape_unpack_stereo(s, blockstodecode);
00923     emms_c();
00924 
00925     if (s->error) {
00926         s->samples=0;
00927         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
00928         return AVERROR_INVALIDDATA;
00929     }
00930 
00931     switch (s->bps) {
00932     case 8:
00933         sample8 = (uint8_t *)s->frame.data[0];
00934         for (i = 0; i < blockstodecode; i++) {
00935             *sample8++ = (s->decoded[0][i] + 0x80) & 0xff;
00936             if (s->channels == 2)
00937                 *sample8++ = (s->decoded[1][i] + 0x80) & 0xff;
00938         }
00939         break;
00940     case 16:
00941         sample16 = (int16_t *)s->frame.data[0];
00942         for (i = 0; i < blockstodecode; i++) {
00943             *sample16++ = s->decoded[0][i];
00944             if (s->channels == 2)
00945                 *sample16++ = s->decoded[1][i];
00946         }
00947         break;
00948     case 24:
00949         sample24 = (int32_t *)s->frame.data[0];
00950         for (i = 0; i < blockstodecode; i++) {
00951             *sample24++ = s->decoded[0][i] << 8;
00952             if (s->channels == 2)
00953                 *sample24++ = s->decoded[1][i] << 8;
00954         }
00955         break;
00956     }
00957 
00958     s->samples -= blockstodecode;
00959 
00960     *got_frame_ptr   = 1;
00961     *(AVFrame *)data = s->frame;
00962 
00963     return bytes_used;
00964 }
00965 
00966 static void ape_flush(AVCodecContext *avctx)
00967 {
00968     APEContext *s = avctx->priv_data;
00969     s->samples= 0;
00970 }
00971 
00972 #define OFFSET(x) offsetof(APEContext, x)
00973 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
00974 static const AVOption options[] = {
00975     { "max_samples", "maximum number of samples decoded per call",             OFFSET(blocks_per_loop), AV_OPT_TYPE_INT,   { .i64 = 4608 },    1,       INT_MAX, PAR, "max_samples" },
00976     { "all",         "no maximum. decode all samples for each packet at once", 0,                       AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
00977     { NULL},
00978 };
00979 
00980 static const AVClass ape_decoder_class = {
00981     .class_name = "APE decoder",
00982     .item_name  = av_default_item_name,
00983     .option     = options,
00984     .version    = LIBAVUTIL_VERSION_INT,
00985 };
00986 
00987 AVCodec ff_ape_decoder = {
00988     .name           = "ape",
00989     .type           = AVMEDIA_TYPE_AUDIO,
00990     .id             = AV_CODEC_ID_APE,
00991     .priv_data_size = sizeof(APEContext),
00992     .init           = ape_decode_init,
00993     .close          = ape_decode_close,
00994     .decode         = ape_decode_frame,
00995     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
00996     .flush          = ape_flush,
00997     .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
00998     .priv_class     = &ape_decoder_class,
00999 };