1594 lines · 50.6 KB · C
RawDownload
/* * Monkey's Audio lossless audio decoder * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org> *  based upon libdemac from Dave Chapman. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/avassert.h"#include "libavutil/channel_layout.h"#include "libavutil/opt.h"#include "lossless_audiodsp.h"#include "avcodec.h"#include "bswapdsp.h"#include "bytestream.h"#include "internal.h"#include "get_bits.h"#include "unary.h" /** * @file * Monkey's Audio lossless audio decoder */ #define MAX_CHANNELS        2#define MAX_BYTESPERSAMPLE  3 #define APE_FRAMECODE_MONO_SILENCE    1#define APE_FRAMECODE_STEREO_SILENCE  3#define APE_FRAMECODE_PSEUDO_STEREO   4 #define HISTORY_SIZE 512#define PREDICTOR_ORDER 8/** Total size of all predictor histories */#define PREDICTOR_SIZE 50 #define YDELAYA (18 + PREDICTOR_ORDER*4)#define YDELAYB (18 + PREDICTOR_ORDER*3)#define XDELAYA (18 + PREDICTOR_ORDER*2)#define XDELAYB (18 + PREDICTOR_ORDER) #define YADAPTCOEFFSA 18#define XADAPTCOEFFSA 14#define YADAPTCOEFFSB 10#define XADAPTCOEFFSB 5 /** * Possible compression levels * @{ */enum APECompressionLevel {    COMPRESSION_LEVEL_FAST       = 1000,    COMPRESSION_LEVEL_NORMAL     = 2000,    COMPRESSION_LEVEL_HIGH       = 3000,    COMPRESSION_LEVEL_EXTRA_HIGH = 4000,    COMPRESSION_LEVEL_INSANE     = 5000};/** @} */ #define APE_FILTER_LEVELS 3 /** Filter orders depending on compression level */static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {    {  0,   0,    0 },    { 16,   0,    0 },    { 64,   0,    0 },    { 32, 256,    0 },    { 16, 256, 1280 }}; /** Filter fraction bits depending on compression level */static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {    {  0,  0,  0 },    { 11,  0,  0 },    { 11,  0,  0 },    { 10, 13,  0 },    { 11, 13, 15 }};  /** Filters applied to the decoded data */typedef struct APEFilter {    int16_t *coeffs;        ///< actual coefficients used in filtering    int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients    int16_t *historybuffer; ///< filter memory    int16_t *delay;         ///< filtered values     int avg;} APEFilter; typedef struct APERice {    uint32_t k;    uint32_t ksum;} APERice; typedef struct APERangecoder {    uint32_t low;           ///< low end of interval    uint32_t range;         ///< length of interval    uint32_t help;          ///< bytes_to_follow resp. intermediate value    unsigned int buffer;    ///< buffer for input/output} APERangecoder; /** Filter histories */typedef struct APEPredictor {    int32_t *buf;     int32_t lastA[2];     int32_t filterA[2];    int32_t filterB[2];     int32_t coeffsA[2][4];  ///< adaption coefficients    int32_t coeffsB[2][5];  ///< adaption coefficients    int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];     unsigned int sample_pos;} APEPredictor; /** Decoder context */typedef struct APEContext {    AVClass *class;                          ///< class for AVOptions    AVCodecContext *avctx;    BswapDSPContext bdsp;    LLAudDSPContext adsp;    int channels;    int samples;                             ///< samples left to decode in current frame    int bps;     int fileversion;                         ///< codec version, very important in decoding process    int compression_level;                   ///< compression levels    int fset;                                ///< which filter set to use (calculated from compression level)    int flags;                               ///< global decoder flags     uint32_t CRC;                            ///< frame CRC    int frameflags;                          ///< frame flags    APEPredictor predictor;                  ///< predictor used for final reconstruction     int32_t *decoded_buffer;    int decoded_size;    int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel    int blocks_per_loop;                     ///< maximum number of samples to decode for each call     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory     APERangecoder rc;                        ///< rangecoder used to decode actual values    APERice riceX;                           ///< rice code parameters for the second channel    APERice riceY;                           ///< rice code parameters for the first channel    APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction    GetBitContext gb;     uint8_t *data;                           ///< current frame data    uint8_t *data_end;                       ///< frame data end    int data_size;                           ///< frame data allocated size    const uint8_t *ptr;                      ///< current position in frame data     int error;     void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);    void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);    void (*predictor_decode_mono)(struct APEContext *ctx, int count);    void (*predictor_decode_stereo)(struct APEContext *ctx, int count);} APEContext; static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,                              int32_t *decoded1, int count); static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode); static void predictor_decode_mono_3800(APEContext *ctx, int count);static void predictor_decode_stereo_3800(APEContext *ctx, int count);static void predictor_decode_mono_3930(APEContext *ctx, int count);static void predictor_decode_stereo_3930(APEContext *ctx, int count);static void predictor_decode_mono_3950(APEContext *ctx, int count);static void predictor_decode_stereo_3950(APEContext *ctx, int count); static av_cold int ape_decode_close(AVCodecContext *avctx){    APEContext *s = avctx->priv_data;    int i;     for (i = 0; i < APE_FILTER_LEVELS; i++)        av_freep(&s->filterbuf[i]);     av_freep(&s->decoded_buffer);    av_freep(&s->data);    s->decoded_size = s->data_size = 0;     return 0;} static av_cold int ape_decode_init(AVCodecContext *avctx){    APEContext *s = avctx->priv_data;    int i;     if (avctx->extradata_size != 6) {        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");        return AVERROR(EINVAL);    }    if (avctx->channels > 2) {        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");        return AVERROR(EINVAL);    }    s->bps = avctx->bits_per_coded_sample;    switch (s->bps) {    case 8:        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;        break;    case 16:        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;        break;    case 24:        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;        break;    default:        avpriv_request_sample(avctx,                              "%d bits per coded sample", s->bps);        return AVERROR_PATCHWELCOME;    }    s->avctx             = avctx;    s->channels          = avctx->channels;    s->fileversion       = AV_RL16(avctx->extradata);    s->compression_level = AV_RL16(avctx->extradata + 2);    s->flags             = AV_RL16(avctx->extradata + 4);     av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",           s->compression_level, s->flags);    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||        !s->compression_level ||        (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",               s->compression_level);        return AVERROR_INVALIDDATA;    }    s->fset = s->compression_level / 1000 - 1;    for (i = 0; i < APE_FILTER_LEVELS; i++) {        if (!ape_filter_orders[s->fset][i])            break;        FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],                         (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,                         filter_alloc_fail);    }     if (s->fileversion < 3860) {        s->entropy_decode_mono   = entropy_decode_mono_0000;        s->entropy_decode_stereo = entropy_decode_stereo_0000;    } else if (s->fileversion < 3900) {        s->entropy_decode_mono   = entropy_decode_mono_3860;        s->entropy_decode_stereo = entropy_decode_stereo_3860;    } else if (s->fileversion < 3930) {        s->entropy_decode_mono   = entropy_decode_mono_3900;        s->entropy_decode_stereo = entropy_decode_stereo_3900;    } else if (s->fileversion < 3990) {        s->entropy_decode_mono   = entropy_decode_mono_3900;        s->entropy_decode_stereo = entropy_decode_stereo_3930;    } else {        s->entropy_decode_mono   = entropy_decode_mono_3990;        s->entropy_decode_stereo = entropy_decode_stereo_3990;    }     if (s->fileversion < 3930) {        s->predictor_decode_mono   = predictor_decode_mono_3800;        s->predictor_decode_stereo = predictor_decode_stereo_3800;    } else if (s->fileversion < 3950) {        s->predictor_decode_mono   = predictor_decode_mono_3930;        s->predictor_decode_stereo = predictor_decode_stereo_3930;    } else {        s->predictor_decode_mono   = predictor_decode_mono_3950;        s->predictor_decode_stereo = predictor_decode_stereo_3950;    }     ff_bswapdsp_init(&s->bdsp);    ff_llauddsp_init(&s->adsp);    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;     return 0;filter_alloc_fail:    ape_decode_close(avctx);    return AVERROR(ENOMEM);} /** * @name APE range decoding functions * @{ */ #define CODE_BITS    32#define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))#define SHIFT_BITS   (CODE_BITS - 9)#define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)#define BOTTOM_VALUE (TOP_VALUE >> 8) /** Start the decoder */static inline void range_start_decoding(APEContext *ctx){    ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);    ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);    ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;} /** Perform normalization */static inline void range_dec_normalize(APEContext *ctx){    while (ctx->rc.range <= BOTTOM_VALUE) {        ctx->rc.buffer <<= 8;        if(ctx->ptr < ctx->data_end) {            ctx->rc.buffer += *ctx->ptr;            ctx->ptr++;        } else {            ctx->error = 1;        }        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);        ctx->rc.range  <<= 8;    }} /** * Calculate cumulative frequency for next symbol. Does NO update! * @param ctx decoder context * @param tot_f is the total frequency or (code_value)1<<shift * @return the cumulative frequency */static inline int range_decode_culfreq(APEContext *ctx, int tot_f){    range_dec_normalize(ctx);    ctx->rc.help = ctx->rc.range / tot_f;    return ctx->rc.low / ctx->rc.help;} /** * Decode value with given size in bits * @param ctx decoder context * @param shift number of bits to decode */static inline int range_decode_culshift(APEContext *ctx, int shift){    range_dec_normalize(ctx);    ctx->rc.help = ctx->rc.range >> shift;    return ctx->rc.low / ctx->rc.help;}  /** * Update decoding state * @param ctx decoder context * @param sy_f the interval length (frequency of the symbol) * @param lt_f the lower end (frequency sum of < symbols) */static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f){    ctx->rc.low  -= ctx->rc.help * lt_f;    ctx->rc.range = ctx->rc.help * sy_f;} /** Decode n bits (n <= 16) without modelling */static inline int range_decode_bits(APEContext *ctx, int n){    int sym = range_decode_culshift(ctx, n);    range_decode_update(ctx, 1, sym);    return sym;}  #define MODEL_ELEMENTS 64 /** * Fixed probabilities for symbols in Monkey Audio version 3.97 */static const uint16_t counts_3970[22] = {        0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,    62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,    65450, 65469, 65480, 65487, 65491, 65493,}; /** * Probability ranges for symbols in Monkey Audio version 3.97 */static const uint16_t counts_diff_3970[21] = {    14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,    1104, 677, 415, 248, 150, 89, 54, 31,    19, 11, 7, 4, 2,}; /** * Fixed probabilities for symbols in Monkey Audio version 3.98 */static const uint16_t counts_3980[22] = {        0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,    64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,    65485, 65488, 65490, 65491, 65492, 65493,}; /** * Probability ranges for symbols in Monkey Audio version 3.98 */static const uint16_t counts_diff_3980[21] = {    19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,    261, 119, 65, 31, 19, 10, 6, 3,    3, 2, 1, 1, 1,}; /** * Decode symbol * @param ctx decoder context * @param counts probability range start position * @param counts_diff probability range widths */static inline int range_get_symbol(APEContext *ctx,                                   const uint16_t counts[],                                   const uint16_t counts_diff[]){    int symbol, cf;     cf = range_decode_culshift(ctx, 16);     if(cf > 65492){        symbol= cf - 65535 + 63;        range_decode_update(ctx, 1, cf);        if(cf > 65535)            ctx->error=1;        return symbol;    }    /* figure out the symbol inefficiently; a binary search would be much better */    for (symbol = 0; counts[symbol + 1] <= cf; symbol++);     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);     return symbol;}/** @} */ // group rangecoder static inline void update_rice(APERice *rice, unsigned int x){    int lim = rice->k ? (1 << (rice->k + 4)) : 0;    rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);     if (rice->ksum < lim)        rice->k--;    else if (rice->ksum >= (1 << (rice->k + 5)))        rice->k++;} static inline int get_rice_ook(GetBitContext *gb, int k){    unsigned int x;     x = get_unary(gb, 1, get_bits_left(gb));     if (k)        x = (x << k) | get_bits(gb, k);     return x;} static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,                                        APERice *rice){    unsigned int x, overflow;     overflow = get_unary(gb, 1, get_bits_left(gb));     if (ctx->fileversion > 3880) {        while (overflow >= 16) {            overflow -= 16;            rice->k  += 4;        }    }     if (!rice->k)        x = overflow;    else if(rice->k <= MIN_CACHE_BITS) {        x = (overflow << rice->k) + get_bits(gb, rice->k);    } else {        av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);        return AVERROR_INVALIDDATA;    }

Lines 1–500 of 1594.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t