xref: /plan9/sys/src/games/mp3enc/reservoir.c (revision 8f5875f3e9b20916b4c52ad4336922bc8653eb7b)
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.14 2001/01/05 15:20:33 aleidinger Exp $ */
23 
24 #ifdef HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27 
28 #include <assert.h>
29 #include "util.h"
30 #include "reservoir.h"
31 
32 #ifdef WITH_DMALLOC
33 #include <dmalloc.h>
34 #endif
35 
36 /*
37   ResvFrameBegin:
38   Called (repeatedly) at the beginning of a frame. Updates the maximum
39   size of the reservoir, and checks to make sure main_data_begin
40   was set properly by the formatter
41 */
42 
43 /*
44  *  Background information:
45  *
46  *  This is the original text from the ISO standard. Because of
47  *  sooo many bugs and irritations correcting comments are added
48  *  in brackets []. A '^W' means you should remove the last word.
49  *
50  *  1) The following rule can be used to calculate the maximum
51  *     number of bits used for one granule [^W frame]:
52  *     At the highest possible bitrate of Layer III (320 kbps
53  *     per stereo signal [^W^W^W], 48 kHz) the frames must be of
54  *     [^W^W^W are designed to have] constant length, i.e.
55  *     one buffer [^W^W the frame] length is:
56  *
57  *         320 kbps * 1152/48 kHz = 7680 bit = 960 byte
58  *
59  *     This value is used as the maximum buffer per channel [^W^W] at
60  *     lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps
61  *     stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit
62  *     [per granule and channel] at 48 kHz sampling frequency.
63  *     This means that there is a maximum deviation (short time buffer
64  *     [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps.
65  *     The actual deviation is equal to the number of bytes [with the
66  *     meaning of octets] denoted by the main_data_end offset pointer.
67  *     The actual maximum deviation is (2^9-1)*8 bit = 4088 bits
68  *     [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].
69  *     ... The xchange of buffer bits between the left and right channel
70  *     is allowed without restrictions [exception: dual channel].
71  *     Because of the [constructed] constraint on the buffer size
72  *     main_data_end is always set to 0 in the case of bit_rate_index==14,
73  *     i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case
74  *     all data are allocated between adjacent header [^W sync] words
75  *     [, i.e. there is no buffering at all].
76  */
77 
78 int
ResvFrameBegin(lame_global_flags * gfp,III_side_info_t * l3_side,int mean_bits,int frameLength)79 ResvFrameBegin(lame_global_flags *gfp,III_side_info_t *l3_side, int mean_bits, int frameLength )
80 {
81     lame_internal_flags *gfc=gfp->internal_flags;
82     int fullFrameBits;
83     int resvLimit;
84     int maxmp3buf;
85 
86 /*
87  *  Meaning of the variables:
88  *      resvLimit: (0, 8, ..., 8*255 (MPEG-2), 8*511 (MPEG-1))
89  *          Number of bits can be stored in previous frame(s) due to
90  *          counter size constaints
91  *      maxmp3buf: ( ??? ... 8*1951 (MPEG-1 and 2), 8*2047 (MPEG-2.5))
92  *          Number of bits allowed to encode one frame (you can take 8*511 bit
93  *          from the bit reservoir and at most 8*1440 bit from the current
94  *          frame (320 kbps, 32 kHz), so 8*1951 bit is the largest possible
95  *          value for MPEG-1 and -2)
96  *      fullFrameBits:
97  *
98  *      mean_bits:
99  *
100  *      frameLength:
101  *
102  *      gfc->ResvMax:
103  *
104  *      gfc->ResvSize:
105  *
106  *      l3_side->resvDrain_pre:
107  *
108  */
109 
110     /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */
111     resvLimit = (gfp->version==1) ? 8*511 : 8*255 ;
112 
113 
114     /* maximum allowed frame size */
115     maxmp3buf = (gfp->strict_ISO) ? 8*960 : 8*2047;
116 
117     if ( frameLength > maxmp3buf ||  gfp->disable_reservoir ) {
118 	gfc->ResvMax = 0;
119     } else {
120 	gfc->ResvMax = maxmp3buf - frameLength;
121 	if ( gfc->ResvMax > resvLimit )
122 	  gfc->ResvMax = resvLimit;
123     }
124 
125     fullFrameBits = mean_bits * gfc->mode_gr + Min ( gfc->ResvSize, gfc->ResvMax );
126 
127     if ( gfp->strict_ISO  &&  fullFrameBits > maxmp3buf )
128         fullFrameBits = maxmp3buf;
129 
130     assert ( 0 == gfc->ResvMax % 8 );
131     assert ( gfc->ResvMax >= 0 );
132 
133     l3_side->resvDrain_pre = 0;
134 
135     if ( gfc->pinfo != NULL ) {
136         gfc->pinfo->mean_bits = mean_bits / 2;  /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */
137         gfc->pinfo->resvsize  = gfc->ResvSize;
138     }
139 
140     return fullFrameBits;
141 }
142 
143 
144 /*
145   ResvMaxBits
146   returns targ_bits:  target number of bits to use for 1 granule
147          extra_bits:  amount extra available from reservoir
148   Mark Taylor 4/99
149 */
ResvMaxBits(lame_global_flags * gfp,int mean_bits,int * targ_bits,int * extra_bits)150 void ResvMaxBits(lame_global_flags *gfp, int mean_bits, int *targ_bits, int *extra_bits)
151 {
152   lame_internal_flags *gfc=gfp->internal_flags;
153   int add_bits;
154   int full_fac;
155 
156   *targ_bits = mean_bits ;
157 
158   /* extra bits if the reservoir is almost full */
159   full_fac=9;
160   if (gfc->ResvSize > ((gfc->ResvMax * full_fac) / 10)) {
161     add_bits= gfc->ResvSize-((gfc->ResvMax * full_fac) / 10);
162     *targ_bits += add_bits;
163   }else {
164     add_bits =0 ;
165     /* build up reservoir.  this builds the reservoir a little slower
166      * than FhG.  It could simple be mean_bits/15, but this was rigged
167      * to always produce 100 (the old value) at 128kbs */
168     /*    *targ_bits -= (int) (mean_bits/15.2);*/
169     if (!gfp->disable_reservoir)
170       *targ_bits -= .1*mean_bits;
171   }
172 
173 
174   /* amount from the reservoir we are allowed to use. ISO says 6/10 */
175   *extra_bits =
176     (gfc->ResvSize  < (gfc->ResvMax*6)/10  ? gfc->ResvSize : (gfc->ResvMax*6)/10);
177   *extra_bits -= add_bits;
178 
179   if (*extra_bits < 0) *extra_bits=0;
180 
181 
182 }
183 
184 /*
185   ResvAdjust:
186   Called after a granule's bit allocation. Readjusts the size of
187   the reservoir to reflect the granule's usage.
188 */
189 void
ResvAdjust(lame_internal_flags * gfc,gr_info * gi,III_side_info_t * l3_side,int mean_bits)190 ResvAdjust(lame_internal_flags *gfc,gr_info *gi, III_side_info_t *l3_side, int mean_bits )
191 {
192   gfc->ResvSize += (mean_bits / gfc->channels_out) - gi->part2_3_length;
193 #if 0
194   printf("part2_3_length:  %i  avg=%i  incres: %i  resvsize=%i\n",gi->part2_3_length,
195 	 mean_bits/gfc->channels_out,
196 mean_bits/gfc->channels_out-gi->part2_3_length,gfc->ResvSize);
197 #endif
198 }
199 
200 
201 /*
202   ResvFrameEnd:
203   Called after all granules in a frame have been allocated. Makes sure
204   that the reservoir size is within limits, possibly by adding stuffing
205   bits.
206 */
207 void
ResvFrameEnd(lame_internal_flags * gfc,III_side_info_t * l3_side,int mean_bits)208 ResvFrameEnd(lame_internal_flags *gfc, III_side_info_t *l3_side, int mean_bits)
209 {
210     int stuffingBits;
211     int over_bits;
212 
213 
214     /* just in case mean_bits is odd, this is necessary... */
215     if ( gfc->channels_out == 2  &&  (mean_bits & 1) )
216 	gfc->ResvSize += 1;
217 
218     stuffingBits=0;
219     l3_side->resvDrain_post = 0;
220     l3_side->resvDrain_pre = 0;
221 
222     /* we must be byte aligned */
223     if ( (over_bits = gfc->ResvSize % 8) != 0 )
224 	stuffingBits += over_bits;
225 
226 
227     over_bits = (gfc->ResvSize - stuffingBits) - gfc->ResvMax;
228     if (over_bits > 0) {
229       assert ( 0 == over_bits % 8 );
230       assert ( over_bits >= 0 );
231       stuffingBits += over_bits;
232     }
233 
234 
235 #define NEW_DRAINXX
236 #ifdef NEW_DRAIN
237     /* drain as many bits as possible into previous frame ancillary data
238      * In particular, in VBR mode ResvMax may have changed, and we have
239      * to make sure main_data_begin does not create a reservoir bigger
240      * than ResvMax  mt 4/00*/
241   {
242     int mdb_bytes = Min(l3_side->main_data_begin*8,stuffingBits)/8;
243     l3_side->resvDrain_pre += 8*mdb_bytes;
244     stuffingBits -= 8*mdb_bytes;
245     gfc->ResvSize -= 8*mdb_bytes;
246     l3_side->main_data_begin -= mdb_bytes;
247 
248 
249     /* drain just enough to be byte aligned.  The remaining bits will
250      * be added to the reservoir, and we will deal with them next frame.
251      * If the next frame is at a lower bitrate, it may have a larger ResvMax,
252      * and we will not have to waste these bits!  mt 4/00 */
253     assert ( stuffingBits >= 0 );
254     l3_side->resvDrain_post += (stuffingBits % 8);
255     gfc->ResvSize -= stuffingBits % 8;
256   }
257 #else
258     /* drain the rest into this frames ancillary data*/
259     l3_side->resvDrain_post += stuffingBits;
260     gfc->ResvSize -= stuffingBits;
261 #endif
262 
263     return;
264 }
265 
266 
267