bitstream.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /*
  2. * MP3 bitstream Output interface for LAME
  3. *
  4. * Copyright (c) 1999-2000 Mark Taylor
  5. * Copyright (c) 1999-2002 Takehiro Tominaga
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the
  19. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  20. * Boston, MA 02111-1307, USA.
  21. *
  22. * $Id: bitstream.c,v 1.99 2017/08/31 14:14:46 robert Exp $
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. #include <config.h>
  26. #endif
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include "lame.h"
  30. #include "machine.h"
  31. #include "encoder.h"
  32. #include "util.h"
  33. #include "tables.h"
  34. #include "quantize_pvt.h"
  35. #include "lame_global_flags.h"
  36. #include "gain_analysis.h"
  37. #include "VbrTag.h"
  38. #include "bitstream.h"
  39. #include "tables.h"
  40. /* unsigned int is at least this large: */
  41. /* we work with ints, so when doing bit manipulation, we limit
  42. * ourselves to MAX_LENGTH-2 just to be on the safe side */
  43. #define MAX_LENGTH 32
  44. #ifdef DEBUG
  45. static int hogege;
  46. #endif
  47. static int
  48. calcFrameLength(SessionConfig_t const *const cfg, int kbps, int pad)
  49. {
  50. return 8 * ((cfg->version + 1) * 72000 * kbps / cfg->samplerate_out + pad);
  51. }
  52. /***********************************************************************
  53. * compute bitsperframe and mean_bits for a layer III frame
  54. **********************************************************************/
  55. int
  56. getframebits(const lame_internal_flags * gfc)
  57. {
  58. SessionConfig_t const *const cfg = &gfc->cfg;
  59. EncResult_t const *const eov = &gfc->ov_enc;
  60. int bit_rate;
  61. /* get bitrate in kbps [?] */
  62. if (eov->bitrate_index)
  63. bit_rate = bitrate_table[cfg->version][eov->bitrate_index];
  64. else
  65. bit_rate = cfg->avg_bitrate;
  66. /*assert(bit_rate <= 550); */
  67. assert(8 <= bit_rate && bit_rate <= 640);
  68. /* main encoding routine toggles padding on and off */
  69. /* one Layer3 Slot consists of 8 bits */
  70. return calcFrameLength(cfg, bit_rate, eov->padding);
  71. }
  72. int
  73. get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint)
  74. {
  75. int maxmp3buf = 0;
  76. if (cfg->avg_bitrate > 320) {
  77. /* in freeformat the buffer is constant */
  78. if (constraint == MDB_STRICT_ISO) {
  79. maxmp3buf = calcFrameLength(cfg, cfg->avg_bitrate, 0);
  80. }
  81. else {
  82. /* maximum allowed bits per granule are 7680 */
  83. maxmp3buf = 7680 * (cfg->version + 1);
  84. }
  85. }
  86. else {
  87. int max_kbps;
  88. if (cfg->samplerate_out < 16000) {
  89. max_kbps = bitrate_table[cfg->version][8]; /* default: allow 64 kbps (MPEG-2.5) */
  90. }
  91. else {
  92. max_kbps = bitrate_table[cfg->version][14];
  93. }
  94. switch (constraint)
  95. {
  96. default:
  97. case MDB_DEFAULT:
  98. /* Bouvigne suggests this more lax interpretation of the ISO doc instead of using 8*960. */
  99. /* All mp3 decoders should have enough buffer to handle this value: size of a 320kbps 32kHz frame */
  100. maxmp3buf = 8 * 1440;
  101. break;
  102. case MDB_STRICT_ISO:
  103. maxmp3buf = calcFrameLength(cfg, max_kbps, 0);
  104. break;
  105. case MDB_MAXIMUM:
  106. maxmp3buf = 7680 * (cfg->version + 1);
  107. break;
  108. }
  109. }
  110. return maxmp3buf;
  111. }
  112. static void
  113. putheader_bits(lame_internal_flags * gfc)
  114. {
  115. SessionConfig_t const *const cfg = &gfc->cfg;
  116. EncStateVar_t *const esv = &gfc->sv_enc;
  117. Bit_stream_struc *bs = &gfc->bs;
  118. #ifdef DEBUG
  119. hogege += cfg->sideinfo_len * 8;
  120. #endif
  121. memcpy(&bs->buf[bs->buf_byte_idx], esv->header[esv->w_ptr].buf, cfg->sideinfo_len);
  122. bs->buf_byte_idx += cfg->sideinfo_len;
  123. bs->totbit += cfg->sideinfo_len * 8;
  124. esv->w_ptr = (esv->w_ptr + 1) & (MAX_HEADER_BUF - 1);
  125. }
  126. /*write j bits into the bit stream */
  127. inline static void
  128. putbits2(lame_internal_flags * gfc, int val, int j)
  129. {
  130. EncStateVar_t const *const esv = &gfc->sv_enc;
  131. Bit_stream_struc *bs;
  132. bs = &gfc->bs;
  133. assert(j < MAX_LENGTH - 2);
  134. while (j > 0) {
  135. int k;
  136. if (bs->buf_bit_idx == 0) {
  137. bs->buf_bit_idx = 8;
  138. bs->buf_byte_idx++;
  139. assert(bs->buf_byte_idx < BUFFER_SIZE);
  140. assert(esv->header[esv->w_ptr].write_timing >= bs->totbit);
  141. if (esv->header[esv->w_ptr].write_timing == bs->totbit) {
  142. putheader_bits(gfc);
  143. }
  144. bs->buf[bs->buf_byte_idx] = 0;
  145. }
  146. k = Min(j, bs->buf_bit_idx);
  147. j -= k;
  148. bs->buf_bit_idx -= k;
  149. assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
  150. assert(bs->buf_bit_idx < MAX_LENGTH);
  151. bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
  152. bs->totbit += k;
  153. }
  154. }
  155. /*write j bits into the bit stream, ignoring frame headers */
  156. inline static void
  157. putbits_noheaders(lame_internal_flags * gfc, int val, int j)
  158. {
  159. Bit_stream_struc *bs;
  160. bs = &gfc->bs;
  161. assert(j < MAX_LENGTH - 2);
  162. while (j > 0) {
  163. int k;
  164. if (bs->buf_bit_idx == 0) {
  165. bs->buf_bit_idx = 8;
  166. bs->buf_byte_idx++;
  167. assert(bs->buf_byte_idx < BUFFER_SIZE);
  168. bs->buf[bs->buf_byte_idx] = 0;
  169. }
  170. k = Min(j, bs->buf_bit_idx);
  171. j -= k;
  172. bs->buf_bit_idx -= k;
  173. assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
  174. assert(bs->buf_bit_idx < MAX_LENGTH);
  175. bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
  176. bs->totbit += k;
  177. }
  178. }
  179. /*
  180. Some combinations of bitrate, Fs, and stereo make it impossible to stuff
  181. out a frame using just main_data, due to the limited number of bits to
  182. indicate main_data_length. In these situations, we put stuffing bits into
  183. the ancillary data...
  184. */
  185. inline static void
  186. drain_into_ancillary(lame_internal_flags * gfc, int remainingBits)
  187. {
  188. SessionConfig_t const *const cfg = &gfc->cfg;
  189. EncStateVar_t *const esv = &gfc->sv_enc;
  190. int i;
  191. assert(remainingBits >= 0);
  192. if (remainingBits >= 8) {
  193. putbits2(gfc, 0x4c, 8);
  194. remainingBits -= 8;
  195. }
  196. if (remainingBits >= 8) {
  197. putbits2(gfc, 0x41, 8);
  198. remainingBits -= 8;
  199. }
  200. if (remainingBits >= 8) {
  201. putbits2(gfc, 0x4d, 8);
  202. remainingBits -= 8;
  203. }
  204. if (remainingBits >= 8) {
  205. putbits2(gfc, 0x45, 8);
  206. remainingBits -= 8;
  207. }
  208. if (remainingBits >= 32) {
  209. const char *const version = get_lame_short_version();
  210. if (remainingBits >= 32)
  211. for (i = 0; i < (int) strlen(version) && remainingBits >= 8; ++i) {
  212. remainingBits -= 8;
  213. putbits2(gfc, version[i], 8);
  214. }
  215. }
  216. for (; remainingBits >= 1; remainingBits -= 1) {
  217. putbits2(gfc, esv->ancillary_flag, 1);
  218. esv->ancillary_flag ^= !cfg->disable_reservoir;
  219. }
  220. assert(remainingBits == 0);
  221. }
  222. /*write N bits into the header */
  223. inline static void
  224. writeheader(lame_internal_flags * gfc, int val, int j)
  225. {
  226. EncStateVar_t *const esv = &gfc->sv_enc;
  227. int ptr = esv->header[esv->h_ptr].ptr;
  228. while (j > 0) {
  229. int const k = Min(j, 8 - (ptr & 7));
  230. j -= k;
  231. assert(j < MAX_LENGTH); /* >> 32 too large for 32 bit machines */
  232. esv->header[esv->h_ptr].buf[ptr >> 3]
  233. |= ((val >> j)) << (8 - (ptr & 7) - k);
  234. ptr += k;
  235. }
  236. esv->header[esv->h_ptr].ptr = ptr;
  237. }
  238. static int
  239. CRC_update(int value, int crc)
  240. {
  241. int i;
  242. value <<= 8;
  243. for (i = 0; i < 8; i++) {
  244. value <<= 1;
  245. crc <<= 1;
  246. if (((crc ^ value) & 0x10000))
  247. crc ^= CRC16_POLYNOMIAL;
  248. }
  249. return crc;
  250. }
  251. void
  252. CRC_writeheader(lame_internal_flags const *gfc, char *header)
  253. {
  254. SessionConfig_t const *const cfg = &gfc->cfg;
  255. int crc = 0xffff; /* (jo) init crc16 for error_protection */
  256. int i;
  257. crc = CRC_update(((unsigned char *) header)[2], crc);
  258. crc = CRC_update(((unsigned char *) header)[3], crc);
  259. for (i = 6; i < cfg->sideinfo_len; i++) {
  260. crc = CRC_update(((unsigned char *) header)[i], crc);
  261. }
  262. header[4] = crc >> 8;
  263. header[5] = crc & 255;
  264. }
  265. inline static void
  266. encodeSideInfo2(lame_internal_flags * gfc, int bitsPerFrame)
  267. {
  268. SessionConfig_t const *const cfg = &gfc->cfg;
  269. EncResult_t const *const eov = &gfc->ov_enc;
  270. EncStateVar_t *const esv = &gfc->sv_enc;
  271. III_side_info_t *l3_side;
  272. int gr, ch;
  273. l3_side = &gfc->l3_side;
  274. esv->header[esv->h_ptr].ptr = 0;
  275. memset(esv->header[esv->h_ptr].buf, 0, cfg->sideinfo_len);
  276. if (cfg->samplerate_out < 16000)
  277. writeheader(gfc, 0xffe, 12);
  278. else
  279. writeheader(gfc, 0xfff, 12);
  280. writeheader(gfc, (cfg->version), 1);
  281. writeheader(gfc, 4 - 3, 2);
  282. writeheader(gfc, (!cfg->error_protection), 1);
  283. writeheader(gfc, (eov->bitrate_index), 4);
  284. writeheader(gfc, (cfg->samplerate_index), 2);
  285. writeheader(gfc, (eov->padding), 1);
  286. writeheader(gfc, (cfg->extension), 1);
  287. writeheader(gfc, (cfg->mode), 2);
  288. writeheader(gfc, (eov->mode_ext), 2);
  289. writeheader(gfc, (cfg->copyright), 1);
  290. writeheader(gfc, (cfg->original), 1);
  291. writeheader(gfc, (cfg->emphasis), 2);
  292. if (cfg->error_protection) {
  293. writeheader(gfc, 0, 16); /* dummy */
  294. }
  295. if (cfg->version == 1) {
  296. /* MPEG1 */
  297. assert(l3_side->main_data_begin >= 0);
  298. writeheader(gfc, (l3_side->main_data_begin), 9);
  299. if (cfg->channels_out == 2)
  300. writeheader(gfc, l3_side->private_bits, 3);
  301. else
  302. writeheader(gfc, l3_side->private_bits, 5);
  303. for (ch = 0; ch < cfg->channels_out; ch++) {
  304. int band;
  305. for (band = 0; band < 4; band++) {
  306. writeheader(gfc, l3_side->scfsi[ch][band], 1);
  307. }
  308. }
  309. for (gr = 0; gr < 2; gr++) {
  310. for (ch = 0; ch < cfg->channels_out; ch++) {
  311. gr_info *const gi = &l3_side->tt[gr][ch];
  312. writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
  313. writeheader(gfc, gi->big_values / 2, 9);
  314. writeheader(gfc, gi->global_gain, 8);
  315. writeheader(gfc, gi->scalefac_compress, 4);
  316. if (gi->block_type != NORM_TYPE) {
  317. writeheader(gfc, 1, 1); /* window_switching_flag */
  318. writeheader(gfc, gi->block_type, 2);
  319. writeheader(gfc, gi->mixed_block_flag, 1);
  320. if (gi->table_select[0] == 14)
  321. gi->table_select[0] = 16;
  322. writeheader(gfc, gi->table_select[0], 5);
  323. if (gi->table_select[1] == 14)
  324. gi->table_select[1] = 16;
  325. writeheader(gfc, gi->table_select[1], 5);
  326. writeheader(gfc, gi->subblock_gain[0], 3);
  327. writeheader(gfc, gi->subblock_gain[1], 3);
  328. writeheader(gfc, gi->subblock_gain[2], 3);
  329. }
  330. else {
  331. writeheader(gfc, 0, 1); /* window_switching_flag */
  332. if (gi->table_select[0] == 14)
  333. gi->table_select[0] = 16;
  334. writeheader(gfc, gi->table_select[0], 5);
  335. if (gi->table_select[1] == 14)
  336. gi->table_select[1] = 16;
  337. writeheader(gfc, gi->table_select[1], 5);
  338. if (gi->table_select[2] == 14)
  339. gi->table_select[2] = 16;
  340. writeheader(gfc, gi->table_select[2], 5);
  341. assert(0 <= gi->region0_count && gi->region0_count < 16);
  342. assert(0 <= gi->region1_count && gi->region1_count < 8);
  343. writeheader(gfc, gi->region0_count, 4);
  344. writeheader(gfc, gi->region1_count, 3);
  345. }
  346. writeheader(gfc, gi->preflag, 1);
  347. writeheader(gfc, gi->scalefac_scale, 1);
  348. writeheader(gfc, gi->count1table_select, 1);
  349. }
  350. }
  351. }
  352. else {
  353. /* MPEG2 */
  354. assert(l3_side->main_data_begin >= 0);
  355. writeheader(gfc, (l3_side->main_data_begin), 8);
  356. writeheader(gfc, l3_side->private_bits, cfg->channels_out);
  357. gr = 0;
  358. for (ch = 0; ch < cfg->channels_out; ch++) {
  359. gr_info *const gi = &l3_side->tt[gr][ch];
  360. writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
  361. writeheader(gfc, gi->big_values / 2, 9);
  362. writeheader(gfc, gi->global_gain, 8);
  363. writeheader(gfc, gi->scalefac_compress, 9);
  364. if (gi->block_type != NORM_TYPE) {
  365. writeheader(gfc, 1, 1); /* window_switching_flag */
  366. writeheader(gfc, gi->block_type, 2);
  367. writeheader(gfc, gi->mixed_block_flag, 1);
  368. if (gi->table_select[0] == 14)
  369. gi->table_select[0] = 16;
  370. writeheader(gfc, gi->table_select[0], 5);
  371. if (gi->table_select[1] == 14)
  372. gi->table_select[1] = 16;
  373. writeheader(gfc, gi->table_select[1], 5);
  374. writeheader(gfc, gi->subblock_gain[0], 3);
  375. writeheader(gfc, gi->subblock_gain[1], 3);
  376. writeheader(gfc, gi->subblock_gain[2], 3);
  377. }
  378. else {
  379. writeheader(gfc, 0, 1); /* window_switching_flag */
  380. if (gi->table_select[0] == 14)
  381. gi->table_select[0] = 16;
  382. writeheader(gfc, gi->table_select[0], 5);
  383. if (gi->table_select[1] == 14)
  384. gi->table_select[1] = 16;
  385. writeheader(gfc, gi->table_select[1], 5);
  386. if (gi->table_select[2] == 14)
  387. gi->table_select[2] = 16;
  388. writeheader(gfc, gi->table_select[2], 5);
  389. assert(0 <= gi->region0_count && gi->region0_count < 16);
  390. assert(0 <= gi->region1_count && gi->region1_count < 8);
  391. writeheader(gfc, gi->region0_count, 4);
  392. writeheader(gfc, gi->region1_count, 3);
  393. }
  394. writeheader(gfc, gi->scalefac_scale, 1);
  395. writeheader(gfc, gi->count1table_select, 1);
  396. }
  397. }
  398. if (cfg->error_protection) {
  399. /* (jo) error_protection: add crc16 information to header */
  400. CRC_writeheader(gfc, esv->header[esv->h_ptr].buf);
  401. }
  402. {
  403. int const old = esv->h_ptr;
  404. assert(esv->header[old].ptr == cfg->sideinfo_len * 8);
  405. esv->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
  406. esv->header[esv->h_ptr].write_timing = esv->header[old].write_timing + bitsPerFrame;
  407. if (esv->h_ptr == esv->w_ptr) {
  408. /* yikes! we are out of header buffer space */
  409. ERRORF(gfc, "Error: MAX_HEADER_BUF too small in bitstream.c \n");
  410. }
  411. }
  412. }
  413. inline static int
  414. huffman_coder_count1(lame_internal_flags * gfc, gr_info const *gi)
  415. {
  416. /* Write count1 area */
  417. struct huffcodetab const *const h = &ht[gi->count1table_select + 32];
  418. int i, bits = 0;
  419. #ifdef DEBUG
  420. int gegebo = gfc->bs.totbit;
  421. #endif
  422. int const *ix = &gi->l3_enc[gi->big_values];
  423. FLOAT const *xr = &gi->xr[gi->big_values];
  424. assert(gi->count1table_select < 2);
  425. for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
  426. int huffbits = 0;
  427. int p = 0, v;
  428. v = ix[0];
  429. if (v) {
  430. p += 8;
  431. if (xr[0] < 0.0f)
  432. huffbits++;
  433. assert(v <= 1);
  434. }
  435. v = ix[1];
  436. if (v) {
  437. p += 4;
  438. huffbits *= 2;
  439. if (xr[1] < 0.0f)
  440. huffbits++;
  441. assert(v <= 1);
  442. }
  443. v = ix[2];
  444. if (v) {
  445. p += 2;
  446. huffbits *= 2;
  447. if (xr[2] < 0.0f)
  448. huffbits++;
  449. assert(v <= 1);
  450. }
  451. v = ix[3];
  452. if (v) {
  453. p++;
  454. huffbits *= 2;
  455. if (xr[3] < 0.0f)
  456. huffbits++;
  457. assert(v <= 1);
  458. }
  459. ix += 4;
  460. xr += 4;
  461. putbits2(gfc, huffbits + h->table[p], h->hlen[p]);
  462. bits += h->hlen[p];
  463. }
  464. #ifdef DEBUG
  465. DEBUGF(gfc, "count1: real: %ld counted:%d (bigv %d count1len %d)\n",
  466. gfc->bs.totbit - gegebo, gi->count1bits, gi->big_values, gi->count1);
  467. #endif
  468. return bits;
  469. }
  470. /*
  471. Implements the pseudocode of page 98 of the IS
  472. */
  473. inline static int
  474. Huffmancode(lame_internal_flags * const gfc, const unsigned int tableindex,
  475. int start, int end, gr_info const *gi)
  476. {
  477. struct huffcodetab const *const h = &ht[tableindex];
  478. unsigned int const linbits = h->xlen;
  479. int i, bits = 0;
  480. assert(tableindex < 32u);
  481. if (!tableindex)
  482. return bits;
  483. for (i = start; i < end; i += 2) {
  484. int16_t cbits = 0;
  485. uint16_t xbits = 0;
  486. unsigned int xlen = h->xlen;
  487. unsigned int ext = 0;
  488. unsigned int x1 = gi->l3_enc[i];
  489. unsigned int x2 = gi->l3_enc[i + 1];
  490. assert(gi->l3_enc[i] >= 0);
  491. assert(gi->l3_enc[i+1] >= 0);
  492. if (x1 != 0u) {
  493. if (gi->xr[i] < 0.0f)
  494. ext++;
  495. cbits--;
  496. }
  497. if (tableindex > 15u) {
  498. /* use ESC-words */
  499. if (x1 >= 15u) {
  500. uint16_t const linbits_x1 = x1 - 15u;
  501. assert(linbits_x1 <= h->linmax);
  502. ext |= linbits_x1 << 1u;
  503. xbits = linbits;
  504. x1 = 15u;
  505. }
  506. if (x2 >= 15u) {
  507. uint16_t const linbits_x2 = x2 - 15u;
  508. assert(linbits_x2 <= h->linmax);
  509. ext <<= linbits;
  510. ext |= linbits_x2;
  511. xbits += linbits;
  512. x2 = 15u;
  513. }
  514. xlen = 16;
  515. }
  516. if (x2 != 0u) {
  517. ext <<= 1;
  518. if (gi->xr[i + 1] < 0.0f)
  519. ext++;
  520. cbits--;
  521. }
  522. assert((x1 | x2) < 16u);
  523. x1 = x1 * xlen + x2;
  524. xbits -= cbits;
  525. cbits += h->hlen[x1];
  526. assert(cbits <= MAX_LENGTH);
  527. assert(xbits <= MAX_LENGTH);
  528. putbits2(gfc, h->table[x1], cbits);
  529. putbits2(gfc, (int)ext, xbits);
  530. bits += cbits + xbits;
  531. }
  532. return bits;
  533. }
  534. /*
  535. Note the discussion of huffmancodebits() on pages 28
  536. and 29 of the IS, as well as the definitions of the side
  537. information on pages 26 and 27.
  538. */
  539. static int
  540. ShortHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
  541. {
  542. int bits;
  543. int region1Start;
  544. region1Start = 3 * gfc->scalefac_band.s[3];
  545. if (region1Start > gi->big_values)
  546. region1Start = gi->big_values;
  547. /* short blocks do not have a region2 */
  548. bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
  549. bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);
  550. return bits;
  551. }
  552. static int
  553. LongHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
  554. {
  555. unsigned int i;
  556. int bigvalues, bits;
  557. int region1Start, region2Start;
  558. bigvalues = gi->big_values;
  559. assert(0 <= bigvalues && bigvalues <= 576);
  560. assert(gi->region0_count >= -1);
  561. assert(gi->region1_count >= -1);
  562. i = gi->region0_count + 1;
  563. assert((size_t) i < dimension_of(gfc->scalefac_band.l));
  564. region1Start = gfc->scalefac_band.l[i];
  565. i += gi->region1_count + 1;
  566. assert((size_t) i < dimension_of(gfc->scalefac_band.l));
  567. region2Start = gfc->scalefac_band.l[i];
  568. if (region1Start > bigvalues)
  569. region1Start = bigvalues;
  570. if (region2Start > bigvalues)
  571. region2Start = bigvalues;
  572. bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
  573. bits += Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);
  574. bits += Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);
  575. return bits;
  576. }
  577. inline static int
  578. writeMainData(lame_internal_flags * const gfc)
  579. {
  580. SessionConfig_t const *const cfg = &gfc->cfg;
  581. III_side_info_t const *const l3_side = &gfc->l3_side;
  582. int gr, ch, sfb, data_bits, tot_bits = 0;
  583. if (cfg->version == 1) {
  584. /* MPEG 1 */
  585. for (gr = 0; gr < 2; gr++) {
  586. for (ch = 0; ch < cfg->channels_out; ch++) {
  587. gr_info const *const gi = &l3_side->tt[gr][ch];
  588. int const slen1 = slen1_tab[gi->scalefac_compress];
  589. int const slen2 = slen2_tab[gi->scalefac_compress];
  590. data_bits = 0;
  591. #ifdef DEBUG
  592. hogege = gfc->bs.totbit;
  593. #endif
  594. for (sfb = 0; sfb < gi->sfbdivide; sfb++) {
  595. if (gi->scalefac[sfb] == -1)
  596. continue; /* scfsi is used */
  597. putbits2(gfc, gi->scalefac[sfb], slen1);
  598. data_bits += slen1;
  599. }
  600. for (; sfb < gi->sfbmax; sfb++) {
  601. if (gi->scalefac[sfb] == -1)
  602. continue; /* scfsi is used */
  603. putbits2(gfc, gi->scalefac[sfb], slen2);
  604. data_bits += slen2;
  605. }
  606. assert(data_bits == gi->part2_length);
  607. if (gi->block_type == SHORT_TYPE) {
  608. data_bits += ShortHuffmancodebits(gfc, gi);
  609. }
  610. else {
  611. data_bits += LongHuffmancodebits(gfc, gi);
  612. }
  613. data_bits += huffman_coder_count1(gfc, gi);
  614. #ifdef DEBUG
  615. DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
  616. #endif
  617. /* does bitcount in quantize.c agree with actual bit count? */
  618. assert(data_bits == gi->part2_3_length + gi->part2_length);
  619. tot_bits += data_bits;
  620. } /* for ch */
  621. } /* for gr */
  622. }
  623. else {
  624. /* MPEG 2 */
  625. gr = 0;
  626. for (ch = 0; ch < cfg->channels_out; ch++) {
  627. gr_info const *const gi = &l3_side->tt[gr][ch];
  628. int i, sfb_partition, scale_bits = 0;
  629. assert(gi->sfb_partition_table);
  630. data_bits = 0;
  631. #ifdef DEBUG
  632. hogege = gfc->bs.totbit;
  633. #endif
  634. sfb = 0;
  635. sfb_partition = 0;
  636. if (gi->block_type == SHORT_TYPE) {
  637. for (; sfb_partition < 4; sfb_partition++) {
  638. int const sfbs = gi->sfb_partition_table[sfb_partition] / 3;
  639. int const slen = gi->slen[sfb_partition];
  640. for (i = 0; i < sfbs; i++, sfb++) {
  641. putbits2(gfc, Max(gi->scalefac[sfb * 3 + 0], 0), slen);
  642. putbits2(gfc, Max(gi->scalefac[sfb * 3 + 1], 0), slen);
  643. putbits2(gfc, Max(gi->scalefac[sfb * 3 + 2], 0), slen);
  644. scale_bits += 3 * slen;
  645. }
  646. }
  647. data_bits += ShortHuffmancodebits(gfc, gi);
  648. }
  649. else {
  650. for (; sfb_partition < 4; sfb_partition++) {
  651. int const sfbs = gi->sfb_partition_table[sfb_partition];
  652. int const slen = gi->slen[sfb_partition];
  653. for (i = 0; i < sfbs; i++, sfb++) {
  654. putbits2(gfc, Max(gi->scalefac[sfb], 0), slen);
  655. scale_bits += slen;
  656. }
  657. }
  658. data_bits += LongHuffmancodebits(gfc, gi);
  659. }
  660. data_bits += huffman_coder_count1(gfc, gi);
  661. #ifdef DEBUG
  662. DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
  663. #endif
  664. /* does bitcount in quantize.c agree with actual bit count? */
  665. assert(data_bits == gi->part2_3_length);
  666. assert(scale_bits == gi->part2_length);
  667. tot_bits += scale_bits + data_bits;
  668. } /* for ch */
  669. } /* for gf */
  670. return tot_bits;
  671. } /* main_data */
  672. /* compute the number of bits required to flush all mp3 frames
  673. currently in the buffer. This should be the same as the
  674. reservoir size. Only call this routine between frames - i.e.
  675. only after all headers and data have been added to the buffer
  676. by format_bitstream().
  677. Also compute total_bits_output =
  678. size of mp3 buffer (including frame headers which may not
  679. have yet been send to the mp3 buffer) +
  680. number of bits needed to flush all mp3 frames.
  681. total_bytes_output is the size of the mp3 output buffer if
  682. lame_encode_flush_nogap() was called right now.
  683. */
  684. int
  685. compute_flushbits(const lame_internal_flags * gfc, int *total_bytes_output)
  686. {
  687. SessionConfig_t const *const cfg = &gfc->cfg;
  688. EncStateVar_t const *const esv = &gfc->sv_enc;
  689. int flushbits, remaining_headers;
  690. int bitsPerFrame;
  691. int last_ptr, first_ptr;
  692. first_ptr = esv->w_ptr; /* first header to add to bitstream */
  693. last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
  694. if (last_ptr == -1)
  695. last_ptr = MAX_HEADER_BUF - 1;
  696. /* add this many bits to bitstream so we can flush all headers */
  697. flushbits = esv->header[last_ptr].write_timing - gfc->bs.totbit;
  698. *total_bytes_output = flushbits;
  699. if (flushbits >= 0) {
  700. /* if flushbits >= 0, some headers have not yet been written */
  701. /* reduce flushbits by the size of the headers */
  702. remaining_headers = 1 + last_ptr - first_ptr;
  703. if (last_ptr < first_ptr)
  704. remaining_headers = 1 + last_ptr - first_ptr + MAX_HEADER_BUF;
  705. flushbits -= remaining_headers * 8 * cfg->sideinfo_len;
  706. }
  707. /* finally, add some bits so that the last frame is complete
  708. * these bits are not necessary to decode the last frame, but
  709. * some decoders will ignore last frame if these bits are missing
  710. */
  711. bitsPerFrame = getframebits(gfc);
  712. flushbits += bitsPerFrame;
  713. *total_bytes_output += bitsPerFrame;
  714. /* round up: */
  715. if (*total_bytes_output % 8)
  716. *total_bytes_output = 1 + (*total_bytes_output / 8);
  717. else
  718. *total_bytes_output = (*total_bytes_output / 8);
  719. *total_bytes_output += gfc->bs.buf_byte_idx + 1;
  720. if (flushbits < 0) {
  721. #if 0
  722. /* if flushbits < 0, this would mean that the buffer looks like:
  723. * (data...) last_header (data...) (extra data that should not be here...)
  724. */
  725. DEBUGF(gfc, "last header write_timing = %i \n", esv->header[last_ptr].write_timing);
  726. DEBUGF(gfc, "first header write_timing = %i \n", esv->header[first_ptr].write_timing);
  727. DEBUGF(gfc, "bs.totbit: %i \n", gfc->bs.totbit);
  728. DEBUGF(gfc, "first_ptr, last_ptr %i %i \n", first_ptr, last_ptr);
  729. DEBUGF(gfc, "remaining_headers = %i \n", remaining_headers);
  730. DEBUGF(gfc, "bitsperframe: %i \n", bitsPerFrame);
  731. DEBUGF(gfc, "sidelen: %i \n", cfg->sideinfo_len);
  732. #endif
  733. ERRORF(gfc, "strange error flushing buffer ... \n");
  734. }
  735. return flushbits;
  736. }
  737. void
  738. flush_bitstream(lame_internal_flags * gfc)
  739. {
  740. EncStateVar_t *const esv = &gfc->sv_enc;
  741. III_side_info_t *l3_side;
  742. int nbytes;
  743. int flushbits;
  744. int last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
  745. if (last_ptr == -1)
  746. last_ptr = MAX_HEADER_BUF - 1;
  747. l3_side = &gfc->l3_side;
  748. if ((flushbits = compute_flushbits(gfc, &nbytes)) < 0)
  749. return;
  750. drain_into_ancillary(gfc, flushbits);
  751. /* check that the 100% of the last frame has been written to bitstream */
  752. assert(esv->header[last_ptr].write_timing + getframebits(gfc)
  753. == gfc->bs.totbit);
  754. /* we have padded out all frames with ancillary data, which is the
  755. same as filling the bitreservoir with ancillary data, so : */
  756. esv->ResvSize = 0;
  757. l3_side->main_data_begin = 0;
  758. }
  759. void
  760. add_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n)
  761. {
  762. EncStateVar_t *const esv = &gfc->sv_enc;
  763. int i;
  764. while (n-- > 0u) {
  765. putbits_noheaders(gfc, val, 8);
  766. for (i = 0; i < MAX_HEADER_BUF; ++i)
  767. esv->header[i].write_timing += 8;
  768. }
  769. }
  770. /*
  771. format_bitstream()
  772. This is called after a frame of audio has been quantized and coded.
  773. It will write the encoded audio to the bitstream. Note that
  774. from a layer3 encoder's perspective the bit stream is primarily
  775. a series of main_data() blocks, with header and side information
  776. inserted at the proper locations to maintain framing. (See Figure A.7
  777. in the IS).
  778. */
  779. int
  780. format_bitstream(lame_internal_flags * gfc)
  781. {
  782. SessionConfig_t const *const cfg = &gfc->cfg;
  783. EncStateVar_t *const esv = &gfc->sv_enc;
  784. int bits, nbytes;
  785. III_side_info_t *l3_side;
  786. int bitsPerFrame;
  787. l3_side = &gfc->l3_side;
  788. bitsPerFrame = getframebits(gfc);
  789. drain_into_ancillary(gfc, l3_side->resvDrain_pre);
  790. encodeSideInfo2(gfc, bitsPerFrame);
  791. bits = 8 * cfg->sideinfo_len;
  792. bits += writeMainData(gfc);
  793. drain_into_ancillary(gfc, l3_side->resvDrain_post);
  794. bits += l3_side->resvDrain_post;
  795. l3_side->main_data_begin += (bitsPerFrame - bits) / 8;
  796. /* compare number of bits needed to clear all buffered mp3 frames
  797. * with what we think the resvsize is: */
  798. if (compute_flushbits(gfc, &nbytes) != esv->ResvSize) {
  799. ERRORF(gfc, "Internal buffer inconsistency. flushbits <> ResvSize");
  800. }
  801. /* compare main_data_begin for the next frame with what we
  802. * think the resvsize is: */
  803. if ((l3_side->main_data_begin * 8) != esv->ResvSize) {
  804. ERRORF(gfc, "bit reservoir error: \n"
  805. "l3_side->main_data_begin: %i \n"
  806. "Resvoir size: %i \n"
  807. "resv drain (post) %i \n"
  808. "resv drain (pre) %i \n"
  809. "header and sideinfo: %i \n"
  810. "data bits: %i \n"
  811. "total bits: %i (remainder: %i) \n"
  812. "bitsperframe: %i \n",
  813. 8 * l3_side->main_data_begin,
  814. esv->ResvSize,
  815. l3_side->resvDrain_post,
  816. l3_side->resvDrain_pre,
  817. 8 * cfg->sideinfo_len,
  818. bits - l3_side->resvDrain_post - 8 * cfg->sideinfo_len,
  819. bits, bits % 8, bitsPerFrame);
  820. ERRORF(gfc, "This is a fatal error. It has several possible causes:");
  821. ERRORF(gfc, "90%% LAME compiled with buggy version of gcc using advanced optimizations");
  822. ERRORF(gfc, " 9%% Your system is overclocked");
  823. ERRORF(gfc, " 1%% bug in LAME encoding library");
  824. esv->ResvSize = l3_side->main_data_begin * 8;
  825. };
  826. assert(gfc->bs.totbit % 8 == 0);
  827. if (gfc->bs.totbit > 1000000000) {
  828. /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter */
  829. int i;
  830. for (i = 0; i < MAX_HEADER_BUF; ++i)
  831. esv->header[i].write_timing -= gfc->bs.totbit;
  832. gfc->bs.totbit = 0;
  833. }
  834. return 0;
  835. }
  836. static int
  837. do_gain_analysis(lame_internal_flags * gfc, unsigned char* buffer, int minimum)
  838. {
  839. SessionConfig_t const *const cfg = &gfc->cfg;
  840. RpgStateVar_t const *const rsv = &gfc->sv_rpg;
  841. RpgResult_t *const rov = &gfc->ov_rpg;
  842. #ifdef DECODE_ON_THE_FLY
  843. if (cfg->decode_on_the_fly) { /* decode the frame */
  844. sample_t pcm_buf[2][1152];
  845. int mp3_in = minimum;
  846. int samples_out = -1;
  847. /* re-synthesis to pcm. Repeat until we get a samples_out=0 */
  848. while (samples_out != 0) {
  849. samples_out = hip_decode1_unclipped(gfc->hip, buffer, mp3_in, pcm_buf[0], pcm_buf[1]);
  850. /* samples_out = 0: need more data to decode
  851. * samples_out = -1: error. Lets assume 0 pcm output
  852. * samples_out = number of samples output */
  853. /* set the lenght of the mp3 input buffer to zero, so that in the
  854. * next iteration of the loop we will be querying mpglib about
  855. * buffered data */
  856. mp3_in = 0;
  857. if (samples_out == -1) {
  858. /* error decoding. Not fatal, but might screw up
  859. * the ReplayGain tag. What should we do? Ignore for now */
  860. samples_out = 0;
  861. }
  862. if (samples_out > 0) {
  863. /* process the PCM data */
  864. /* this should not be possible, and indicates we have
  865. * overflown the pcm_buf buffer */
  866. assert(samples_out <= 1152);
  867. if (cfg->findPeakSample) {
  868. int i;
  869. /* FIXME: is this correct? maybe Max(fabs(pcm),PeakSample) */
  870. for (i = 0; i < samples_out; i++) {
  871. if (pcm_buf[0][i] > rov->PeakSample)
  872. rov->PeakSample = pcm_buf[0][i];
  873. else if (-pcm_buf[0][i] > rov->PeakSample)
  874. rov->PeakSample = -pcm_buf[0][i];
  875. }
  876. if (cfg->channels_out > 1)
  877. for (i = 0; i < samples_out; i++) {
  878. if (pcm_buf[1][i] > rov->PeakSample)
  879. rov->PeakSample = pcm_buf[1][i];
  880. else if (-pcm_buf[1][i] > rov->PeakSample)
  881. rov->PeakSample = -pcm_buf[1][i];
  882. }
  883. }
  884. if (cfg->findReplayGain)
  885. if (AnalyzeSamples
  886. (rsv->rgdata, pcm_buf[0], pcm_buf[1], samples_out,
  887. cfg->channels_out) == GAIN_ANALYSIS_ERROR)
  888. return -6;
  889. } /* if (samples_out>0) */
  890. } /* while (samples_out!=0) */
  891. } /* if (gfc->decode_on_the_fly) */
  892. #endif
  893. return minimum;
  894. }
  895. static int
  896. do_copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size)
  897. {
  898. Bit_stream_struc *const bs = &gfc->bs;
  899. int const minimum = bs->buf_byte_idx + 1;
  900. if (minimum <= 0)
  901. return 0;
  902. if (minimum > size)
  903. return -1; /* buffer is too small */
  904. memcpy(buffer, bs->buf, minimum);
  905. bs->buf_byte_idx = -1;
  906. bs->buf_bit_idx = 0;
  907. return minimum;
  908. }
  909. /* copy data out of the internal MP3 bit buffer into a user supplied
  910. unsigned char buffer.
  911. mp3data=0 indicates data in buffer is an id3tags and VBR tags
  912. mp3data=1 data is real mp3 frame data.
  913. */
  914. int
  915. copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size, int mp3data)
  916. {
  917. int const minimum = do_copy_buffer(gfc, buffer, size);
  918. if (minimum > 0 && mp3data) {
  919. UpdateMusicCRC(&gfc->nMusicCRC, buffer, minimum);
  920. /** sum number of bytes belonging to the mp3 stream
  921. * this info will be written into the Xing/LAME header for seeking
  922. */
  923. gfc->VBR_seek_table.nBytesWritten += minimum;
  924. return do_gain_analysis(gfc, buffer, minimum);
  925. } /* if (mp3data) */
  926. return minimum;
  927. }
  928. void
  929. init_bit_stream_w(lame_internal_flags * gfc)
  930. {
  931. EncStateVar_t *const esv = &gfc->sv_enc;
  932. esv->h_ptr = esv->w_ptr = 0;
  933. esv->header[esv->h_ptr].write_timing = 0;
  934. gfc->bs.buf = lame_calloc(unsigned char, BUFFER_SIZE);
  935. gfc->bs.buf_size = BUFFER_SIZE;
  936. gfc->bs.buf_byte_idx = -1;
  937. gfc->bs.buf_bit_idx = 0;
  938. gfc->bs.totbit = 0;
  939. }
  940. /* end of bitstream.c */