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