Blame libmp3lame/reservoir.c

Packit 47f805
/*
Packit 47f805
 *      bit reservoir source file
Packit 47f805
 *
Packit 47f805
 *      Copyright (c) 1999-2000 Mark Taylor
Packit 47f805
 *
Packit 47f805
 * This library is free software; you can redistribute it and/or
Packit 47f805
 * modify it under the terms of the GNU Library General Public
Packit 47f805
 * License as published by the Free Software Foundation; either
Packit 47f805
 * version 2 of the License, or (at your option) any later version.
Packit 47f805
 *
Packit 47f805
 * This library is distributed in the hope that it will be useful,
Packit 47f805
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 47f805
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit 47f805
 * Library General Public License for more details.
Packit 47f805
 *
Packit 47f805
 * You should have received a copy of the GNU Library General Public
Packit 47f805
 * License along with this library; if not, write to the
Packit 47f805
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Packit 47f805
 * Boston, MA 02111-1307, USA.
Packit 47f805
 */
Packit 47f805
Packit 47f805
/* $Id: reservoir.c,v 1.45 2011/05/07 16:05:17 rbrito Exp $ */
Packit 47f805
Packit 47f805
#ifdef HAVE_CONFIG_H
Packit 47f805
# include <config.h>
Packit 47f805
#endif
Packit 47f805
Packit 47f805
Packit 47f805
#include "lame.h"
Packit 47f805
#include "machine.h"
Packit 47f805
#include "encoder.h"
Packit 47f805
#include "util.h"
Packit 47f805
#include "reservoir.h"
Packit 47f805
Packit 47f805
#include "bitstream.h"
Packit 47f805
#include "lame-analysis.h"
Packit 47f805
#include "lame_global_flags.h"
Packit 47f805
Packit 47f805
Packit 47f805
/*
Packit 47f805
  ResvFrameBegin:
Packit 47f805
  Called (repeatedly) at the beginning of a frame. Updates the maximum
Packit 47f805
  size of the reservoir, and checks to make sure main_data_begin
Packit 47f805
  was set properly by the formatter
Packit 47f805
*/
Packit 47f805
Packit 47f805
/*
Packit 47f805
 *  Background information:
Packit 47f805
 *
Packit 47f805
 *  This is the original text from the ISO standard. Because of
Packit 47f805
 *  sooo many bugs and irritations correcting comments are added
Packit 47f805
 *  in brackets []. A '^W' means you should remove the last word.
Packit 47f805
 *
Packit 47f805
 *  1) The following rule can be used to calculate the maximum
Packit 47f805
 *     number of bits used for one granule [^W frame]:
Packit 47f805
 *     At the highest possible bitrate of Layer III (320 kbps
Packit 47f805
 *     per stereo signal [^W^W^W], 48 kHz) the frames must be of
Packit 47f805
 *     [^W^W^W are designed to have] constant length, i.e.
Packit 47f805
 *     one buffer [^W^W the frame] length is:
Packit 47f805
 *
Packit 47f805
 *         320 kbps * 1152/48 kHz = 7680 bit = 960 byte
Packit 47f805
 *
Packit 47f805
 *     This value is used as the maximum buffer per channel [^W^W] at
Packit 47f805
 *     lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps
Packit 47f805
 *     stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit
Packit 47f805
 *     [per granule and channel] at 48 kHz sampling frequency.
Packit 47f805
 *     This means that there is a maximum deviation (short time buffer
Packit 47f805
 *     [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps.
Packit 47f805
 *     The actual deviation is equal to the number of bytes [with the
Packit 47f805
 *     meaning of octets] denoted by the main_data_end offset pointer.
Packit 47f805
 *     The actual maximum deviation is (2^9-1)*8 bit = 4088 bits
Packit 47f805
 *     [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].
Packit 47f805
 *     ... The xchange of buffer bits between the left and right channel
Packit 47f805
 *     is allowed without restrictions [exception: dual channel].
Packit 47f805
 *     Because of the [constructed] constraint on the buffer size
Packit 47f805
 *     main_data_end is always set to 0 in the case of bit_rate_index==14,
Packit 47f805
 *     i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case
Packit 47f805
 *     all data are allocated between adjacent header [^W sync] words
Packit 47f805
 *     [, i.e. there is no buffering at all].
Packit 47f805
 */
Packit 47f805
Packit 47f805
int
Packit 47f805
ResvFrameBegin(lame_internal_flags * gfc, int *mean_bits)
Packit 47f805
{
Packit 47f805
    SessionConfig_t const *const cfg = &gfc->cfg;
Packit 47f805
    EncStateVar_t *const esv = &gfc->sv_enc;
Packit 47f805
    int     fullFrameBits;
Packit 47f805
    int     resvLimit;
Packit 47f805
    int     maxmp3buf;
Packit 47f805
    III_side_info_t *const l3_side = &gfc->l3_side;
Packit 47f805
    int     frameLength;
Packit 47f805
    int     meanBits;
Packit 47f805
Packit 47f805
    frameLength = getframebits(gfc);
Packit 47f805
    meanBits = (frameLength - cfg->sideinfo_len * 8) / cfg->mode_gr;
Packit 47f805
Packit 47f805
/*
Packit 47f805
 *  Meaning of the variables:
Packit 47f805
 *      resvLimit: (0, 8, ..., 8*255 (MPEG-2), 8*511 (MPEG-1))
Packit 47f805
 *          Number of bits can be stored in previous frame(s) due to
Packit 47f805
 *          counter size constaints
Packit 47f805
 *      maxmp3buf: ( ??? ... 8*1951 (MPEG-1 and 2), 8*2047 (MPEG-2.5))
Packit 47f805
 *          Number of bits allowed to encode one frame (you can take 8*511 bit
Packit 47f805
 *          from the bit reservoir and at most 8*1440 bit from the current
Packit 47f805
 *          frame (320 kbps, 32 kHz), so 8*1951 bit is the largest possible
Packit 47f805
 *          value for MPEG-1 and -2)
Packit 47f805
 *
Packit 47f805
 *          maximum allowed granule/channel size times 4 = 8*2047 bits.,
Packit 47f805
 *          so this is the absolute maximum supported by the format.
Packit 47f805
 *
Packit 47f805
 *
Packit 47f805
 *      fullFrameBits:  maximum number of bits available for encoding
Packit 47f805
 *                      the current frame.
Packit 47f805
 *
Packit 47f805
 *      mean_bits:      target number of bits per granule.
Packit 47f805
 *
Packit 47f805
 *      frameLength:
Packit 47f805
 *
Packit 47f805
 *      gfc->ResvMax:   maximum allowed reservoir
Packit 47f805
 *
Packit 47f805
 *      gfc->ResvSize:  current reservoir size
Packit 47f805
 *
Packit 47f805
 *      l3_side->resvDrain_pre:
Packit 47f805
 *         ancillary data to be added to previous frame:
Packit 47f805
 *         (only usefull in VBR modes if it is possible to have
Packit 47f805
 *         maxmp3buf < fullFrameBits)).  Currently disabled,
Packit 47f805
 *         see #define NEW_DRAIN
Packit 47f805
 *         2010-02-13: RH now enabled, it seems to be needed for CBR too,
Packit 47f805
 *                     as there exists one example, where the FhG decoder
Packit 47f805
 *                     can't decode a -b320 CBR file anymore.
Packit 47f805
 *
Packit 47f805
 *      l3_side->resvDrain_post:
Packit 47f805
 *         ancillary data to be added to this frame:
Packit 47f805
 *
Packit 47f805
 */
Packit 47f805
Packit 47f805
    /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */
Packit 47f805
    resvLimit = (8 * 256) * cfg->mode_gr - 8;
Packit 47f805
Packit 47f805
    /* maximum allowed frame size.  dont use more than this number of
Packit 47f805
       bits, even if the frame has the space for them: */
Packit 47f805
    maxmp3buf = cfg->buffer_constraint;
Packit 47f805
    esv->ResvMax = maxmp3buf - frameLength;
Packit 47f805
    if (esv->ResvMax > resvLimit)
Packit 47f805
        esv->ResvMax = resvLimit;
Packit 47f805
    if (esv->ResvMax < 0 || cfg->disable_reservoir)
Packit 47f805
        esv->ResvMax = 0;
Packit 47f805
    
Packit 47f805
    fullFrameBits = meanBits * cfg->mode_gr + Min(esv->ResvSize, esv->ResvMax);
Packit 47f805
Packit 47f805
    if (fullFrameBits > maxmp3buf)
Packit 47f805
        fullFrameBits = maxmp3buf;
Packit 47f805
Packit 47f805
    assert(0 == esv->ResvMax % 8);
Packit 47f805
    assert(esv->ResvMax >= 0);
Packit 47f805
Packit 47f805
    l3_side->resvDrain_pre = 0;
Packit 47f805
Packit 47f805
    if (gfc->pinfo != NULL) {
Packit 47f805
        gfc->pinfo->mean_bits = meanBits / 2; /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */
Packit 47f805
        gfc->pinfo->resvsize = esv->ResvSize;
Packit 47f805
    }
Packit 47f805
    *mean_bits = meanBits;
Packit 47f805
    return fullFrameBits;
Packit 47f805
}
Packit 47f805
Packit 47f805
Packit 47f805
/*
Packit 47f805
  ResvMaxBits
Packit 47f805
  returns targ_bits:  target number of bits to use for 1 granule
Packit 47f805
         extra_bits:  amount extra available from reservoir
Packit 47f805
  Mark Taylor 4/99
Packit 47f805
*/
Packit 47f805
void
Packit 47f805
ResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *extra_bits, int cbr)
Packit 47f805
{
Packit 47f805
    SessionConfig_t const *const cfg = &gfc->cfg;
Packit 47f805
    EncStateVar_t *const esv = &gfc->sv_enc;
Packit 47f805
    int     add_bits, targBits, extraBits;
Packit 47f805
    int     ResvSize = esv->ResvSize, ResvMax = esv->ResvMax;
Packit 47f805
Packit 47f805
    /* conpensate the saved bits used in the 1st granule */
Packit 47f805
    if (cbr)
Packit 47f805
        ResvSize += mean_bits;
Packit 47f805
Packit 47f805
    if (gfc->sv_qnt.substep_shaping & 1)
Packit 47f805
        ResvMax *= 0.9;
Packit 47f805
Packit 47f805
    targBits = mean_bits;
Packit 47f805
Packit 47f805
    /* extra bits if the reservoir is almost full */
Packit 47f805
    if (ResvSize * 10 > ResvMax * 9) {
Packit 47f805
        add_bits = ResvSize - (ResvMax * 9) / 10;
Packit 47f805
        targBits += add_bits;
Packit 47f805
        gfc->sv_qnt.substep_shaping |= 0x80;
Packit 47f805
    }
Packit 47f805
    else {
Packit 47f805
        add_bits = 0;
Packit 47f805
        gfc->sv_qnt.substep_shaping &= 0x7f;
Packit 47f805
        /* build up reservoir.  this builds the reservoir a little slower
Packit 47f805
         * than FhG.  It could simple be mean_bits/15, but this was rigged
Packit 47f805
         * to always produce 100 (the old value) at 128kbs */
Packit 47f805
        /*    *targ_bits -= (int) (mean_bits/15.2); */
Packit 47f805
        if (!cfg->disable_reservoir && !(gfc->sv_qnt.substep_shaping & 1))
Packit 47f805
            targBits -= .1 * mean_bits;
Packit 47f805
    }
Packit 47f805
Packit 47f805
Packit 47f805
    /* amount from the reservoir we are allowed to use. ISO says 6/10 */
Packit 47f805
    extraBits = (ResvSize < (esv->ResvMax * 6) / 10 ? ResvSize : (esv->ResvMax * 6) / 10);
Packit 47f805
    extraBits -= add_bits;
Packit 47f805
Packit 47f805
    if (extraBits < 0)
Packit 47f805
        extraBits = 0;
Packit 47f805
Packit 47f805
    *targ_bits = targBits;
Packit 47f805
    *extra_bits = extraBits;
Packit 47f805
}
Packit 47f805
Packit 47f805
/*
Packit 47f805
  ResvAdjust:
Packit 47f805
  Called after a granule's bit allocation. Readjusts the size of
Packit 47f805
  the reservoir to reflect the granule's usage.
Packit 47f805
*/
Packit 47f805
void
Packit 47f805
ResvAdjust(lame_internal_flags * gfc, gr_info const *gi)
Packit 47f805
{
Packit 47f805
    gfc->sv_enc.ResvSize -= gi->part2_3_length + gi->part2_length;
Packit 47f805
}
Packit 47f805
Packit 47f805
Packit 47f805
/*
Packit 47f805
  ResvFrameEnd:
Packit 47f805
  Called after all granules in a frame have been allocated. Makes sure
Packit 47f805
  that the reservoir size is within limits, possibly by adding stuffing
Packit 47f805
  bits.
Packit 47f805
*/
Packit 47f805
void
Packit 47f805
ResvFrameEnd(lame_internal_flags * gfc, int mean_bits)
Packit 47f805
{
Packit 47f805
    SessionConfig_t const *const cfg = &gfc->cfg;
Packit 47f805
    EncStateVar_t *const esv = &gfc->sv_enc;
Packit 47f805
    III_side_info_t *const l3_side = &gfc->l3_side;
Packit 47f805
    int     stuffingBits;
Packit 47f805
    int     over_bits;
Packit 47f805
Packit 47f805
    esv->ResvSize += mean_bits * cfg->mode_gr;
Packit 47f805
    stuffingBits = 0;
Packit 47f805
    l3_side->resvDrain_post = 0;
Packit 47f805
    l3_side->resvDrain_pre = 0;
Packit 47f805
Packit 47f805
    /* we must be byte aligned */
Packit 47f805
    if ((over_bits = esv->ResvSize % 8) != 0)
Packit 47f805
        stuffingBits += over_bits;
Packit 47f805
Packit 47f805
Packit 47f805
    over_bits = (esv->ResvSize - stuffingBits) - esv->ResvMax;
Packit 47f805
    if (over_bits > 0) {
Packit 47f805
        assert(0 == over_bits % 8);
Packit 47f805
        assert(over_bits >= 0);
Packit 47f805
        stuffingBits += over_bits;
Packit 47f805
    }
Packit 47f805
Packit 47f805
Packit 47f805
    /* NOTE: enabling the NEW_DRAIN code fixes some problems with FhG decoder
Packit 47f805
             shipped with MS Windows operating systems. Using this, it is even
Packit 47f805
             possible to use Gabriel's lax buffer consideration again, which
Packit 47f805
             assumes, any decoder should have a buffer large enough
Packit 47f805
             for a 320 kbps frame at 32 kHz sample rate.
Packit 47f805
Packit 47f805
       old drain code:
Packit 47f805
             lame -b320 BlackBird.wav ---> does not play with GraphEdit.exe using FhG decoder V1.5 Build 50
Packit 47f805
Packit 47f805
       new drain code:
Packit 47f805
             lame -b320 BlackBird.wav ---> plays fine with GraphEdit.exe using FhG decoder V1.5 Build 50
Packit 47f805
Packit 47f805
             Robert Hegemann, 2010-02-13.
Packit 47f805
     */
Packit 47f805
    /* drain as many bits as possible into previous frame ancillary data
Packit 47f805
     * In particular, in VBR mode ResvMax may have changed, and we have
Packit 47f805
     * to make sure main_data_begin does not create a reservoir bigger
Packit 47f805
     * than ResvMax  mt 4/00*/
Packit 47f805
    {
Packit 47f805
        int     mdb_bytes = Min(l3_side->main_data_begin * 8, stuffingBits) / 8;
Packit 47f805
        l3_side->resvDrain_pre += 8 * mdb_bytes;
Packit 47f805
        stuffingBits -= 8 * mdb_bytes;
Packit 47f805
        esv->ResvSize -= 8 * mdb_bytes;
Packit 47f805
        l3_side->main_data_begin -= mdb_bytes;
Packit 47f805
    }
Packit 47f805
    /* drain the rest into this frames ancillary data */
Packit 47f805
    l3_side->resvDrain_post += stuffingBits;
Packit 47f805
    esv->ResvSize -= stuffingBits;
Packit 47f805
}