Newer
Older
DH_Apicture / scripts / new_node_modules / lamejs / src / js / BitStream.js
@zhangqy zhangqy on 29 Nov 35 KB first commit
  1. var common = require('./common.js');
  2. var System = common.System;
  3. var VbrMode = common.VbrMode;
  4. var Float = common.Float;
  5. var ShortBlock = common.ShortBlock;
  6. var Util = common.Util;
  7. var Arrays = common.Arrays;
  8. var new_array_n = common.new_array_n;
  9. var new_byte = common.new_byte;
  10. var new_double = common.new_double;
  11. var new_float = common.new_float;
  12. var new_float_n = common.new_float_n;
  13. var new_int = common.new_int;
  14. var new_int_n = common.new_int_n;
  15. var assert = common.assert;
  16.  
  17. var Takehiro = require('./Takehiro.js');
  18. var Tables = require('./Tables.js');
  19. var Encoder = require('./Encoder.js');
  20. var LameInternalFlags = require('./LameInternalFlags.js');
  21.  
  22. BitStream.EQ = function (a, b) {
  23. return (Math.abs(a) > Math.abs(b)) ? (Math.abs((a) - (b)) <= (Math
  24. .abs(a) * 1e-6))
  25. : (Math.abs((a) - (b)) <= (Math.abs(b) * 1e-6));
  26. };
  27.  
  28. BitStream.NEQ = function (a, b) {
  29. return !BitStream.EQ(a, b);
  30. };
  31.  
  32. function BitStream () {
  33. var Lame = require('./Lame.js');
  34. var self = this;
  35. var CRC16_POLYNOMIAL = 0x8005;
  36.  
  37. /*
  38. * we work with ints, so when doing bit manipulation, we limit ourselves to
  39. * MAX_LENGTH-2 just to be on the safe side
  40. */
  41. var MAX_LENGTH = 32;
  42.  
  43. //GainAnalysis ga;
  44. //MPGLib mpg;
  45. //Version ver;
  46. //VBRTag vbr;
  47. var ga = null;
  48. var mpg = null;
  49. var ver = null;
  50. var vbr = null;
  51.  
  52. //public final void setModules(GainAnalysis ga, MPGLib mpg, Version ver,
  53. // VBRTag vbr) {
  54.  
  55. this.setModules = function (_ga, _mpg, _ver, _vbr) {
  56. ga = _ga;
  57. mpg = _mpg;
  58. ver = _ver;
  59. vbr = _vbr;
  60. };
  61.  
  62. /**
  63. * Bit stream buffer.
  64. */
  65. //private byte[] buf;
  66. var buf = null;
  67. /**
  68. * Bit counter of bit stream.
  69. */
  70. var totbit = 0;
  71. /**
  72. * Pointer to top byte in buffer.
  73. */
  74. var bufByteIdx = 0;
  75. /**
  76. * Pointer to top bit of top byte in buffer.
  77. */
  78. var bufBitIdx = 0;
  79.  
  80. /**
  81. * compute bitsperframe and mean_bits for a layer III frame
  82. */
  83. this.getframebits = function (gfp) {
  84. var gfc = gfp.internal_flags;
  85. var bit_rate;
  86.  
  87. /* get bitrate in kbps [?] */
  88. if (gfc.bitrate_index != 0)
  89. bit_rate = Tables.bitrate_table[gfp.version][gfc.bitrate_index];
  90. else
  91. bit_rate = gfp.brate;
  92. assert(8 <= bit_rate && bit_rate <= 640);
  93.  
  94. /* main encoding routine toggles padding on and off */
  95. /* one Layer3 Slot consists of 8 bits */
  96. var bytes = 0 | (gfp.version + 1) * 72000 * bit_rate / gfp.out_samplerate + gfc.padding;
  97. return 8 * bytes;
  98. };
  99.  
  100. function putheader_bits (gfc) {
  101. System.arraycopy(gfc.header[gfc.w_ptr].buf, 0, buf, bufByteIdx, gfc.sideinfo_len);
  102. bufByteIdx += gfc.sideinfo_len;
  103. totbit += gfc.sideinfo_len * 8;
  104. gfc.w_ptr = (gfc.w_ptr + 1) & (LameInternalFlags.MAX_HEADER_BUF - 1);
  105. }
  106.  
  107. /**
  108. * write j bits into the bit stream
  109. */
  110. function putbits2 (gfc, val, j) {
  111. assert(j < MAX_LENGTH - 2);
  112.  
  113. while (j > 0) {
  114. var k;
  115. if (bufBitIdx == 0) {
  116. bufBitIdx = 8;
  117. bufByteIdx++;
  118. assert(bufByteIdx < Lame.LAME_MAXMP3BUFFER);
  119. assert(gfc.header[gfc.w_ptr].write_timing >= totbit);
  120. if (gfc.header[gfc.w_ptr].write_timing == totbit) {
  121. putheader_bits(gfc);
  122. }
  123. buf[bufByteIdx] = 0;
  124. }
  125.  
  126. k = Math.min(j, bufBitIdx);
  127. j -= k;
  128.  
  129. bufBitIdx -= k;
  130.  
  131. assert(j < MAX_LENGTH);
  132. /* 32 too large on 32 bit machines */
  133. assert(bufBitIdx < MAX_LENGTH);
  134.  
  135. buf[bufByteIdx] |= ((val >> j) << bufBitIdx);
  136. totbit += k;
  137. }
  138. }
  139.  
  140. /**
  141. * write j bits into the bit stream, ignoring frame headers
  142. */
  143. function putbits_noheaders (gfc, val, j) {
  144. assert(j < MAX_LENGTH - 2);
  145.  
  146. while (j > 0) {
  147. var k;
  148. if (bufBitIdx == 0) {
  149. bufBitIdx = 8;
  150. bufByteIdx++;
  151. assert(bufByteIdx < Lame.LAME_MAXMP3BUFFER);
  152. buf[bufByteIdx] = 0;
  153. }
  154.  
  155. k = Math.min(j, bufBitIdx);
  156. j -= k;
  157.  
  158. bufBitIdx -= k;
  159.  
  160. assert(j < MAX_LENGTH);
  161. /* 32 too large on 32 bit machines */
  162. assert(bufBitIdx < MAX_LENGTH);
  163.  
  164. buf[bufByteIdx] |= ((val >> j) << bufBitIdx);
  165. totbit += k;
  166. }
  167. }
  168.  
  169. /**
  170. * Some combinations of bitrate, Fs, and stereo make it impossible to stuff
  171. * out a frame using just main_data, due to the limited number of bits to
  172. * indicate main_data_length. In these situations, we put stuffing bits into
  173. * the ancillary data...
  174. */
  175. function drain_into_ancillary (gfp, remainingBits) {
  176. var gfc = gfp.internal_flags;
  177. var i;
  178. assert(remainingBits >= 0);
  179.  
  180. if (remainingBits >= 8) {
  181. putbits2(gfc, 0x4c, 8);
  182. remainingBits -= 8;
  183. }
  184. if (remainingBits >= 8) {
  185. putbits2(gfc, 0x41, 8);
  186. remainingBits -= 8;
  187. }
  188. if (remainingBits >= 8) {
  189. putbits2(gfc, 0x4d, 8);
  190. remainingBits -= 8;
  191. }
  192. if (remainingBits >= 8) {
  193. putbits2(gfc, 0x45, 8);
  194. remainingBits -= 8;
  195. }
  196.  
  197. if (remainingBits >= 32) {
  198. var version = ver.getLameShortVersion();
  199. if (remainingBits >= 32)
  200. for (i = 0; i < version.length && remainingBits >= 8; ++i) {
  201. remainingBits -= 8;
  202. putbits2(gfc, version.charAt(i), 8);
  203. }
  204. }
  205.  
  206. for (; remainingBits >= 1; remainingBits -= 1) {
  207. putbits2(gfc, gfc.ancillary_flag, 1);
  208. gfc.ancillary_flag ^= (!gfp.disable_reservoir ? 1 : 0);
  209. }
  210.  
  211. assert(remainingBits == 0);
  212.  
  213. }
  214.  
  215. /**
  216. * write N bits into the header
  217. */
  218. function writeheader (gfc, val, j) {
  219. var ptr = gfc.header[gfc.h_ptr].ptr;
  220.  
  221. while (j > 0) {
  222. var k = Math.min(j, 8 - (ptr & 7));
  223. j -= k;
  224. assert(j < MAX_LENGTH);
  225. /* >> 32 too large for 32 bit machines */
  226.  
  227. gfc.header[gfc.h_ptr].buf[ptr >> 3] |= ((val >> j)) << (8 - (ptr & 7) - k);
  228. ptr += k;
  229. }
  230. gfc.header[gfc.h_ptr].ptr = ptr;
  231. }
  232.  
  233. function CRC_update (value, crc) {
  234. value <<= 8;
  235. for (var i = 0; i < 8; i++) {
  236. value <<= 1;
  237. crc <<= 1;
  238.  
  239. if ((((crc ^ value) & 0x10000) != 0))
  240. crc ^= CRC16_POLYNOMIAL;
  241. }
  242. return crc;
  243. }
  244.  
  245. this.CRC_writeheader = function (gfc, header) {
  246. var crc = 0xffff;
  247. /* (jo) init crc16 for error_protection */
  248.  
  249. crc = CRC_update(header[2] & 0xff, crc);
  250. crc = CRC_update(header[3] & 0xff, crc);
  251. for (var i = 6; i < gfc.sideinfo_len; i++) {
  252. crc = CRC_update(header[i] & 0xff, crc);
  253. }
  254.  
  255. header[4] = (byte)(crc >> 8);
  256. header[5] = (byte)(crc & 255);
  257. };
  258.  
  259. function encodeSideInfo2 (gfp, bitsPerFrame) {
  260. var gfc = gfp.internal_flags;
  261. var l3_side;
  262. var gr, ch;
  263.  
  264. l3_side = gfc.l3_side;
  265. gfc.header[gfc.h_ptr].ptr = 0;
  266. Arrays.fill(gfc.header[gfc.h_ptr].buf, 0, gfc.sideinfo_len, 0);
  267. if (gfp.out_samplerate < 16000)
  268. writeheader(gfc, 0xffe, 12);
  269. else
  270. writeheader(gfc, 0xfff, 12);
  271. writeheader(gfc, (gfp.version), 1);
  272. writeheader(gfc, 4 - 3, 2);
  273. writeheader(gfc, (!gfp.error_protection ? 1 : 0), 1);
  274. writeheader(gfc, (gfc.bitrate_index), 4);
  275. writeheader(gfc, (gfc.samplerate_index), 2);
  276. writeheader(gfc, (gfc.padding), 1);
  277. writeheader(gfc, (gfp.extension), 1);
  278. writeheader(gfc, (gfp.mode.ordinal()), 2);
  279. writeheader(gfc, (gfc.mode_ext), 2);
  280. writeheader(gfc, (gfp.copyright), 1);
  281. writeheader(gfc, (gfp.original), 1);
  282. writeheader(gfc, (gfp.emphasis), 2);
  283. if (gfp.error_protection) {
  284. writeheader(gfc, 0, 16);
  285. /* dummy */
  286. }
  287.  
  288. if (gfp.version == 1) {
  289. /* MPEG1 */
  290. assert(l3_side.main_data_begin >= 0);
  291. writeheader(gfc, (l3_side.main_data_begin), 9);
  292.  
  293. if (gfc.channels_out == 2)
  294. writeheader(gfc, l3_side.private_bits, 3);
  295. else
  296. writeheader(gfc, l3_side.private_bits, 5);
  297.  
  298. for (ch = 0; ch < gfc.channels_out; ch++) {
  299. var band;
  300. for (band = 0; band < 4; band++) {
  301. writeheader(gfc, l3_side.scfsi[ch][band], 1);
  302. }
  303. }
  304.  
  305. for (gr = 0; gr < 2; gr++) {
  306. for (ch = 0; ch < gfc.channels_out; ch++) {
  307. var gi = l3_side.tt[gr][ch];
  308. writeheader(gfc, gi.part2_3_length + gi.part2_length, 12);
  309. writeheader(gfc, gi.big_values / 2, 9);
  310. writeheader(gfc, gi.global_gain, 8);
  311. writeheader(gfc, gi.scalefac_compress, 4);
  312.  
  313. if (gi.block_type != Encoder.NORM_TYPE) {
  314. writeheader(gfc, 1, 1);
  315. /* window_switching_flag */
  316. writeheader(gfc, gi.block_type, 2);
  317. writeheader(gfc, gi.mixed_block_flag, 1);
  318.  
  319. if (gi.table_select[0] == 14)
  320. gi.table_select[0] = 16;
  321. writeheader(gfc, gi.table_select[0], 5);
  322. if (gi.table_select[1] == 14)
  323. gi.table_select[1] = 16;
  324. writeheader(gfc, gi.table_select[1], 5);
  325.  
  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. } else {
  330. writeheader(gfc, 0, 1);
  331. /* 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.  
  342. assert(0 <= gi.region0_count && gi.region0_count < 16);
  343. assert(0 <= gi.region1_count && gi.region1_count < 8);
  344. writeheader(gfc, gi.region0_count, 4);
  345. writeheader(gfc, gi.region1_count, 3);
  346. }
  347. writeheader(gfc, gi.preflag, 1);
  348. writeheader(gfc, gi.scalefac_scale, 1);
  349. writeheader(gfc, gi.count1table_select, 1);
  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, gfc.channels_out);
  357.  
  358. gr = 0;
  359. for (ch = 0; ch < gfc.channels_out; ch++) {
  360. var gi = l3_side.tt[gr][ch];
  361. writeheader(gfc, gi.part2_3_length + gi.part2_length, 12);
  362. writeheader(gfc, gi.big_values / 2, 9);
  363. writeheader(gfc, gi.global_gain, 8);
  364. writeheader(gfc, gi.scalefac_compress, 9);
  365.  
  366. if (gi.block_type != Encoder.NORM_TYPE) {
  367. writeheader(gfc, 1, 1);
  368. /* window_switching_flag */
  369. writeheader(gfc, gi.block_type, 2);
  370. writeheader(gfc, gi.mixed_block_flag, 1);
  371.  
  372. if (gi.table_select[0] == 14)
  373. gi.table_select[0] = 16;
  374. writeheader(gfc, gi.table_select[0], 5);
  375. if (gi.table_select[1] == 14)
  376. gi.table_select[1] = 16;
  377. writeheader(gfc, gi.table_select[1], 5);
  378.  
  379. writeheader(gfc, gi.subblock_gain[0], 3);
  380. writeheader(gfc, gi.subblock_gain[1], 3);
  381. writeheader(gfc, gi.subblock_gain[2], 3);
  382. } else {
  383. writeheader(gfc, 0, 1);
  384. /* window_switching_flag */
  385. if (gi.table_select[0] == 14)
  386. gi.table_select[0] = 16;
  387. writeheader(gfc, gi.table_select[0], 5);
  388. if (gi.table_select[1] == 14)
  389. gi.table_select[1] = 16;
  390. writeheader(gfc, gi.table_select[1], 5);
  391. if (gi.table_select[2] == 14)
  392. gi.table_select[2] = 16;
  393. writeheader(gfc, gi.table_select[2], 5);
  394.  
  395. assert(0 <= gi.region0_count && gi.region0_count < 16);
  396. assert(0 <= gi.region1_count && gi.region1_count < 8);
  397. writeheader(gfc, gi.region0_count, 4);
  398. writeheader(gfc, gi.region1_count, 3);
  399. }
  400.  
  401. writeheader(gfc, gi.scalefac_scale, 1);
  402. writeheader(gfc, gi.count1table_select, 1);
  403. }
  404. }
  405.  
  406. if (gfp.error_protection) {
  407. /* (jo) error_protection: add crc16 information to header */
  408. CRC_writeheader(gfc, gfc.header[gfc.h_ptr].buf);
  409. }
  410.  
  411. {
  412. var old = gfc.h_ptr;
  413. assert(gfc.header[old].ptr == gfc.sideinfo_len * 8);
  414.  
  415. gfc.h_ptr = (old + 1) & (LameInternalFlags.MAX_HEADER_BUF - 1);
  416. gfc.header[gfc.h_ptr].write_timing = gfc.header[old].write_timing
  417. + bitsPerFrame;
  418.  
  419. if (gfc.h_ptr == gfc.w_ptr) {
  420. /* yikes! we are out of header buffer space */
  421. System.err
  422. .println("Error: MAX_HEADER_BUF too small in bitstream.c \n");
  423. }
  424.  
  425. }
  426. }
  427.  
  428. function huffman_coder_count1 (gfc, gi) {
  429. /* Write count1 area */
  430. var h = Tables.ht[gi.count1table_select + 32];
  431. var i, bits = 0;
  432.  
  433. var ix = gi.big_values;
  434. var xr = gi.big_values;
  435. assert(gi.count1table_select < 2);
  436.  
  437. for (i = (gi.count1 - gi.big_values) / 4; i > 0; --i) {
  438. var huffbits = 0;
  439. var p = 0, v;
  440.  
  441. v = gi.l3_enc[ix + 0];
  442. if (v != 0) {
  443. p += 8;
  444. if (gi.xr[xr + 0] < 0)
  445. huffbits++;
  446. assert(v <= 1);
  447. }
  448.  
  449. v = gi.l3_enc[ix + 1];
  450. if (v != 0) {
  451. p += 4;
  452. huffbits *= 2;
  453. if (gi.xr[xr + 1] < 0)
  454. huffbits++;
  455. assert(v <= 1);
  456. }
  457.  
  458. v = gi.l3_enc[ix + 2];
  459. if (v != 0) {
  460. p += 2;
  461. huffbits *= 2;
  462. if (gi.xr[xr + 2] < 0)
  463. huffbits++;
  464. assert(v <= 1);
  465. }
  466.  
  467. v = gi.l3_enc[ix + 3];
  468. if (v != 0) {
  469. p++;
  470. huffbits *= 2;
  471. if (gi.xr[xr + 3] < 0)
  472. huffbits++;
  473. assert(v <= 1);
  474. }
  475.  
  476. ix += 4;
  477. xr += 4;
  478. putbits2(gfc, huffbits + h.table[p], h.hlen[p]);
  479. bits += h.hlen[p];
  480. }
  481. return bits;
  482. }
  483.  
  484. /**
  485. * Implements the pseudocode of page 98 of the IS
  486. */
  487. function Huffmancode (gfc, tableindex, start, end, gi) {
  488. var h = Tables.ht[tableindex];
  489. var bits = 0;
  490.  
  491. assert(tableindex < 32);
  492. if (0 == tableindex)
  493. return bits;
  494.  
  495. for (var i = start; i < end; i += 2) {
  496. var cbits = 0;
  497. var xbits = 0;
  498. var linbits = h.xlen;
  499. var xlen = h.xlen;
  500. var ext = 0;
  501. var x1 = gi.l3_enc[i];
  502. var x2 = gi.l3_enc[i + 1];
  503.  
  504. if (x1 != 0) {
  505. if (gi.xr[i] < 0)
  506. ext++;
  507. cbits--;
  508. }
  509.  
  510. if (tableindex > 15) {
  511. /* use ESC-words */
  512. if (x1 > 14) {
  513. var linbits_x1 = x1 - 15;
  514. assert(linbits_x1 <= h.linmax);
  515. ext |= linbits_x1 << 1;
  516. xbits = linbits;
  517. x1 = 15;
  518. }
  519.  
  520. if (x2 > 14) {
  521. var linbits_x2 = x2 - 15;
  522. assert(linbits_x2 <= h.linmax);
  523. ext <<= linbits;
  524. ext |= linbits_x2;
  525. xbits += linbits;
  526. x2 = 15;
  527. }
  528. xlen = 16;
  529. }
  530.  
  531. if (x2 != 0) {
  532. ext <<= 1;
  533. if (gi.xr[i + 1] < 0)
  534. ext++;
  535. cbits--;
  536. }
  537.  
  538. assert((x1 | x2) < 16);
  539.  
  540. x1 = x1 * xlen + x2;
  541. xbits -= cbits;
  542. cbits += h.hlen[x1];
  543.  
  544. assert(cbits <= MAX_LENGTH);
  545. assert(xbits <= MAX_LENGTH);
  546.  
  547. putbits2(gfc, h.table[x1], cbits);
  548. putbits2(gfc, ext, xbits);
  549. bits += cbits + xbits;
  550. }
  551. return bits;
  552. }
  553.  
  554. /**
  555. * Note the discussion of huffmancodebits() on pages 28 and 29 of the IS, as
  556. * well as the definitions of the side information on pages 26 and 27.
  557. */
  558. function ShortHuffmancodebits (gfc, gi) {
  559. var region1Start = 3 * gfc.scalefac_band.s[3];
  560. if (region1Start > gi.big_values)
  561. region1Start = gi.big_values;
  562.  
  563. /* short blocks do not have a region2 */
  564. var bits = Huffmancode(gfc, gi.table_select[0], 0, region1Start, gi);
  565. bits += Huffmancode(gfc, gi.table_select[1], region1Start,
  566. gi.big_values, gi);
  567. return bits;
  568. }
  569.  
  570. function LongHuffmancodebits (gfc, gi) {
  571. var bigvalues, bits;
  572. var region1Start, region2Start;
  573.  
  574. bigvalues = gi.big_values;
  575. assert(0 <= bigvalues && bigvalues <= 576);
  576.  
  577. var i = gi.region0_count + 1;
  578. assert(0 <= i);
  579. assert(i < gfc.scalefac_band.l.length);
  580. region1Start = gfc.scalefac_band.l[i];
  581. i += gi.region1_count + 1;
  582. assert(0 <= i);
  583. assert(i < gfc.scalefac_band.l.length);
  584. region2Start = gfc.scalefac_band.l[i];
  585.  
  586. if (region1Start > bigvalues)
  587. region1Start = bigvalues;
  588.  
  589. if (region2Start > bigvalues)
  590. region2Start = bigvalues;
  591.  
  592. bits = Huffmancode(gfc, gi.table_select[0], 0, region1Start, gi);
  593. bits += Huffmancode(gfc, gi.table_select[1], region1Start,
  594. region2Start, gi);
  595. bits += Huffmancode(gfc, gi.table_select[2], region2Start, bigvalues,
  596. gi);
  597. return bits;
  598. }
  599.  
  600. function writeMainData (gfp) {
  601. var gr, ch, sfb, data_bits, tot_bits = 0;
  602. var gfc = gfp.internal_flags;
  603. var l3_side = gfc.l3_side;
  604.  
  605. if (gfp.version == 1) {
  606. /* MPEG 1 */
  607. for (gr = 0; gr < 2; gr++) {
  608. for (ch = 0; ch < gfc.channels_out; ch++) {
  609. var gi = l3_side.tt[gr][ch];
  610. var slen1 = Takehiro.slen1_tab[gi.scalefac_compress];
  611. var slen2 = Takehiro.slen2_tab[gi.scalefac_compress];
  612. data_bits = 0;
  613. for (sfb = 0; sfb < gi.sfbdivide; sfb++) {
  614. if (gi.scalefac[sfb] == -1)
  615. continue;
  616. /* scfsi is used */
  617. putbits2(gfc, gi.scalefac[sfb], slen1);
  618. data_bits += slen1;
  619. }
  620. for (; sfb < gi.sfbmax; sfb++) {
  621. if (gi.scalefac[sfb] == -1)
  622. continue;
  623. /* scfsi is used */
  624. putbits2(gfc, gi.scalefac[sfb], slen2);
  625. data_bits += slen2;
  626. }
  627. assert(data_bits == gi.part2_length);
  628.  
  629. if (gi.block_type == Encoder.SHORT_TYPE) {
  630. data_bits += ShortHuffmancodebits(gfc, gi);
  631. } else {
  632. data_bits += LongHuffmancodebits(gfc, gi);
  633. }
  634. data_bits += huffman_coder_count1(gfc, gi);
  635. /* does bitcount in quantize.c agree with actual bit count? */
  636. assert(data_bits == gi.part2_3_length + gi.part2_length);
  637. tot_bits += data_bits;
  638. }
  639. /* for ch */
  640. }
  641. /* for gr */
  642. } else {
  643. /* MPEG 2 */
  644. gr = 0;
  645. for (ch = 0; ch < gfc.channels_out; ch++) {
  646. var gi = l3_side.tt[gr][ch];
  647. var i, sfb_partition, scale_bits = 0;
  648. assert(gi.sfb_partition_table != null);
  649. data_bits = 0;
  650. sfb = 0;
  651. sfb_partition = 0;
  652.  
  653. if (gi.block_type == Encoder.SHORT_TYPE) {
  654. for (; sfb_partition < 4; sfb_partition++) {
  655. var sfbs = gi.sfb_partition_table[sfb_partition] / 3;
  656. var slen = gi.slen[sfb_partition];
  657. for (i = 0; i < sfbs; i++, sfb++) {
  658. putbits2(gfc,
  659. Math.max(gi.scalefac[sfb * 3 + 0], 0), slen);
  660. putbits2(gfc,
  661. Math.max(gi.scalefac[sfb * 3 + 1], 0), slen);
  662. putbits2(gfc,
  663. Math.max(gi.scalefac[sfb * 3 + 2], 0), slen);
  664. scale_bits += 3 * slen;
  665. }
  666. }
  667. data_bits += ShortHuffmancodebits(gfc, gi);
  668. } else {
  669. for (; sfb_partition < 4; sfb_partition++) {
  670. var sfbs = gi.sfb_partition_table[sfb_partition];
  671. var slen = gi.slen[sfb_partition];
  672. for (i = 0; i < sfbs; i++, sfb++) {
  673. putbits2(gfc, Math.max(gi.scalefac[sfb], 0), slen);
  674. scale_bits += slen;
  675. }
  676. }
  677. data_bits += LongHuffmancodebits(gfc, gi);
  678. }
  679. data_bits += huffman_coder_count1(gfc, gi);
  680. /* does bitcount in quantize.c agree with actual bit count? */
  681. assert(data_bits == gi.part2_3_length);
  682. assert(scale_bits == gi.part2_length);
  683. tot_bits += scale_bits + data_bits;
  684. }
  685. /* for ch */
  686. }
  687. /* for gf */
  688. return tot_bits;
  689. }
  690.  
  691. /* main_data */
  692.  
  693. function TotalBytes () {
  694. this.total = 0;
  695. }
  696.  
  697. /*
  698. * compute the number of bits required to flush all mp3 frames currently in
  699. * the buffer. This should be the same as the reservoir size. Only call this
  700. * routine between frames - i.e. only after all headers and data have been
  701. * added to the buffer by format_bitstream().
  702. *
  703. * Also compute total_bits_output = size of mp3 buffer (including frame
  704. * headers which may not have yet been send to the mp3 buffer) + number of
  705. * bits needed to flush all mp3 frames.
  706. *
  707. * total_bytes_output is the size of the mp3 output buffer if
  708. * lame_encode_flush_nogap() was called right now.
  709. */
  710. function compute_flushbits (gfp, total_bytes_output) {
  711. var gfc = gfp.internal_flags;
  712. var flushbits, remaining_headers;
  713. var bitsPerFrame;
  714. var last_ptr, first_ptr;
  715. first_ptr = gfc.w_ptr;
  716. /* first header to add to bitstream */
  717. last_ptr = gfc.h_ptr - 1;
  718. /* last header to add to bitstream */
  719. if (last_ptr == -1)
  720. last_ptr = LameInternalFlags.MAX_HEADER_BUF - 1;
  721.  
  722. /* add this many bits to bitstream so we can flush all headers */
  723. flushbits = gfc.header[last_ptr].write_timing - totbit;
  724. total_bytes_output.total = flushbits;
  725.  
  726. if (flushbits >= 0) {
  727. /* if flushbits >= 0, some headers have not yet been written */
  728. /* reduce flushbits by the size of the headers */
  729. remaining_headers = 1 + last_ptr - first_ptr;
  730. if (last_ptr < first_ptr)
  731. remaining_headers = 1 + last_ptr - first_ptr
  732. + LameInternalFlags.MAX_HEADER_BUF;
  733. flushbits -= remaining_headers * 8 * gfc.sideinfo_len;
  734. }
  735.  
  736. /*
  737. * finally, add some bits so that the last frame is complete these bits
  738. * are not necessary to decode the last frame, but some decoders will
  739. * ignore last frame if these bits are missing
  740. */
  741. bitsPerFrame = self.getframebits(gfp);
  742. flushbits += bitsPerFrame;
  743. total_bytes_output.total += bitsPerFrame;
  744. /* round up: */
  745. if ((total_bytes_output.total % 8) != 0)
  746. total_bytes_output.total = 1 + (total_bytes_output.total / 8);
  747. else
  748. total_bytes_output.total = (total_bytes_output.total / 8);
  749. total_bytes_output.total += bufByteIdx + 1;
  750.  
  751. if (flushbits < 0) {
  752. System.err.println("strange error flushing buffer ... \n");
  753. }
  754. return flushbits;
  755. }
  756.  
  757. this.flush_bitstream = function (gfp) {
  758. var gfc = gfp.internal_flags;
  759. var l3_side;
  760. var flushbits;
  761. var last_ptr = gfc.h_ptr - 1;
  762. /* last header to add to bitstream */
  763. if (last_ptr == -1)
  764. last_ptr = LameInternalFlags.MAX_HEADER_BUF - 1;
  765. l3_side = gfc.l3_side;
  766.  
  767. if ((flushbits = compute_flushbits(gfp, new TotalBytes())) < 0)
  768. return;
  769. drain_into_ancillary(gfp, flushbits);
  770.  
  771. /* check that the 100% of the last frame has been written to bitstream */
  772. assert(gfc.header[last_ptr].write_timing + this.getframebits(gfp) == totbit);
  773.  
  774. /*
  775. * we have padded out all frames with ancillary data, which is the same
  776. * as filling the bitreservoir with ancillary data, so :
  777. */
  778. gfc.ResvSize = 0;
  779. l3_side.main_data_begin = 0;
  780.  
  781. /* save the ReplayGain value */
  782. if (gfc.findReplayGain) {
  783. var RadioGain = ga.GetTitleGain(gfc.rgdata);
  784. assert(NEQ(RadioGain, GainAnalysis.GAIN_NOT_ENOUGH_SAMPLES));
  785. gfc.RadioGain = Math.floor(RadioGain * 10.0 + 0.5) | 0;
  786. /* round to nearest */
  787. }
  788.  
  789. /* find the gain and scale change required for no clipping */
  790. if (gfc.findPeakSample) {
  791. gfc.noclipGainChange = Math.ceil(Math
  792. .log10(gfc.PeakSample / 32767.0) * 20.0 * 10.0) | 0;
  793. /* round up */
  794.  
  795. if (gfc.noclipGainChange > 0) {
  796. /* clipping occurs */
  797. if (EQ(gfp.scale, 1.0) || EQ(gfp.scale, 0.0))
  798. gfc.noclipScale = (Math
  799. .floor((32767.0 / gfc.PeakSample) * 100.0) / 100.0);
  800. /* round down */
  801. else {
  802. /*
  803. * the user specified his own scaling factor. We could
  804. * suggest the scaling factor of
  805. * (32767.0/gfp.PeakSample)*(gfp.scale) but it's usually
  806. * very inaccurate. So we'd rather not advice him on the
  807. * scaling factor.
  808. */
  809. gfc.noclipScale = -1;
  810. }
  811. } else
  812. /* no clipping */
  813. gfc.noclipScale = -1;
  814. }
  815. };
  816.  
  817. this.add_dummy_byte = function (gfp, val, n) {
  818. var gfc = gfp.internal_flags;
  819. var i;
  820.  
  821. while (n-- > 0) {
  822. putbits_noheaders(gfc, val, 8);
  823.  
  824. for (i = 0; i < LameInternalFlags.MAX_HEADER_BUF; ++i)
  825. gfc.header[i].write_timing += 8;
  826. }
  827. };
  828.  
  829. /**
  830. * This is called after a frame of audio has been quantized and coded. It
  831. * will write the encoded audio to the bitstream. Note that from a layer3
  832. * encoder's perspective the bit stream is primarily a series of main_data()
  833. * blocks, with header and side information inserted at the proper locations
  834. * to maintain framing. (See Figure A.7 in the IS).
  835. */
  836. this.format_bitstream = function (gfp) {
  837. var gfc = gfp.internal_flags;
  838. var l3_side;
  839. l3_side = gfc.l3_side;
  840.  
  841. var bitsPerFrame = this.getframebits(gfp);
  842. drain_into_ancillary(gfp, l3_side.resvDrain_pre);
  843.  
  844. encodeSideInfo2(gfp, bitsPerFrame);
  845. var bits = 8 * gfc.sideinfo_len;
  846. bits += writeMainData(gfp);
  847. drain_into_ancillary(gfp, l3_side.resvDrain_post);
  848. bits += l3_side.resvDrain_post;
  849.  
  850. l3_side.main_data_begin += (bitsPerFrame - bits) / 8;
  851.  
  852. /*
  853. * compare number of bits needed to clear all buffered mp3 frames with
  854. * what we think the resvsize is:
  855. */
  856. if (compute_flushbits(gfp, new TotalBytes()) != gfc.ResvSize) {
  857. System.err.println("Internal buffer inconsistency. flushbits <> ResvSize");
  858. }
  859.  
  860. /*
  861. * compare main_data_begin for the next frame with what we think the
  862. * resvsize is:
  863. */
  864. if ((l3_side.main_data_begin * 8) != gfc.ResvSize) {
  865. System.err.printf("bit reservoir error: \n"
  866. + "l3_side.main_data_begin: %d \n"
  867. + "Resvoir size: %d \n"
  868. + "resv drain (post) %d \n"
  869. + "resv drain (pre) %d \n"
  870. + "header and sideinfo: %d \n"
  871. + "data bits: %d \n"
  872. + "total bits: %d (remainder: %d) \n"
  873. + "bitsperframe: %d \n",
  874. 8 * l3_side.main_data_begin, gfc.ResvSize,
  875. l3_side.resvDrain_post, l3_side.resvDrain_pre,
  876. 8 * gfc.sideinfo_len, bits - l3_side.resvDrain_post - 8
  877. * gfc.sideinfo_len, bits, bits % 8, bitsPerFrame);
  878.  
  879. System.err.println("This is a fatal error. It has several possible causes:");
  880. System.err.println("90%% LAME compiled with buggy version of gcc using advanced optimizations");
  881. System.err.println(" 9%% Your system is overclocked");
  882. System.err.println(" 1%% bug in LAME encoding library");
  883.  
  884. gfc.ResvSize = l3_side.main_data_begin * 8;
  885. }
  886. //;
  887. assert(totbit % 8 == 0);
  888.  
  889. if (totbit > 1000000000) {
  890. /*
  891. * to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset
  892. * bit counter
  893. */
  894. var i;
  895. for (i = 0; i < LameInternalFlags.MAX_HEADER_BUF; ++i)
  896. gfc.header[i].write_timing -= totbit;
  897. totbit = 0;
  898. }
  899.  
  900. return 0;
  901. };
  902.  
  903. /**
  904. * <PRE>
  905. * copy data out of the internal MP3 bit buffer into a user supplied
  906. * unsigned char buffer.
  907. *
  908. * mp3data=0 indicates data in buffer is an id3tags and VBR tags
  909. * mp3data=1 data is real mp3 frame data.
  910. * </PRE>
  911. */
  912. this.copy_buffer = function (gfc, buffer, bufferPos, size, mp3data) {
  913. var minimum = bufByteIdx + 1;
  914. if (minimum <= 0)
  915. return 0;
  916. if (size != 0 && minimum > size) {
  917. /* buffer is too small */
  918. return -1;
  919. }
  920. System.arraycopy(buf, 0, buffer, bufferPos, minimum);
  921. bufByteIdx = -1;
  922. bufBitIdx = 0;
  923.  
  924. if (mp3data != 0) {
  925. var crc = new_int(1);
  926. crc[0] = gfc.nMusicCRC;
  927. vbr.updateMusicCRC(crc, buffer, bufferPos, minimum);
  928. gfc.nMusicCRC = crc[0];
  929.  
  930. /**
  931. * sum number of bytes belonging to the mp3 stream this info will be
  932. * written into the Xing/LAME header for seeking
  933. */
  934. if (minimum > 0) {
  935. gfc.VBR_seek_table.nBytesWritten += minimum;
  936. }
  937.  
  938. if (gfc.decode_on_the_fly) { /* decode the frame */
  939. var pcm_buf = new_float_n([2, 1152]);
  940. var mp3_in = minimum;
  941. var samples_out = -1;
  942. var i;
  943.  
  944. /* re-synthesis to pcm. Repeat until we get a samples_out=0 */
  945. while (samples_out != 0) {
  946.  
  947. samples_out = mpg.hip_decode1_unclipped(gfc.hip, buffer,
  948. bufferPos, mp3_in, pcm_buf[0], pcm_buf[1]);
  949. /*
  950. * samples_out = 0: need more data to decode samples_out =
  951. * -1: error. Lets assume 0 pcm output samples_out = number
  952. * of samples output
  953. */
  954.  
  955. /*
  956. * set the lenght of the mp3 input buffer to zero, so that
  957. * in the next iteration of the loop we will be querying
  958. * mpglib about buffered data
  959. */
  960. mp3_in = 0;
  961.  
  962. if (samples_out == -1) {
  963. /*
  964. * error decoding. Not fatal, but might screw up the
  965. * ReplayGain tag. What should we do? Ignore for now
  966. */
  967. samples_out = 0;
  968. }
  969. if (samples_out > 0) {
  970. /* process the PCM data */
  971.  
  972. /*
  973. * this should not be possible, and indicates we have
  974. * overflown the pcm_buf buffer
  975. */
  976. assert(samples_out <= 1152);
  977.  
  978. if (gfc.findPeakSample) {
  979. for (i = 0; i < samples_out; i++) {
  980. if (pcm_buf[0][i] > gfc.PeakSample)
  981. gfc.PeakSample = pcm_buf[0][i];
  982. else if (-pcm_buf[0][i] > gfc.PeakSample)
  983. gfc.PeakSample = -pcm_buf[0][i];
  984. }
  985. if (gfc.channels_out > 1)
  986. for (i = 0; i < samples_out; i++) {
  987. if (pcm_buf[1][i] > gfc.PeakSample)
  988. gfc.PeakSample = pcm_buf[1][i];
  989. else if (-pcm_buf[1][i] > gfc.PeakSample)
  990. gfc.PeakSample = -pcm_buf[1][i];
  991. }
  992. }
  993.  
  994. if (gfc.findReplayGain)
  995. if (ga.AnalyzeSamples(gfc.rgdata, pcm_buf[0], 0,
  996. pcm_buf[1], 0, samples_out,
  997. gfc.channels_out) == GainAnalysis.GAIN_ANALYSIS_ERROR)
  998. return -6;
  999.  
  1000. }
  1001. /* if (samples_out>0) */
  1002. }
  1003. /* while (samples_out!=0) */
  1004. }
  1005. /* if (gfc.decode_on_the_fly) */
  1006.  
  1007. }
  1008. /* if (mp3data) */
  1009. return minimum;
  1010. };
  1011.  
  1012. this.init_bit_stream_w = function (gfc) {
  1013. buf = new_byte(Lame.LAME_MAXMP3BUFFER);
  1014.  
  1015. gfc.h_ptr = gfc.w_ptr = 0;
  1016. gfc.header[gfc.h_ptr].write_timing = 0;
  1017. bufByteIdx = -1;
  1018. bufBitIdx = 0;
  1019. totbit = 0;
  1020. };
  1021.  
  1022. // From machine.h
  1023.  
  1024.  
  1025. }
  1026.  
  1027. module.exports = BitStream;