reservoir.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * bit reservoir source file
  3. *
  4. * Copyright (c) 1999-2000 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. /* $Id: reservoir.c,v 1.45 2011/05/07 16:05:17 rbrito Exp $ */
  22. #ifdef HAVE_CONFIG_H
  23. # include <config.h>
  24. #endif
  25. #include "lame.h"
  26. #include "machine.h"
  27. #include "encoder.h"
  28. #include "util.h"
  29. #include "reservoir.h"
  30. #include "bitstream.h"
  31. #include "lame-analysis.h"
  32. #include "lame_global_flags.h"
  33. /*
  34. ResvFrameBegin:
  35. Called (repeatedly) at the beginning of a frame. Updates the maximum
  36. size of the reservoir, and checks to make sure main_data_begin
  37. was set properly by the formatter
  38. */
  39. /*
  40. * Background information:
  41. *
  42. * This is the original text from the ISO standard. Because of
  43. * sooo many bugs and irritations correcting comments are added
  44. * in brackets []. A '^W' means you should remove the last word.
  45. *
  46. * 1) The following rule can be used to calculate the maximum
  47. * number of bits used for one granule [^W frame]:
  48. * At the highest possible bitrate of Layer III (320 kbps
  49. * per stereo signal [^W^W^W], 48 kHz) the frames must be of
  50. * [^W^W^W are designed to have] constant length, i.e.
  51. * one buffer [^W^W the frame] length is:
  52. *
  53. * 320 kbps * 1152/48 kHz = 7680 bit = 960 byte
  54. *
  55. * This value is used as the maximum buffer per channel [^W^W] at
  56. * lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps
  57. * stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit
  58. * [per granule and channel] at 48 kHz sampling frequency.
  59. * This means that there is a maximum deviation (short time buffer
  60. * [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps.
  61. * The actual deviation is equal to the number of bytes [with the
  62. * meaning of octets] denoted by the main_data_end offset pointer.
  63. * The actual maximum deviation is (2^9-1)*8 bit = 4088 bits
  64. * [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].
  65. * ... The xchange of buffer bits between the left and right channel
  66. * is allowed without restrictions [exception: dual channel].
  67. * Because of the [constructed] constraint on the buffer size
  68. * main_data_end is always set to 0 in the case of bit_rate_index==14,
  69. * i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case
  70. * all data are allocated between adjacent header [^W sync] words
  71. * [, i.e. there is no buffering at all].
  72. */
  73. int
  74. ResvFrameBegin(lame_internal_flags * gfc, int *mean_bits)
  75. {
  76. SessionConfig_t const *const cfg = &gfc->cfg;
  77. EncStateVar_t *const esv = &gfc->sv_enc;
  78. int fullFrameBits;
  79. int resvLimit;
  80. int maxmp3buf;
  81. III_side_info_t *const l3_side = &gfc->l3_side;
  82. int frameLength;
  83. int meanBits;
  84. frameLength = getframebits(gfc);
  85. meanBits = (frameLength - cfg->sideinfo_len * 8) / cfg->mode_gr;
  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. *
  97. * maximum allowed granule/channel size times 4 = 8*2047 bits.,
  98. * so this is the absolute maximum supported by the format.
  99. *
  100. *
  101. * fullFrameBits: maximum number of bits available for encoding
  102. * the current frame.
  103. *
  104. * mean_bits: target number of bits per granule.
  105. *
  106. * frameLength:
  107. *
  108. * gfc->ResvMax: maximum allowed reservoir
  109. *
  110. * gfc->ResvSize: current reservoir size
  111. *
  112. * l3_side->resvDrain_pre:
  113. * ancillary data to be added to previous frame:
  114. * (only usefull in VBR modes if it is possible to have
  115. * maxmp3buf < fullFrameBits)). Currently disabled,
  116. * see #define NEW_DRAIN
  117. * 2010-02-13: RH now enabled, it seems to be needed for CBR too,
  118. * as there exists one example, where the FhG decoder
  119. * can't decode a -b320 CBR file anymore.
  120. *
  121. * l3_side->resvDrain_post:
  122. * ancillary data to be added to this frame:
  123. *
  124. */
  125. /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */
  126. resvLimit = (8 * 256) * cfg->mode_gr - 8;
  127. /* maximum allowed frame size. dont use more than this number of
  128. bits, even if the frame has the space for them: */
  129. maxmp3buf = cfg->buffer_constraint;
  130. esv->ResvMax = maxmp3buf - frameLength;
  131. if (esv->ResvMax > resvLimit)
  132. esv->ResvMax = resvLimit;
  133. if (esv->ResvMax < 0 || cfg->disable_reservoir)
  134. esv->ResvMax = 0;
  135. fullFrameBits = meanBits * cfg->mode_gr + Min(esv->ResvSize, esv->ResvMax);
  136. if (fullFrameBits > maxmp3buf)
  137. fullFrameBits = maxmp3buf;
  138. assert(0 == esv->ResvMax % 8);
  139. assert(esv->ResvMax >= 0);
  140. l3_side->resvDrain_pre = 0;
  141. if (gfc->pinfo != NULL) {
  142. gfc->pinfo->mean_bits = meanBits / 2; /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */
  143. gfc->pinfo->resvsize = esv->ResvSize;
  144. }
  145. *mean_bits = meanBits;
  146. return fullFrameBits;
  147. }
  148. /*
  149. ResvMaxBits
  150. returns targ_bits: target number of bits to use for 1 granule
  151. extra_bits: amount extra available from reservoir
  152. Mark Taylor 4/99
  153. */
  154. void
  155. ResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *extra_bits, int cbr)
  156. {
  157. SessionConfig_t const *const cfg = &gfc->cfg;
  158. EncStateVar_t *const esv = &gfc->sv_enc;
  159. int add_bits, targBits, extraBits;
  160. int ResvSize = esv->ResvSize, ResvMax = esv->ResvMax;
  161. /* conpensate the saved bits used in the 1st granule */
  162. if (cbr)
  163. ResvSize += mean_bits;
  164. if (gfc->sv_qnt.substep_shaping & 1)
  165. ResvMax *= 0.9;
  166. targBits = mean_bits;
  167. /* extra bits if the reservoir is almost full */
  168. if (ResvSize * 10 > ResvMax * 9) {
  169. add_bits = ResvSize - (ResvMax * 9) / 10;
  170. targBits += add_bits;
  171. gfc->sv_qnt.substep_shaping |= 0x80;
  172. }
  173. else {
  174. add_bits = 0;
  175. gfc->sv_qnt.substep_shaping &= 0x7f;
  176. /* build up reservoir. this builds the reservoir a little slower
  177. * than FhG. It could simple be mean_bits/15, but this was rigged
  178. * to always produce 100 (the old value) at 128kbs */
  179. /* *targ_bits -= (int) (mean_bits/15.2); */
  180. if (!cfg->disable_reservoir && !(gfc->sv_qnt.substep_shaping & 1))
  181. targBits -= .1 * mean_bits;
  182. }
  183. /* amount from the reservoir we are allowed to use. ISO says 6/10 */
  184. extraBits = (ResvSize < (esv->ResvMax * 6) / 10 ? ResvSize : (esv->ResvMax * 6) / 10);
  185. extraBits -= add_bits;
  186. if (extraBits < 0)
  187. extraBits = 0;
  188. *targ_bits = targBits;
  189. *extra_bits = extraBits;
  190. }
  191. /*
  192. ResvAdjust:
  193. Called after a granule's bit allocation. Readjusts the size of
  194. the reservoir to reflect the granule's usage.
  195. */
  196. void
  197. ResvAdjust(lame_internal_flags * gfc, gr_info const *gi)
  198. {
  199. gfc->sv_enc.ResvSize -= gi->part2_3_length + gi->part2_length;
  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
  208. ResvFrameEnd(lame_internal_flags * gfc, int mean_bits)
  209. {
  210. SessionConfig_t const *const cfg = &gfc->cfg;
  211. EncStateVar_t *const esv = &gfc->sv_enc;
  212. III_side_info_t *const l3_side = &gfc->l3_side;
  213. int stuffingBits;
  214. int over_bits;
  215. esv->ResvSize += mean_bits * cfg->mode_gr;
  216. stuffingBits = 0;
  217. l3_side->resvDrain_post = 0;
  218. l3_side->resvDrain_pre = 0;
  219. /* we must be byte aligned */
  220. if ((over_bits = esv->ResvSize % 8) != 0)
  221. stuffingBits += over_bits;
  222. over_bits = (esv->ResvSize - stuffingBits) - esv->ResvMax;
  223. if (over_bits > 0) {
  224. assert(0 == over_bits % 8);
  225. assert(over_bits >= 0);
  226. stuffingBits += over_bits;
  227. }
  228. /* NOTE: enabling the NEW_DRAIN code fixes some problems with FhG decoder
  229. shipped with MS Windows operating systems. Using this, it is even
  230. possible to use Gabriel's lax buffer consideration again, which
  231. assumes, any decoder should have a buffer large enough
  232. for a 320 kbps frame at 32 kHz sample rate.
  233. old drain code:
  234. lame -b320 BlackBird.wav ---> does not play with GraphEdit.exe using FhG decoder V1.5 Build 50
  235. new drain code:
  236. lame -b320 BlackBird.wav ---> plays fine with GraphEdit.exe using FhG decoder V1.5 Build 50
  237. Robert Hegemann, 2010-02-13.
  238. */
  239. /* drain as many bits as possible into previous frame ancillary data
  240. * In particular, in VBR mode ResvMax may have changed, and we have
  241. * to make sure main_data_begin does not create a reservoir bigger
  242. * than ResvMax mt 4/00*/
  243. {
  244. int mdb_bytes = Min(l3_side->main_data_begin * 8, stuffingBits) / 8;
  245. l3_side->resvDrain_pre += 8 * mdb_bytes;
  246. stuffingBits -= 8 * mdb_bytes;
  247. esv->ResvSize -= 8 * mdb_bytes;
  248. l3_side->main_data_begin -= mdb_bytes;
  249. }
  250. /* drain the rest into this frames ancillary data */
  251. l3_side->resvDrain_post += stuffingBits;
  252. esv->ResvSize -= stuffingBits;
  253. }