quantize.c 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. /*
  2. * MP3 quantization
  3. *
  4. * Copyright (c) 1999-2000 Mark Taylor
  5. * Copyright (c) 1999-2003 Takehiro Tominaga
  6. * Copyright (c) 2000-2011 Robert Hegemann
  7. * Copyright (c) 2001-2005 Gabriel Bouvigne
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Library General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Library General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Library General Public
  20. * License along with this library; if not, write to the
  21. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  22. * Boston, MA 02111-1307, USA.
  23. */
  24. /* $Id: quantize.c,v 1.219 2017/08/02 19:48:05 robert Exp $ */
  25. #ifdef HAVE_CONFIG_H
  26. # include <config.h>
  27. #endif
  28. #include "lame.h"
  29. #include "machine.h"
  30. #include "encoder.h"
  31. #include "util.h"
  32. #include "quantize_pvt.h"
  33. #include "reservoir.h"
  34. #include "bitstream.h"
  35. #include "vbrquantize.h"
  36. #include "quantize.h"
  37. #ifdef HAVE_XMMINTRIN_H
  38. #include "vector/lame_intrin.h"
  39. #endif
  40. /* convert from L/R <-> Mid/Side */
  41. static void
  42. ms_convert(III_side_info_t * l3_side, int gr)
  43. {
  44. int i;
  45. for (i = 0; i < 576; ++i) {
  46. FLOAT l, r;
  47. l = l3_side->tt[gr][0].xr[i];
  48. r = l3_side->tt[gr][1].xr[i];
  49. l3_side->tt[gr][0].xr[i] = (l + r) * (FLOAT) (SQRT2 * 0.5);
  50. l3_side->tt[gr][1].xr[i] = (l - r) * (FLOAT) (SQRT2 * 0.5);
  51. }
  52. }
  53. /************************************************************************
  54. *
  55. * init_outer_loop()
  56. * mt 6/99
  57. *
  58. * initializes cod_info, scalefac and xrpow
  59. *
  60. * returns 0 if all energies in xr are zero, else 1
  61. *
  62. ************************************************************************/
  63. static void
  64. init_xrpow_core_c(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)
  65. {
  66. int i;
  67. FLOAT tmp;
  68. *sum = 0;
  69. for (i = 0; i <= upper; ++i) {
  70. tmp = fabs(cod_info->xr[i]);
  71. *sum += tmp;
  72. xrpow[i] = sqrt(tmp * sqrt(tmp));
  73. if (xrpow[i] > cod_info->xrpow_max)
  74. cod_info->xrpow_max = xrpow[i];
  75. }
  76. }
  77. void
  78. init_xrpow_core_init(lame_internal_flags * const gfc)
  79. {
  80. gfc->init_xrpow_core = init_xrpow_core_c;
  81. #if defined(HAVE_XMMINTRIN_H)
  82. if (gfc->CPU_features.SSE)
  83. gfc->init_xrpow_core = init_xrpow_core_sse;
  84. #endif
  85. #ifndef HAVE_NASM
  86. #ifdef MIN_ARCH_SSE
  87. gfc->init_xrpow_core = init_xrpow_core_sse;
  88. #endif
  89. #endif
  90. }
  91. static int
  92. init_xrpow(lame_internal_flags * gfc, gr_info * const cod_info, FLOAT xrpow[576])
  93. {
  94. FLOAT sum = 0;
  95. int i;
  96. int const upper = cod_info->max_nonzero_coeff;
  97. assert(xrpow != NULL);
  98. cod_info->xrpow_max = 0;
  99. /* check if there is some energy we have to quantize
  100. * and calculate xrpow matching our fresh scalefactors
  101. */
  102. assert(0 <= upper && upper <= 575);
  103. memset(&(xrpow[upper]), 0, (576 - upper) * sizeof(xrpow[0]));
  104. gfc->init_xrpow_core(cod_info, xrpow, upper, &sum);
  105. /* return 1 if we have something to quantize, else 0
  106. */
  107. if (sum > (FLOAT) 1E-20) {
  108. int j = 0;
  109. if (gfc->sv_qnt.substep_shaping & 2)
  110. j = 1;
  111. for (i = 0; i < cod_info->psymax; i++)
  112. gfc->sv_qnt.pseudohalf[i] = j;
  113. return 1;
  114. }
  115. memset(&cod_info->l3_enc[0], 0, sizeof(int) * 576);
  116. return 0;
  117. }
  118. /*
  119. Gabriel Bouvigne feb/apr 2003
  120. Analog silence detection in partitionned sfb21
  121. or sfb12 for short blocks
  122. From top to bottom of sfb, changes to 0
  123. coeffs which are below ath. It stops on the first
  124. coeff higher than ath.
  125. */
  126. static void
  127. psfb21_analogsilence(lame_internal_flags const *gfc, gr_info * const cod_info)
  128. {
  129. ATH_t const *const ATH = gfc->ATH;
  130. FLOAT *const xr = cod_info->xr;
  131. if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT blocks */
  132. int gsfb;
  133. int stop = 0;
  134. for (gsfb = PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {
  135. int const start = gfc->scalefac_band.psfb21[gsfb];
  136. int const end = gfc->scalefac_band.psfb21[gsfb + 1];
  137. int j;
  138. FLOAT ath21;
  139. ath21 = athAdjust(ATH->adjust_factor, ATH->psfb21[gsfb], ATH->floor, 0);
  140. if (gfc->sv_qnt.longfact[21] > 1e-12f)
  141. ath21 *= gfc->sv_qnt.longfact[21];
  142. for (j = end - 1; j >= start; j--) {
  143. if (fabs(xr[j]) < ath21)
  144. xr[j] = 0;
  145. else {
  146. stop = 1;
  147. break;
  148. }
  149. }
  150. }
  151. }
  152. else {
  153. /*note: short blocks coeffs are reordered */
  154. int block;
  155. for (block = 0; block < 3; block++) {
  156. int gsfb;
  157. int stop = 0;
  158. for (gsfb = PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {
  159. int const start = gfc->scalefac_band.s[12] * 3 +
  160. (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) * block +
  161. (gfc->scalefac_band.psfb12[gsfb] - gfc->scalefac_band.psfb12[0]);
  162. int const end =
  163. start + (gfc->scalefac_band.psfb12[gsfb + 1] - gfc->scalefac_band.psfb12[gsfb]);
  164. int j;
  165. FLOAT ath12;
  166. ath12 = athAdjust(ATH->adjust_factor, ATH->psfb12[gsfb], ATH->floor, 0);
  167. if (gfc->sv_qnt.shortfact[12] > 1e-12f)
  168. ath12 *= gfc->sv_qnt.shortfact[12];
  169. for (j = end - 1; j >= start; j--) {
  170. if (fabs(xr[j]) < ath12)
  171. xr[j] = 0;
  172. else {
  173. stop = 1;
  174. break;
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }
  181. static void
  182. init_outer_loop(lame_internal_flags const *gfc, gr_info * const cod_info)
  183. {
  184. SessionConfig_t const *const cfg = &gfc->cfg;
  185. int sfb, j;
  186. /* initialize fresh cod_info
  187. */
  188. cod_info->part2_3_length = 0;
  189. cod_info->big_values = 0;
  190. cod_info->count1 = 0;
  191. cod_info->global_gain = 210;
  192. cod_info->scalefac_compress = 0;
  193. /* mixed_block_flag, block_type was set in psymodel.c */
  194. cod_info->table_select[0] = 0;
  195. cod_info->table_select[1] = 0;
  196. cod_info->table_select[2] = 0;
  197. cod_info->subblock_gain[0] = 0;
  198. cod_info->subblock_gain[1] = 0;
  199. cod_info->subblock_gain[2] = 0;
  200. cod_info->subblock_gain[3] = 0; /* this one is always 0 */
  201. cod_info->region0_count = 0;
  202. cod_info->region1_count = 0;
  203. cod_info->preflag = 0;
  204. cod_info->scalefac_scale = 0;
  205. cod_info->count1table_select = 0;
  206. cod_info->part2_length = 0;
  207. if (cfg->samplerate_out <= 8000) {
  208. cod_info->sfb_lmax = 17;
  209. cod_info->sfb_smin = 9;
  210. cod_info->psy_lmax = 17;
  211. }
  212. else {
  213. cod_info->sfb_lmax = SBPSY_l;
  214. cod_info->sfb_smin = SBPSY_s;
  215. cod_info->psy_lmax = gfc->sv_qnt.sfb21_extra ? SBMAX_l : SBPSY_l;
  216. }
  217. cod_info->psymax = cod_info->psy_lmax;
  218. cod_info->sfbmax = cod_info->sfb_lmax;
  219. cod_info->sfbdivide = 11;
  220. for (sfb = 0; sfb < SBMAX_l; sfb++) {
  221. cod_info->width[sfb]
  222. = gfc->scalefac_band.l[sfb + 1] - gfc->scalefac_band.l[sfb];
  223. cod_info->window[sfb] = 3; /* which is always 0. */
  224. }
  225. if (cod_info->block_type == SHORT_TYPE) {
  226. FLOAT ixwork[576];
  227. FLOAT *ix;
  228. cod_info->sfb_smin = 0;
  229. cod_info->sfb_lmax = 0;
  230. if (cod_info->mixed_block_flag) {
  231. /*
  232. * MPEG-1: sfbs 0-7 long block, 3-12 short blocks
  233. * MPEG-2(.5): sfbs 0-5 long block, 3-12 short blocks
  234. */
  235. cod_info->sfb_smin = 3;
  236. cod_info->sfb_lmax = cfg->mode_gr * 2 + 4;
  237. }
  238. if (cfg->samplerate_out <= 8000) {
  239. cod_info->psymax
  240. = cod_info->sfb_lmax
  241. + 3 * (9 - cod_info->sfb_smin);
  242. cod_info->sfbmax = cod_info->sfb_lmax + 3 * (9 - cod_info->sfb_smin);
  243. }
  244. else {
  245. cod_info->psymax
  246. = cod_info->sfb_lmax
  247. + 3 * ((gfc->sv_qnt.sfb21_extra ? SBMAX_s : SBPSY_s) - cod_info->sfb_smin);
  248. cod_info->sfbmax = cod_info->sfb_lmax + 3 * (SBPSY_s - cod_info->sfb_smin);
  249. }
  250. cod_info->sfbdivide = cod_info->sfbmax - 18;
  251. cod_info->psy_lmax = cod_info->sfb_lmax;
  252. /* re-order the short blocks, for more efficient encoding below */
  253. /* By Takehiro TOMINAGA */
  254. /*
  255. Within each scalefactor band, data is given for successive
  256. time windows, beginning with window 0 and ending with window 2.
  257. Within each window, the quantized values are then arranged in
  258. order of increasing frequency...
  259. */
  260. ix = &cod_info->xr[gfc->scalefac_band.l[cod_info->sfb_lmax]];
  261. memcpy(ixwork, cod_info->xr, 576 * sizeof(FLOAT));
  262. for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
  263. int const start = gfc->scalefac_band.s[sfb];
  264. int const end = gfc->scalefac_band.s[sfb + 1];
  265. int window, l;
  266. for (window = 0; window < 3; window++) {
  267. for (l = start; l < end; l++) {
  268. *ix++ = ixwork[3 * l + window];
  269. }
  270. }
  271. }
  272. j = cod_info->sfb_lmax;
  273. for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
  274. cod_info->width[j] = cod_info->width[j + 1] = cod_info->width[j + 2]
  275. = gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb];
  276. cod_info->window[j] = 0;
  277. cod_info->window[j + 1] = 1;
  278. cod_info->window[j + 2] = 2;
  279. j += 3;
  280. }
  281. }
  282. cod_info->count1bits = 0;
  283. cod_info->sfb_partition_table = nr_of_sfb_block[0][0];
  284. cod_info->slen[0] = 0;
  285. cod_info->slen[1] = 0;
  286. cod_info->slen[2] = 0;
  287. cod_info->slen[3] = 0;
  288. cod_info->max_nonzero_coeff = 575;
  289. /* fresh scalefactors are all zero
  290. */
  291. memset(cod_info->scalefac, 0, sizeof(cod_info->scalefac));
  292. if (cfg->vbr != vbr_mt && cfg->vbr != vbr_mtrh && cfg->vbr != vbr_abr && cfg->vbr != vbr_off) {
  293. psfb21_analogsilence(gfc, cod_info);
  294. }
  295. }
  296. /************************************************************************
  297. *
  298. * bin_search_StepSize()
  299. *
  300. * author/date??
  301. *
  302. * binary step size search
  303. * used by outer_loop to get a quantizer step size to start with
  304. *
  305. ************************************************************************/
  306. typedef enum {
  307. BINSEARCH_NONE,
  308. BINSEARCH_UP,
  309. BINSEARCH_DOWN
  310. } binsearchDirection_t;
  311. static int
  312. bin_search_StepSize(lame_internal_flags * const gfc, gr_info * const cod_info,
  313. int desired_rate, const int ch, const FLOAT xrpow[576])
  314. {
  315. int nBits;
  316. int CurrentStep = gfc->sv_qnt.CurrentStep[ch];
  317. int flag_GoneOver = 0;
  318. int const start = gfc->sv_qnt.OldValue[ch];
  319. binsearchDirection_t Direction = BINSEARCH_NONE;
  320. cod_info->global_gain = start;
  321. desired_rate -= cod_info->part2_length;
  322. assert(CurrentStep);
  323. for (;;) {
  324. int step;
  325. nBits = count_bits(gfc, xrpow, cod_info, 0);
  326. if (CurrentStep == 1 || nBits == desired_rate)
  327. break; /* nothing to adjust anymore */
  328. if (nBits > desired_rate) {
  329. /* increase Quantize_StepSize */
  330. if (Direction == BINSEARCH_DOWN)
  331. flag_GoneOver = 1;
  332. if (flag_GoneOver)
  333. CurrentStep /= 2;
  334. Direction = BINSEARCH_UP;
  335. step = CurrentStep;
  336. }
  337. else {
  338. /* decrease Quantize_StepSize */
  339. if (Direction == BINSEARCH_UP)
  340. flag_GoneOver = 1;
  341. if (flag_GoneOver)
  342. CurrentStep /= 2;
  343. Direction = BINSEARCH_DOWN;
  344. step = -CurrentStep;
  345. }
  346. cod_info->global_gain += step;
  347. if (cod_info->global_gain < 0) {
  348. cod_info->global_gain = 0;
  349. flag_GoneOver = 1;
  350. }
  351. if (cod_info->global_gain > 255) {
  352. cod_info->global_gain = 255;
  353. flag_GoneOver = 1;
  354. }
  355. }
  356. assert(cod_info->global_gain >= 0);
  357. assert(cod_info->global_gain < 256);
  358. while (nBits > desired_rate && cod_info->global_gain < 255) {
  359. cod_info->global_gain++;
  360. nBits = count_bits(gfc, xrpow, cod_info, 0);
  361. }
  362. gfc->sv_qnt.CurrentStep[ch] = (start - cod_info->global_gain >= 4) ? 4 : 2;
  363. gfc->sv_qnt.OldValue[ch] = cod_info->global_gain;
  364. cod_info->part2_3_length = nBits;
  365. return nBits;
  366. }
  367. /************************************************************************
  368. *
  369. * trancate_smallspectrums()
  370. *
  371. * Takehiro TOMINAGA 2002-07-21
  372. *
  373. * trancate smaller nubmers into 0 as long as the noise threshold is allowed.
  374. *
  375. ************************************************************************/
  376. static int
  377. floatcompare(const void *v1, const void *v2)
  378. {
  379. const FLOAT *const a = v1, *const b = v2;
  380. if (*a > *b)
  381. return 1;
  382. if (*a < *b)
  383. return -1;
  384. return 0;
  385. }
  386. static void
  387. trancate_smallspectrums(lame_internal_flags const *gfc,
  388. gr_info * const gi, const FLOAT * const l3_xmin, FLOAT * const work)
  389. {
  390. int sfb, j, width;
  391. FLOAT distort[SFBMAX];
  392. calc_noise_result dummy;
  393. if ((!(gfc->sv_qnt.substep_shaping & 4) && gi->block_type == SHORT_TYPE)
  394. || gfc->sv_qnt.substep_shaping & 0x80)
  395. return;
  396. (void) calc_noise(gi, l3_xmin, distort, &dummy, 0);
  397. for (j = 0; j < 576; j++) {
  398. FLOAT xr = 0.0;
  399. if (gi->l3_enc[j] != 0)
  400. xr = fabs(gi->xr[j]);
  401. work[j] = xr;
  402. }
  403. j = 0;
  404. sfb = 8;
  405. if (gi->block_type == SHORT_TYPE)
  406. sfb = 6;
  407. do {
  408. FLOAT allowedNoise, trancateThreshold;
  409. int nsame, start;
  410. width = gi->width[sfb];
  411. j += width;
  412. if (distort[sfb] >= 1.0)
  413. continue;
  414. qsort(&work[j - width], width, sizeof(FLOAT), floatcompare);
  415. if (EQ(work[j - 1], 0.0))
  416. continue; /* all zero sfb */
  417. allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];
  418. trancateThreshold = 0.0;
  419. start = 0;
  420. do {
  421. FLOAT noise;
  422. for (nsame = 1; start + nsame < width; nsame++)
  423. if (NEQ(work[start + j - width], work[start + j + nsame - width]))
  424. break;
  425. noise = work[start + j - width] * work[start + j - width] * nsame;
  426. if (allowedNoise < noise) {
  427. if (start != 0)
  428. trancateThreshold = work[start + j - width - 1];
  429. break;
  430. }
  431. allowedNoise -= noise;
  432. start += nsame;
  433. } while (start < width);
  434. if (EQ(trancateThreshold, 0.0))
  435. continue;
  436. /* printf("%e %e %e\n", */
  437. /* trancateThreshold/l3_xmin[sfb], */
  438. /* trancateThreshold/(l3_xmin[sfb]*start), */
  439. /* trancateThreshold/(l3_xmin[sfb]*(start+width)) */
  440. /* ); */
  441. /* if (trancateThreshold > 1000*l3_xmin[sfb]*start) */
  442. /* trancateThreshold = 1000*l3_xmin[sfb]*start; */
  443. do {
  444. if (fabs(gi->xr[j - width]) <= trancateThreshold)
  445. gi->l3_enc[j - width] = 0;
  446. } while (--width > 0);
  447. } while (++sfb < gi->psymax);
  448. gi->part2_3_length = noquant_count_bits(gfc, gi, 0);
  449. }
  450. /*************************************************************************
  451. *
  452. * loop_break()
  453. *
  454. * author/date??
  455. *
  456. * Function: Returns zero if there is a scalefac which has not been
  457. * amplified. Otherwise it returns one.
  458. *
  459. *************************************************************************/
  460. inline static int
  461. loop_break(const gr_info * const cod_info)
  462. {
  463. int sfb;
  464. for (sfb = 0; sfb < cod_info->sfbmax; sfb++)
  465. if (cod_info->scalefac[sfb]
  466. + cod_info->subblock_gain[cod_info->window[sfb]] == 0)
  467. return 0;
  468. return 1;
  469. }
  470. /* mt 5/99: Function: Improved calc_noise for a single channel */
  471. /*************************************************************************
  472. *
  473. * quant_compare()
  474. *
  475. * author/date??
  476. *
  477. * several different codes to decide which quantization is better
  478. *
  479. *************************************************************************/
  480. static double
  481. penalties(double noise)
  482. {
  483. return FAST_LOG10(0.368 + 0.632 * noise * noise * noise);
  484. }
  485. static double
  486. get_klemm_noise(const FLOAT * distort, const gr_info * const gi)
  487. {
  488. int sfb;
  489. double klemm_noise = 1E-37;
  490. for (sfb = 0; sfb < gi->psymax; sfb++)
  491. klemm_noise += penalties(distort[sfb]);
  492. return Max(1e-20, klemm_noise);
  493. }
  494. inline static int
  495. quant_compare(const int quant_comp,
  496. const calc_noise_result * const best,
  497. calc_noise_result * const calc, const gr_info * const gi, const FLOAT * distort)
  498. {
  499. /*
  500. noise is given in decibels (dB) relative to masking thesholds.
  501. over_noise: ??? (the previous comment is fully wrong)
  502. tot_noise: ??? (the previous comment is fully wrong)
  503. max_noise: max quantization noise
  504. */
  505. int better;
  506. switch (quant_comp) {
  507. default:
  508. case 9:{
  509. if (best->over_count > 0) {
  510. /* there are distorted sfb */
  511. better = calc->over_SSD <= best->over_SSD;
  512. if (calc->over_SSD == best->over_SSD)
  513. better = calc->bits < best->bits;
  514. }
  515. else {
  516. /* no distorted sfb */
  517. better = ((calc->max_noise < 0) &&
  518. ((calc->max_noise * 10 + calc->bits) <=
  519. (best->max_noise * 10 + best->bits)));
  520. }
  521. break;
  522. }
  523. case 0:
  524. better = calc->over_count < best->over_count
  525. || (calc->over_count == best->over_count && calc->over_noise < best->over_noise)
  526. || (calc->over_count == best->over_count &&
  527. EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
  528. break;
  529. case 8:
  530. calc->max_noise = get_klemm_noise(distort, gi);
  531. /*lint --fallthrough */
  532. case 1:
  533. better = calc->max_noise < best->max_noise;
  534. break;
  535. case 2:
  536. better = calc->tot_noise < best->tot_noise;
  537. break;
  538. case 3:
  539. better = (calc->tot_noise < best->tot_noise)
  540. && (calc->max_noise < best->max_noise);
  541. break;
  542. case 4:
  543. better = (calc->max_noise <= 0.0 && best->max_noise > 0.2)
  544. || (calc->max_noise <= 0.0 &&
  545. best->max_noise < 0.0 &&
  546. best->max_noise > calc->max_noise - 0.2 && calc->tot_noise < best->tot_noise)
  547. || (calc->max_noise <= 0.0 &&
  548. best->max_noise > 0.0 &&
  549. best->max_noise > calc->max_noise - 0.2 &&
  550. calc->tot_noise < best->tot_noise + best->over_noise)
  551. || (calc->max_noise > 0.0 &&
  552. best->max_noise > -0.05 &&
  553. best->max_noise > calc->max_noise - 0.1 &&
  554. calc->tot_noise + calc->over_noise < best->tot_noise + best->over_noise)
  555. || (calc->max_noise > 0.0 &&
  556. best->max_noise > -0.1 &&
  557. best->max_noise > calc->max_noise - 0.15 &&
  558. calc->tot_noise + calc->over_noise + calc->over_noise <
  559. best->tot_noise + best->over_noise + best->over_noise);
  560. break;
  561. case 5:
  562. better = calc->over_noise < best->over_noise
  563. || (EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
  564. break;
  565. case 6:
  566. better = calc->over_noise < best->over_noise
  567. || (EQ(calc->over_noise, best->over_noise) &&
  568. (calc->max_noise < best->max_noise
  569. || (EQ(calc->max_noise, best->max_noise) && calc->tot_noise <= best->tot_noise)
  570. ));
  571. break;
  572. case 7:
  573. better = calc->over_count < best->over_count || calc->over_noise < best->over_noise;
  574. break;
  575. }
  576. if (best->over_count == 0) {
  577. /*
  578. If no distorted bands, only use this quantization
  579. if it is better, and if it uses less bits.
  580. Unfortunately, part2_3_length is sometimes a poor
  581. estimator of the final size at low bitrates.
  582. */
  583. better = better && calc->bits < best->bits;
  584. }
  585. return better;
  586. }
  587. /*************************************************************************
  588. *
  589. * amp_scalefac_bands()
  590. *
  591. * author/date??
  592. *
  593. * Amplify the scalefactor bands that violate the masking threshold.
  594. * See ISO 11172-3 Section C.1.5.4.3.5
  595. *
  596. * distort[] = noise/masking
  597. * distort[] > 1 ==> noise is not masked
  598. * distort[] < 1 ==> noise is masked
  599. * max_dist = maximum value of distort[]
  600. *
  601. * Three algorithms:
  602. * noise_shaping_amp
  603. * 0 Amplify all bands with distort[]>1.
  604. *
  605. * 1 Amplify all bands with distort[] >= max_dist^(.5);
  606. * ( 50% in the db scale)
  607. *
  608. * 2 Amplify first band with distort[] >= max_dist;
  609. *
  610. *
  611. * For algorithms 0 and 1, if max_dist < 1, then amplify all bands
  612. * with distort[] >= .95*max_dist. This is to make sure we always
  613. * amplify at least one band.
  614. *
  615. *
  616. *************************************************************************/
  617. static void
  618. amp_scalefac_bands(lame_internal_flags * gfc,
  619. gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
  620. {
  621. SessionConfig_t const *const cfg = &gfc->cfg;
  622. int j, sfb;
  623. FLOAT ifqstep34, trigger;
  624. int noise_shaping_amp;
  625. if (cod_info->scalefac_scale == 0) {
  626. ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5) */
  627. }
  628. else {
  629. ifqstep34 = 1.68179283050742922612; /* 2**(.75*1) */
  630. }
  631. /* compute maximum value of distort[] */
  632. trigger = 0;
  633. for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
  634. if (trigger < distort[sfb])
  635. trigger = distort[sfb];
  636. }
  637. noise_shaping_amp = cfg->noise_shaping_amp;
  638. if (noise_shaping_amp == 3) {
  639. if (bRefine == 1)
  640. noise_shaping_amp = 2;
  641. else
  642. noise_shaping_amp = 1;
  643. }
  644. switch (noise_shaping_amp) {
  645. case 2:
  646. /* amplify exactly 1 band */
  647. break;
  648. case 1:
  649. /* amplify bands within 50% of max (on db scale) */
  650. if (trigger > 1.0)
  651. trigger = pow(trigger, .5);
  652. else
  653. trigger *= .95;
  654. break;
  655. case 0:
  656. default:
  657. /* ISO algorithm. amplify all bands with distort>1 */
  658. if (trigger > 1.0)
  659. trigger = 1.0;
  660. else
  661. trigger *= .95;
  662. break;
  663. }
  664. j = 0;
  665. for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
  666. int const width = cod_info->width[sfb];
  667. int l;
  668. j += width;
  669. if (distort[sfb] < trigger)
  670. continue;
  671. if (gfc->sv_qnt.substep_shaping & 2) {
  672. gfc->sv_qnt.pseudohalf[sfb] = !gfc->sv_qnt.pseudohalf[sfb];
  673. if (!gfc->sv_qnt.pseudohalf[sfb] && cfg->noise_shaping_amp == 2)
  674. return;
  675. }
  676. cod_info->scalefac[sfb]++;
  677. for (l = -width; l < 0; l++) {
  678. xrpow[j + l] *= ifqstep34;
  679. if (xrpow[j + l] > cod_info->xrpow_max)
  680. cod_info->xrpow_max = xrpow[j + l];
  681. }
  682. if (cfg->noise_shaping_amp == 2)
  683. return;
  684. }
  685. }
  686. /*************************************************************************
  687. *
  688. * inc_scalefac_scale()
  689. *
  690. * Takehiro Tominaga 2000-xx-xx
  691. *
  692. * turns on scalefac scale and adjusts scalefactors
  693. *
  694. *************************************************************************/
  695. static void
  696. inc_scalefac_scale(gr_info * const cod_info, FLOAT xrpow[576])
  697. {
  698. int l, j, sfb;
  699. const FLOAT ifqstep34 = 1.29683955465100964055;
  700. j = 0;
  701. for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
  702. int const width = cod_info->width[sfb];
  703. int s = cod_info->scalefac[sfb];
  704. if (cod_info->preflag)
  705. s += pretab[sfb];
  706. j += width;
  707. if (s & 1) {
  708. s++;
  709. for (l = -width; l < 0; l++) {
  710. xrpow[j + l] *= ifqstep34;
  711. if (xrpow[j + l] > cod_info->xrpow_max)
  712. cod_info->xrpow_max = xrpow[j + l];
  713. }
  714. }
  715. cod_info->scalefac[sfb] = s >> 1;
  716. }
  717. cod_info->preflag = 0;
  718. cod_info->scalefac_scale = 1;
  719. }
  720. /*************************************************************************
  721. *
  722. * inc_subblock_gain()
  723. *
  724. * Takehiro Tominaga 2000-xx-xx
  725. *
  726. * increases the subblock gain and adjusts scalefactors
  727. *
  728. *************************************************************************/
  729. static int
  730. inc_subblock_gain(const lame_internal_flags * const gfc, gr_info * const cod_info, FLOAT xrpow[576])
  731. {
  732. int sfb, window;
  733. int *const scalefac = cod_info->scalefac;
  734. /* subbloc_gain can't do anything in the long block region */
  735. for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
  736. if (scalefac[sfb] >= 16)
  737. return 1;
  738. }
  739. for (window = 0; window < 3; window++) {
  740. int s1, s2, l, j;
  741. s1 = s2 = 0;
  742. for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbdivide; sfb += 3) {
  743. if (s1 < scalefac[sfb])
  744. s1 = scalefac[sfb];
  745. }
  746. for (; sfb < cod_info->sfbmax; sfb += 3) {
  747. if (s2 < scalefac[sfb])
  748. s2 = scalefac[sfb];
  749. }
  750. if (s1 < 16 && s2 < 8)
  751. continue;
  752. if (cod_info->subblock_gain[window] >= 7)
  753. return 1;
  754. /* even though there is no scalefactor for sfb12
  755. * subblock gain affects upper frequencies too, that's why
  756. * we have to go up to SBMAX_s
  757. */
  758. cod_info->subblock_gain[window]++;
  759. j = gfc->scalefac_band.l[cod_info->sfb_lmax];
  760. for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbmax; sfb += 3) {
  761. FLOAT amp;
  762. int const width = cod_info->width[sfb];
  763. int s = scalefac[sfb];
  764. assert(s >= 0);
  765. s = s - (4 >> cod_info->scalefac_scale);
  766. if (s >= 0) {
  767. scalefac[sfb] = s;
  768. j += width * 3;
  769. continue;
  770. }
  771. scalefac[sfb] = 0;
  772. {
  773. int const gain = 210 + (s << (cod_info->scalefac_scale + 1));
  774. amp = IPOW20(gain);
  775. }
  776. j += width * (window + 1);
  777. for (l = -width; l < 0; l++) {
  778. xrpow[j + l] *= amp;
  779. if (xrpow[j + l] > cod_info->xrpow_max)
  780. cod_info->xrpow_max = xrpow[j + l];
  781. }
  782. j += width * (3 - window - 1);
  783. }
  784. {
  785. FLOAT const amp = IPOW20(202);
  786. j += cod_info->width[sfb] * (window + 1);
  787. for (l = -cod_info->width[sfb]; l < 0; l++) {
  788. xrpow[j + l] *= amp;
  789. if (xrpow[j + l] > cod_info->xrpow_max)
  790. cod_info->xrpow_max = xrpow[j + l];
  791. }
  792. }
  793. }
  794. return 0;
  795. }
  796. /********************************************************************
  797. *
  798. * balance_noise()
  799. *
  800. * Takehiro Tominaga /date??
  801. * Robert Hegemann 2000-09-06: made a function of it
  802. *
  803. * amplifies scalefactor bands,
  804. * - if all are already amplified returns 0
  805. * - if some bands are amplified too much:
  806. * * try to increase scalefac_scale
  807. * * if already scalefac_scale was set
  808. * try on short blocks to increase subblock gain
  809. *
  810. ********************************************************************/
  811. inline static int
  812. balance_noise(lame_internal_flags * gfc,
  813. gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
  814. {
  815. SessionConfig_t const *const cfg = &gfc->cfg;
  816. int status;
  817. amp_scalefac_bands(gfc, cod_info, distort, xrpow, bRefine);
  818. /* check to make sure we have not amplified too much
  819. * loop_break returns 0 if there is an unamplified scalefac
  820. * scale_bitcount returns 0 if no scalefactors are too large
  821. */
  822. status = loop_break(cod_info);
  823. if (status)
  824. return 0; /* all bands amplified */
  825. /* not all scalefactors have been amplified. so these
  826. * scalefacs are possibly valid. encode them:
  827. */
  828. status = scale_bitcount(gfc, cod_info);
  829. if (!status)
  830. return 1; /* amplified some bands not exceeding limits */
  831. /* some scalefactors are too large.
  832. * lets try setting scalefac_scale=1
  833. */
  834. if (cfg->noise_shaping > 1) {
  835. memset(&gfc->sv_qnt.pseudohalf[0], 0, sizeof(gfc->sv_qnt.pseudohalf));
  836. if (!cod_info->scalefac_scale) {
  837. inc_scalefac_scale(cod_info, xrpow);
  838. status = 0;
  839. }
  840. else {
  841. if (cod_info->block_type == SHORT_TYPE && cfg->subblock_gain > 0) {
  842. status = inc_subblock_gain(gfc, cod_info, xrpow)
  843. || loop_break(cod_info);
  844. }
  845. }
  846. }
  847. if (!status) {
  848. status = scale_bitcount(gfc, cod_info);
  849. }
  850. return !status;
  851. }
  852. /************************************************************************
  853. *
  854. * outer_loop ()
  855. *
  856. * Function: The outer iteration loop controls the masking conditions
  857. * of all scalefactorbands. It computes the best scalefac and
  858. * global gain. This module calls the inner iteration loop
  859. *
  860. * mt 5/99 completely rewritten to allow for bit reservoir control,
  861. * mid/side channels with L/R or mid/side masking thresholds,
  862. * and chooses best quantization instead of last quantization when
  863. * no distortion free quantization can be found.
  864. *
  865. * added VBR support mt 5/99
  866. *
  867. * some code shuffle rh 9/00
  868. ************************************************************************/
  869. static int
  870. outer_loop(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion */
  871. FLOAT xrpow[576], /* coloured magnitudes of spectral */
  872. const int ch, const int targ_bits)
  873. { /* maximum allowed bits */
  874. SessionConfig_t const *const cfg = &gfc->cfg;
  875. gr_info cod_info_w;
  876. FLOAT save_xrpow[576];
  877. FLOAT distort[SFBMAX];
  878. calc_noise_result best_noise_info;
  879. int huff_bits;
  880. int better;
  881. int age;
  882. calc_noise_data prev_noise;
  883. int best_part2_3_length = 9999999;
  884. int bEndOfSearch = 0;
  885. int bRefine = 0;
  886. int best_ggain_pass1 = 0;
  887. (void) bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);
  888. if (!cfg->noise_shaping)
  889. /* fast mode, no noise shaping, we are ready */
  890. return 100; /* default noise_info.over_count */
  891. memset(&prev_noise, 0, sizeof(calc_noise_data));
  892. /* compute the distortion in this quantization */
  893. /* coefficients and thresholds both l/r (or both mid/side) */
  894. (void) calc_noise(cod_info, l3_xmin, distort, &best_noise_info, &prev_noise);
  895. best_noise_info.bits = cod_info->part2_3_length;
  896. cod_info_w = *cod_info;
  897. age = 0;
  898. /* if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */
  899. memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
  900. while (!bEndOfSearch) {
  901. /* BEGIN MAIN LOOP */
  902. do {
  903. calc_noise_result noise_info;
  904. int search_limit;
  905. int maxggain = 255;
  906. /* When quantization with no distorted bands is found,
  907. * allow up to X new unsuccesful tries in serial. This
  908. * gives us more possibilities for different quant_compare modes.
  909. * Much more than 3 makes not a big difference, it is only slower.
  910. */
  911. if (gfc->sv_qnt.substep_shaping & 2) {
  912. search_limit = 20;
  913. }
  914. else {
  915. search_limit = 3;
  916. }
  917. /* Check if the last scalefactor band is distorted.
  918. * in VBR mode we can't get rid of the distortion, so quit now
  919. * and VBR mode will try again with more bits.
  920. * (makes a 10% speed increase, the files I tested were
  921. * binary identical, 2000/05/20 Robert Hegemann)
  922. * distort[] > 1 means noise > allowed noise
  923. */
  924. if (gfc->sv_qnt.sfb21_extra) {
  925. if (distort[cod_info_w.sfbmax] > 1.0)
  926. break;
  927. if (cod_info_w.block_type == SHORT_TYPE
  928. && (distort[cod_info_w.sfbmax + 1] > 1.0
  929. || distort[cod_info_w.sfbmax + 2] > 1.0))
  930. break;
  931. }
  932. /* try a new scalefactor conbination on cod_info_w */
  933. if (balance_noise(gfc, &cod_info_w, distort, xrpow, bRefine) == 0)
  934. break;
  935. if (cod_info_w.scalefac_scale)
  936. maxggain = 254;
  937. /* inner_loop starts with the initial quantization step computed above
  938. * and slowly increases until the bits < huff_bits.
  939. * Thus it is important not to start with too large of an inital
  940. * quantization step. Too small is ok, but inner_loop will take longer
  941. */
  942. huff_bits = targ_bits - cod_info_w.part2_length;
  943. if (huff_bits <= 0)
  944. break;
  945. /* increase quantizer stepsize until needed bits are below maximum
  946. */
  947. while ((cod_info_w.part2_3_length
  948. = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > huff_bits
  949. && cod_info_w.global_gain <= maxggain)
  950. cod_info_w.global_gain++;
  951. if (cod_info_w.global_gain > maxggain)
  952. break;
  953. if (best_noise_info.over_count == 0) {
  954. while ((cod_info_w.part2_3_length
  955. = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > best_part2_3_length
  956. && cod_info_w.global_gain <= maxggain)
  957. cod_info_w.global_gain++;
  958. if (cod_info_w.global_gain > maxggain)
  959. break;
  960. }
  961. /* compute the distortion in this quantization */
  962. (void) calc_noise(&cod_info_w, l3_xmin, distort, &noise_info, &prev_noise);
  963. noise_info.bits = cod_info_w.part2_3_length;
  964. /* check if this quantization is better
  965. * than our saved quantization */
  966. if (cod_info->block_type != SHORT_TYPE) /* NORM, START or STOP type */
  967. better = cfg->quant_comp;
  968. else
  969. better = cfg->quant_comp_short;
  970. better = quant_compare(better, &best_noise_info, &noise_info, &cod_info_w, distort);
  971. /* save data so we can restore this quantization later */
  972. if (better) {
  973. best_part2_3_length = cod_info->part2_3_length;
  974. best_noise_info = noise_info;
  975. *cod_info = cod_info_w;
  976. age = 0;
  977. /* save data so we can restore this quantization later */
  978. /*if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */ {
  979. /* store for later reuse */
  980. memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
  981. }
  982. }
  983. else {
  984. /* early stop? */
  985. if (cfg->full_outer_loop == 0) {
  986. if (++age > search_limit && best_noise_info.over_count == 0)
  987. break;
  988. if ((cfg->noise_shaping_amp == 3) && bRefine && age > 30)
  989. break;
  990. if ((cfg->noise_shaping_amp == 3) && bRefine &&
  991. (cod_info_w.global_gain - best_ggain_pass1) > 15)
  992. break;
  993. }
  994. }
  995. }
  996. while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);
  997. if (cfg->noise_shaping_amp == 3) {
  998. if (!bRefine) {
  999. /* refine search */
  1000. cod_info_w = *cod_info;
  1001. memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
  1002. age = 0;
  1003. best_ggain_pass1 = cod_info_w.global_gain;
  1004. bRefine = 1;
  1005. }
  1006. else {
  1007. /* search already refined, stop */
  1008. bEndOfSearch = 1;
  1009. }
  1010. }
  1011. else {
  1012. bEndOfSearch = 1;
  1013. }
  1014. }
  1015. assert((cod_info->global_gain + cod_info->scalefac_scale) <= 255);
  1016. /* finish up
  1017. */
  1018. if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh || cfg->vbr == vbr_mt)
  1019. /* restore for reuse on next try */
  1020. memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
  1021. /* do the 'substep shaping'
  1022. */
  1023. else if (gfc->sv_qnt.substep_shaping & 1)
  1024. trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);
  1025. return best_noise_info.over_count;
  1026. }
  1027. /************************************************************************
  1028. *
  1029. * iteration_finish_one()
  1030. *
  1031. * Robert Hegemann 2000-09-06
  1032. *
  1033. * update reservoir status after FINAL quantization/bitrate
  1034. *
  1035. ************************************************************************/
  1036. static void
  1037. iteration_finish_one(lame_internal_flags * gfc, int gr, int ch)
  1038. {
  1039. SessionConfig_t const *const cfg = &gfc->cfg;
  1040. III_side_info_t *const l3_side = &gfc->l3_side;
  1041. gr_info *const cod_info = &l3_side->tt[gr][ch];
  1042. /* try some better scalefac storage
  1043. */
  1044. best_scalefac_store(gfc, gr, ch, l3_side);
  1045. /* best huffman_divide may save some bits too
  1046. */
  1047. if (cfg->use_best_huffman == 1)
  1048. best_huffman_divide(gfc, cod_info);
  1049. /* update reservoir status after FINAL quantization/bitrate
  1050. */
  1051. ResvAdjust(gfc, cod_info);
  1052. }
  1053. /*********************************************************************
  1054. *
  1055. * VBR_encode_granule()
  1056. *
  1057. * 2000-09-04 Robert Hegemann
  1058. *
  1059. *********************************************************************/
  1060. static void
  1061. VBR_encode_granule(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion of the scalefactor */
  1062. FLOAT xrpow[576], /* coloured magnitudes of spectral values */
  1063. const int ch, int min_bits, int max_bits)
  1064. {
  1065. gr_info bst_cod_info;
  1066. FLOAT bst_xrpow[576];
  1067. int const Max_bits = max_bits;
  1068. int real_bits = max_bits + 1;
  1069. int this_bits = (max_bits + min_bits) / 2;
  1070. int dbits, over, found = 0;
  1071. int const sfb21_extra = gfc->sv_qnt.sfb21_extra;
  1072. assert(Max_bits <= MAX_BITS_PER_CHANNEL);
  1073. memset(bst_cod_info.l3_enc, 0, sizeof(bst_cod_info.l3_enc));
  1074. /* search within round about 40 bits of optimal
  1075. */
  1076. do {
  1077. assert(this_bits >= min_bits);
  1078. assert(this_bits <= max_bits);
  1079. assert(min_bits <= max_bits);
  1080. if (this_bits > Max_bits - 42)
  1081. gfc->sv_qnt.sfb21_extra = 0;
  1082. else
  1083. gfc->sv_qnt.sfb21_extra = sfb21_extra;
  1084. over = outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, this_bits);
  1085. /* is quantization as good as we are looking for ?
  1086. * in this case: is no scalefactor band distorted?
  1087. */
  1088. if (over <= 0) {
  1089. found = 1;
  1090. /* now we know it can be done with "real_bits"
  1091. * and maybe we can skip some iterations
  1092. */
  1093. real_bits = cod_info->part2_3_length;
  1094. /* store best quantization so far
  1095. */
  1096. bst_cod_info = *cod_info;
  1097. memcpy(bst_xrpow, xrpow, sizeof(FLOAT) * 576);
  1098. /* try with fewer bits
  1099. */
  1100. max_bits = real_bits - 32;
  1101. dbits = max_bits - min_bits;
  1102. this_bits = (max_bits + min_bits) / 2;
  1103. }
  1104. else {
  1105. /* try with more bits
  1106. */
  1107. min_bits = this_bits + 32;
  1108. dbits = max_bits - min_bits;
  1109. this_bits = (max_bits + min_bits) / 2;
  1110. if (found) {
  1111. found = 2;
  1112. /* start again with best quantization so far
  1113. */
  1114. *cod_info = bst_cod_info;
  1115. memcpy(xrpow, bst_xrpow, sizeof(FLOAT) * 576);
  1116. }
  1117. }
  1118. } while (dbits > 12);
  1119. gfc->sv_qnt.sfb21_extra = sfb21_extra;
  1120. /* found=0 => nothing found, use last one
  1121. * found=1 => we just found the best and left the loop
  1122. * found=2 => we restored a good one and have now l3_enc to restore too
  1123. */
  1124. if (found == 2) {
  1125. memcpy(cod_info->l3_enc, bst_cod_info.l3_enc, sizeof(int) * 576);
  1126. }
  1127. assert(cod_info->part2_3_length <= Max_bits);
  1128. }
  1129. /************************************************************************
  1130. *
  1131. * get_framebits()
  1132. *
  1133. * Robert Hegemann 2000-09-05
  1134. *
  1135. * calculates
  1136. * * how many bits are available for analog silent granules
  1137. * * how many bits to use for the lowest allowed bitrate
  1138. * * how many bits each bitrate would provide
  1139. *
  1140. ************************************************************************/
  1141. static void
  1142. get_framebits(lame_internal_flags * gfc, int frameBits[15])
  1143. {
  1144. SessionConfig_t const *const cfg = &gfc->cfg;
  1145. EncResult_t *const eov = &gfc->ov_enc;
  1146. int bitsPerFrame, i;
  1147. /* always use at least this many bits per granule per channel
  1148. * unless we detect analog silence, see below
  1149. */
  1150. eov->bitrate_index = cfg->vbr_min_bitrate_index;
  1151. bitsPerFrame = getframebits(gfc);
  1152. /* bits for analog silence
  1153. */
  1154. eov->bitrate_index = 1;
  1155. bitsPerFrame = getframebits(gfc);
  1156. for (i = 1; i <= cfg->vbr_max_bitrate_index; i++) {
  1157. eov->bitrate_index = i;
  1158. frameBits[i] = ResvFrameBegin(gfc, &bitsPerFrame);
  1159. }
  1160. }
  1161. /*********************************************************************
  1162. *
  1163. * VBR_prepare()
  1164. *
  1165. * 2000-09-04 Robert Hegemann
  1166. *
  1167. * * converts LR to MS coding when necessary
  1168. * * calculates allowed/adjusted quantization noise amounts
  1169. * * detects analog silent frames
  1170. *
  1171. * some remarks:
  1172. * - lower masking depending on Quality setting
  1173. * - quality control together with adjusted ATH MDCT scaling
  1174. * on lower quality setting allocate more noise from
  1175. * ATH masking, and on higher quality setting allocate
  1176. * less noise from ATH masking.
  1177. * - experiments show that going more than 2dB over GPSYCHO's
  1178. * limits ends up in very annoying artefacts
  1179. *
  1180. *********************************************************************/
  1181. /* RH: this one needs to be overhauled sometime */
  1182. static int
  1183. VBR_old_prepare(lame_internal_flags * gfc,
  1184. const FLOAT pe[2][2], FLOAT const ms_ener_ratio[2],
  1185. const III_psy_ratio ratio[2][2],
  1186. FLOAT l3_xmin[2][2][SFBMAX],
  1187. int frameBits[16], int min_bits[2][2], int max_bits[2][2], int bands[2][2])
  1188. {
  1189. SessionConfig_t const *const cfg = &gfc->cfg;
  1190. EncResult_t *const eov = &gfc->ov_enc;
  1191. FLOAT masking_lower_db, adjust = 0.0;
  1192. int gr, ch;
  1193. int analog_silence = 1;
  1194. int avg, mxb, bits = 0;
  1195. eov->bitrate_index = cfg->vbr_max_bitrate_index;
  1196. avg = ResvFrameBegin(gfc, &avg) / cfg->mode_gr;
  1197. get_framebits(gfc, frameBits);
  1198. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1199. mxb = on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
  1200. if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
  1201. ms_convert(&gfc->l3_side, gr);
  1202. reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);
  1203. }
  1204. for (ch = 0; ch < cfg->channels_out; ++ch) {
  1205. gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
  1206. if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
  1207. adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;
  1208. masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
  1209. }
  1210. else {
  1211. adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;
  1212. masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
  1213. }
  1214. gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
  1215. init_outer_loop(gfc, cod_info);
  1216. bands[gr][ch] = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]);
  1217. if (bands[gr][ch])
  1218. analog_silence = 0;
  1219. min_bits[gr][ch] = 126;
  1220. bits += max_bits[gr][ch];
  1221. }
  1222. }
  1223. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1224. for (ch = 0; ch < cfg->channels_out; ch++) {
  1225. if (bits > frameBits[cfg->vbr_max_bitrate_index] && bits > 0) {
  1226. max_bits[gr][ch] *= frameBits[cfg->vbr_max_bitrate_index];
  1227. max_bits[gr][ch] /= bits;
  1228. }
  1229. if (min_bits[gr][ch] > max_bits[gr][ch])
  1230. min_bits[gr][ch] = max_bits[gr][ch];
  1231. } /* for ch */
  1232. } /* for gr */
  1233. return analog_silence;
  1234. }
  1235. static void
  1236. bitpressure_strategy(lame_internal_flags const *gfc,
  1237. FLOAT l3_xmin[2][2][SFBMAX], const int min_bits[2][2], int max_bits[2][2])
  1238. {
  1239. SessionConfig_t const *const cfg = &gfc->cfg;
  1240. int gr, ch, sfb;
  1241. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1242. for (ch = 0; ch < cfg->channels_out; ch++) {
  1243. gr_info const *const gi = &gfc->l3_side.tt[gr][ch];
  1244. FLOAT *pxmin = l3_xmin[gr][ch];
  1245. for (sfb = 0; sfb < gi->psy_lmax; sfb++)
  1246. *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_l / SBMAX_l;
  1247. if (gi->block_type == SHORT_TYPE) {
  1248. for (sfb = gi->sfb_smin; sfb < SBMAX_s; sfb++) {
  1249. *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
  1250. *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
  1251. *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
  1252. }
  1253. }
  1254. max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9 * max_bits[gr][ch]);
  1255. }
  1256. }
  1257. }
  1258. /************************************************************************
  1259. *
  1260. * VBR_iteration_loop()
  1261. *
  1262. * tries to find out how many bits are needed for each granule and channel
  1263. * to get an acceptable quantization. An appropriate bitrate will then be
  1264. * choosed for quantization. rh 8/99
  1265. *
  1266. * Robert Hegemann 2000-09-06 rewrite
  1267. *
  1268. ************************************************************************/
  1269. void
  1270. VBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
  1271. const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
  1272. {
  1273. SessionConfig_t const *const cfg = &gfc->cfg;
  1274. EncResult_t *const eov = &gfc->ov_enc;
  1275. FLOAT l3_xmin[2][2][SFBMAX];
  1276. FLOAT xrpow[576];
  1277. int bands[2][2];
  1278. int frameBits[15];
  1279. int used_bits;
  1280. int bits;
  1281. int min_bits[2][2], max_bits[2][2];
  1282. int mean_bits;
  1283. int ch, gr, analog_silence;
  1284. III_side_info_t *const l3_side = &gfc->l3_side;
  1285. analog_silence = VBR_old_prepare(gfc, pe, ms_ener_ratio, ratio,
  1286. l3_xmin, frameBits, min_bits, max_bits, bands);
  1287. /*---------------------------------*/
  1288. for (;;) {
  1289. /* quantize granules with lowest possible number of bits
  1290. */
  1291. used_bits = 0;
  1292. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1293. for (ch = 0; ch < cfg->channels_out; ch++) {
  1294. int ret;
  1295. gr_info *const cod_info = &l3_side->tt[gr][ch];
  1296. /* init_outer_loop sets up cod_info, scalefac and xrpow
  1297. */
  1298. ret = init_xrpow(gfc, cod_info, xrpow);
  1299. if (ret == 0 || max_bits[gr][ch] == 0) {
  1300. /* xr contains no energy
  1301. * l3_enc, our encoding data, will be quantized to zero
  1302. */
  1303. continue; /* with next channel */
  1304. }
  1305. VBR_encode_granule(gfc, cod_info, l3_xmin[gr][ch], xrpow,
  1306. ch, min_bits[gr][ch], max_bits[gr][ch]);
  1307. /* do the 'substep shaping'
  1308. */
  1309. if (gfc->sv_qnt.substep_shaping & 1) {
  1310. trancate_smallspectrums(gfc, &l3_side->tt[gr][ch], l3_xmin[gr][ch], xrpow);
  1311. }
  1312. ret = cod_info->part2_3_length + cod_info->part2_length;
  1313. used_bits += ret;
  1314. } /* for ch */
  1315. } /* for gr */
  1316. /* find lowest bitrate able to hold used bits
  1317. */
  1318. if (analog_silence && !cfg->enforce_min_bitrate)
  1319. /* we detected analog silence and the user did not specify
  1320. * any hard framesize limit, so start with smallest possible frame
  1321. */
  1322. eov->bitrate_index = 1;
  1323. else
  1324. eov->bitrate_index = cfg->vbr_min_bitrate_index;
  1325. for (; eov->bitrate_index < cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
  1326. if (used_bits <= frameBits[eov->bitrate_index])
  1327. break;
  1328. }
  1329. bits = ResvFrameBegin(gfc, &mean_bits);
  1330. if (used_bits <= bits)
  1331. break;
  1332. bitpressure_strategy(gfc, l3_xmin, (const int (*)[2])min_bits, max_bits);
  1333. } /* breaks adjusted */
  1334. /*--------------------------------------*/
  1335. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1336. for (ch = 0; ch < cfg->channels_out; ch++) {
  1337. iteration_finish_one(gfc, gr, ch);
  1338. } /* for ch */
  1339. } /* for gr */
  1340. ResvFrameEnd(gfc, mean_bits);
  1341. }
  1342. static int
  1343. VBR_new_prepare(lame_internal_flags * gfc,
  1344. const FLOAT pe[2][2], const III_psy_ratio ratio[2][2],
  1345. FLOAT l3_xmin[2][2][SFBMAX], int frameBits[16], int max_bits[2][2],
  1346. int* max_resv)
  1347. {
  1348. SessionConfig_t const *const cfg = &gfc->cfg;
  1349. EncResult_t *const eov = &gfc->ov_enc;
  1350. int gr, ch;
  1351. int analog_silence = 1;
  1352. int avg, bits = 0;
  1353. int maximum_framebits;
  1354. if (!cfg->free_format) {
  1355. eov->bitrate_index = cfg->vbr_max_bitrate_index;
  1356. (void) ResvFrameBegin(gfc, &avg);
  1357. *max_resv = gfc->sv_enc.ResvMax;
  1358. get_framebits(gfc, frameBits);
  1359. maximum_framebits = frameBits[cfg->vbr_max_bitrate_index];
  1360. }
  1361. else {
  1362. eov->bitrate_index = 0;
  1363. maximum_framebits = ResvFrameBegin(gfc, &avg);
  1364. frameBits[0] = maximum_framebits;
  1365. *max_resv = gfc->sv_enc.ResvMax;
  1366. }
  1367. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1368. (void) on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
  1369. if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
  1370. ms_convert(&gfc->l3_side, gr);
  1371. }
  1372. for (ch = 0; ch < cfg->channels_out; ++ch) {
  1373. gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
  1374. gfc->sv_qnt.masking_lower = pow(10.0, gfc->sv_qnt.mask_adjust * 0.1);
  1375. init_outer_loop(gfc, cod_info);
  1376. if (0 != calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]))
  1377. analog_silence = 0;
  1378. bits += max_bits[gr][ch];
  1379. }
  1380. }
  1381. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1382. for (ch = 0; ch < cfg->channels_out; ch++) {
  1383. if (bits > maximum_framebits && bits > 0) {
  1384. max_bits[gr][ch] *= maximum_framebits;
  1385. max_bits[gr][ch] /= bits;
  1386. }
  1387. } /* for ch */
  1388. } /* for gr */
  1389. if (analog_silence) {
  1390. *max_resv = 0;
  1391. }
  1392. return analog_silence;
  1393. }
  1394. void
  1395. VBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
  1396. const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
  1397. {
  1398. SessionConfig_t const *const cfg = &gfc->cfg;
  1399. EncResult_t *const eov = &gfc->ov_enc;
  1400. FLOAT l3_xmin[2][2][SFBMAX];
  1401. FLOAT xrpow[2][2][576];
  1402. int frameBits[15];
  1403. int used_bits;
  1404. int max_bits[2][2];
  1405. int ch, gr, analog_silence, pad;
  1406. III_side_info_t *const l3_side = &gfc->l3_side;
  1407. const FLOAT (*const_l3_xmin)[2][SFBMAX] = (const FLOAT (*)[2][SFBMAX])l3_xmin;
  1408. const FLOAT (*const_xrpow)[2][576] = (const FLOAT (*)[2][576])xrpow;
  1409. const int (*const_max_bits)[2] = (const int (*)[2])max_bits;
  1410. (void) ms_ener_ratio; /* not used */
  1411. memset(xrpow, 0, sizeof(xrpow));
  1412. analog_silence = VBR_new_prepare(gfc, pe, ratio, l3_xmin, frameBits, max_bits, &pad);
  1413. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1414. for (ch = 0; ch < cfg->channels_out; ch++) {
  1415. gr_info *const cod_info = &l3_side->tt[gr][ch];
  1416. /* init_outer_loop sets up cod_info, scalefac and xrpow
  1417. */
  1418. if (0 == init_xrpow(gfc, cod_info, xrpow[gr][ch])) {
  1419. max_bits[gr][ch] = 0; /* silent granule needs no bits */
  1420. }
  1421. } /* for ch */
  1422. } /* for gr */
  1423. /* quantize granules with lowest possible number of bits
  1424. */
  1425. used_bits = VBR_encode_frame(gfc, const_xrpow, const_l3_xmin, const_max_bits);
  1426. if (!cfg->free_format) {
  1427. int i, j;
  1428. /* find lowest bitrate able to hold used bits
  1429. */
  1430. if (analog_silence && !cfg->enforce_min_bitrate) {
  1431. /* we detected analog silence and the user did not specify
  1432. * any hard framesize limit, so start with smallest possible frame
  1433. */
  1434. i = 1;
  1435. }
  1436. else {
  1437. i = cfg->vbr_min_bitrate_index;
  1438. }
  1439. for (; i < cfg->vbr_max_bitrate_index; i++) {
  1440. if (used_bits <= frameBits[i])
  1441. break;
  1442. }
  1443. if (i > cfg->vbr_max_bitrate_index) {
  1444. i = cfg->vbr_max_bitrate_index;
  1445. }
  1446. if (pad > 0) {
  1447. for (j = cfg->vbr_max_bitrate_index; j > i; --j) {
  1448. int const unused = frameBits[j] - used_bits;
  1449. if (unused <= pad)
  1450. break;
  1451. }
  1452. eov->bitrate_index = j;
  1453. }
  1454. else {
  1455. eov->bitrate_index = i;
  1456. }
  1457. }
  1458. else {
  1459. #if 0
  1460. static int mmm = 0;
  1461. int fff = getFramesize_kbps(gfc, used_bits);
  1462. int hhh = getFramesize_kbps(gfc, MAX_BITS_PER_GRANULE * cfg->mode_gr);
  1463. if (mmm < fff)
  1464. mmm = fff;
  1465. printf("demand=%3d kbps max=%3d kbps limit=%3d kbps\n", fff, mmm, hhh);
  1466. #endif
  1467. eov->bitrate_index = 0;
  1468. }
  1469. if (used_bits <= frameBits[eov->bitrate_index]) {
  1470. /* update Reservoire status */
  1471. int mean_bits, fullframebits;
  1472. fullframebits = ResvFrameBegin(gfc, &mean_bits);
  1473. assert(used_bits <= fullframebits);
  1474. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1475. for (ch = 0; ch < cfg->channels_out; ch++) {
  1476. gr_info const *const cod_info = &l3_side->tt[gr][ch];
  1477. ResvAdjust(gfc, cod_info);
  1478. }
  1479. }
  1480. ResvFrameEnd(gfc, mean_bits);
  1481. }
  1482. else {
  1483. /* SHOULD NOT HAPPEN INTERNAL ERROR
  1484. */
  1485. ERRORF(gfc, "INTERNAL ERROR IN VBR NEW CODE, please send bug report\n");
  1486. exit(-1);
  1487. }
  1488. }
  1489. /********************************************************************
  1490. *
  1491. * calc_target_bits()
  1492. *
  1493. * calculates target bits for ABR encoding
  1494. *
  1495. * mt 2000/05/31
  1496. *
  1497. ********************************************************************/
  1498. static void
  1499. calc_target_bits(lame_internal_flags * gfc,
  1500. const FLOAT pe[2][2],
  1501. FLOAT const ms_ener_ratio[2],
  1502. int targ_bits[2][2], int *analog_silence_bits, int *max_frame_bits)
  1503. {
  1504. SessionConfig_t const *const cfg = &gfc->cfg;
  1505. EncResult_t *const eov = &gfc->ov_enc;
  1506. III_side_info_t const *const l3_side = &gfc->l3_side;
  1507. FLOAT res_factor;
  1508. int gr, ch, totbits, mean_bits;
  1509. int framesize = 576 * cfg->mode_gr;
  1510. eov->bitrate_index = cfg->vbr_max_bitrate_index;
  1511. *max_frame_bits = ResvFrameBegin(gfc, &mean_bits);
  1512. eov->bitrate_index = 1;
  1513. mean_bits = getframebits(gfc) - cfg->sideinfo_len * 8;
  1514. *analog_silence_bits = mean_bits / (cfg->mode_gr * cfg->channels_out);
  1515. mean_bits = cfg->vbr_avg_bitrate_kbps * framesize * 1000;
  1516. if (gfc->sv_qnt.substep_shaping & 1)
  1517. mean_bits *= 1.09;
  1518. mean_bits /= cfg->samplerate_out;
  1519. mean_bits -= cfg->sideinfo_len * 8;
  1520. mean_bits /= (cfg->mode_gr * cfg->channels_out);
  1521. /*
  1522. res_factor is the percentage of the target bitrate that should
  1523. be used on average. the remaining bits are added to the
  1524. bitreservoir and used for difficult to encode frames.
  1525. Since we are tracking the average bitrate, we should adjust
  1526. res_factor "on the fly", increasing it if the average bitrate
  1527. is greater than the requested bitrate, and decreasing it
  1528. otherwise. Reasonable ranges are from .9 to 1.0
  1529. Until we get the above suggestion working, we use the following
  1530. tuning:
  1531. compression ratio res_factor
  1532. 5.5 (256kbps) 1.0 no need for bitreservoir
  1533. 11 (128kbps) .93 7% held for reservoir
  1534. with linear interpolation for other values.
  1535. */
  1536. res_factor = .93 + .07 * (11.0 - cfg->compression_ratio) / (11.0 - 5.5);
  1537. if (res_factor < .90)
  1538. res_factor = .90;
  1539. if (res_factor > 1.00)
  1540. res_factor = 1.00;
  1541. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1542. int sum = 0;
  1543. for (ch = 0; ch < cfg->channels_out; ch++) {
  1544. targ_bits[gr][ch] = res_factor * mean_bits;
  1545. if (pe[gr][ch] > 700) {
  1546. int add_bits = (pe[gr][ch] - 700) / 1.4;
  1547. gr_info const *const cod_info = &l3_side->tt[gr][ch];
  1548. targ_bits[gr][ch] = res_factor * mean_bits;
  1549. /* short blocks use a little extra, no matter what the pe */
  1550. if (cod_info->block_type == SHORT_TYPE) {
  1551. if (add_bits < mean_bits / 2)
  1552. add_bits = mean_bits / 2;
  1553. }
  1554. /* at most increase bits by 1.5*average */
  1555. if (add_bits > mean_bits * 3 / 2)
  1556. add_bits = mean_bits * 3 / 2;
  1557. else if (add_bits < 0)
  1558. add_bits = 0;
  1559. targ_bits[gr][ch] += add_bits;
  1560. }
  1561. if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL) {
  1562. targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
  1563. }
  1564. sum += targ_bits[gr][ch];
  1565. } /* for ch */
  1566. if (sum > MAX_BITS_PER_GRANULE) {
  1567. for (ch = 0; ch < cfg->channels_out; ++ch) {
  1568. targ_bits[gr][ch] *= MAX_BITS_PER_GRANULE;
  1569. targ_bits[gr][ch] /= sum;
  1570. }
  1571. }
  1572. } /* for gr */
  1573. if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR)
  1574. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1575. reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits * cfg->channels_out,
  1576. MAX_BITS_PER_GRANULE);
  1577. }
  1578. /* sum target bits
  1579. */
  1580. totbits = 0;
  1581. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1582. for (ch = 0; ch < cfg->channels_out; ch++) {
  1583. if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL)
  1584. targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
  1585. totbits += targ_bits[gr][ch];
  1586. }
  1587. }
  1588. /* repartion target bits if needed
  1589. */
  1590. if (totbits > *max_frame_bits && totbits > 0) {
  1591. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1592. for (ch = 0; ch < cfg->channels_out; ch++) {
  1593. targ_bits[gr][ch] *= *max_frame_bits;
  1594. targ_bits[gr][ch] /= totbits;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. /********************************************************************
  1600. *
  1601. * ABR_iteration_loop()
  1602. *
  1603. * encode a frame with a disired average bitrate
  1604. *
  1605. * mt 2000/05/31
  1606. *
  1607. ********************************************************************/
  1608. void
  1609. ABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
  1610. const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
  1611. {
  1612. SessionConfig_t const *const cfg = &gfc->cfg;
  1613. EncResult_t *const eov = &gfc->ov_enc;
  1614. FLOAT l3_xmin[SFBMAX];
  1615. FLOAT xrpow[576];
  1616. int targ_bits[2][2];
  1617. int mean_bits, max_frame_bits;
  1618. int ch, gr, ath_over;
  1619. int analog_silence_bits;
  1620. gr_info *cod_info;
  1621. III_side_info_t *const l3_side = &gfc->l3_side;
  1622. mean_bits = 0;
  1623. calc_target_bits(gfc, pe, ms_ener_ratio, targ_bits, &analog_silence_bits, &max_frame_bits);
  1624. /* encode granules
  1625. */
  1626. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1627. if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
  1628. ms_convert(&gfc->l3_side, gr);
  1629. }
  1630. for (ch = 0; ch < cfg->channels_out; ch++) {
  1631. FLOAT adjust, masking_lower_db;
  1632. cod_info = &l3_side->tt[gr][ch];
  1633. if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
  1634. /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
  1635. adjust = 0;
  1636. masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
  1637. }
  1638. else {
  1639. /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
  1640. adjust = 0;
  1641. masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
  1642. }
  1643. gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
  1644. /* cod_info, scalefac and xrpow get initialized in init_outer_loop
  1645. */
  1646. init_outer_loop(gfc, cod_info);
  1647. if (init_xrpow(gfc, cod_info, xrpow)) {
  1648. /* xr contains energy we will have to encode
  1649. * calculate the masking abilities
  1650. * find some good quantization in outer_loop
  1651. */
  1652. ath_over = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
  1653. if (0 == ath_over) /* analog silence */
  1654. targ_bits[gr][ch] = analog_silence_bits;
  1655. (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[gr][ch]);
  1656. }
  1657. iteration_finish_one(gfc, gr, ch);
  1658. } /* ch */
  1659. } /* gr */
  1660. /* find a bitrate which can refill the resevoir to positive size.
  1661. */
  1662. for (eov->bitrate_index = cfg->vbr_min_bitrate_index;
  1663. eov->bitrate_index <= cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
  1664. if (ResvFrameBegin(gfc, &mean_bits) >= 0)
  1665. break;
  1666. }
  1667. assert(eov->bitrate_index <= cfg->vbr_max_bitrate_index);
  1668. ResvFrameEnd(gfc, mean_bits);
  1669. }
  1670. /************************************************************************
  1671. *
  1672. * CBR_iteration_loop()
  1673. *
  1674. * author/date??
  1675. *
  1676. * encodes one frame of MP3 data with constant bitrate
  1677. *
  1678. ************************************************************************/
  1679. void
  1680. CBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
  1681. const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
  1682. {
  1683. SessionConfig_t const *const cfg = &gfc->cfg;
  1684. FLOAT l3_xmin[SFBMAX];
  1685. FLOAT xrpow[576];
  1686. int targ_bits[2];
  1687. int mean_bits, max_bits;
  1688. int gr, ch;
  1689. III_side_info_t *const l3_side = &gfc->l3_side;
  1690. gr_info *cod_info;
  1691. (void) ResvFrameBegin(gfc, &mean_bits);
  1692. /* quantize! */
  1693. for (gr = 0; gr < cfg->mode_gr; gr++) {
  1694. /* calculate needed bits
  1695. */
  1696. max_bits = on_pe(gfc, pe, targ_bits, mean_bits, gr, gr);
  1697. if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
  1698. ms_convert(&gfc->l3_side, gr);
  1699. reduce_side(targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);
  1700. }
  1701. for (ch = 0; ch < cfg->channels_out; ch++) {
  1702. FLOAT adjust, masking_lower_db;
  1703. cod_info = &l3_side->tt[gr][ch];
  1704. if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
  1705. /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
  1706. adjust = 0;
  1707. masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
  1708. }
  1709. else {
  1710. /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
  1711. adjust = 0;
  1712. masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
  1713. }
  1714. gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
  1715. /* init_outer_loop sets up cod_info, scalefac and xrpow
  1716. */
  1717. init_outer_loop(gfc, cod_info);
  1718. if (init_xrpow(gfc, cod_info, xrpow)) {
  1719. /* xr contains energy we will have to encode
  1720. * calculate the masking abilities
  1721. * find some good quantization in outer_loop
  1722. */
  1723. (void) calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
  1724. (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[ch]);
  1725. }
  1726. iteration_finish_one(gfc, gr, ch);
  1727. assert(cod_info->part2_3_length <= MAX_BITS_PER_CHANNEL);
  1728. assert(cod_info->part2_3_length <= targ_bits[ch]);
  1729. } /* for ch */
  1730. } /* for gr */
  1731. ResvFrameEnd(gfc, mean_bits);
  1732. }