fixed graphics bug
[swftools.git] / lib / lame / reservoir.c
1 /*
2  *      bit reservoir source file
3  *
4  *      Copyright (c) 1999 Mark Taylor
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /* $Id: reservoir.c,v 1.1 2002/04/28 17:30:27 kramm Exp $ */
23
24 #include "config_static.h"
25
26 #include <assert.h>
27 #include "util.h"
28 #include "reservoir.h"
29
30 #ifdef WITH_DMALLOC
31 #include <dmalloc.h>
32 #endif
33
34 /*
35   ResvFrameBegin:
36   Called (repeatedly) at the beginning of a frame. Updates the maximum
37   size of the reservoir, and checks to make sure main_data_begin
38   was set properly by the formatter
39 */
40
41 /*
42  *  Background information:
43  *
44  *  This is the original text from the ISO standard. Because of 
45  *  sooo many bugs and irritations correcting comments are added 
46  *  in brackets []. A '^W' means you should remove the last word.
47  *
48  *  1) The following rule can be used to calculate the maximum 
49  *     number of bits used for one granule [^W frame]: 
50  *     At the highest possible bitrate of Layer III (320 kbps 
51  *     per stereo signal [^W^W^W], 48 kHz) the frames must be of
52  *     [^W^W^W are designed to have] constant length, i.e. 
53  *     one buffer [^W^W the frame] length is:
54  *
55  *         320 kbps * 1152/48 kHz = 7680 bit = 960 byte
56  *
57  *     This value is used as the maximum buffer per channel [^W^W] at 
58  *     lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps 
59  *     stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit
60  *     [per granule and channel] at 48 kHz sampling frequency. 
61  *     This means that there is a maximum deviation (short time buffer 
62  *     [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps. 
63  *     The actual deviation is equal to the number of bytes [with the 
64  *     meaning of octets] denoted by the main_data_end offset pointer. 
65  *     The actual maximum deviation is (2^9-1)*8 bit = 4088 bits 
66  *     [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].
67  *     ... The xchange of buffer bits between the left and right channel
68  *     is allowed without restrictions [exception: dual channel].
69  *     Because of the [constructed] constraint on the buffer size
70  *     main_data_end is always set to 0 in the case of bit_rate_index==14, 
71  *     i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case 
72  *     all data are allocated between adjacent header [^W sync] words 
73  *     [, i.e. there is no buffering at all].
74  */
75
76 int
77 ResvFrameBegin(lame_global_flags *gfp,III_side_info_t *l3_side, int mean_bits, int frameLength )
78 {
79     lame_internal_flags *gfc=gfp->internal_flags;
80     int fullFrameBits;
81     int resvLimit;
82     int maxmp3buf;
83
84 /*
85  *  Meaning of the variables:
86  *      resvLimit: (0, 8, ..., 8*255 (MPEG-2), 8*511 (MPEG-1))
87  *          Number of bits can be stored in previous frame(s) due to 
88  *          counter size constaints
89  *      maxmp3buf: ( ??? ... 8*1951 (MPEG-1 and 2), 8*2047 (MPEG-2.5))
90  *          Number of bits allowed to encode one frame (you can take 8*511 bit 
91  *          from the bit reservoir and at most 8*1440 bit from the current 
92  *          frame (320 kbps, 32 kHz), so 8*1951 bit is the largest possible 
93  *          value for MPEG-1 and -2)
94  *       
95  *          maximum allowed granule/channel size times 4 = 8*2047 bits.,
96  *          so this is the absolute maximum supported by the format.
97  *
98  *          
99  *      fullFrameBits:  maximum number of bits available for encoding
100  *                      the current frame.
101  *
102  *      mean_bits:      target number of bits per granule.  
103  *
104  *      frameLength:
105  *
106  *      gfc->ResvMax:   maximum allowed reservoir 
107  *
108  *      gfc->ResvSize:  current reservoir size
109  *
110  *      l3_side->resvDrain_pre:
111  *         ancillary data to be added to previous frame:
112  *         (only usefull in VBR modes if it is possible to have
113  *         maxmp3buf < fullFrameBits)).  Currently disabled, 
114  *         see #define NEW_DRAIN
115  *
116  *      l3_side->resvDrain_post:
117  *         ancillary data to be added to this frame:
118  *
119  */
120
121     /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */
122     resvLimit = (gfp->version==1) ? 8*511 : 8*255 ;
123
124
125     /* maximum allowed frame size.  dont use more than this number of
126        bits, even if the frame has the space for them: */
127     /* Bouvigne suggests this more lax interpretation of the ISO doc 
128        instead of using 8*960. */
129     if (gfp->strict_ISO) {
130         if (gfp->version==1)
131             maxmp3buf=8*((int)(320000/(gfp->out_samplerate / (FLOAT8)1152)/8 +.5));
132         else
133             maxmp3buf=8*((int)(160000/(gfp->out_samplerate / (FLOAT8)576)/8 +.5));
134     } else
135         /*all mp3 decoders should have enough buffer to handle this value: size of a 320kbps 32kHz frame*/
136         maxmp3buf = 8*1440;
137
138
139     if ( frameLength > maxmp3buf ||  gfp->disable_reservoir ) {
140         gfc->ResvMax = 0;
141     } else {
142         gfc->ResvMax = maxmp3buf - frameLength;
143         if ( gfc->ResvMax > resvLimit )
144           gfc->ResvMax = resvLimit;
145     }
146
147     fullFrameBits = mean_bits * gfc->mode_gr + Min ( gfc->ResvSize, gfc->ResvMax );
148     
149     if ( fullFrameBits > maxmp3buf )
150         fullFrameBits = maxmp3buf;
151
152     assert ( 0 == gfc->ResvMax % 8 );
153     assert ( gfc->ResvMax >= 0 );
154
155     l3_side->resvDrain_pre = 0;
156
157     if ( gfc->pinfo != NULL ) {
158         gfc->pinfo->mean_bits = mean_bits / 2;  /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */
159         gfc->pinfo->resvsize  = gfc->ResvSize;
160     }
161
162     return fullFrameBits;
163 }
164
165
166 /*
167   ResvMaxBits
168   returns targ_bits:  target number of bits to use for 1 granule
169          extra_bits:  amount extra available from reservoir
170   Mark Taylor 4/99
171 */
172 void ResvMaxBits(lame_global_flags *gfp, int mean_bits, int *targ_bits, int *extra_bits)
173 {
174   lame_internal_flags *gfc=gfp->internal_flags;
175   int add_bits;
176   int full_fac;
177   
178   *targ_bits = mean_bits ;
179
180   /* extra bits if the reservoir is almost full */
181   full_fac=9;
182   if (gfc->ResvSize > ((gfc->ResvMax * full_fac) / 10)) {
183     add_bits= gfc->ResvSize-((gfc->ResvMax * full_fac) / 10);
184     *targ_bits += add_bits;
185   }else {
186     add_bits =0 ;
187     /* build up reservoir.  this builds the reservoir a little slower
188      * than FhG.  It could simple be mean_bits/15, but this was rigged
189      * to always produce 100 (the old value) at 128kbs */
190     /*    *targ_bits -= (int) (mean_bits/15.2);*/
191     if (!gfp->disable_reservoir) 
192       *targ_bits -= .1*mean_bits;
193   }
194
195
196   /* amount from the reservoir we are allowed to use. ISO says 6/10 */
197   *extra_bits =
198     (gfc->ResvSize  < (gfc->ResvMax*6)/10  ? gfc->ResvSize : (gfc->ResvMax*6)/10);
199   *extra_bits -= add_bits;
200
201   if (*extra_bits < 0) *extra_bits=0;
202
203
204 }
205
206 /*
207   ResvAdjust:
208   Called after a granule's bit allocation. Readjusts the size of
209   the reservoir to reflect the granule's usage.
210 */
211 void
212 ResvAdjust(lame_internal_flags *gfc,gr_info *gi, III_side_info_t *l3_side, int mean_bits )
213 {
214   gfc->ResvSize += (mean_bits / gfc->channels_out) - gi->part2_3_length;
215 #if 0
216   printf("part2_3_length:  %i  avg=%i  incres: %i  resvsize=%i\n",gi->part2_3_length,
217          mean_bits/gfc->channels_out,
218 mean_bits/gfc->channels_out-gi->part2_3_length,gfc->ResvSize);
219 #endif
220 }
221
222
223 /*
224   ResvFrameEnd:
225   Called after all granules in a frame have been allocated. Makes sure
226   that the reservoir size is within limits, possibly by adding stuffing
227   bits.
228 */
229 void
230 ResvFrameEnd(lame_internal_flags *gfc, III_side_info_t *l3_side, int mean_bits)
231 {
232     int stuffingBits;
233     int over_bits;
234
235
236     /* just in case mean_bits is odd, this is necessary... */
237     if ( gfc->channels_out == 2  &&  (mean_bits & 1) )
238         gfc->ResvSize += 1;
239
240     stuffingBits=0;
241     l3_side->resvDrain_post = 0;
242     l3_side->resvDrain_pre = 0;
243
244     /* we must be byte aligned */
245     if ( (over_bits = gfc->ResvSize % 8) != 0 )
246         stuffingBits += over_bits;
247
248
249     over_bits = (gfc->ResvSize - stuffingBits) - gfc->ResvMax;
250     if (over_bits > 0) {
251       assert ( 0 == over_bits % 8 );
252       assert ( over_bits >= 0 );
253       stuffingBits += over_bits;
254     }
255
256
257 #undef NEW_DRAIN
258 #ifdef NEW_DRAIN
259     /* drain as many bits as possible into previous frame ancillary data
260      * In particular, in VBR mode ResvMax may have changed, and we have
261      * to make sure main_data_begin does not create a reservoir bigger
262      * than ResvMax  mt 4/00*/
263   {
264     int mdb_bytes = Min(l3_side->main_data_begin*8,stuffingBits)/8;
265     l3_side->resvDrain_pre += 8*mdb_bytes;
266     stuffingBits -= 8*mdb_bytes;
267     gfc->ResvSize -= 8*mdb_bytes;
268     l3_side->main_data_begin -= mdb_bytes;
269
270
271     /* drain just enough to be byte aligned.  The remaining bits will
272      * be added to the reservoir, and we will deal with them next frame.
273      * If the next frame is at a lower bitrate, it may have a larger ResvMax,
274      * and we will not have to waste these bits!  mt 4/00 */
275     assert ( stuffingBits >= 0 );
276     l3_side->resvDrain_post += (stuffingBits % 8);
277     gfc->ResvSize -= stuffingBits % 8;
278   }
279 #else
280     /* drain the rest into this frames ancillary data*/
281     l3_side->resvDrain_post += stuffingBits;
282     gfc->ResvSize -= stuffingBits;
283 #endif
284
285     return;
286 }
287
288