lame.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665
  1. /* -*- mode: C; mode: fold -*- */
  2. /*
  3. * LAME MP3 encoding engine
  4. *
  5. * Copyright (c) 1999-2000 Mark Taylor
  6. * Copyright (c) 2000-2005 Takehiro Tominaga
  7. * Copyright (c) 2000-2017 Robert Hegemann
  8. * Copyright (c) 2000-2005 Gabriel Bouvigne
  9. * Copyright (c) 2000-2004 Alexander Leidinger
  10. *
  11. * This library is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Library General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2 of the License, or (at your option) any later version.
  15. *
  16. * This library is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Library General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Library General Public
  22. * License along with this library; if not, write to the
  23. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  24. * Boston, MA 02111-1307, USA.
  25. */
  26. /* $Id: lame.c,v 1.377 2017/09/26 12:14:02 robert Exp $ */
  27. #ifdef HAVE_CONFIG_H
  28. # include <config.h>
  29. #endif
  30. #include "lame.h"
  31. #include "machine.h"
  32. #include "encoder.h"
  33. #include "util.h"
  34. #include "lame_global_flags.h"
  35. #include "gain_analysis.h"
  36. #include "bitstream.h"
  37. #include "quantize_pvt.h"
  38. #include "set_get.h"
  39. #include "quantize.h"
  40. #include "psymodel.h"
  41. #include "version.h"
  42. #include "VbrTag.h"
  43. #include "tables.h"
  44. #if defined(__FreeBSD__) && !defined(__alpha__)
  45. #include <floatingpoint.h>
  46. #endif
  47. #ifdef __riscos__
  48. #include "asmstuff.h"
  49. #endif
  50. #ifdef __sun__
  51. /* woraround for SunOS 4.x, it has SEEK_* defined here */
  52. #include <unistd.h>
  53. #endif
  54. #define LAME_DEFAULT_QUALITY 3
  55. int
  56. is_lame_global_flags_valid(const lame_global_flags * gfp)
  57. {
  58. if (gfp == NULL)
  59. return 0;
  60. if (gfp->class_id != LAME_ID)
  61. return 0;
  62. return 1;
  63. }
  64. int
  65. is_lame_internal_flags_valid(const lame_internal_flags * gfc)
  66. {
  67. if (gfc == NULL)
  68. return 0;
  69. if (gfc->class_id != LAME_ID)
  70. return 0;
  71. if (gfc->lame_init_params_successful <=0)
  72. return 0;
  73. return 1;
  74. }
  75. static FLOAT
  76. filter_coef(FLOAT x)
  77. {
  78. if (x > 1.0)
  79. return 0.0;
  80. if (x <= 0.0)
  81. return 1.0;
  82. return cos(PI / 2 * x);
  83. }
  84. static void
  85. lame_init_params_ppflt(lame_internal_flags * gfc)
  86. {
  87. SessionConfig_t *const cfg = &gfc->cfg;
  88. /***************************************************************/
  89. /* compute info needed for polyphase filter (filter type==0, default) */
  90. /***************************************************************/
  91. int band, maxband, minband;
  92. FLOAT freq;
  93. int lowpass_band = 32;
  94. int highpass_band = -1;
  95. if (cfg->lowpass1 > 0) {
  96. minband = 999;
  97. for (band = 0; band <= 31; band++) {
  98. freq = band / 31.0;
  99. /* this band and above will be zeroed: */
  100. if (freq >= cfg->lowpass2) {
  101. lowpass_band = Min(lowpass_band, band);
  102. }
  103. if (cfg->lowpass1 < freq && freq < cfg->lowpass2) {
  104. minband = Min(minband, band);
  105. }
  106. }
  107. /* compute the *actual* transition band implemented by
  108. * the polyphase filter */
  109. if (minband == 999) {
  110. cfg->lowpass1 = (lowpass_band - .75) / 31.0;
  111. }
  112. else {
  113. cfg->lowpass1 = (minband - .75) / 31.0;
  114. }
  115. cfg->lowpass2 = lowpass_band / 31.0;
  116. }
  117. /* make sure highpass filter is within 90% of what the effective
  118. * highpass frequency will be */
  119. if (cfg->highpass2 > 0) {
  120. if (cfg->highpass2 < .9 * (.75 / 31.0)) {
  121. cfg->highpass1 = 0;
  122. cfg->highpass2 = 0;
  123. MSGF(gfc, "Warning: highpass filter disabled. " "highpass frequency too small\n");
  124. }
  125. }
  126. if (cfg->highpass2 > 0) {
  127. maxband = -1;
  128. for (band = 0; band <= 31; band++) {
  129. freq = band / 31.0;
  130. /* this band and below will be zereod */
  131. if (freq <= cfg->highpass1) {
  132. highpass_band = Max(highpass_band, band);
  133. }
  134. if (cfg->highpass1 < freq && freq < cfg->highpass2) {
  135. maxband = Max(maxband, band);
  136. }
  137. }
  138. /* compute the *actual* transition band implemented by
  139. * the polyphase filter */
  140. cfg->highpass1 = highpass_band / 31.0;
  141. if (maxband == -1) {
  142. cfg->highpass2 = (highpass_band + .75) / 31.0;
  143. }
  144. else {
  145. cfg->highpass2 = (maxband + .75) / 31.0;
  146. }
  147. }
  148. for (band = 0; band < 32; band++) {
  149. FLOAT fc1, fc2;
  150. freq = band / 31.0f;
  151. if (cfg->highpass2 > cfg->highpass1) {
  152. fc1 = filter_coef((cfg->highpass2 - freq) / (cfg->highpass2 - cfg->highpass1 + 1e-20));
  153. }
  154. else {
  155. fc1 = 1.0f;
  156. }
  157. if (cfg->lowpass2 > cfg->lowpass1) {
  158. fc2 = filter_coef((freq - cfg->lowpass1) / (cfg->lowpass2 - cfg->lowpass1 + 1e-20));
  159. }
  160. else {
  161. fc2 = 1.0f;
  162. }
  163. gfc->sv_enc.amp_filter[band] = fc1 * fc2;
  164. }
  165. }
  166. static void
  167. optimum_bandwidth(double *const lowerlimit, double *const upperlimit, const unsigned bitrate)
  168. {
  169. /*
  170. * Input:
  171. * bitrate total bitrate in kbps
  172. *
  173. * Output:
  174. * lowerlimit: best lowpass frequency limit for input filter in Hz
  175. * upperlimit: best highpass frequency limit for input filter in Hz
  176. */
  177. int table_index;
  178. typedef struct {
  179. int bitrate; /* only indicative value */
  180. int lowpass;
  181. } band_pass_t;
  182. const band_pass_t freq_map[] = {
  183. {8, 2000},
  184. {16, 3700},
  185. {24, 3900},
  186. {32, 5500},
  187. {40, 7000},
  188. {48, 7500},
  189. {56, 10000},
  190. {64, 11000},
  191. {80, 13500},
  192. {96, 15100},
  193. {112, 15600},
  194. {128, 17000},
  195. {160, 17500},
  196. {192, 18600},
  197. {224, 19400},
  198. {256, 19700},
  199. {320, 20500}
  200. };
  201. table_index = nearestBitrateFullIndex(bitrate);
  202. (void) freq_map[table_index].bitrate;
  203. *lowerlimit = freq_map[table_index].lowpass;
  204. /*
  205. * Now we try to choose a good high pass filtering frequency.
  206. * This value is currently not used.
  207. * For fu < 16 kHz: sqrt(fu*fl) = 560 Hz
  208. * For fu = 18 kHz: no high pass filtering
  209. * This gives:
  210. *
  211. * 2 kHz => 160 Hz
  212. * 3 kHz => 107 Hz
  213. * 4 kHz => 80 Hz
  214. * 8 kHz => 40 Hz
  215. * 16 kHz => 20 Hz
  216. * 17 kHz => 10 Hz
  217. * 18 kHz => 0 Hz
  218. *
  219. * These are ad hoc values and these can be optimized if a high pass is available.
  220. */
  221. /* if (f_low <= 16000)
  222. f_high = 16000. * 20. / f_low;
  223. else if (f_low <= 18000)
  224. f_high = 180. - 0.01 * f_low;
  225. else
  226. f_high = 0.;*/
  227. /*
  228. * When we sometimes have a good highpass filter, we can add the highpass
  229. * frequency to the lowpass frequency
  230. */
  231. /*if (upperlimit != NULL)
  232. *upperlimit = f_high;*/
  233. (void) upperlimit;
  234. }
  235. static int
  236. optimum_samplefreq(int lowpassfreq, int input_samplefreq)
  237. {
  238. /*
  239. * Rules:
  240. * - if possible, sfb21 should NOT be used
  241. *
  242. */
  243. int suggested_samplefreq = 44100;
  244. if (input_samplefreq >= 48000)
  245. suggested_samplefreq = 48000;
  246. else if (input_samplefreq >= 44100)
  247. suggested_samplefreq = 44100;
  248. else if (input_samplefreq >= 32000)
  249. suggested_samplefreq = 32000;
  250. else if (input_samplefreq >= 24000)
  251. suggested_samplefreq = 24000;
  252. else if (input_samplefreq >= 22050)
  253. suggested_samplefreq = 22050;
  254. else if (input_samplefreq >= 16000)
  255. suggested_samplefreq = 16000;
  256. else if (input_samplefreq >= 12000)
  257. suggested_samplefreq = 12000;
  258. else if (input_samplefreq >= 11025)
  259. suggested_samplefreq = 11025;
  260. else if (input_samplefreq >= 8000)
  261. suggested_samplefreq = 8000;
  262. if (lowpassfreq == -1)
  263. return suggested_samplefreq;
  264. if (lowpassfreq <= 15960)
  265. suggested_samplefreq = 44100;
  266. if (lowpassfreq <= 15250)
  267. suggested_samplefreq = 32000;
  268. if (lowpassfreq <= 11220)
  269. suggested_samplefreq = 24000;
  270. if (lowpassfreq <= 9970)
  271. suggested_samplefreq = 22050;
  272. if (lowpassfreq <= 7230)
  273. suggested_samplefreq = 16000;
  274. if (lowpassfreq <= 5420)
  275. suggested_samplefreq = 12000;
  276. if (lowpassfreq <= 4510)
  277. suggested_samplefreq = 11025;
  278. if (lowpassfreq <= 3970)
  279. suggested_samplefreq = 8000;
  280. if (input_samplefreq < suggested_samplefreq) {
  281. /* choose a valid MPEG sample frequency above the input sample frequency
  282. to avoid SFB21/12 bitrate bloat
  283. rh 061115
  284. */
  285. if (input_samplefreq > 44100) {
  286. return 48000;
  287. }
  288. if (input_samplefreq > 32000) {
  289. return 44100;
  290. }
  291. if (input_samplefreq > 24000) {
  292. return 32000;
  293. }
  294. if (input_samplefreq > 22050) {
  295. return 24000;
  296. }
  297. if (input_samplefreq > 16000) {
  298. return 22050;
  299. }
  300. if (input_samplefreq > 12000) {
  301. return 16000;
  302. }
  303. if (input_samplefreq > 11025) {
  304. return 12000;
  305. }
  306. if (input_samplefreq > 8000) {
  307. return 11025;
  308. }
  309. return 8000;
  310. }
  311. return suggested_samplefreq;
  312. }
  313. /* set internal feature flags. USER should not access these since
  314. * some combinations will produce strange results */
  315. static void
  316. lame_init_qval(lame_global_flags * gfp)
  317. {
  318. lame_internal_flags *const gfc = gfp->internal_flags;
  319. SessionConfig_t *const cfg = &gfc->cfg;
  320. switch (gfp->quality) {
  321. default:
  322. case 9: /* no psymodel, no noise shaping */
  323. cfg->noise_shaping = 0;
  324. cfg->noise_shaping_amp = 0;
  325. cfg->noise_shaping_stop = 0;
  326. cfg->use_best_huffman = 0;
  327. cfg->full_outer_loop = 0;
  328. break;
  329. case 8:
  330. gfp->quality = 7;
  331. /*lint --fallthrough */
  332. case 7: /* use psymodel (for short block and m/s switching), but no noise shapping */
  333. cfg->noise_shaping = 0;
  334. cfg->noise_shaping_amp = 0;
  335. cfg->noise_shaping_stop = 0;
  336. cfg->use_best_huffman = 0;
  337. cfg->full_outer_loop = 0;
  338. if (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) {
  339. cfg->full_outer_loop = -1;
  340. }
  341. break;
  342. case 6:
  343. if (cfg->noise_shaping == 0)
  344. cfg->noise_shaping = 1;
  345. cfg->noise_shaping_amp = 0;
  346. cfg->noise_shaping_stop = 0;
  347. if (cfg->subblock_gain == -1)
  348. cfg->subblock_gain = 1;
  349. cfg->use_best_huffman = 0;
  350. cfg->full_outer_loop = 0;
  351. break;
  352. case 5:
  353. if (cfg->noise_shaping == 0)
  354. cfg->noise_shaping = 1;
  355. cfg->noise_shaping_amp = 0;
  356. cfg->noise_shaping_stop = 0;
  357. if (cfg->subblock_gain == -1)
  358. cfg->subblock_gain = 1;
  359. cfg->use_best_huffman = 0;
  360. cfg->full_outer_loop = 0;
  361. break;
  362. case 4:
  363. if (cfg->noise_shaping == 0)
  364. cfg->noise_shaping = 1;
  365. cfg->noise_shaping_amp = 0;
  366. cfg->noise_shaping_stop = 0;
  367. if (cfg->subblock_gain == -1)
  368. cfg->subblock_gain = 1;
  369. cfg->use_best_huffman = 1;
  370. cfg->full_outer_loop = 0;
  371. break;
  372. case 3:
  373. if (cfg->noise_shaping == 0)
  374. cfg->noise_shaping = 1;
  375. cfg->noise_shaping_amp = 1;
  376. cfg->noise_shaping_stop = 1;
  377. if (cfg->subblock_gain == -1)
  378. cfg->subblock_gain = 1;
  379. cfg->use_best_huffman = 1;
  380. cfg->full_outer_loop = 0;
  381. break;
  382. case 2:
  383. if (cfg->noise_shaping == 0)
  384. cfg->noise_shaping = 1;
  385. if (gfc->sv_qnt.substep_shaping == 0)
  386. gfc->sv_qnt.substep_shaping = 2;
  387. cfg->noise_shaping_amp = 1;
  388. cfg->noise_shaping_stop = 1;
  389. if (cfg->subblock_gain == -1)
  390. cfg->subblock_gain = 1;
  391. cfg->use_best_huffman = 1; /* inner loop */
  392. cfg->full_outer_loop = 0;
  393. break;
  394. case 1:
  395. if (cfg->noise_shaping == 0)
  396. cfg->noise_shaping = 1;
  397. if (gfc->sv_qnt.substep_shaping == 0)
  398. gfc->sv_qnt.substep_shaping = 2;
  399. cfg->noise_shaping_amp = 2;
  400. cfg->noise_shaping_stop = 1;
  401. if (cfg->subblock_gain == -1)
  402. cfg->subblock_gain = 1;
  403. cfg->use_best_huffman = 1;
  404. cfg->full_outer_loop = 0;
  405. break;
  406. case 0:
  407. if (cfg->noise_shaping == 0)
  408. cfg->noise_shaping = 1;
  409. if (gfc->sv_qnt.substep_shaping == 0)
  410. gfc->sv_qnt.substep_shaping = 2;
  411. cfg->noise_shaping_amp = 2;
  412. cfg->noise_shaping_stop = 1;
  413. if (cfg->subblock_gain == -1)
  414. cfg->subblock_gain = 1;
  415. cfg->use_best_huffman = 1; /*type 2 disabled because of it slowness,
  416. in favor of full outer loop search */
  417. cfg->full_outer_loop = 1;
  418. break;
  419. }
  420. }
  421. static double
  422. linear_int(double a, double b, double m)
  423. {
  424. return a + m * (b - a);
  425. }
  426. /********************************************************************
  427. * initialize internal params based on data in gf
  428. * (globalflags struct filled in by calling program)
  429. *
  430. * OUTLINE:
  431. *
  432. * We first have some complex code to determine bitrate,
  433. * output samplerate and mode. It is complicated by the fact
  434. * that we allow the user to set some or all of these parameters,
  435. * and need to determine best possible values for the rest of them:
  436. *
  437. * 1. set some CPU related flags
  438. * 2. check if we are mono->mono, stereo->mono or stereo->stereo
  439. * 3. compute bitrate and output samplerate:
  440. * user may have set compression ratio
  441. * user may have set a bitrate
  442. * user may have set a output samplerate
  443. * 4. set some options which depend on output samplerate
  444. * 5. compute the actual compression ratio
  445. * 6. set mode based on compression ratio
  446. *
  447. * The remaining code is much simpler - it just sets options
  448. * based on the mode & compression ratio:
  449. *
  450. * set allow_diff_short based on mode
  451. * select lowpass filter based on compression ratio & mode
  452. * set the bitrate index, and min/max bitrates for VBR modes
  453. * disable VBR tag if it is not appropriate
  454. * initialize the bitstream
  455. * initialize scalefac_band data
  456. * set sideinfo_len (based on channels, CRC, out_samplerate)
  457. * write an id3v2 tag into the bitstream
  458. * write VBR tag into the bitstream
  459. * set mpeg1/2 flag
  460. * estimate the number of frames (based on a lot of data)
  461. *
  462. * now we set more flags:
  463. * nspsytune:
  464. * see code
  465. * VBR modes
  466. * see code
  467. * CBR/ABR
  468. * see code
  469. *
  470. * Finally, we set the algorithm flags based on the gfp->quality value
  471. * lame_init_qval(gfp);
  472. *
  473. ********************************************************************/
  474. int
  475. lame_init_params(lame_global_flags * gfp)
  476. {
  477. int i;
  478. int j;
  479. lame_internal_flags *gfc;
  480. SessionConfig_t *cfg;
  481. if (!is_lame_global_flags_valid(gfp))
  482. return -1;
  483. gfc = gfp->internal_flags;
  484. if (gfc == 0)
  485. return -1;
  486. if (is_lame_internal_flags_valid(gfc))
  487. return -1; /* already initialized */
  488. /* start updating lame internal flags */
  489. gfc->class_id = LAME_ID;
  490. gfc->lame_init_params_successful = 0; /* will be set to one, when we get through until the end */
  491. if (gfp->samplerate_in < 1)
  492. return -1; /* input sample rate makes no sense */
  493. if (gfp->num_channels < 1 || 2 < gfp->num_channels)
  494. return -1; /* number of input channels makes no sense */
  495. if (gfp->samplerate_out != 0) {
  496. int v=0;
  497. if (SmpFrqIndex(gfp->samplerate_out, &v) < 0)
  498. return -1; /* output sample rate makes no sense */
  499. }
  500. cfg = &gfc->cfg;
  501. cfg->enforce_min_bitrate = gfp->VBR_hard_min;
  502. cfg->analysis = gfp->analysis;
  503. if (cfg->analysis)
  504. gfp->write_lame_tag = 0;
  505. /* some file options not allowed if output is: not specified or stdout */
  506. if (gfc->pinfo != NULL)
  507. gfp->write_lame_tag = 0; /* disable Xing VBR tag */
  508. /* report functions */
  509. gfc->report_msg = gfp->report.msgf;
  510. gfc->report_dbg = gfp->report.debugf;
  511. gfc->report_err = gfp->report.errorf;
  512. if (gfp->asm_optimizations.amd3dnow)
  513. gfc->CPU_features.AMD_3DNow = has_3DNow();
  514. else
  515. gfc->CPU_features.AMD_3DNow = 0;
  516. if (gfp->asm_optimizations.mmx)
  517. gfc->CPU_features.MMX = has_MMX();
  518. else
  519. gfc->CPU_features.MMX = 0;
  520. if (gfp->asm_optimizations.sse) {
  521. gfc->CPU_features.SSE = has_SSE();
  522. gfc->CPU_features.SSE2 = has_SSE2();
  523. }
  524. else {
  525. gfc->CPU_features.SSE = 0;
  526. gfc->CPU_features.SSE2 = 0;
  527. }
  528. cfg->vbr = gfp->VBR;
  529. cfg->error_protection = gfp->error_protection;
  530. cfg->copyright = gfp->copyright;
  531. cfg->original = gfp->original;
  532. cfg->extension = gfp->extension;
  533. cfg->emphasis = gfp->emphasis;
  534. cfg->channels_in = gfp->num_channels;
  535. if (cfg->channels_in == 1)
  536. gfp->mode = MONO;
  537. cfg->channels_out = (gfp->mode == MONO) ? 1 : 2;
  538. if (gfp->mode != JOINT_STEREO)
  539. gfp->force_ms = 0; /* forced mid/side stereo for j-stereo only */
  540. cfg->force_ms = gfp->force_ms;
  541. if (cfg->vbr == vbr_off && gfp->VBR_mean_bitrate_kbps != 128 && gfp->brate == 0)
  542. gfp->brate = gfp->VBR_mean_bitrate_kbps;
  543. switch (cfg->vbr) {
  544. case vbr_off:
  545. case vbr_mtrh:
  546. case vbr_mt:
  547. /* these modes can handle free format condition */
  548. break;
  549. default:
  550. gfp->free_format = 0; /* mode can't be mixed with free format */
  551. break;
  552. }
  553. cfg->free_format = gfp->free_format;
  554. if (cfg->vbr == vbr_off && gfp->brate == 0) {
  555. /* no bitrate or compression ratio specified, use 11.025 */
  556. if (EQ(gfp->compression_ratio, 0))
  557. gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */
  558. }
  559. /* find bitrate if user specify a compression ratio */
  560. if (cfg->vbr == vbr_off && gfp->compression_ratio > 0) {
  561. if (gfp->samplerate_out == 0)
  562. gfp->samplerate_out = map2MP3Frequency((int) (0.97 * gfp->samplerate_in)); /* round up with a margin of 3% */
  563. /* choose a bitrate for the output samplerate which achieves
  564. * specified compression ratio
  565. */
  566. gfp->brate = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->compression_ratio);
  567. /* we need the version for the bitrate table look up */
  568. cfg->samplerate_index = SmpFrqIndex(gfp->samplerate_out, &cfg->version);
  569. assert(cfg->samplerate_index >=0);
  570. if (!cfg->free_format) /* for non Free Format find the nearest allowed bitrate */
  571. gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, gfp->samplerate_out);
  572. }
  573. if (gfp->samplerate_out) {
  574. if (gfp->samplerate_out < 16000) {
  575. gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
  576. gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 64);
  577. }
  578. else if (gfp->samplerate_out < 32000) {
  579. gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
  580. gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 160);
  581. }
  582. else {
  583. gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 32);
  584. gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 320);
  585. }
  586. }
  587. /* WORK IN PROGRESS */
  588. /* mapping VBR scale to internal VBR quality settings */
  589. if (gfp->samplerate_out == 0 && (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh)) {
  590. float const qval = gfp->VBR_q + gfp->VBR_q_frac;
  591. struct q_map { int sr_a; float qa, qb, ta, tb; int lp; };
  592. struct q_map const m[9]
  593. = { {48000, 0.0,6.5, 0.0,6.5, 23700}
  594. , {44100, 0.0,6.5, 0.0,6.5, 21780}
  595. , {32000, 6.5,8.0, 5.2,6.5, 15800}
  596. , {24000, 8.0,8.5, 5.2,6.0, 11850}
  597. , {22050, 8.5,9.01, 5.2,6.5, 10892}
  598. , {16000, 9.01,9.4, 4.9,6.5, 7903}
  599. , {12000, 9.4,9.6, 4.5,6.0, 5928}
  600. , {11025, 9.6,9.9, 5.1,6.5, 5446}
  601. , { 8000, 9.9,10., 4.9,6.5, 3952}
  602. };
  603. for (i = 2; i < 9; ++i) {
  604. if (gfp->samplerate_in == m[i].sr_a) {
  605. if (qval < m[i].qa) {
  606. double d = qval / m[i].qa;
  607. d = d * m[i].ta;
  608. gfp->VBR_q = (int)d;
  609. gfp->VBR_q_frac = d - gfp->VBR_q;
  610. }
  611. }
  612. if (gfp->samplerate_in >= m[i].sr_a) {
  613. if (m[i].qa <= qval && qval < m[i].qb) {
  614. float const q_ = m[i].qb-m[i].qa;
  615. float const t_ = m[i].tb-m[i].ta;
  616. double d = m[i].ta + t_ * (qval-m[i].qa) / q_;
  617. gfp->VBR_q = (int)d;
  618. gfp->VBR_q_frac = d - gfp->VBR_q;
  619. gfp->samplerate_out = m[i].sr_a;
  620. if (gfp->lowpassfreq == 0) {
  621. gfp->lowpassfreq = -1;
  622. }
  623. break;
  624. }
  625. }
  626. }
  627. }
  628. /****************************************************************/
  629. /* if a filter has not been enabled, see if we should add one: */
  630. /****************************************************************/
  631. if (gfp->lowpassfreq == 0) {
  632. double lowpass = 16000;
  633. double highpass;
  634. switch (cfg->vbr) {
  635. case vbr_off:{
  636. optimum_bandwidth(&lowpass, &highpass, gfp->brate);
  637. break;
  638. }
  639. case vbr_abr:{
  640. optimum_bandwidth(&lowpass, &highpass, gfp->VBR_mean_bitrate_kbps);
  641. break;
  642. }
  643. case vbr_rh:{
  644. int const x[11] = {
  645. 19500, 19000, 18600, 18000, 17500, 16000, 15600, 14900, 12500, 10000, 3950
  646. };
  647. if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
  648. double a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
  649. lowpass = linear_int(a, b, m);
  650. }
  651. else {
  652. lowpass = 19500;
  653. }
  654. break;
  655. }
  656. case vbr_mtrh:
  657. case vbr_mt:{
  658. int const x[11] = {
  659. 24000, 19500, 18500, 18000, 17500, 17000, 16500, 15600, 15200, 7230, 3950
  660. };
  661. if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
  662. double a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
  663. lowpass = linear_int(a, b, m);
  664. }
  665. else {
  666. lowpass = 21500;
  667. }
  668. break;
  669. }
  670. default:{
  671. int const x[11] = {
  672. 19500, 19000, 18500, 18000, 17500, 16500, 15500, 14500, 12500, 9500, 3950
  673. };
  674. if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
  675. double a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
  676. lowpass = linear_int(a, b, m);
  677. }
  678. else {
  679. lowpass = 19500;
  680. }
  681. }
  682. }
  683. if (gfp->mode == MONO && (cfg->vbr == vbr_off || cfg->vbr == vbr_abr))
  684. lowpass *= 1.5;
  685. gfp->lowpassfreq = lowpass;
  686. }
  687. if (gfp->samplerate_out == 0) {
  688. if (2 * gfp->lowpassfreq > gfp->samplerate_in) {
  689. gfp->lowpassfreq = gfp->samplerate_in / 2;
  690. }
  691. gfp->samplerate_out = optimum_samplefreq((int) gfp->lowpassfreq, gfp->samplerate_in);
  692. }
  693. if (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) {
  694. gfp->lowpassfreq = Min(24000, gfp->lowpassfreq);
  695. }
  696. else {
  697. gfp->lowpassfreq = Min(20500, gfp->lowpassfreq);
  698. }
  699. gfp->lowpassfreq = Min(gfp->samplerate_out / 2, gfp->lowpassfreq);
  700. if (cfg->vbr == vbr_off) {
  701. gfp->compression_ratio = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
  702. }
  703. if (cfg->vbr == vbr_abr) {
  704. gfp->compression_ratio =
  705. gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
  706. }
  707. cfg->disable_reservoir = gfp->disable_reservoir;
  708. cfg->lowpassfreq = gfp->lowpassfreq;
  709. cfg->highpassfreq = gfp->highpassfreq;
  710. cfg->samplerate_in = gfp->samplerate_in;
  711. cfg->samplerate_out = gfp->samplerate_out;
  712. cfg->mode_gr = cfg->samplerate_out <= 24000 ? 1 : 2; /* Number of granules per frame */
  713. /*
  714. * sample freq bitrate compression ratio
  715. * [kHz] [kbps/channel] for 16 bit input
  716. * 44.1 56 12.6
  717. * 44.1 64 11.025
  718. * 44.1 80 8.82
  719. * 22.05 24 14.7
  720. * 22.05 32 11.025
  721. * 22.05 40 8.82
  722. * 16 16 16.0
  723. * 16 24 10.667
  724. *
  725. */
  726. /*
  727. * For VBR, take a guess at the compression_ratio.
  728. * For example:
  729. *
  730. * VBR_q compression like
  731. * - 4.4 320 kbps/44 kHz
  732. * 0...1 5.5 256 kbps/44 kHz
  733. * 2 7.3 192 kbps/44 kHz
  734. * 4 8.8 160 kbps/44 kHz
  735. * 6 11 128 kbps/44 kHz
  736. * 9 14.7 96 kbps
  737. *
  738. * for lower bitrates, downsample with --resample
  739. */
  740. switch (cfg->vbr) {
  741. case vbr_mt:
  742. case vbr_rh:
  743. case vbr_mtrh:
  744. {
  745. /*numbers are a bit strange, but they determine the lowpass value */
  746. FLOAT const cmp[] = { 5.7, 6.5, 7.3, 8.2, 10, 11.9, 13, 14, 15, 16.5 };
  747. gfp->compression_ratio = cmp[gfp->VBR_q];
  748. }
  749. break;
  750. case vbr_abr:
  751. gfp->compression_ratio =
  752. cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
  753. break;
  754. default:
  755. gfp->compression_ratio = cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
  756. break;
  757. }
  758. /* mode = -1 (not set by user) or
  759. * mode = MONO (because of only 1 input channel).
  760. * If mode has not been set, then select J-STEREO
  761. */
  762. if (gfp->mode == NOT_SET) {
  763. gfp->mode = JOINT_STEREO;
  764. }
  765. cfg->mode = gfp->mode;
  766. /* apply user driven high pass filter */
  767. if (cfg->highpassfreq > 0) {
  768. cfg->highpass1 = 2. * cfg->highpassfreq;
  769. if (gfp->highpasswidth >= 0)
  770. cfg->highpass2 = 2. * (cfg->highpassfreq + gfp->highpasswidth);
  771. else /* 0% above on default */
  772. cfg->highpass2 = (1 + 0.00) * 2. * cfg->highpassfreq;
  773. cfg->highpass1 /= cfg->samplerate_out;
  774. cfg->highpass2 /= cfg->samplerate_out;
  775. }
  776. else {
  777. cfg->highpass1 = 0;
  778. cfg->highpass2 = 0;
  779. }
  780. /* apply user driven low pass filter */
  781. cfg->lowpass1 = 0;
  782. cfg->lowpass2 = 0;
  783. if (cfg->lowpassfreq > 0 && cfg->lowpassfreq < (cfg->samplerate_out / 2) ) {
  784. cfg->lowpass2 = 2. * cfg->lowpassfreq;
  785. if (gfp->lowpasswidth >= 0) {
  786. cfg->lowpass1 = 2. * (cfg->lowpassfreq - gfp->lowpasswidth);
  787. if (cfg->lowpass1 < 0) /* has to be >= 0 */
  788. cfg->lowpass1 = 0;
  789. }
  790. else { /* 0% below on default */
  791. cfg->lowpass1 = (1 - 0.00) * 2. * cfg->lowpassfreq;
  792. }
  793. cfg->lowpass1 /= cfg->samplerate_out;
  794. cfg->lowpass2 /= cfg->samplerate_out;
  795. }
  796. /**********************************************************************/
  797. /* compute info needed for polyphase filter (filter type==0, default) */
  798. /**********************************************************************/
  799. lame_init_params_ppflt(gfc);
  800. /*******************************************************
  801. * samplerate and bitrate index
  802. *******************************************************/
  803. cfg->samplerate_index = SmpFrqIndex(cfg->samplerate_out, &cfg->version);
  804. assert(cfg->samplerate_index >= 0);
  805. if (cfg->vbr == vbr_off) {
  806. if (cfg->free_format) {
  807. gfc->ov_enc.bitrate_index = 0;
  808. }
  809. else {
  810. gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, cfg->samplerate_out);
  811. gfc->ov_enc.bitrate_index = BitrateIndex(gfp->brate, cfg->version, cfg->samplerate_out);
  812. if (gfc->ov_enc.bitrate_index <= 0) {
  813. /* This never happens, because of preceding FindNearestBitrate!
  814. * But, set a sane value, just in case
  815. */
  816. assert(0);
  817. gfc->ov_enc.bitrate_index = 8;
  818. }
  819. }
  820. }
  821. else {
  822. gfc->ov_enc.bitrate_index = 1;
  823. }
  824. init_bit_stream_w(gfc);
  825. j = cfg->samplerate_index + (3 * cfg->version) + 6 * (cfg->samplerate_out < 16000);
  826. for (i = 0; i < SBMAX_l + 1; i++)
  827. gfc->scalefac_band.l[i] = sfBandIndex[j].l[i];
  828. for (i = 0; i < PSFB21 + 1; i++) {
  829. int const size = (gfc->scalefac_band.l[22] - gfc->scalefac_band.l[21]) / PSFB21;
  830. int const start = gfc->scalefac_band.l[21] + i * size;
  831. gfc->scalefac_band.psfb21[i] = start;
  832. }
  833. gfc->scalefac_band.psfb21[PSFB21] = 576;
  834. for (i = 0; i < SBMAX_s + 1; i++)
  835. gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];
  836. for (i = 0; i < PSFB12 + 1; i++) {
  837. int const size = (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) / PSFB12;
  838. int const start = gfc->scalefac_band.s[12] + i * size;
  839. gfc->scalefac_band.psfb12[i] = start;
  840. }
  841. gfc->scalefac_band.psfb12[PSFB12] = 192;
  842. /* determine the mean bitrate for main data */
  843. if (cfg->mode_gr == 2) /* MPEG 1 */
  844. cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 17 : 4 + 32;
  845. else /* MPEG 2 */
  846. cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 9 : 4 + 17;
  847. if (cfg->error_protection)
  848. cfg->sideinfo_len += 2;
  849. {
  850. int k;
  851. for (k = 0; k < 19; k++)
  852. gfc->sv_enc.pefirbuf[k] = 700 * cfg->mode_gr * cfg->channels_out;
  853. if (gfp->ATHtype == -1)
  854. gfp->ATHtype = 4;
  855. }
  856. assert(gfp->VBR_q <= 9);
  857. assert(gfp->VBR_q >= 0);
  858. switch (cfg->vbr) {
  859. case vbr_mt:
  860. case vbr_mtrh:{
  861. if (gfp->strict_ISO < 0) {
  862. gfp->strict_ISO = MDB_MAXIMUM;
  863. }
  864. if (gfp->useTemporal < 0) {
  865. gfp->useTemporal = 0; /* off by default for this VBR mode */
  866. }
  867. (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
  868. /* The newer VBR code supports only a limited
  869. subset of quality levels:
  870. 9-5=5 are the same, uses x^3/4 quantization
  871. 4-0=0 are the same 5 plus best huffman divide code
  872. */
  873. if (gfp->quality < 0)
  874. gfp->quality = LAME_DEFAULT_QUALITY;
  875. if (gfp->quality < 5)
  876. gfp->quality = 0;
  877. if (gfp->quality > 7)
  878. gfp->quality = 7;
  879. /* sfb21 extra only with MPEG-1 at higher sampling rates
  880. */
  881. if (gfp->experimentalY)
  882. gfc->sv_qnt.sfb21_extra = 0;
  883. else
  884. gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
  885. break;
  886. }
  887. case vbr_rh:{
  888. (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
  889. /* sfb21 extra only with MPEG-1 at higher sampling rates
  890. */
  891. if (gfp->experimentalY)
  892. gfc->sv_qnt.sfb21_extra = 0;
  893. else
  894. gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
  895. /* VBR needs at least the output of GPSYCHO,
  896. * so we have to garantee that by setting a minimum
  897. * quality level, actually level 6 does it.
  898. * down to level 6
  899. */
  900. if (gfp->quality > 6)
  901. gfp->quality = 6;
  902. if (gfp->quality < 0)
  903. gfp->quality = LAME_DEFAULT_QUALITY;
  904. break;
  905. }
  906. default: /* cbr/abr */ {
  907. /* no sfb21 extra with CBR code
  908. */
  909. gfc->sv_qnt.sfb21_extra = 0;
  910. if (gfp->quality < 0)
  911. gfp->quality = LAME_DEFAULT_QUALITY;
  912. if (cfg->vbr == vbr_off)
  913. (void) lame_set_VBR_mean_bitrate_kbps(gfp, gfp->brate);
  914. /* second, set parameters depending on bitrate */
  915. (void) apply_preset(gfp, gfp->VBR_mean_bitrate_kbps, 0);
  916. gfp->VBR = cfg->vbr;
  917. break;
  918. }
  919. }
  920. /*initialize default values common for all modes */
  921. gfc->sv_qnt.mask_adjust = gfp->maskingadjust;
  922. gfc->sv_qnt.mask_adjust_short = gfp->maskingadjust_short;
  923. /* just another daily changing developer switch */
  924. if (gfp->tune) {
  925. gfc->sv_qnt.mask_adjust += gfp->tune_value_a;
  926. gfc->sv_qnt.mask_adjust_short += gfp->tune_value_a;
  927. }
  928. if (cfg->vbr != vbr_off) { /* choose a min/max bitrate for VBR */
  929. /* if the user didn't specify VBR_max_bitrate: */
  930. cfg->vbr_min_bitrate_index = 1; /* default: allow 8 kbps (MPEG-2) or 32 kbps (MPEG-1) */
  931. cfg->vbr_max_bitrate_index = 14; /* default: allow 160 kbps (MPEG-2) or 320 kbps (MPEG-1) */
  932. if (cfg->samplerate_out < 16000)
  933. cfg->vbr_max_bitrate_index = 8; /* default: allow 64 kbps (MPEG-2.5) */
  934. if (gfp->VBR_min_bitrate_kbps) {
  935. gfp->VBR_min_bitrate_kbps =
  936. FindNearestBitrate(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
  937. cfg->vbr_min_bitrate_index =
  938. BitrateIndex(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
  939. if (cfg->vbr_min_bitrate_index < 0) {
  940. /* This never happens, because of preceding FindNearestBitrate!
  941. * But, set a sane value, just in case
  942. */
  943. assert(0);
  944. cfg->vbr_min_bitrate_index = 1;
  945. }
  946. }
  947. if (gfp->VBR_max_bitrate_kbps) {
  948. gfp->VBR_max_bitrate_kbps =
  949. FindNearestBitrate(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
  950. cfg->vbr_max_bitrate_index =
  951. BitrateIndex(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
  952. if (cfg->vbr_max_bitrate_index < 0) {
  953. /* This never happens, because of preceding FindNearestBitrate!
  954. * But, set a sane value, just in case
  955. */
  956. assert(0);
  957. cfg->vbr_max_bitrate_index = cfg->samplerate_out < 16000 ? 8 : 14;
  958. }
  959. }
  960. gfp->VBR_min_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];
  961. gfp->VBR_max_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_max_bitrate_index];
  962. gfp->VBR_mean_bitrate_kbps =
  963. Min(bitrate_table[cfg->version][cfg->vbr_max_bitrate_index],
  964. gfp->VBR_mean_bitrate_kbps);
  965. gfp->VBR_mean_bitrate_kbps =
  966. Max(bitrate_table[cfg->version][cfg->vbr_min_bitrate_index],
  967. gfp->VBR_mean_bitrate_kbps);
  968. }
  969. cfg->preset = gfp->preset;
  970. cfg->write_lame_tag = gfp->write_lame_tag;
  971. gfc->sv_qnt.substep_shaping = gfp->substep_shaping;
  972. cfg->noise_shaping = gfp->noise_shaping;
  973. cfg->subblock_gain = gfp->subblock_gain;
  974. cfg->use_best_huffman = gfp->use_best_huffman;
  975. cfg->avg_bitrate = gfp->brate;
  976. cfg->vbr_avg_bitrate_kbps = gfp->VBR_mean_bitrate_kbps;
  977. cfg->compression_ratio = gfp->compression_ratio;
  978. /* initialize internal qval settings */
  979. lame_init_qval(gfp);
  980. /* automatic ATH adjustment on
  981. */
  982. if (gfp->athaa_type < 0)
  983. gfc->ATH->use_adjust = 3;
  984. else
  985. gfc->ATH->use_adjust = gfp->athaa_type;
  986. /* initialize internal adaptive ATH settings -jd */
  987. gfc->ATH->aa_sensitivity_p = pow(10.0, gfp->athaa_sensitivity / -10.0);
  988. if (gfp->short_blocks == short_block_not_set) {
  989. gfp->short_blocks = short_block_allowed;
  990. }
  991. /*Note Jan/2003: Many hardware decoders cannot handle short blocks in regular
  992. stereo mode unless they are coupled (same type in both channels)
  993. it is a rare event (1 frame per min. or so) that LAME would use
  994. uncoupled short blocks, so lets turn them off until we decide
  995. how to handle this. No other encoders allow uncoupled short blocks,
  996. even though it is in the standard. */
  997. /* rh 20040217: coupling makes no sense for mono and dual-mono streams
  998. */
  999. if (gfp->short_blocks == short_block_allowed
  1000. && (cfg->mode == JOINT_STEREO || cfg->mode == STEREO)) {
  1001. gfp->short_blocks = short_block_coupled;
  1002. }
  1003. cfg->short_blocks = gfp->short_blocks;
  1004. if (lame_get_quant_comp(gfp) < 0)
  1005. (void) lame_set_quant_comp(gfp, 1);
  1006. if (lame_get_quant_comp_short(gfp) < 0)
  1007. (void) lame_set_quant_comp_short(gfp, 0);
  1008. if (lame_get_msfix(gfp) < 0)
  1009. lame_set_msfix(gfp, 0);
  1010. /* select psychoacoustic model */
  1011. (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 1);
  1012. if (gfp->ATHtype < 0)
  1013. gfp->ATHtype = 4;
  1014. if (gfp->ATHcurve < 0)
  1015. gfp->ATHcurve = 4;
  1016. if (gfp->interChRatio < 0)
  1017. gfp->interChRatio = 0;
  1018. if (gfp->useTemporal < 0)
  1019. gfp->useTemporal = 1; /* on by default */
  1020. cfg->interChRatio = gfp->interChRatio;
  1021. cfg->msfix = gfp->msfix;
  1022. cfg->ATH_offset_db = 0-gfp->ATH_lower_db;
  1023. cfg->ATH_offset_factor = powf(10.f, cfg->ATH_offset_db * 0.1f);
  1024. cfg->ATHcurve = gfp->ATHcurve;
  1025. cfg->ATHtype = gfp->ATHtype;
  1026. cfg->ATHonly = gfp->ATHonly;
  1027. cfg->ATHshort = gfp->ATHshort;
  1028. cfg->noATH = gfp->noATH;
  1029. cfg->quant_comp = gfp->quant_comp;
  1030. cfg->quant_comp_short = gfp->quant_comp_short;
  1031. cfg->use_temporal_masking_effect = gfp->useTemporal;
  1032. if (cfg->mode == JOINT_STEREO) {
  1033. cfg->use_safe_joint_stereo = gfp->exp_nspsytune & 2;
  1034. }
  1035. else {
  1036. cfg->use_safe_joint_stereo = 0;
  1037. }
  1038. {
  1039. cfg->adjust_bass_db = (gfp->exp_nspsytune >> 2) & 63;
  1040. if (cfg->adjust_bass_db >= 32.f)
  1041. cfg->adjust_bass_db -= 64.f;
  1042. cfg->adjust_bass_db *= 0.25f;
  1043. cfg->adjust_alto_db = (gfp->exp_nspsytune >> 8) & 63;
  1044. if (cfg->adjust_alto_db >= 32.f)
  1045. cfg->adjust_alto_db -= 64.f;
  1046. cfg->adjust_alto_db *= 0.25f;
  1047. cfg->adjust_treble_db = (gfp->exp_nspsytune >> 14) & 63;
  1048. if (cfg->adjust_treble_db >= 32.f)
  1049. cfg->adjust_treble_db -= 64.f;
  1050. cfg->adjust_treble_db *= 0.25f;
  1051. /* to be compatible with Naoki's original code, the next 6 bits
  1052. * define only the amount of changing treble for sfb21 */
  1053. cfg->adjust_sfb21_db = (gfp->exp_nspsytune >> 20) & 63;
  1054. if (cfg->adjust_sfb21_db >= 32.f)
  1055. cfg->adjust_sfb21_db -= 64.f;
  1056. cfg->adjust_sfb21_db *= 0.25f;
  1057. cfg->adjust_sfb21_db += cfg->adjust_treble_db;
  1058. }
  1059. /* Setting up the PCM input data transform matrix, to apply
  1060. * user defined re-scaling, and or two-to-one channel downmix.
  1061. */
  1062. {
  1063. FLOAT m[2][2] = { {1.0f, 0.0f}, {0.0f, 1.0f} };
  1064. /* user selected scaling of the samples */
  1065. m[0][0] *= gfp->scale;
  1066. m[0][1] *= gfp->scale;
  1067. m[1][0] *= gfp->scale;
  1068. m[1][1] *= gfp->scale;
  1069. /* user selected scaling of the channel 0 (left) samples */
  1070. m[0][0] *= gfp->scale_left;
  1071. m[0][1] *= gfp->scale_left;
  1072. /* user selected scaling of the channel 1 (right) samples */
  1073. m[1][0] *= gfp->scale_right;
  1074. m[1][1] *= gfp->scale_right;
  1075. /* Downsample to Mono if 2 channels in and 1 channel out */
  1076. if (cfg->channels_in == 2 && cfg->channels_out == 1) {
  1077. m[0][0] = 0.5f * (m[0][0] + m[1][0]);
  1078. m[0][1] = 0.5f * (m[0][1] + m[1][1]);
  1079. m[1][0] = 0;
  1080. m[1][1] = 0;
  1081. }
  1082. cfg->pcm_transform[0][0] = m[0][0];
  1083. cfg->pcm_transform[0][1] = m[0][1];
  1084. cfg->pcm_transform[1][0] = m[1][0];
  1085. cfg->pcm_transform[1][1] = m[1][1];
  1086. }
  1087. /* padding method as described in
  1088. * "MPEG-Layer3 / Bitstream Syntax and Decoding"
  1089. * by Martin Sieler, Ralph Sperschneider
  1090. *
  1091. * note: there is no padding for the very first frame
  1092. *
  1093. * Robert Hegemann 2000-06-22
  1094. */
  1095. gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF = 0;
  1096. if (cfg->vbr == vbr_off)
  1097. gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF
  1098. = ((cfg->version + 1) * 72000L * cfg->avg_bitrate) % cfg->samplerate_out;
  1099. (void) lame_init_bitstream(gfp);
  1100. iteration_init(gfc);
  1101. (void) psymodel_init(gfp);
  1102. cfg->buffer_constraint = get_max_frame_buffer_size_by_constraint(cfg, gfp->strict_ISO);
  1103. cfg->findReplayGain = gfp->findReplayGain;
  1104. cfg->decode_on_the_fly = gfp->decode_on_the_fly;
  1105. if (cfg->decode_on_the_fly)
  1106. cfg->findPeakSample = 1;
  1107. if (cfg->findReplayGain) {
  1108. if (InitGainAnalysis(gfc->sv_rpg.rgdata, cfg->samplerate_out) == INIT_GAIN_ANALYSIS_ERROR) {
  1109. /* Actually this never happens, our samplerates are the ones RG accepts!
  1110. * But just in case, turn RG off
  1111. */
  1112. assert(0);
  1113. cfg->findReplayGain = 0;
  1114. }
  1115. }
  1116. #ifdef DECODE_ON_THE_FLY
  1117. if (cfg->decode_on_the_fly && !gfp->decode_only) {
  1118. if (gfc->hip) {
  1119. hip_decode_exit(gfc->hip);
  1120. }
  1121. gfc->hip = hip_decode_init();
  1122. /* report functions */
  1123. hip_set_errorf(gfc->hip, gfp->report.errorf);
  1124. hip_set_debugf(gfc->hip, gfp->report.debugf);
  1125. hip_set_msgf(gfc->hip, gfp->report.msgf);
  1126. }
  1127. #endif
  1128. /* updating lame internal flags finished successful */
  1129. gfc->lame_init_params_successful = 1;
  1130. return 0;
  1131. }
  1132. static void
  1133. concatSep(char* dest, char const* sep, char const* str)
  1134. {
  1135. if (*dest != 0) strcat(dest, sep);
  1136. strcat(dest, str);
  1137. }
  1138. /*
  1139. * print_config
  1140. *
  1141. * Prints some selected information about the coding parameters via
  1142. * the macro command MSGF(), which is currently mapped to lame_errorf
  1143. * (reports via a error function?), which is a printf-like function
  1144. * for <stderr>.
  1145. */
  1146. void
  1147. lame_print_config(const lame_global_flags * gfp)
  1148. {
  1149. lame_internal_flags const *const gfc = gfp->internal_flags;
  1150. SessionConfig_t const *const cfg = &gfc->cfg;
  1151. double const out_samplerate = cfg->samplerate_out;
  1152. double const in_samplerate = cfg->samplerate_in;
  1153. MSGF(gfc, "LAME %s %s (%s)\n", get_lame_version(), get_lame_os_bitness(), get_lame_url());
  1154. #if (LAME_ALPHA_VERSION)
  1155. MSGF(gfc, "warning: alpha versions should be used for testing only\n");
  1156. #endif
  1157. if (gfc->CPU_features.MMX
  1158. || gfc->CPU_features.AMD_3DNow || gfc->CPU_features.SSE || gfc->CPU_features.SSE2) {
  1159. char text[256] = { 0 };
  1160. int fft_asm_used = 0;
  1161. #ifdef HAVE_NASM
  1162. if (gfc->CPU_features.AMD_3DNow) {
  1163. fft_asm_used = 1;
  1164. }
  1165. else if (gfc->CPU_features.SSE) {
  1166. fft_asm_used = 2;
  1167. }
  1168. #else
  1169. # if defined( HAVE_XMMINTRIN_H ) && defined( MIN_ARCH_SSE )
  1170. {
  1171. fft_asm_used = 3;
  1172. }
  1173. # endif
  1174. #endif
  1175. if (gfc->CPU_features.MMX) {
  1176. #ifdef MMX_choose_table
  1177. concatSep(text, ", ", "MMX (ASM used)");
  1178. #else
  1179. concatSep(text, ", ", "MMX");
  1180. #endif
  1181. }
  1182. if (gfc->CPU_features.AMD_3DNow) {
  1183. concatSep(text, ", ", (fft_asm_used == 1) ? "3DNow! (ASM used)" : "3DNow!");
  1184. }
  1185. if (gfc->CPU_features.SSE) {
  1186. #if defined(HAVE_XMMINTRIN_H)
  1187. concatSep(text, ", ", "SSE (ASM used)");
  1188. #else
  1189. concatSep(text, ", ", (fft_asm_used == 2) ? "SSE (ASM used)" : "SSE");
  1190. #endif
  1191. }
  1192. if (gfc->CPU_features.SSE2) {
  1193. concatSep(text, ", ", (fft_asm_used == 3) ? "SSE2 (ASM used)" : "SSE2");
  1194. }
  1195. MSGF(gfc, "CPU features: %s\n", text);
  1196. }
  1197. if (cfg->channels_in == 2 && cfg->channels_out == 1 /* mono */ ) {
  1198. MSGF(gfc, "Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
  1199. }
  1200. if (isResamplingNecessary(cfg)) {
  1201. MSGF(gfc, "Resampling: input %g kHz output %g kHz\n",
  1202. 1.e-3 * in_samplerate, 1.e-3 * out_samplerate);
  1203. }
  1204. if (cfg->highpass2 > 0.)
  1205. MSGF(gfc,
  1206. "Using polyphase highpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
  1207. 0.5 * cfg->highpass1 * out_samplerate, 0.5 * cfg->highpass2 * out_samplerate);
  1208. if (0. < cfg->lowpass1 || 0. < cfg->lowpass2) {
  1209. MSGF(gfc,
  1210. "Using polyphase lowpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
  1211. 0.5 * cfg->lowpass1 * out_samplerate, 0.5 * cfg->lowpass2 * out_samplerate);
  1212. }
  1213. else {
  1214. MSGF(gfc, "polyphase lowpass filter disabled\n");
  1215. }
  1216. if (cfg->free_format) {
  1217. MSGF(gfc, "Warning: many decoders cannot handle free format bitstreams\n");
  1218. if (cfg->avg_bitrate > 320) {
  1219. MSGF(gfc,
  1220. "Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\n");
  1221. }
  1222. }
  1223. }
  1224. /** rh:
  1225. * some pretty printing is very welcome at this point!
  1226. * so, if someone is willing to do so, please do it!
  1227. * add more, if you see more...
  1228. */
  1229. void
  1230. lame_print_internals(const lame_global_flags * gfp)
  1231. {
  1232. lame_internal_flags const *const gfc = gfp->internal_flags;
  1233. SessionConfig_t const *const cfg = &gfc->cfg;
  1234. const char *pc = "";
  1235. /* compiler/processor optimizations, operational, etc.
  1236. */
  1237. MSGF(gfc, "\nmisc:\n\n");
  1238. MSGF(gfc, "\tscaling: %g\n", gfp->scale);
  1239. MSGF(gfc, "\tch0 (left) scaling: %g\n", gfp->scale_left);
  1240. MSGF(gfc, "\tch1 (right) scaling: %g\n", gfp->scale_right);
  1241. switch (cfg->use_best_huffman) {
  1242. default:
  1243. pc = "normal";
  1244. break;
  1245. case 1:
  1246. pc = "best (outside loop)";
  1247. break;
  1248. case 2:
  1249. pc = "best (inside loop, slow)";
  1250. break;
  1251. }
  1252. MSGF(gfc, "\thuffman search: %s\n", pc);
  1253. MSGF(gfc, "\texperimental Y=%d\n", gfp->experimentalY);
  1254. MSGF(gfc, "\t...\n");
  1255. /* everything controlling the stream format
  1256. */
  1257. MSGF(gfc, "\nstream format:\n\n");
  1258. switch (cfg->version) {
  1259. case 0:
  1260. pc = "2.5";
  1261. break;
  1262. case 1:
  1263. pc = "1";
  1264. break;
  1265. case 2:
  1266. pc = "2";
  1267. break;
  1268. default:
  1269. pc = "?";
  1270. break;
  1271. }
  1272. MSGF(gfc, "\tMPEG-%s Layer 3\n", pc);
  1273. switch (cfg->mode) {
  1274. case JOINT_STEREO:
  1275. pc = "joint stereo";
  1276. break;
  1277. case STEREO:
  1278. pc = "stereo";
  1279. break;
  1280. case DUAL_CHANNEL:
  1281. pc = "dual channel";
  1282. break;
  1283. case MONO:
  1284. pc = "mono";
  1285. break;
  1286. case NOT_SET:
  1287. pc = "not set (error)";
  1288. break;
  1289. default:
  1290. pc = "unknown (error)";
  1291. break;
  1292. }
  1293. MSGF(gfc, "\t%d channel - %s\n", cfg->channels_out, pc);
  1294. switch (cfg->vbr) {
  1295. case vbr_off:
  1296. pc = "off";
  1297. break;
  1298. default:
  1299. pc = "all";
  1300. break;
  1301. }
  1302. MSGF(gfc, "\tpadding: %s\n", pc);
  1303. if (vbr_default == cfg->vbr)
  1304. pc = "(default)";
  1305. else if (cfg->free_format)
  1306. pc = "(free format)";
  1307. else
  1308. pc = "";
  1309. switch (cfg->vbr) {
  1310. case vbr_off:
  1311. MSGF(gfc, "\tconstant bitrate - CBR %s\n", pc);
  1312. break;
  1313. case vbr_abr:
  1314. MSGF(gfc, "\tvariable bitrate - ABR %s\n", pc);
  1315. break;
  1316. case vbr_rh:
  1317. MSGF(gfc, "\tvariable bitrate - VBR rh %s\n", pc);
  1318. break;
  1319. case vbr_mt:
  1320. MSGF(gfc, "\tvariable bitrate - VBR mt %s\n", pc);
  1321. break;
  1322. case vbr_mtrh:
  1323. MSGF(gfc, "\tvariable bitrate - VBR mtrh %s\n", pc);
  1324. break;
  1325. default:
  1326. MSGF(gfc, "\t ?? oops, some new one ?? \n");
  1327. break;
  1328. }
  1329. if (cfg->write_lame_tag)
  1330. MSGF(gfc, "\tusing LAME Tag\n");
  1331. MSGF(gfc, "\t...\n");
  1332. /* everything controlling psychoacoustic settings, like ATH, etc.
  1333. */
  1334. MSGF(gfc, "\npsychoacoustic:\n\n");
  1335. switch (cfg->short_blocks) {
  1336. default:
  1337. case short_block_not_set:
  1338. pc = "?";
  1339. break;
  1340. case short_block_allowed:
  1341. pc = "allowed";
  1342. break;
  1343. case short_block_coupled:
  1344. pc = "channel coupled";
  1345. break;
  1346. case short_block_dispensed:
  1347. pc = "dispensed";
  1348. break;
  1349. case short_block_forced:
  1350. pc = "forced";
  1351. break;
  1352. }
  1353. MSGF(gfc, "\tusing short blocks: %s\n", pc);
  1354. MSGF(gfc, "\tsubblock gain: %d\n", cfg->subblock_gain);
  1355. MSGF(gfc, "\tadjust masking: %g dB\n", gfc->sv_qnt.mask_adjust);
  1356. MSGF(gfc, "\tadjust masking short: %g dB\n", gfc->sv_qnt.mask_adjust_short);
  1357. MSGF(gfc, "\tquantization comparison: %d\n", cfg->quant_comp);
  1358. MSGF(gfc, "\t ^ comparison short blocks: %d\n", cfg->quant_comp_short);
  1359. MSGF(gfc, "\tnoise shaping: %d\n", cfg->noise_shaping);
  1360. MSGF(gfc, "\t ^ amplification: %d\n", cfg->noise_shaping_amp);
  1361. MSGF(gfc, "\t ^ stopping: %d\n", cfg->noise_shaping_stop);
  1362. pc = "using";
  1363. if (cfg->ATHshort)
  1364. pc = "the only masking for short blocks";
  1365. if (cfg->ATHonly)
  1366. pc = "the only masking";
  1367. if (cfg->noATH)
  1368. pc = "not used";
  1369. MSGF(gfc, "\tATH: %s\n", pc);
  1370. MSGF(gfc, "\t ^ type: %d\n", cfg->ATHtype);
  1371. MSGF(gfc, "\t ^ shape: %g%s\n", cfg->ATHcurve, " (only for type 4)");
  1372. MSGF(gfc, "\t ^ level adjustement: %g dB\n", cfg->ATH_offset_db);
  1373. MSGF(gfc, "\t ^ adjust type: %d\n", gfc->ATH->use_adjust);
  1374. MSGF(gfc, "\t ^ adjust sensitivity power: %f\n", gfc->ATH->aa_sensitivity_p);
  1375. MSGF(gfc, "\texperimental psy tunings by Naoki Shibata\n");
  1376. MSGF(gfc, "\t adjust masking bass=%g dB, alto=%g dB, treble=%g dB, sfb21=%g dB\n",
  1377. 10 * log10(gfc->sv_qnt.longfact[0]),
  1378. 10 * log10(gfc->sv_qnt.longfact[7]),
  1379. 10 * log10(gfc->sv_qnt.longfact[14]), 10 * log10(gfc->sv_qnt.longfact[21]));
  1380. pc = cfg->use_temporal_masking_effect ? "yes" : "no";
  1381. MSGF(gfc, "\tusing temporal masking effect: %s\n", pc);
  1382. MSGF(gfc, "\tinterchannel masking ratio: %g\n", cfg->interChRatio);
  1383. MSGF(gfc, "\t...\n");
  1384. /* that's all ?
  1385. */
  1386. MSGF(gfc, "\n");
  1387. return;
  1388. }
  1389. static void
  1390. save_gain_values(lame_internal_flags * gfc)
  1391. {
  1392. SessionConfig_t const *const cfg = &gfc->cfg;
  1393. RpgStateVar_t const *const rsv = &gfc->sv_rpg;
  1394. RpgResult_t *const rov = &gfc->ov_rpg;
  1395. /* save the ReplayGain value */
  1396. if (cfg->findReplayGain) {
  1397. FLOAT const RadioGain = (FLOAT) GetTitleGain(rsv->rgdata);
  1398. if (NEQ(RadioGain, GAIN_NOT_ENOUGH_SAMPLES)) {
  1399. rov->RadioGain = (int) floor(RadioGain * 10.0 + 0.5); /* round to nearest */
  1400. }
  1401. else {
  1402. rov->RadioGain = 0;
  1403. }
  1404. }
  1405. /* find the gain and scale change required for no clipping */
  1406. if (cfg->findPeakSample) {
  1407. rov->noclipGainChange = (int) ceil(log10(rov->PeakSample / 32767.0) * 20.0 * 10.0); /* round up */
  1408. if (rov->noclipGainChange > 0) { /* clipping occurs */
  1409. rov->noclipScale = floor((32767.0f / rov->PeakSample) * 100.0f) / 100.0f; /* round down */
  1410. }
  1411. else /* no clipping */
  1412. rov->noclipScale = -1.0f;
  1413. }
  1414. }
  1415. static int
  1416. update_inbuffer_size(lame_internal_flags * gfc, const int nsamples)
  1417. {
  1418. EncStateVar_t *const esv = &gfc->sv_enc;
  1419. if (esv->in_buffer_0 == 0 || esv->in_buffer_nsamples < nsamples) {
  1420. if (esv->in_buffer_0) {
  1421. free(esv->in_buffer_0);
  1422. }
  1423. if (esv->in_buffer_1) {
  1424. free(esv->in_buffer_1);
  1425. }
  1426. esv->in_buffer_0 = lame_calloc(sample_t, nsamples);
  1427. esv->in_buffer_1 = lame_calloc(sample_t, nsamples);
  1428. esv->in_buffer_nsamples = nsamples;
  1429. }
  1430. if (esv->in_buffer_0 == NULL || esv->in_buffer_1 == NULL) {
  1431. if (esv->in_buffer_0) {
  1432. free(esv->in_buffer_0);
  1433. }
  1434. if (esv->in_buffer_1) {
  1435. free(esv->in_buffer_1);
  1436. }
  1437. esv->in_buffer_0 = 0;
  1438. esv->in_buffer_1 = 0;
  1439. esv->in_buffer_nsamples = 0;
  1440. ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
  1441. return -2;
  1442. }
  1443. return 0;
  1444. }
  1445. static int
  1446. calcNeeded(SessionConfig_t const * cfg)
  1447. {
  1448. int mf_needed;
  1449. int pcm_samples_per_frame = 576 * cfg->mode_gr;
  1450. /* some sanity checks */
  1451. #if ENCDELAY < MDCTDELAY
  1452. # error ENCDELAY is less than MDCTDELAY, see encoder.h
  1453. #endif
  1454. #if FFTOFFSET > BLKSIZE
  1455. # error FFTOFFSET is greater than BLKSIZE, see encoder.h
  1456. #endif
  1457. mf_needed = BLKSIZE + pcm_samples_per_frame - FFTOFFSET; /* amount needed for FFT */
  1458. /*mf_needed = Max(mf_needed, 286 + 576 * (1 + gfc->mode_gr)); */
  1459. mf_needed = Max(mf_needed, 512 + pcm_samples_per_frame - 32);
  1460. assert(MFSIZE >= mf_needed);
  1461. return mf_needed;
  1462. }
  1463. /*
  1464. * THE MAIN LAME ENCODING INTERFACE
  1465. * mt 3/00
  1466. *
  1467. * input pcm data, output (maybe) mp3 frames.
  1468. * This routine handles all buffering, resampling and filtering for you.
  1469. * The required mp3buffer_size can be computed from num_samples,
  1470. * samplerate and encoding rate, but here is a worst case estimate:
  1471. *
  1472. * mp3buffer_size in bytes = 1.25*num_samples + 7200
  1473. *
  1474. * return code = number of bytes output in mp3buffer. can be 0
  1475. *
  1476. * NOTE: this routine uses LAME's internal PCM data representation,
  1477. * 'sample_t'. It should not be used by any application.
  1478. * applications should use lame_encode_buffer(),
  1479. * lame_encode_buffer_float()
  1480. * lame_encode_buffer_int()
  1481. * etc... depending on what type of data they are working with.
  1482. */
  1483. static int
  1484. lame_encode_buffer_sample_t(lame_internal_flags * gfc,
  1485. int nsamples, unsigned char *mp3buf, const int mp3buf_size)
  1486. {
  1487. SessionConfig_t const *const cfg = &gfc->cfg;
  1488. EncStateVar_t *const esv = &gfc->sv_enc;
  1489. int pcm_samples_per_frame = 576 * cfg->mode_gr;
  1490. int mp3size = 0, ret, i, ch, mf_needed;
  1491. int mp3out;
  1492. sample_t *mfbuf[2];
  1493. sample_t *in_buffer[2];
  1494. if (gfc->class_id != LAME_ID)
  1495. return -3;
  1496. if (nsamples == 0)
  1497. return 0;
  1498. /* copy out any tags that may have been written into bitstream */
  1499. { /* if user specifed buffer size = 0, dont check size */
  1500. int const buf_size = mp3buf_size == 0 ? INT_MAX : mp3buf_size;
  1501. mp3out = copy_buffer(gfc, mp3buf, buf_size, 0);
  1502. }
  1503. if (mp3out < 0)
  1504. return mp3out; /* not enough buffer space */
  1505. mp3buf += mp3out;
  1506. mp3size += mp3out;
  1507. in_buffer[0] = esv->in_buffer_0;
  1508. in_buffer[1] = esv->in_buffer_1;
  1509. mf_needed = calcNeeded(cfg);
  1510. mfbuf[0] = esv->mfbuf[0];
  1511. mfbuf[1] = esv->mfbuf[1];
  1512. while (nsamples > 0) {
  1513. sample_t const *in_buffer_ptr[2];
  1514. int n_in = 0; /* number of input samples processed with fill_buffer */
  1515. int n_out = 0; /* number of samples output with fill_buffer */
  1516. /* n_in <> n_out if we are resampling */
  1517. in_buffer_ptr[0] = in_buffer[0];
  1518. in_buffer_ptr[1] = in_buffer[1];
  1519. /* copy in new samples into mfbuf, with resampling */
  1520. fill_buffer(gfc, mfbuf, &in_buffer_ptr[0], nsamples, &n_in, &n_out);
  1521. /* compute ReplayGain of resampled input if requested */
  1522. if (cfg->findReplayGain && !cfg->decode_on_the_fly)
  1523. if (AnalyzeSamples
  1524. (gfc->sv_rpg.rgdata, &mfbuf[0][esv->mf_size], &mfbuf[1][esv->mf_size], n_out,
  1525. cfg->channels_out) == GAIN_ANALYSIS_ERROR)
  1526. return -6;
  1527. /* update in_buffer counters */
  1528. nsamples -= n_in;
  1529. in_buffer[0] += n_in;
  1530. if (cfg->channels_out == 2)
  1531. in_buffer[1] += n_in;
  1532. /* update mfbuf[] counters */
  1533. esv->mf_size += n_out;
  1534. assert(esv->mf_size <= MFSIZE);
  1535. /* lame_encode_flush may have set gfc->mf_sample_to_encode to 0
  1536. * so we have to reinitialize it here when that happened.
  1537. */
  1538. if (esv->mf_samples_to_encode < 1) {
  1539. esv->mf_samples_to_encode = ENCDELAY + POSTDELAY;
  1540. }
  1541. esv->mf_samples_to_encode += n_out;
  1542. if (esv->mf_size >= mf_needed) {
  1543. /* encode the frame. */
  1544. /* mp3buf = pointer to current location in buffer */
  1545. /* mp3buf_size = size of original mp3 output buffer */
  1546. /* = 0 if we should not worry about the */
  1547. /* buffer size because calling program is */
  1548. /* to lazy to compute it */
  1549. /* mp3size = size of data written to buffer so far */
  1550. /* mp3buf_size-mp3size = amount of space avalable */
  1551. int buf_size = mp3buf_size - mp3size;
  1552. if (mp3buf_size == 0)
  1553. buf_size = INT_MAX;
  1554. ret = lame_encode_mp3_frame(gfc, mfbuf[0], mfbuf[1], mp3buf, buf_size);
  1555. if (ret < 0)
  1556. return ret;
  1557. mp3buf += ret;
  1558. mp3size += ret;
  1559. /* shift out old samples */
  1560. esv->mf_size -= pcm_samples_per_frame;
  1561. esv->mf_samples_to_encode -= pcm_samples_per_frame;
  1562. for (ch = 0; ch < cfg->channels_out; ch++)
  1563. for (i = 0; i < esv->mf_size; i++)
  1564. mfbuf[ch][i] = mfbuf[ch][i + pcm_samples_per_frame];
  1565. }
  1566. }
  1567. assert(nsamples == 0);
  1568. return mp3size;
  1569. }
  1570. enum PCMSampleType
  1571. { pcm_short_type
  1572. , pcm_int_type
  1573. , pcm_long_type
  1574. , pcm_float_type
  1575. , pcm_double_type
  1576. };
  1577. static void
  1578. lame_copy_inbuffer(lame_internal_flags* gfc,
  1579. void const* l, void const* r, int nsamples,
  1580. enum PCMSampleType pcm_type, int jump, FLOAT s)
  1581. {
  1582. SessionConfig_t const *const cfg = &gfc->cfg;
  1583. EncStateVar_t *const esv = &gfc->sv_enc;
  1584. sample_t* ib0 = esv->in_buffer_0;
  1585. sample_t* ib1 = esv->in_buffer_1;
  1586. FLOAT m[2][2];
  1587. /* Apply user defined re-scaling */
  1588. m[0][0] = s * cfg->pcm_transform[0][0];
  1589. m[0][1] = s * cfg->pcm_transform[0][1];
  1590. m[1][0] = s * cfg->pcm_transform[1][0];
  1591. m[1][1] = s * cfg->pcm_transform[1][1];
  1592. /* make a copy of input buffer, changing type to sample_t */
  1593. #define COPY_AND_TRANSFORM(T) \
  1594. { \
  1595. T const *bl = l, *br = r; \
  1596. int i; \
  1597. for (i = 0; i < nsamples; i++) { \
  1598. sample_t const xl = *bl; \
  1599. sample_t const xr = *br; \
  1600. sample_t const u = xl * m[0][0] + xr * m[0][1]; \
  1601. sample_t const v = xl * m[1][0] + xr * m[1][1]; \
  1602. ib0[i] = u; \
  1603. ib1[i] = v; \
  1604. bl += jump; \
  1605. br += jump; \
  1606. } \
  1607. }
  1608. switch ( pcm_type ) {
  1609. case pcm_short_type:
  1610. COPY_AND_TRANSFORM(short int);
  1611. break;
  1612. case pcm_int_type:
  1613. COPY_AND_TRANSFORM(int);
  1614. break;
  1615. case pcm_long_type:
  1616. COPY_AND_TRANSFORM(long int);
  1617. break;
  1618. case pcm_float_type:
  1619. COPY_AND_TRANSFORM(float);
  1620. break;
  1621. case pcm_double_type:
  1622. COPY_AND_TRANSFORM(double);
  1623. break;
  1624. }
  1625. }
  1626. static int
  1627. lame_encode_buffer_template(lame_global_flags * gfp,
  1628. void const* buffer_l, void const* buffer_r, const int nsamples,
  1629. unsigned char *mp3buf, const int mp3buf_size, enum PCMSampleType pcm_type, int aa, FLOAT norm)
  1630. {
  1631. if (is_lame_global_flags_valid(gfp)) {
  1632. lame_internal_flags *const gfc = gfp->internal_flags;
  1633. if (is_lame_internal_flags_valid(gfc)) {
  1634. SessionConfig_t const *const cfg = &gfc->cfg;
  1635. if (nsamples == 0)
  1636. return 0;
  1637. if (update_inbuffer_size(gfc, nsamples) != 0) {
  1638. return -2;
  1639. }
  1640. /* make a copy of input buffer, changing type to sample_t */
  1641. if (cfg->channels_in > 1) {
  1642. if (buffer_l == 0 || buffer_r == 0) {
  1643. return 0;
  1644. }
  1645. lame_copy_inbuffer(gfc, buffer_l, buffer_r, nsamples, pcm_type, aa, norm);
  1646. }
  1647. else {
  1648. if (buffer_l == 0) {
  1649. return 0;
  1650. }
  1651. lame_copy_inbuffer(gfc, buffer_l, buffer_l, nsamples, pcm_type, aa, norm);
  1652. }
  1653. return lame_encode_buffer_sample_t(gfc, nsamples, mp3buf, mp3buf_size);
  1654. }
  1655. }
  1656. return -3;
  1657. }
  1658. int
  1659. lame_encode_buffer(lame_global_flags * gfp,
  1660. const short int pcm_l[], const short int pcm_r[], const int nsamples,
  1661. unsigned char *mp3buf, const int mp3buf_size)
  1662. {
  1663. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_short_type, 1, 1.0);
  1664. }
  1665. int
  1666. lame_encode_buffer_float(lame_global_flags * gfp,
  1667. const float pcm_l[], const float pcm_r[], const int nsamples,
  1668. unsigned char *mp3buf, const int mp3buf_size)
  1669. {
  1670. /* input is assumed to be normalized to +/- 32768 for full scale */
  1671. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 1.0);
  1672. }
  1673. int
  1674. lame_encode_buffer_ieee_float(lame_t gfp,
  1675. const float pcm_l[], const float pcm_r[], const int nsamples,
  1676. unsigned char *mp3buf, const int mp3buf_size)
  1677. {
  1678. /* input is assumed to be normalized to +/- 1.0 for full scale */
  1679. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 32767.0);
  1680. }
  1681. int
  1682. lame_encode_buffer_interleaved_ieee_float(lame_t gfp,
  1683. const float pcm[], const int nsamples,
  1684. unsigned char *mp3buf, const int mp3buf_size)
  1685. {
  1686. /* input is assumed to be normalized to +/- 1.0 for full scale */
  1687. return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_float_type, 2, 32767.0);
  1688. }
  1689. int
  1690. lame_encode_buffer_ieee_double(lame_t gfp,
  1691. const double pcm_l[], const double pcm_r[], const int nsamples,
  1692. unsigned char *mp3buf, const int mp3buf_size)
  1693. {
  1694. /* input is assumed to be normalized to +/- 1.0 for full scale */
  1695. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_double_type, 1, 32767.0);
  1696. }
  1697. int
  1698. lame_encode_buffer_interleaved_ieee_double(lame_t gfp,
  1699. const double pcm[], const int nsamples,
  1700. unsigned char *mp3buf, const int mp3buf_size)
  1701. {
  1702. /* input is assumed to be normalized to +/- 1.0 for full scale */
  1703. return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_double_type, 2, 32767.0);
  1704. }
  1705. int
  1706. lame_encode_buffer_int(lame_global_flags * gfp,
  1707. const int pcm_l[], const int pcm_r[], const int nsamples,
  1708. unsigned char *mp3buf, const int mp3buf_size)
  1709. {
  1710. /* input is assumed to be normalized to +/- MAX_INT for full scale */
  1711. FLOAT const norm = (1.0 / (1L << (8 * sizeof(int) - 16)));
  1712. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_int_type, 1, norm);
  1713. }
  1714. int
  1715. lame_encode_buffer_long2(lame_global_flags * gfp,
  1716. const long pcm_l[], const long pcm_r[], const int nsamples,
  1717. unsigned char *mp3buf, const int mp3buf_size)
  1718. {
  1719. /* input is assumed to be normalized to +/- MAX_LONG for full scale */
  1720. FLOAT const norm = (1.0 / (1L << (8 * sizeof(long) - 16)));
  1721. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, norm);
  1722. }
  1723. int
  1724. lame_encode_buffer_long(lame_global_flags * gfp,
  1725. const long pcm_l[], const long pcm_r[], const int nsamples,
  1726. unsigned char *mp3buf, const int mp3buf_size)
  1727. {
  1728. /* input is assumed to be normalized to +/- 32768 for full scale */
  1729. return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, 1.0);
  1730. }
  1731. int
  1732. lame_encode_buffer_interleaved(lame_global_flags * gfp,
  1733. short int pcm[], int nsamples,
  1734. unsigned char *mp3buf, int mp3buf_size)
  1735. {
  1736. /* input is assumed to be normalized to +/- MAX_SHORT for full scale */
  1737. return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_short_type, 2, 1.0);
  1738. }
  1739. int
  1740. lame_encode_buffer_interleaved_int(lame_t gfp,
  1741. const int pcm[], const int nsamples,
  1742. unsigned char *mp3buf, const int mp3buf_size)
  1743. {
  1744. /* input is assumed to be normalized to +/- MAX(int) for full scale */
  1745. FLOAT const norm = (1.0 / (1L << (8 * sizeof(int)-16)));
  1746. return lame_encode_buffer_template(gfp, pcm, pcm + 1, nsamples, mp3buf, mp3buf_size, pcm_int_type, 2, norm);
  1747. }
  1748. /*****************************************************************
  1749. Flush mp3 buffer, pad with ancillary data so last frame is complete.
  1750. Reset reservoir size to 0
  1751. but keep all PCM samples and MDCT data in memory
  1752. This option is used to break a large file into several mp3 files
  1753. that when concatenated together will decode with no gaps
  1754. Because we set the reservoir=0, they will also decode seperately
  1755. with no errors.
  1756. *********************************************************************/
  1757. int
  1758. lame_encode_flush_nogap(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
  1759. {
  1760. int rc = -3;
  1761. if (is_lame_global_flags_valid(gfp)) {
  1762. lame_internal_flags *const gfc = gfp->internal_flags;
  1763. if (is_lame_internal_flags_valid(gfc)) {
  1764. flush_bitstream(gfc);
  1765. /* if user specifed buffer size = 0, dont check size */
  1766. if (mp3buffer_size == 0)
  1767. mp3buffer_size = INT_MAX;
  1768. rc = copy_buffer(gfc, mp3buffer, mp3buffer_size, 1);
  1769. save_gain_values(gfc);
  1770. }
  1771. }
  1772. return rc;
  1773. }
  1774. /* called by lame_init_params. You can also call this after flush_nogap
  1775. if you want to write new id3v2 and Xing VBR tags into the bitstream */
  1776. int
  1777. lame_init_bitstream(lame_global_flags * gfp)
  1778. {
  1779. if (is_lame_global_flags_valid(gfp)) {
  1780. lame_internal_flags *const gfc = gfp->internal_flags;
  1781. if (gfc != 0) {
  1782. gfc->ov_enc.frame_number = 0;
  1783. if (gfp->write_id3tag_automatic) {
  1784. (void) id3tag_write_v2(gfp);
  1785. }
  1786. /* initialize histogram data optionally used by frontend */
  1787. memset(gfc->ov_enc.bitrate_channelmode_hist, 0,
  1788. sizeof(gfc->ov_enc.bitrate_channelmode_hist));
  1789. memset(gfc->ov_enc.bitrate_blocktype_hist, 0,
  1790. sizeof(gfc->ov_enc.bitrate_blocktype_hist));
  1791. gfc->ov_rpg.PeakSample = 0.0;
  1792. /* Write initial VBR Header to bitstream and init VBR data */
  1793. if (gfc->cfg.write_lame_tag)
  1794. (void) InitVbrTag(gfp);
  1795. return 0;
  1796. }
  1797. }
  1798. return -3;
  1799. }
  1800. /*****************************************************************/
  1801. /* flush internal PCM sample buffers, then mp3 buffers */
  1802. /* then write id3 v1 tags into bitstream. */
  1803. /*****************************************************************/
  1804. int
  1805. lame_encode_flush(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
  1806. {
  1807. lame_internal_flags *gfc;
  1808. SessionConfig_t const *cfg;
  1809. EncStateVar_t *esv;
  1810. short int buffer[2][1152];
  1811. int imp3 = 0, mp3count, mp3buffer_size_remaining;
  1812. /* we always add POSTDELAY=288 padding to make sure granule with real
  1813. * data can be complety decoded (because of 50% overlap with next granule */
  1814. int end_padding;
  1815. int frames_left;
  1816. int samples_to_encode;
  1817. int pcm_samples_per_frame;
  1818. int mf_needed;
  1819. int is_resampling_necessary;
  1820. double resample_ratio = 1;
  1821. if (!is_lame_global_flags_valid(gfp)) {
  1822. return -3;
  1823. }
  1824. gfc = gfp->internal_flags;
  1825. if (!is_lame_internal_flags_valid(gfc)) {
  1826. return -3;
  1827. }
  1828. cfg = &gfc->cfg;
  1829. esv = &gfc->sv_enc;
  1830. /* Was flush already called? */
  1831. if (esv->mf_samples_to_encode < 1) {
  1832. return 0;
  1833. }
  1834. pcm_samples_per_frame = 576 * cfg->mode_gr;
  1835. mf_needed = calcNeeded(cfg);
  1836. samples_to_encode = esv->mf_samples_to_encode - POSTDELAY;
  1837. memset(buffer, 0, sizeof(buffer));
  1838. mp3count = 0;
  1839. is_resampling_necessary = isResamplingNecessary(cfg);
  1840. if (is_resampling_necessary) {
  1841. resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;
  1842. /* delay due to resampling; needs to be fixed, if resampling code gets changed */
  1843. samples_to_encode += 16. / resample_ratio;
  1844. }
  1845. end_padding = pcm_samples_per_frame - (samples_to_encode % pcm_samples_per_frame);
  1846. if (end_padding < 576)
  1847. end_padding += pcm_samples_per_frame;
  1848. gfc->ov_enc.encoder_padding = end_padding;
  1849. frames_left = (samples_to_encode + end_padding) / pcm_samples_per_frame;
  1850. while (frames_left > 0 && imp3 >= 0) {
  1851. int const frame_num = gfc->ov_enc.frame_number;
  1852. int bunch = mf_needed - esv->mf_size;
  1853. bunch *= resample_ratio;
  1854. if (bunch > 1152) bunch = 1152;
  1855. if (bunch < 1) bunch = 1;
  1856. mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1857. /* if user specifed buffer size = 0, dont check size */
  1858. if (mp3buffer_size == 0)
  1859. mp3buffer_size_remaining = 0;
  1860. /* send in a frame of 0 padding until all internal sample buffers
  1861. * are flushed
  1862. */
  1863. imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], bunch,
  1864. mp3buffer, mp3buffer_size_remaining);
  1865. mp3buffer += imp3;
  1866. mp3count += imp3;
  1867. { /* even a single pcm sample can produce several frames!
  1868. * for example: 1 Hz input file resampled to 8 kHz mpeg2.5
  1869. */
  1870. int const new_frames = gfc->ov_enc.frame_number - frame_num;
  1871. if (new_frames > 0)
  1872. frames_left -= new_frames;
  1873. }
  1874. }
  1875. /* Set esv->mf_samples_to_encode to 0, so we may detect
  1876. * and break loops calling it more than once in a row.
  1877. */
  1878. esv->mf_samples_to_encode = 0;
  1879. if (imp3 < 0) {
  1880. /* some type of fatal error */
  1881. return imp3;
  1882. }
  1883. mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1884. /* if user specifed buffer size = 0, dont check size */
  1885. if (mp3buffer_size == 0)
  1886. mp3buffer_size_remaining = INT_MAX;
  1887. /* mp3 related stuff. bit buffer might still contain some mp3 data */
  1888. flush_bitstream(gfc);
  1889. imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 1);
  1890. save_gain_values(gfc);
  1891. if (imp3 < 0) {
  1892. /* some type of fatal error */
  1893. return imp3;
  1894. }
  1895. mp3buffer += imp3;
  1896. mp3count += imp3;
  1897. mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1898. /* if user specifed buffer size = 0, dont check size */
  1899. if (mp3buffer_size == 0)
  1900. mp3buffer_size_remaining = INT_MAX;
  1901. if (gfp->write_id3tag_automatic) {
  1902. /* write a id3 tag to the bitstream */
  1903. (void) id3tag_write_v1(gfp);
  1904. imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 0);
  1905. if (imp3 < 0) {
  1906. return imp3;
  1907. }
  1908. mp3count += imp3;
  1909. }
  1910. #if 0
  1911. {
  1912. int const ed = gfc->ov_enc.encoder_delay;
  1913. int const ep = gfc->ov_enc.encoder_padding;
  1914. int const ns = (gfc->ov_enc.frame_number * pcm_samples_per_frame) - (ed + ep);
  1915. double duration = ns;
  1916. duration /= cfg->samplerate_out;
  1917. MSGF(gfc, "frames=%d\n", gfc->ov_enc.frame_number);
  1918. MSGF(gfc, "pcm_samples_per_frame=%d\n", pcm_samples_per_frame);
  1919. MSGF(gfc, "encoder delay=%d\n", ed);
  1920. MSGF(gfc, "encoder padding=%d\n", ep);
  1921. MSGF(gfc, "sample count=%d (%g)\n", ns, cfg->samplerate_in * duration);
  1922. MSGF(gfc, "duration=%g sec\n", duration);
  1923. }
  1924. #endif
  1925. return mp3count;
  1926. }
  1927. /***********************************************************************
  1928. *
  1929. * lame_close ()
  1930. *
  1931. * frees internal buffers
  1932. *
  1933. ***********************************************************************/
  1934. int
  1935. lame_close(lame_global_flags * gfp)
  1936. {
  1937. int ret = 0;
  1938. if (gfp && gfp->class_id == LAME_ID) {
  1939. lame_internal_flags *const gfc = gfp->internal_flags;
  1940. gfp->class_id = 0;
  1941. if (NULL == gfc || gfc->class_id != LAME_ID) {
  1942. ret = -3;
  1943. }
  1944. if (NULL != gfc) {
  1945. gfc->lame_init_params_successful = 0;
  1946. gfc->class_id = 0;
  1947. /* this routine will free all malloc'd data in gfc, and then free gfc: */
  1948. freegfc(gfc);
  1949. gfp->internal_flags = NULL;
  1950. }
  1951. if (gfp->lame_allocated_gfp) {
  1952. gfp->lame_allocated_gfp = 0;
  1953. free(gfp);
  1954. }
  1955. }
  1956. return ret;
  1957. }
  1958. /*****************************************************************/
  1959. /* flush internal mp3 buffers, and free internal buffers */
  1960. /*****************************************************************/
  1961. #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
  1962. int CDECL
  1963. lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size);
  1964. #else
  1965. #endif
  1966. int
  1967. lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
  1968. {
  1969. int const ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);
  1970. (void) lame_close(gfp);
  1971. return ret;
  1972. }
  1973. /*****************************************************************/
  1974. /* write VBR Xing header, and ID3 version 1 tag, if asked for */
  1975. /*****************************************************************/
  1976. void lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream);
  1977. void
  1978. lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)
  1979. {
  1980. lame_internal_flags *gfc;
  1981. SessionConfig_t const *cfg;
  1982. if (!is_lame_global_flags_valid(gfp)) {
  1983. return;
  1984. }
  1985. gfc = gfp->internal_flags;
  1986. if (!is_lame_internal_flags_valid(gfc)) {
  1987. return;
  1988. }
  1989. cfg = &gfc->cfg;
  1990. if (!cfg->write_lame_tag) {
  1991. return;
  1992. }
  1993. /* Write Xing header again */
  1994. if (fpStream && !fseek(fpStream, 0, SEEK_SET)) {
  1995. int rc = PutVbrTag(gfp, fpStream);
  1996. switch (rc) {
  1997. default:
  1998. /* OK */
  1999. break;
  2000. case -1:
  2001. ERRORF(gfc, "Error: could not update LAME tag.\n");
  2002. break;
  2003. case -2:
  2004. ERRORF(gfc, "Error: could not update LAME tag, file not seekable.\n");
  2005. break;
  2006. case -3:
  2007. ERRORF(gfc, "Error: could not update LAME tag, file not readable.\n");
  2008. break;
  2009. }
  2010. }
  2011. }
  2012. static int
  2013. lame_init_internal_flags(lame_internal_flags* gfc)
  2014. {
  2015. if (NULL == gfc)
  2016. return -1;
  2017. gfc->cfg.vbr_min_bitrate_index = 1; /* not 0 ????? */
  2018. gfc->cfg.vbr_max_bitrate_index = 13; /* not 14 ????? */
  2019. gfc->cfg.decode_on_the_fly = 0;
  2020. gfc->cfg.findReplayGain = 0;
  2021. gfc->cfg.findPeakSample = 0;
  2022. gfc->sv_qnt.OldValue[0] = 180;
  2023. gfc->sv_qnt.OldValue[1] = 180;
  2024. gfc->sv_qnt.CurrentStep[0] = 4;
  2025. gfc->sv_qnt.CurrentStep[1] = 4;
  2026. gfc->sv_qnt.masking_lower = 1;
  2027. /* The reason for
  2028. * int mf_samples_to_encode = ENCDELAY + POSTDELAY;
  2029. * ENCDELAY = internal encoder delay. And then we have to add POSTDELAY=288
  2030. * because of the 50% MDCT overlap. A 576 MDCT granule decodes to
  2031. * 1152 samples. To synthesize the 576 samples centered under this granule
  2032. * we need the previous granule for the first 288 samples (no problem), and
  2033. * the next granule for the next 288 samples (not possible if this is last
  2034. * granule). So we need to pad with 288 samples to make sure we can
  2035. * encode the 576 samples we are interested in.
  2036. */
  2037. gfc->sv_enc.mf_samples_to_encode = ENCDELAY + POSTDELAY;
  2038. gfc->sv_enc.mf_size = ENCDELAY - MDCTDELAY; /* we pad input with this many 0's */
  2039. gfc->ov_enc.encoder_padding = 0;
  2040. gfc->ov_enc.encoder_delay = ENCDELAY;
  2041. gfc->ov_rpg.RadioGain = 0;
  2042. gfc->ov_rpg.noclipGainChange = 0;
  2043. gfc->ov_rpg.noclipScale = -1.0;
  2044. gfc->ATH = lame_calloc(ATH_t, 1);
  2045. if (NULL == gfc->ATH)
  2046. return -2; /* maybe error codes should be enumerated in lame.h ?? */
  2047. gfc->sv_rpg.rgdata = lame_calloc(replaygain_t, 1);
  2048. if (NULL == gfc->sv_rpg.rgdata) {
  2049. return -2;
  2050. }
  2051. return 0;
  2052. }
  2053. /* initialize mp3 encoder */
  2054. #if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
  2055. static
  2056. #else
  2057. #endif
  2058. int
  2059. lame_init_old(lame_global_flags * gfp)
  2060. {
  2061. disable_FPE(); /* disable floating point exceptions */
  2062. memset(gfp, 0, sizeof(lame_global_flags));
  2063. gfp->class_id = LAME_ID;
  2064. /* Global flags. set defaults here for non-zero values */
  2065. /* see lame.h for description */
  2066. /* set integer values to -1 to mean that LAME will compute the
  2067. * best value, UNLESS the calling program as set it
  2068. * (and the value is no longer -1)
  2069. */
  2070. gfp->strict_ISO = MDB_MAXIMUM;
  2071. gfp->mode = NOT_SET;
  2072. gfp->original = 1;
  2073. gfp->samplerate_in = 44100;
  2074. gfp->num_channels = 2;
  2075. gfp->num_samples = MAX_U_32_NUM;
  2076. gfp->write_lame_tag = 1;
  2077. gfp->quality = -1;
  2078. gfp->short_blocks = short_block_not_set;
  2079. gfp->subblock_gain = -1;
  2080. gfp->lowpassfreq = 0;
  2081. gfp->highpassfreq = 0;
  2082. gfp->lowpasswidth = -1;
  2083. gfp->highpasswidth = -1;
  2084. gfp->VBR = vbr_off;
  2085. gfp->VBR_q = 4;
  2086. gfp->VBR_mean_bitrate_kbps = 128;
  2087. gfp->VBR_min_bitrate_kbps = 0;
  2088. gfp->VBR_max_bitrate_kbps = 0;
  2089. gfp->VBR_hard_min = 0;
  2090. gfp->quant_comp = -1;
  2091. gfp->quant_comp_short = -1;
  2092. gfp->msfix = -1;
  2093. gfp->attackthre = -1;
  2094. gfp->attackthre_s = -1;
  2095. gfp->scale = 1;
  2096. gfp->scale_left = 1;
  2097. gfp->scale_right = 1;
  2098. gfp->ATHcurve = -1;
  2099. gfp->ATHtype = -1; /* default = -1 = set in lame_init_params */
  2100. /* 2 = equal loudness curve */
  2101. gfp->athaa_sensitivity = 0.0; /* no offset */
  2102. gfp->athaa_type = -1;
  2103. gfp->useTemporal = -1;
  2104. gfp->interChRatio = -1;
  2105. gfp->findReplayGain = 0;
  2106. gfp->decode_on_the_fly = 0;
  2107. gfp->asm_optimizations.mmx = 1;
  2108. gfp->asm_optimizations.amd3dnow = 1;
  2109. gfp->asm_optimizations.sse = 1;
  2110. gfp->preset = 0;
  2111. gfp->write_id3tag_automatic = 1;
  2112. gfp->report.debugf = &lame_report_def;
  2113. gfp->report.errorf = &lame_report_def;
  2114. gfp->report.msgf = &lame_report_def;
  2115. gfp->internal_flags = lame_calloc(lame_internal_flags, 1);
  2116. if (lame_init_internal_flags(gfp->internal_flags) < 0) {
  2117. freegfc(gfp->internal_flags);
  2118. gfp->internal_flags = 0;
  2119. return -1;
  2120. }
  2121. return 0;
  2122. }
  2123. lame_global_flags *
  2124. lame_init(void)
  2125. {
  2126. lame_global_flags *gfp;
  2127. int ret;
  2128. init_log_table();
  2129. gfp = lame_calloc(lame_global_flags, 1);
  2130. if (gfp == NULL)
  2131. return NULL;
  2132. ret = lame_init_old(gfp);
  2133. if (ret != 0) {
  2134. free(gfp);
  2135. return NULL;
  2136. }
  2137. gfp->lame_allocated_gfp = 1;
  2138. return gfp;
  2139. }
  2140. /***********************************************************************
  2141. *
  2142. * some simple statistics
  2143. *
  2144. * Robert Hegemann 2000-10-11
  2145. *
  2146. ***********************************************************************/
  2147. /* histogram of used bitrate indexes:
  2148. * One has to weight them to calculate the average bitrate in kbps
  2149. *
  2150. * bitrate indices:
  2151. * there are 14 possible bitrate indices, 0 has the special meaning
  2152. * "free format" which is not possible to mix with VBR and 15 is forbidden
  2153. * anyway.
  2154. *
  2155. * stereo modes:
  2156. * 0: LR number of left-right encoded frames
  2157. * 1: LR-I number of left-right and intensity encoded frames
  2158. * 2: MS number of mid-side encoded frames
  2159. * 3: MS-I number of mid-side and intensity encoded frames
  2160. *
  2161. * 4: number of encoded frames
  2162. *
  2163. */
  2164. void
  2165. lame_bitrate_kbps(const lame_global_flags * gfp, int bitrate_kbps[14])
  2166. {
  2167. if (is_lame_global_flags_valid(gfp)) {
  2168. lame_internal_flags const *const gfc = gfp->internal_flags;
  2169. if (is_lame_internal_flags_valid(gfc)) {
  2170. SessionConfig_t const *const cfg = &gfc->cfg;
  2171. int i;
  2172. if (cfg->free_format) {
  2173. for (i = 0; i < 14; i++)
  2174. bitrate_kbps[i] = -1;
  2175. bitrate_kbps[0] = cfg->avg_bitrate;
  2176. }
  2177. else {
  2178. for (i = 0; i < 14; i++)
  2179. bitrate_kbps[i] = bitrate_table[cfg->version][i + 1];
  2180. }
  2181. }
  2182. }
  2183. }
  2184. void
  2185. lame_bitrate_hist(const lame_global_flags * gfp, int bitrate_count[14])
  2186. {
  2187. if (is_lame_global_flags_valid(gfp)) {
  2188. lame_internal_flags const *const gfc = gfp->internal_flags;
  2189. if (is_lame_internal_flags_valid(gfc)) {
  2190. SessionConfig_t const *const cfg = &gfc->cfg;
  2191. EncResult_t const *const eov = &gfc->ov_enc;
  2192. int i;
  2193. if (cfg->free_format) {
  2194. for (i = 0; i < 14; i++) {
  2195. bitrate_count[i] = 0;
  2196. }
  2197. bitrate_count[0] = eov->bitrate_channelmode_hist[0][4];
  2198. }
  2199. else {
  2200. for (i = 0; i < 14; i++) {
  2201. bitrate_count[i] = eov->bitrate_channelmode_hist[i + 1][4];
  2202. }
  2203. }
  2204. }
  2205. }
  2206. }
  2207. void
  2208. lame_stereo_mode_hist(const lame_global_flags * gfp, int stmode_count[4])
  2209. {
  2210. if (is_lame_global_flags_valid(gfp)) {
  2211. lame_internal_flags const *const gfc = gfp->internal_flags;
  2212. if (is_lame_internal_flags_valid(gfc)) {
  2213. EncResult_t const *const eov = &gfc->ov_enc;
  2214. int i;
  2215. for (i = 0; i < 4; i++) {
  2216. stmode_count[i] = eov->bitrate_channelmode_hist[15][i];
  2217. }
  2218. }
  2219. }
  2220. }
  2221. void
  2222. lame_bitrate_stereo_mode_hist(const lame_global_flags * gfp, int bitrate_stmode_count[14][4])
  2223. {
  2224. if (is_lame_global_flags_valid(gfp)) {
  2225. lame_internal_flags const *const gfc = gfp->internal_flags;
  2226. if (is_lame_internal_flags_valid(gfc)) {
  2227. SessionConfig_t const *const cfg = &gfc->cfg;
  2228. EncResult_t const *const eov = &gfc->ov_enc;
  2229. int i;
  2230. int j;
  2231. if (cfg->free_format) {
  2232. for (j = 0; j < 14; j++)
  2233. for (i = 0; i < 4; i++) {
  2234. bitrate_stmode_count[j][i] = 0;
  2235. }
  2236. for (i = 0; i < 4; i++) {
  2237. bitrate_stmode_count[0][i] = eov->bitrate_channelmode_hist[0][i];
  2238. }
  2239. }
  2240. else {
  2241. for (j = 0; j < 14; j++) {
  2242. for (i = 0; i < 4; i++) {
  2243. bitrate_stmode_count[j][i] = eov->bitrate_channelmode_hist[j + 1][i];
  2244. }
  2245. }
  2246. }
  2247. }
  2248. }
  2249. }
  2250. void
  2251. lame_block_type_hist(const lame_global_flags * gfp, int btype_count[6])
  2252. {
  2253. if (is_lame_global_flags_valid(gfp)) {
  2254. lame_internal_flags const *const gfc = gfp->internal_flags;
  2255. if (is_lame_internal_flags_valid(gfc)) {
  2256. EncResult_t const *const eov = &gfc->ov_enc;
  2257. int i;
  2258. for (i = 0; i < 6; ++i) {
  2259. btype_count[i] = eov->bitrate_blocktype_hist[15][i];
  2260. }
  2261. }
  2262. }
  2263. }
  2264. void
  2265. lame_bitrate_block_type_hist(const lame_global_flags * gfp, int bitrate_btype_count[14][6])
  2266. {
  2267. if (is_lame_global_flags_valid(gfp)) {
  2268. lame_internal_flags const *const gfc = gfp->internal_flags;
  2269. if (is_lame_internal_flags_valid(gfc)) {
  2270. SessionConfig_t const *const cfg = &gfc->cfg;
  2271. EncResult_t const *const eov = &gfc->ov_enc;
  2272. int i, j;
  2273. if (cfg->free_format) {
  2274. for (j = 0; j < 14; ++j) {
  2275. for (i = 0; i < 6; ++i) {
  2276. bitrate_btype_count[j][i] = 0;
  2277. }
  2278. }
  2279. for (i = 0; i < 6; ++i) {
  2280. bitrate_btype_count[0][i] = eov->bitrate_blocktype_hist[0][i];
  2281. }
  2282. }
  2283. else {
  2284. for (j = 0; j < 14; ++j) {
  2285. for (i = 0; i < 6; ++i) {
  2286. bitrate_btype_count[j][i] = eov->bitrate_blocktype_hist[j + 1][i];
  2287. }
  2288. }
  2289. }
  2290. }
  2291. }
  2292. }
  2293. /* end of lame.c */