• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

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

Generated on Fri Sep 16 2011 17:17:33 for FFmpeg by  doxygen 1.7.1