BZip2OutputStream.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. using System;
  2. using System.IO;
  3. using ICSharpCode.SharpZipLib.Checksum;
  4. namespace ICSharpCode.SharpZipLib.BZip2
  5. {
  6. /// <summary>
  7. /// An output stream that compresses into the BZip2 format
  8. /// including file header chars into another stream.
  9. /// </summary>
  10. public class BZip2OutputStream : Stream
  11. {
  12. #region Constants
  13. const int SETMASK = (1 << 21);
  14. const int CLEARMASK = (~SETMASK);
  15. const int GREATER_ICOST = 15;
  16. const int LESSER_ICOST = 0;
  17. const int SMALL_THRESH = 20;
  18. const int DEPTH_THRESH = 10;
  19. /*--
  20. If you are ever unlucky/improbable enough
  21. to get a stack overflow whilst sorting,
  22. increase the following constant and try
  23. again. In practice I have never seen the
  24. stack go above 27 elems, so the following
  25. limit seems very generous.
  26. --*/
  27. const int QSORT_STACK_SIZE = 1000;
  28. /*--
  29. Knuth's increments seem to work better
  30. than Incerpi-Sedgewick here. Possibly
  31. because the number of elems to sort is
  32. usually small, typically <= 20.
  33. --*/
  34. readonly int[] increments = {
  35. 1, 4, 13, 40, 121, 364, 1093, 3280,
  36. 9841, 29524, 88573, 265720,
  37. 797161, 2391484
  38. };
  39. #endregion
  40. #region Instance Fields
  41. /*--
  42. index of the last char in the block, so
  43. the block size == last + 1.
  44. --*/
  45. int last;
  46. /*--
  47. index in zptr[] of original string after sorting.
  48. --*/
  49. int origPtr;
  50. /*--
  51. always: in the range 0 .. 9.
  52. The current block size is 100000 * this number.
  53. --*/
  54. int blockSize100k;
  55. bool blockRandomised;
  56. int bytesOut;
  57. int bsBuff;
  58. int bsLive;
  59. IChecksum mCrc = new BZip2Crc();
  60. bool[] inUse = new bool[256];
  61. int nInUse;
  62. char[] seqToUnseq = new char[256];
  63. char[] unseqToSeq = new char[256];
  64. char[] selector = new char[BZip2Constants.MaximumSelectors];
  65. char[] selectorMtf = new char[BZip2Constants.MaximumSelectors];
  66. byte[] block;
  67. int[] quadrant;
  68. int[] zptr;
  69. short[] szptr;
  70. int[] ftab;
  71. int nMTF;
  72. int[] mtfFreq = new int[BZip2Constants.MaximumAlphaSize];
  73. /*
  74. * Used when sorting. If too many long comparisons
  75. * happen, we stop sorting, randomise the block
  76. * slightly, and try again.
  77. */
  78. int workFactor;
  79. int workDone;
  80. int workLimit;
  81. bool firstAttempt;
  82. int nBlocksRandomised;
  83. int currentChar = -1;
  84. int runLength;
  85. uint blockCRC, combinedCRC;
  86. int allowableBlockSize;
  87. readonly Stream baseStream;
  88. bool disposed_;
  89. #endregion
  90. /// <summary>
  91. /// Construct a default output stream with maximum block size
  92. /// </summary>
  93. /// <param name="stream">The stream to write BZip data onto.</param>
  94. public BZip2OutputStream(Stream stream) : this(stream, 9)
  95. {
  96. }
  97. /// <summary>
  98. /// Initialise a new instance of the <see cref="BZip2OutputStream"></see>
  99. /// for the specified stream, using the given blocksize.
  100. /// </summary>
  101. /// <param name="stream">The stream to write compressed data to.</param>
  102. /// <param name="blockSize">The block size to use.</param>
  103. /// <remarks>
  104. /// Valid block sizes are in the range 1..9, with 1 giving
  105. /// the lowest compression and 9 the highest.
  106. /// </remarks>
  107. public BZip2OutputStream(Stream stream, int blockSize)
  108. {
  109. if (stream == null)
  110. throw new ArgumentNullException("nameof(stream)");
  111. baseStream = stream;
  112. bsLive = 0;
  113. bsBuff = 0;
  114. bytesOut = 0;
  115. workFactor = 50;
  116. if (blockSize > 9) {
  117. blockSize = 9;
  118. }
  119. if (blockSize < 1) {
  120. blockSize = 1;
  121. }
  122. blockSize100k = blockSize;
  123. AllocateCompressStructures();
  124. Initialize();
  125. InitBlock();
  126. }
  127. /// <summary>
  128. /// Ensures that resources are freed and other cleanup operations
  129. /// are performed when the garbage collector reclaims the BZip2OutputStream.
  130. /// </summary>
  131. ~BZip2OutputStream()
  132. {
  133. Dispose(false);
  134. }
  135. /// <summary>
  136. /// Gets or sets a flag indicating ownership of underlying stream.
  137. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
  138. /// </summary>
  139. /// <remarks>The default value is true.</remarks>
  140. private bool isStreamOwner = true;
  141. public bool IsStreamOwner
  142. {
  143. get { return isStreamOwner;}
  144. set { isStreamOwner = value; }
  145. }
  146. /// <summary>
  147. /// Gets a value indicating whether the current stream supports reading
  148. /// </summary>
  149. public override bool CanRead
  150. {
  151. get
  152. {
  153. return false;
  154. }
  155. }
  156. /// <summary>
  157. /// Gets a value indicating whether the current stream supports seeking
  158. /// </summary>
  159. public override bool CanSeek
  160. {
  161. get
  162. {
  163. return false;
  164. }
  165. }
  166. /// <summary>
  167. /// Gets a value indicating whether the current stream supports writing
  168. /// </summary>
  169. public override bool CanWrite
  170. {
  171. get
  172. {
  173. return baseStream.CanWrite;
  174. }
  175. }
  176. /// <summary>
  177. /// Gets the length in bytes of the stream
  178. /// </summary>
  179. public override long Length
  180. {
  181. get
  182. {
  183. return baseStream.Length;
  184. }
  185. }
  186. /// <summary>
  187. /// Gets or sets the current position of this stream.
  188. /// </summary>
  189. public override long Position
  190. {
  191. get
  192. {
  193. return baseStream.Position;
  194. }
  195. set
  196. {
  197. throw new NotSupportedException("BZip2OutputStream position cannot be set");
  198. }
  199. }
  200. /// <summary>
  201. /// Sets the current position of this stream to the given value.
  202. /// </summary>
  203. /// <param name="offset">The point relative to the offset from which to being seeking.</param>
  204. /// <param name="origin">The reference point from which to begin seeking.</param>
  205. /// <returns>The new position in the stream.</returns>
  206. public override long Seek(long offset, SeekOrigin origin)
  207. {
  208. throw new NotSupportedException("BZip2OutputStream Seek not supported");
  209. }
  210. /// <summary>
  211. /// Sets the length of this stream to the given value.
  212. /// </summary>
  213. /// <param name="value">The new stream length.</param>
  214. public override void SetLength(long value)
  215. {
  216. throw new NotSupportedException("BZip2OutputStream SetLength not supported");
  217. }
  218. /// <summary>
  219. /// Read a byte from the stream advancing the position.
  220. /// </summary>
  221. /// <returns>The byte read cast to an int; -1 if end of stream.</returns>
  222. public override int ReadByte()
  223. {
  224. throw new NotSupportedException("BZip2OutputStream ReadByte not supported");
  225. }
  226. /// <summary>
  227. /// Read a block of bytes
  228. /// </summary>
  229. /// <param name="buffer">The buffer to read into.</param>
  230. /// <param name="offset">The offset in the buffer to start storing data at.</param>
  231. /// <param name="count">The maximum number of bytes to read.</param>
  232. /// <returns>The total number of bytes read. This might be less than the number of bytes
  233. /// requested if that number of bytes are not currently available, or zero
  234. /// if the end of the stream is reached.</returns>
  235. public override int Read(byte[] buffer, int offset, int count)
  236. {
  237. throw new NotSupportedException("BZip2OutputStream Read not supported");
  238. }
  239. /// <summary>
  240. /// Write a block of bytes to the stream
  241. /// </summary>
  242. /// <param name="buffer">The buffer containing data to write.</param>
  243. /// <param name="offset">The offset of the first byte to write.</param>
  244. /// <param name="count">The number of bytes to write.</param>
  245. public override void Write(byte[] buffer, int offset, int count)
  246. {
  247. if (buffer == null) {
  248. throw new ArgumentNullException("nameof(buffer)");
  249. }
  250. if (offset < 0) {
  251. throw new ArgumentOutOfRangeException("nameof(offset)");
  252. }
  253. if (count < 0) {
  254. throw new ArgumentOutOfRangeException("nameof(count)");
  255. }
  256. if (buffer.Length - offset < count) {
  257. throw new ArgumentException("Offset/count out of range");
  258. }
  259. for (int i = 0; i < count; ++i) {
  260. WriteByte(buffer[offset + i]);
  261. }
  262. }
  263. /// <summary>
  264. /// Write a byte to the stream.
  265. /// </summary>
  266. /// <param name="value">The byte to write to the stream.</param>
  267. public override void WriteByte(byte value)
  268. {
  269. int b = (256 + value) % 256;
  270. if (currentChar != -1) {
  271. if (currentChar == b) {
  272. runLength++;
  273. if (runLength > 254) {
  274. WriteRun();
  275. currentChar = -1;
  276. runLength = 0;
  277. }
  278. } else {
  279. WriteRun();
  280. runLength = 1;
  281. currentChar = b;
  282. }
  283. } else {
  284. currentChar = b;
  285. runLength++;
  286. }
  287. }
  288. void MakeMaps()
  289. {
  290. nInUse = 0;
  291. for (int i = 0; i < 256; i++) {
  292. if (inUse[i]) {
  293. seqToUnseq[nInUse] = (char)i;
  294. unseqToSeq[i] = (char)nInUse;
  295. nInUse++;
  296. }
  297. }
  298. }
  299. /// <summary>
  300. /// Get the number of bytes written to output.
  301. /// </summary>
  302. void WriteRun()
  303. {
  304. if (last < allowableBlockSize) {
  305. inUse[currentChar] = true;
  306. for (int i = 0; i < runLength; i++) {
  307. mCrc.Update(currentChar);
  308. }
  309. switch (runLength) {
  310. case 1:
  311. last++;
  312. block[last + 1] = (byte)currentChar;
  313. break;
  314. case 2:
  315. last++;
  316. block[last + 1] = (byte)currentChar;
  317. last++;
  318. block[last + 1] = (byte)currentChar;
  319. break;
  320. case 3:
  321. last++;
  322. block[last + 1] = (byte)currentChar;
  323. last++;
  324. block[last + 1] = (byte)currentChar;
  325. last++;
  326. block[last + 1] = (byte)currentChar;
  327. break;
  328. default:
  329. inUse[runLength - 4] = true;
  330. last++;
  331. block[last + 1] = (byte)currentChar;
  332. last++;
  333. block[last + 1] = (byte)currentChar;
  334. last++;
  335. block[last + 1] = (byte)currentChar;
  336. last++;
  337. block[last + 1] = (byte)currentChar;
  338. last++;
  339. block[last + 1] = (byte)(runLength - 4);
  340. break;
  341. }
  342. } else {
  343. EndBlock();
  344. InitBlock();
  345. WriteRun();
  346. }
  347. }
  348. /// <summary>
  349. /// Get the number of bytes written to the output.
  350. /// </summary>
  351. public int BytesWritten
  352. {
  353. get { return bytesOut; }
  354. }
  355. /// <summary>
  356. /// Releases the unmanaged resources used by the <see cref="BZip2OutputStream"/> and optionally releases the managed resources.
  357. /// </summary>
  358. /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
  359. override protected void Dispose(bool disposing)
  360. {
  361. try {
  362. try {
  363. base.Dispose(disposing);
  364. if (!disposed_) {
  365. disposed_ = true;
  366. if (runLength > 0) {
  367. WriteRun();
  368. }
  369. currentChar = -1;
  370. EndBlock();
  371. EndCompression();
  372. Flush();
  373. }
  374. } finally {
  375. if (disposing) {
  376. if (IsStreamOwner) {
  377. baseStream.Dispose();
  378. }
  379. }
  380. }
  381. } catch {
  382. }
  383. }
  384. /// <summary>
  385. /// Flush output buffers
  386. /// </summary>
  387. public override void Flush()
  388. {
  389. baseStream.Flush();
  390. }
  391. void Initialize()
  392. {
  393. bytesOut = 0;
  394. nBlocksRandomised = 0;
  395. /*--- Write header `magic' bytes indicating file-format == huffmanised,
  396. followed by a digit indicating blockSize100k.
  397. ---*/
  398. BsPutUChar('B');
  399. BsPutUChar('Z');
  400. BsPutUChar('h');
  401. BsPutUChar('0' + blockSize100k);
  402. combinedCRC = 0;
  403. }
  404. void InitBlock()
  405. {
  406. mCrc.Reset();
  407. last = -1;
  408. for (int i = 0; i < 256; i++) {
  409. inUse[i] = false;
  410. }
  411. /*--- 20 is just a paranoia constant ---*/
  412. allowableBlockSize = BZip2Constants.BaseBlockSize * blockSize100k - 20;
  413. }
  414. void EndBlock()
  415. {
  416. if (last < 0) { // dont do anything for empty files, (makes empty files compatible with original Bzip)
  417. return;
  418. }
  419. blockCRC = unchecked((uint)mCrc.Value);
  420. combinedCRC = (combinedCRC << 1) | (combinedCRC >> 31);
  421. combinedCRC ^= blockCRC;
  422. /*-- sort the block and establish position of original string --*/
  423. DoReversibleTransformation();
  424. /*--
  425. A 6-byte block header, the value chosen arbitrarily
  426. as 0x314159265359 :-). A 32 bit value does not really
  427. give a strong enough guarantee that the value will not
  428. appear by chance in the compressed datastream. Worst-case
  429. probability of this event, for a 900k block, is about
  430. 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
  431. For a compressed file of size 100Gb -- about 100000 blocks --
  432. only a 48-bit marker will do. NB: normal compression/
  433. decompression do *not* rely on these statistical properties.
  434. They are only important when trying to recover blocks from
  435. damaged files.
  436. --*/
  437. BsPutUChar(0x31);
  438. BsPutUChar(0x41);
  439. BsPutUChar(0x59);
  440. BsPutUChar(0x26);
  441. BsPutUChar(0x53);
  442. BsPutUChar(0x59);
  443. /*-- Now the block's CRC, so it is in a known place. --*/
  444. unchecked {
  445. BsPutint((int)blockCRC);
  446. }
  447. /*-- Now a single bit indicating randomisation. --*/
  448. if (blockRandomised) {
  449. BsW(1, 1);
  450. nBlocksRandomised++;
  451. } else {
  452. BsW(1, 0);
  453. }
  454. /*-- Finally, block's contents proper. --*/
  455. MoveToFrontCodeAndSend();
  456. }
  457. void EndCompression()
  458. {
  459. /*--
  460. Now another magic 48-bit number, 0x177245385090, to
  461. indicate the end of the last block. (sqrt(pi), if
  462. you want to know. I did want to use e, but it contains
  463. too much repetition -- 27 18 28 18 28 46 -- for me
  464. to feel statistically comfortable. Call me paranoid.)
  465. --*/
  466. BsPutUChar(0x17);
  467. BsPutUChar(0x72);
  468. BsPutUChar(0x45);
  469. BsPutUChar(0x38);
  470. BsPutUChar(0x50);
  471. BsPutUChar(0x90);
  472. unchecked {
  473. BsPutint((int)combinedCRC);
  474. }
  475. BsFinishedWithStream();
  476. }
  477. void BsFinishedWithStream()
  478. {
  479. while (bsLive > 0) {
  480. int ch = (bsBuff >> 24);
  481. baseStream.WriteByte((byte)ch); // write 8-bit
  482. bsBuff <<= 8;
  483. bsLive -= 8;
  484. bytesOut++;
  485. }
  486. }
  487. void BsW(int n, int v)
  488. {
  489. while (bsLive >= 8) {
  490. int ch = (bsBuff >> 24);
  491. unchecked { baseStream.WriteByte((byte)ch); } // write 8-bit
  492. bsBuff <<= 8;
  493. bsLive -= 8;
  494. ++bytesOut;
  495. }
  496. bsBuff |= (v << (32 - bsLive - n));
  497. bsLive += n;
  498. }
  499. void BsPutUChar(int c)
  500. {
  501. BsW(8, c);
  502. }
  503. void BsPutint(int u)
  504. {
  505. BsW(8, (u >> 24) & 0xFF);
  506. BsW(8, (u >> 16) & 0xFF);
  507. BsW(8, (u >> 8) & 0xFF);
  508. BsW(8, u & 0xFF);
  509. }
  510. void BsPutIntVS(int numBits, int c)
  511. {
  512. BsW(numBits, c);
  513. }
  514. void SendMTFValues()
  515. {
  516. char[][] len = new char[BZip2Constants.GroupCount][];
  517. for (int i = 0; i < BZip2Constants.GroupCount; ++i) {
  518. len[i] = new char[BZip2Constants.MaximumAlphaSize];
  519. }
  520. int gs, ge, totc, bt, bc, iter;
  521. int nSelectors = 0, alphaSize, minLen, maxLen, selCtr;
  522. int nGroups;
  523. alphaSize = nInUse + 2;
  524. for (int t = 0; t < BZip2Constants.GroupCount; t++) {
  525. for (int v = 0; v < alphaSize; v++) {
  526. len[t][v] = (char)GREATER_ICOST;
  527. }
  528. }
  529. /*--- Decide how many coding tables to use ---*/
  530. if (nMTF <= 0) {
  531. Panic();
  532. }
  533. if (nMTF < 200) {
  534. nGroups = 2;
  535. } else if (nMTF < 600) {
  536. nGroups = 3;
  537. } else if (nMTF < 1200) {
  538. nGroups = 4;
  539. } else if (nMTF < 2400) {
  540. nGroups = 5;
  541. } else {
  542. nGroups = 6;
  543. }
  544. /*--- Generate an initial set of coding tables ---*/
  545. int nPart = nGroups;
  546. int remF = nMTF;
  547. gs = 0;
  548. while (nPart > 0) {
  549. int tFreq = remF / nPart;
  550. int aFreq = 0;
  551. ge = gs - 1;
  552. while (aFreq < tFreq && ge < alphaSize - 1) {
  553. ge++;
  554. aFreq += mtfFreq[ge];
  555. }
  556. if (ge > gs && nPart != nGroups && nPart != 1 && ((nGroups - nPart) % 2 == 1)) {
  557. aFreq -= mtfFreq[ge];
  558. ge--;
  559. }
  560. for (int v = 0; v < alphaSize; v++) {
  561. if (v >= gs && v <= ge) {
  562. len[nPart - 1][v] = (char)LESSER_ICOST;
  563. } else {
  564. len[nPart - 1][v] = (char)GREATER_ICOST;
  565. }
  566. }
  567. nPart--;
  568. gs = ge + 1;
  569. remF -= aFreq;
  570. }
  571. int[][] rfreq = new int[BZip2Constants.GroupCount][];
  572. for (int i = 0; i < BZip2Constants.GroupCount; ++i) {
  573. rfreq[i] = new int[BZip2Constants.MaximumAlphaSize];
  574. }
  575. int[] fave = new int[BZip2Constants.GroupCount];
  576. short[] cost = new short[BZip2Constants.GroupCount];
  577. /*---
  578. Iterate up to N_ITERS times to improve the tables.
  579. ---*/
  580. for (iter = 0; iter < BZip2Constants.NumberOfIterations; ++iter) {
  581. for (int t = 0; t < nGroups; ++t) {
  582. fave[t] = 0;
  583. }
  584. for (int t = 0; t < nGroups; ++t) {
  585. for (int v = 0; v < alphaSize; ++v) {
  586. rfreq[t][v] = 0;
  587. }
  588. }
  589. nSelectors = 0;
  590. totc = 0;
  591. gs = 0;
  592. while (true) {
  593. /*--- Set group start & end marks. --*/
  594. if (gs >= nMTF) {
  595. break;
  596. }
  597. ge = gs + BZip2Constants.GroupSize - 1;
  598. if (ge >= nMTF) {
  599. ge = nMTF - 1;
  600. }
  601. /*--
  602. Calculate the cost of this group as coded
  603. by each of the coding tables.
  604. --*/
  605. for (int t = 0; t < nGroups; t++) {
  606. cost[t] = 0;
  607. }
  608. if (nGroups == 6) {
  609. short cost0, cost1, cost2, cost3, cost4, cost5;
  610. cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0;
  611. for (int i = gs; i <= ge; ++i) {
  612. short icv = szptr[i];
  613. cost0 += (short)len[0][icv];
  614. cost1 += (short)len[1][icv];
  615. cost2 += (short)len[2][icv];
  616. cost3 += (short)len[3][icv];
  617. cost4 += (short)len[4][icv];
  618. cost5 += (short)len[5][icv];
  619. }
  620. cost[0] = cost0;
  621. cost[1] = cost1;
  622. cost[2] = cost2;
  623. cost[3] = cost3;
  624. cost[4] = cost4;
  625. cost[5] = cost5;
  626. } else {
  627. for (int i = gs; i <= ge; ++i) {
  628. short icv = szptr[i];
  629. for (int t = 0; t < nGroups; t++) {
  630. cost[t] += (short)len[t][icv];
  631. }
  632. }
  633. }
  634. /*--
  635. Find the coding table which is best for this group,
  636. and record its identity in the selector table.
  637. --*/
  638. bc = 999999999;
  639. bt = -1;
  640. for (int t = 0; t < nGroups; ++t) {
  641. if (cost[t] < bc) {
  642. bc = cost[t];
  643. bt = t;
  644. }
  645. }
  646. totc += bc;
  647. fave[bt]++;
  648. selector[nSelectors] = (char)bt;
  649. nSelectors++;
  650. /*--
  651. Increment the symbol frequencies for the selected table.
  652. --*/
  653. for (int i = gs; i <= ge; ++i) {
  654. ++rfreq[bt][szptr[i]];
  655. }
  656. gs = ge + 1;
  657. }
  658. /*--
  659. Recompute the tables based on the accumulated frequencies.
  660. --*/
  661. for (int t = 0; t < nGroups; ++t) {
  662. HbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20);
  663. }
  664. }
  665. rfreq = null;
  666. fave = null;
  667. cost = null;
  668. if (!(nGroups < 8)) {
  669. Panic();
  670. }
  671. if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.GroupSize)))) {
  672. Panic();
  673. }
  674. /*--- Compute MTF values for the selectors. ---*/
  675. char[] pos = new char[BZip2Constants.GroupCount];
  676. char ll_i, tmp2, tmp;
  677. for (int i = 0; i < nGroups; i++) {
  678. pos[i] = (char)i;
  679. }
  680. for (int i = 0; i < nSelectors; i++) {
  681. ll_i = selector[i];
  682. int j = 0;
  683. tmp = pos[j];
  684. while (ll_i != tmp) {
  685. j++;
  686. tmp2 = tmp;
  687. tmp = pos[j];
  688. pos[j] = tmp2;
  689. }
  690. pos[0] = tmp;
  691. selectorMtf[i] = (char)j;
  692. }
  693. int[][] code = new int[BZip2Constants.GroupCount][];
  694. for (int i = 0; i < BZip2Constants.GroupCount; ++i) {
  695. code[i] = new int[BZip2Constants.MaximumAlphaSize];
  696. }
  697. /*--- Assign actual codes for the tables. --*/
  698. for (int t = 0; t < nGroups; t++) {
  699. minLen = 32;
  700. maxLen = 0;
  701. for (int i = 0; i < alphaSize; i++) {
  702. if (len[t][i] > maxLen) {
  703. maxLen = len[t][i];
  704. }
  705. if (len[t][i] < minLen) {
  706. minLen = len[t][i];
  707. }
  708. }
  709. if (maxLen > 20) {
  710. Panic();
  711. }
  712. if (minLen < 1) {
  713. Panic();
  714. }
  715. HbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize);
  716. }
  717. /*--- Transmit the mapping table. ---*/
  718. bool[] inUse16 = new bool[16];
  719. for (int i = 0; i < 16; ++i) {
  720. inUse16[i] = false;
  721. for (int j = 0; j < 16; ++j) {
  722. if (inUse[i * 16 + j]) {
  723. inUse16[i] = true;
  724. }
  725. }
  726. }
  727. for (int i = 0; i < 16; ++i) {
  728. if (inUse16[i]) {
  729. BsW(1, 1);
  730. } else {
  731. BsW(1, 0);
  732. }
  733. }
  734. for (int i = 0; i < 16; ++i) {
  735. if (inUse16[i]) {
  736. for (int j = 0; j < 16; ++j) {
  737. if (inUse[i * 16 + j]) {
  738. BsW(1, 1);
  739. } else {
  740. BsW(1, 0);
  741. }
  742. }
  743. }
  744. }
  745. /*--- Now the selectors. ---*/
  746. BsW(3, nGroups);
  747. BsW(15, nSelectors);
  748. for (int i = 0; i < nSelectors; ++i) {
  749. for (int j = 0; j < selectorMtf[i]; ++j) {
  750. BsW(1, 1);
  751. }
  752. BsW(1, 0);
  753. }
  754. /*--- Now the coding tables. ---*/
  755. for (int t = 0; t < nGroups; ++t) {
  756. int curr = len[t][0];
  757. BsW(5, curr);
  758. for (int i = 0; i < alphaSize; ++i) {
  759. while (curr < len[t][i]) {
  760. BsW(2, 2);
  761. curr++; /* 10 */
  762. }
  763. while (curr > len[t][i]) {
  764. BsW(2, 3);
  765. curr--; /* 11 */
  766. }
  767. BsW(1, 0);
  768. }
  769. }
  770. /*--- And finally, the block data proper ---*/
  771. selCtr = 0;
  772. gs = 0;
  773. while (true) {
  774. if (gs >= nMTF) {
  775. break;
  776. }
  777. ge = gs + BZip2Constants.GroupSize - 1;
  778. if (ge >= nMTF) {
  779. ge = nMTF - 1;
  780. }
  781. for (int i = gs; i <= ge; i++) {
  782. BsW(len[selector[selCtr]][szptr[i]], code[selector[selCtr]][szptr[i]]);
  783. }
  784. gs = ge + 1;
  785. ++selCtr;
  786. }
  787. if (!(selCtr == nSelectors)) {
  788. Panic();
  789. }
  790. }
  791. void MoveToFrontCodeAndSend()
  792. {
  793. BsPutIntVS(24, origPtr);
  794. GenerateMTFValues();
  795. SendMTFValues();
  796. }
  797. void SimpleSort(int lo, int hi, int d)
  798. {
  799. int i, j, h, bigN, hp;
  800. int v;
  801. bigN = hi - lo + 1;
  802. if (bigN < 2) {
  803. return;
  804. }
  805. hp = 0;
  806. while (increments[hp] < bigN) {
  807. hp++;
  808. }
  809. hp--;
  810. for (; hp >= 0; hp--) {
  811. h = increments[hp];
  812. i = lo + h;
  813. while (true) {
  814. /*-- copy 1 --*/
  815. if (i > hi)
  816. break;
  817. v = zptr[i];
  818. j = i;
  819. while (FullGtU(zptr[j - h] + d, v + d)) {
  820. zptr[j] = zptr[j - h];
  821. j = j - h;
  822. if (j <= (lo + h - 1))
  823. break;
  824. }
  825. zptr[j] = v;
  826. i++;
  827. /*-- copy 2 --*/
  828. if (i > hi) {
  829. break;
  830. }
  831. v = zptr[i];
  832. j = i;
  833. while (FullGtU(zptr[j - h] + d, v + d)) {
  834. zptr[j] = zptr[j - h];
  835. j = j - h;
  836. if (j <= (lo + h - 1)) {
  837. break;
  838. }
  839. }
  840. zptr[j] = v;
  841. i++;
  842. /*-- copy 3 --*/
  843. if (i > hi) {
  844. break;
  845. }
  846. v = zptr[i];
  847. j = i;
  848. while (FullGtU(zptr[j - h] + d, v + d)) {
  849. zptr[j] = zptr[j - h];
  850. j = j - h;
  851. if (j <= (lo + h - 1)) {
  852. break;
  853. }
  854. }
  855. zptr[j] = v;
  856. i++;
  857. if (workDone > workLimit && firstAttempt) {
  858. return;
  859. }
  860. }
  861. }
  862. }
  863. void Vswap(int p1, int p2, int n)
  864. {
  865. int temp = 0;
  866. while (n > 0) {
  867. temp = zptr[p1];
  868. zptr[p1] = zptr[p2];
  869. zptr[p2] = temp;
  870. p1++;
  871. p2++;
  872. n--;
  873. }
  874. }
  875. void QSort3(int loSt, int hiSt, int dSt)
  876. {
  877. int unLo, unHi, ltLo, gtHi, med, n, m;
  878. int lo, hi, d;
  879. StackElement[] stack = new StackElement[QSORT_STACK_SIZE];
  880. int sp = 0;
  881. stack[sp].ll = loSt;
  882. stack[sp].hh = hiSt;
  883. stack[sp].dd = dSt;
  884. sp++;
  885. while (sp > 0) {
  886. if (sp >= QSORT_STACK_SIZE) {
  887. Panic();
  888. }
  889. sp--;
  890. lo = stack[sp].ll;
  891. hi = stack[sp].hh;
  892. d = stack[sp].dd;
  893. if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) {
  894. SimpleSort(lo, hi, d);
  895. if (workDone > workLimit && firstAttempt) {
  896. return;
  897. }
  898. continue;
  899. }
  900. med = Med3(block[zptr[lo] + d + 1],
  901. block[zptr[hi] + d + 1],
  902. block[zptr[(lo + hi) >> 1] + d + 1]);
  903. unLo = ltLo = lo;
  904. unHi = gtHi = hi;
  905. while (true) {
  906. while (true) {
  907. if (unLo > unHi) {
  908. break;
  909. }
  910. n = ((int)block[zptr[unLo] + d + 1]) - med;
  911. if (n == 0) {
  912. int temp = zptr[unLo];
  913. zptr[unLo] = zptr[ltLo];
  914. zptr[ltLo] = temp;
  915. ltLo++;
  916. unLo++;
  917. continue;
  918. }
  919. if (n > 0) {
  920. break;
  921. }
  922. unLo++;
  923. }
  924. while (true) {
  925. if (unLo > unHi) {
  926. break;
  927. }
  928. n = ((int)block[zptr[unHi] + d + 1]) - med;
  929. if (n == 0) {
  930. int temp = zptr[unHi];
  931. zptr[unHi] = zptr[gtHi];
  932. zptr[gtHi] = temp;
  933. gtHi--;
  934. unHi--;
  935. continue;
  936. }
  937. if (n < 0) {
  938. break;
  939. }
  940. unHi--;
  941. }
  942. if (unLo > unHi) {
  943. break;
  944. }
  945. {
  946. int temp = zptr[unLo];
  947. zptr[unLo] = zptr[unHi];
  948. zptr[unHi] = temp;
  949. unLo++;
  950. unHi--;
  951. }
  952. }
  953. if (gtHi < ltLo) {
  954. stack[sp].ll = lo;
  955. stack[sp].hh = hi;
  956. stack[sp].dd = d + 1;
  957. sp++;
  958. continue;
  959. }
  960. n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo);
  961. Vswap(lo, unLo - n, n);
  962. m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi);
  963. Vswap(unLo, hi - m + 1, m);
  964. n = lo + unLo - ltLo - 1;
  965. m = hi - (gtHi - unHi) + 1;
  966. stack[sp].ll = lo;
  967. stack[sp].hh = n;
  968. stack[sp].dd = d;
  969. sp++;
  970. stack[sp].ll = n + 1;
  971. stack[sp].hh = m - 1;
  972. stack[sp].dd = d + 1;
  973. sp++;
  974. stack[sp].ll = m;
  975. stack[sp].hh = hi;
  976. stack[sp].dd = d;
  977. sp++;
  978. }
  979. }
  980. void MainSort()
  981. {
  982. int i, j, ss, sb;
  983. int[] runningOrder = new int[256];
  984. int[] copy = new int[256];
  985. bool[] bigDone = new bool[256];
  986. int c1, c2;
  987. int numQSorted;
  988. /*--
  989. In the various block-sized structures, live data runs
  990. from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First,
  991. set up the overshoot area for block.
  992. --*/
  993. // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" );
  994. for (i = 0; i < BZip2Constants.OvershootBytes; i++) {
  995. block[last + i + 2] = block[(i % (last + 1)) + 1];
  996. }
  997. for (i = 0; i <= last + BZip2Constants.OvershootBytes; i++) {
  998. quadrant[i] = 0;
  999. }
  1000. block[0] = (byte)(block[last + 1]);
  1001. if (last < 4000) {
  1002. /*--
  1003. Use simpleSort(), since the full sorting mechanism
  1004. has quite a large constant overhead.
  1005. --*/
  1006. for (i = 0; i <= last; i++) {
  1007. zptr[i] = i;
  1008. }
  1009. firstAttempt = false;
  1010. workDone = workLimit = 0;
  1011. SimpleSort(0, last, 0);
  1012. } else {
  1013. numQSorted = 0;
  1014. for (i = 0; i <= 255; i++) {
  1015. bigDone[i] = false;
  1016. }
  1017. for (i = 0; i <= 65536; i++) {
  1018. ftab[i] = 0;
  1019. }
  1020. c1 = block[0];
  1021. for (i = 0; i <= last; i++) {
  1022. c2 = block[i + 1];
  1023. ftab[(c1 << 8) + c2]++;
  1024. c1 = c2;
  1025. }
  1026. for (i = 1; i <= 65536; i++) {
  1027. ftab[i] += ftab[i - 1];
  1028. }
  1029. c1 = block[1];
  1030. for (i = 0; i < last; i++) {
  1031. c2 = block[i + 2];
  1032. j = (c1 << 8) + c2;
  1033. c1 = c2;
  1034. ftab[j]--;
  1035. zptr[ftab[j]] = i;
  1036. }
  1037. j = ((block[last + 1]) << 8) + (block[1]);
  1038. ftab[j]--;
  1039. zptr[ftab[j]] = last;
  1040. /*--
  1041. Now ftab contains the first loc of every small bucket.
  1042. Calculate the running order, from smallest to largest
  1043. big bucket.
  1044. --*/
  1045. for (i = 0; i <= 255; i++) {
  1046. runningOrder[i] = i;
  1047. }
  1048. int vv;
  1049. int h = 1;
  1050. do {
  1051. h = 3 * h + 1;
  1052. } while (h <= 256);
  1053. do {
  1054. h = h / 3;
  1055. for (i = h; i <= 255; i++) {
  1056. vv = runningOrder[i];
  1057. j = i;
  1058. while ((ftab[((runningOrder[j - h]) + 1) << 8] - ftab[(runningOrder[j - h]) << 8]) > (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) {
  1059. runningOrder[j] = runningOrder[j - h];
  1060. j = j - h;
  1061. if (j <= (h - 1)) {
  1062. break;
  1063. }
  1064. }
  1065. runningOrder[j] = vv;
  1066. }
  1067. } while (h != 1);
  1068. /*--
  1069. The main sorting loop.
  1070. --*/
  1071. for (i = 0; i <= 255; i++) {
  1072. /*--
  1073. Process big buckets, starting with the least full.
  1074. --*/
  1075. ss = runningOrder[i];
  1076. /*--
  1077. Complete the big bucket [ss] by quicksorting
  1078. any unsorted small buckets [ss, j]. Hopefully
  1079. previous pointer-scanning phases have already
  1080. completed many of the small buckets [ss, j], so
  1081. we don't have to sort them at all.
  1082. --*/
  1083. for (j = 0; j <= 255; j++) {
  1084. sb = (ss << 8) + j;
  1085. if (!((ftab[sb] & SETMASK) == SETMASK)) {
  1086. int lo = ftab[sb] & CLEARMASK;
  1087. int hi = (ftab[sb + 1] & CLEARMASK) - 1;
  1088. if (hi > lo) {
  1089. QSort3(lo, hi, 2);
  1090. numQSorted += (hi - lo + 1);
  1091. if (workDone > workLimit && firstAttempt) {
  1092. return;
  1093. }
  1094. }
  1095. ftab[sb] |= SETMASK;
  1096. }
  1097. }
  1098. /*--
  1099. The ss big bucket is now done. Record this fact,
  1100. and update the quadrant descriptors. Remember to
  1101. update quadrants in the overshoot area too, if
  1102. necessary. The "if (i < 255)" test merely skips
  1103. this updating for the last bucket processed, since
  1104. updating for the last bucket is pointless.
  1105. --*/
  1106. bigDone[ss] = true;
  1107. if (i < 255) {
  1108. int bbStart = ftab[ss << 8] & CLEARMASK;
  1109. int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart;
  1110. int shifts = 0;
  1111. while ((bbSize >> shifts) > 65534) {
  1112. shifts++;
  1113. }
  1114. for (j = 0; j < bbSize; j++) {
  1115. int a2update = zptr[bbStart + j];
  1116. int qVal = (j >> shifts);
  1117. quadrant[a2update] = qVal;
  1118. if (a2update < BZip2Constants.OvershootBytes) {
  1119. quadrant[a2update + last + 1] = qVal;
  1120. }
  1121. }
  1122. if (!(((bbSize - 1) >> shifts) <= 65535)) {
  1123. Panic();
  1124. }
  1125. }
  1126. /*--
  1127. Now scan this big bucket so as to synthesise the
  1128. sorted order for small buckets [t, ss] for all t != ss.
  1129. --*/
  1130. for (j = 0; j <= 255; j++) {
  1131. copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
  1132. }
  1133. for (j = ftab[ss << 8] & CLEARMASK; j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) {
  1134. c1 = block[zptr[j]];
  1135. if (!bigDone[c1]) {
  1136. zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
  1137. copy[c1]++;
  1138. }
  1139. }
  1140. for (j = 0; j <= 255; j++) {
  1141. ftab[(j << 8) + ss] |= SETMASK;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. void RandomiseBlock()
  1147. {
  1148. int i;
  1149. int rNToGo = 0;
  1150. int rTPos = 0;
  1151. for (i = 0; i < 256; i++) {
  1152. inUse[i] = false;
  1153. }
  1154. for (i = 0; i <= last; i++) {
  1155. if (rNToGo == 0) {
  1156. rNToGo = (int)BZip2Constants.RandomNumbers[rTPos];
  1157. rTPos++;
  1158. if (rTPos == 512) {
  1159. rTPos = 0;
  1160. }
  1161. }
  1162. rNToGo--;
  1163. block[i + 1] ^= (byte)((rNToGo == 1) ? 1 : 0);
  1164. // handle 16 bit signed numbers
  1165. block[i + 1] &= 0xFF;
  1166. inUse[block[i + 1]] = true;
  1167. }
  1168. }
  1169. void DoReversibleTransformation()
  1170. {
  1171. workLimit = workFactor * last;
  1172. workDone = 0;
  1173. blockRandomised = false;
  1174. firstAttempt = true;
  1175. MainSort();
  1176. if (workDone > workLimit && firstAttempt) {
  1177. RandomiseBlock();
  1178. workLimit = workDone = 0;
  1179. blockRandomised = true;
  1180. firstAttempt = false;
  1181. MainSort();
  1182. }
  1183. origPtr = -1;
  1184. for (int i = 0; i <= last; i++) {
  1185. if (zptr[i] == 0) {
  1186. origPtr = i;
  1187. break;
  1188. }
  1189. }
  1190. if (origPtr == -1) {
  1191. Panic();
  1192. }
  1193. }
  1194. bool FullGtU(int i1, int i2)
  1195. {
  1196. int k;
  1197. byte c1, c2;
  1198. int s1, s2;
  1199. c1 = block[i1 + 1];
  1200. c2 = block[i2 + 1];
  1201. if (c1 != c2) {
  1202. return c1 > c2;
  1203. }
  1204. i1++;
  1205. i2++;
  1206. c1 = block[i1 + 1];
  1207. c2 = block[i2 + 1];
  1208. if (c1 != c2) {
  1209. return c1 > c2;
  1210. }
  1211. i1++;
  1212. i2++;
  1213. c1 = block[i1 + 1];
  1214. c2 = block[i2 + 1];
  1215. if (c1 != c2) {
  1216. return c1 > c2;
  1217. }
  1218. i1++;
  1219. i2++;
  1220. c1 = block[i1 + 1];
  1221. c2 = block[i2 + 1];
  1222. if (c1 != c2) {
  1223. return c1 > c2;
  1224. }
  1225. i1++;
  1226. i2++;
  1227. c1 = block[i1 + 1];
  1228. c2 = block[i2 + 1];
  1229. if (c1 != c2) {
  1230. return c1 > c2;
  1231. }
  1232. i1++;
  1233. i2++;
  1234. c1 = block[i1 + 1];
  1235. c2 = block[i2 + 1];
  1236. if (c1 != c2) {
  1237. return c1 > c2;
  1238. }
  1239. i1++;
  1240. i2++;
  1241. k = last + 1;
  1242. do {
  1243. c1 = block[i1 + 1];
  1244. c2 = block[i2 + 1];
  1245. if (c1 != c2) {
  1246. return c1 > c2;
  1247. }
  1248. s1 = quadrant[i1];
  1249. s2 = quadrant[i2];
  1250. if (s1 != s2) {
  1251. return s1 > s2;
  1252. }
  1253. i1++;
  1254. i2++;
  1255. c1 = block[i1 + 1];
  1256. c2 = block[i2 + 1];
  1257. if (c1 != c2) {
  1258. return c1 > c2;
  1259. }
  1260. s1 = quadrant[i1];
  1261. s2 = quadrant[i2];
  1262. if (s1 != s2) {
  1263. return s1 > s2;
  1264. }
  1265. i1++;
  1266. i2++;
  1267. c1 = block[i1 + 1];
  1268. c2 = block[i2 + 1];
  1269. if (c1 != c2) {
  1270. return c1 > c2;
  1271. }
  1272. s1 = quadrant[i1];
  1273. s2 = quadrant[i2];
  1274. if (s1 != s2) {
  1275. return s1 > s2;
  1276. }
  1277. i1++;
  1278. i2++;
  1279. c1 = block[i1 + 1];
  1280. c2 = block[i2 + 1];
  1281. if (c1 != c2) {
  1282. return c1 > c2;
  1283. }
  1284. s1 = quadrant[i1];
  1285. s2 = quadrant[i2];
  1286. if (s1 != s2) {
  1287. return s1 > s2;
  1288. }
  1289. i1++;
  1290. i2++;
  1291. if (i1 > last) {
  1292. i1 -= last;
  1293. i1--;
  1294. }
  1295. if (i2 > last) {
  1296. i2 -= last;
  1297. i2--;
  1298. }
  1299. k -= 4;
  1300. ++workDone;
  1301. } while (k >= 0);
  1302. return false;
  1303. }
  1304. void AllocateCompressStructures()
  1305. {
  1306. int n = BZip2Constants.BaseBlockSize * blockSize100k;
  1307. block = new byte[(n + 1 + BZip2Constants.OvershootBytes)];
  1308. quadrant = new int[(n + BZip2Constants.OvershootBytes)];
  1309. zptr = new int[n];
  1310. ftab = new int[65537];
  1311. if (block == null || quadrant == null || zptr == null || ftab == null) {
  1312. // int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537;
  1313. // compressOutOfMemory ( totalDraw, n );
  1314. }
  1315. /*
  1316. The back end needs a place to store the MTF values
  1317. whilst it calculates the coding tables. We could
  1318. put them in the zptr array. However, these values
  1319. will fit in a short, so we overlay szptr at the
  1320. start of zptr, in the hope of reducing the number
  1321. of cache misses induced by the multiple traversals
  1322. of the MTF values when calculating coding tables.
  1323. Seems to improve compression speed by about 1%.
  1324. */
  1325. // szptr = zptr;
  1326. szptr = new short[2 * n];
  1327. }
  1328. void GenerateMTFValues()
  1329. {
  1330. char[] yy = new char[256];
  1331. int i, j;
  1332. char tmp;
  1333. char tmp2;
  1334. int zPend;
  1335. int wr;
  1336. int EOB;
  1337. MakeMaps();
  1338. EOB = nInUse + 1;
  1339. for (i = 0; i <= EOB; i++) {
  1340. mtfFreq[i] = 0;
  1341. }
  1342. wr = 0;
  1343. zPend = 0;
  1344. for (i = 0; i < nInUse; i++) {
  1345. yy[i] = (char)i;
  1346. }
  1347. for (i = 0; i <= last; i++) {
  1348. char ll_i;
  1349. ll_i = unseqToSeq[block[zptr[i]]];
  1350. j = 0;
  1351. tmp = yy[j];
  1352. while (ll_i != tmp) {
  1353. j++;
  1354. tmp2 = tmp;
  1355. tmp = yy[j];
  1356. yy[j] = tmp2;
  1357. }
  1358. yy[0] = tmp;
  1359. if (j == 0) {
  1360. zPend++;
  1361. } else {
  1362. if (zPend > 0) {
  1363. zPend--;
  1364. while (true) {
  1365. switch (zPend % 2) {
  1366. case 0:
  1367. szptr[wr] = (short)BZip2Constants.RunA;
  1368. wr++;
  1369. mtfFreq[BZip2Constants.RunA]++;
  1370. break;
  1371. case 1:
  1372. szptr[wr] = (short)BZip2Constants.RunB;
  1373. wr++;
  1374. mtfFreq[BZip2Constants.RunB]++;
  1375. break;
  1376. }
  1377. if (zPend < 2) {
  1378. break;
  1379. }
  1380. zPend = (zPend - 2) / 2;
  1381. }
  1382. zPend = 0;
  1383. }
  1384. szptr[wr] = (short)(j + 1);
  1385. wr++;
  1386. mtfFreq[j + 1]++;
  1387. }
  1388. }
  1389. if (zPend > 0) {
  1390. zPend--;
  1391. while (true) {
  1392. switch (zPend % 2) {
  1393. case 0:
  1394. szptr[wr] = (short)BZip2Constants.RunA;
  1395. wr++;
  1396. mtfFreq[BZip2Constants.RunA]++;
  1397. break;
  1398. case 1:
  1399. szptr[wr] = (short)BZip2Constants.RunB;
  1400. wr++;
  1401. mtfFreq[BZip2Constants.RunB]++;
  1402. break;
  1403. }
  1404. if (zPend < 2) {
  1405. break;
  1406. }
  1407. zPend = (zPend - 2) / 2;
  1408. }
  1409. }
  1410. szptr[wr] = (short)EOB;
  1411. wr++;
  1412. mtfFreq[EOB]++;
  1413. nMTF = wr;
  1414. }
  1415. static void Panic()
  1416. {
  1417. throw new BZip2Exception("BZip2 output stream panic");
  1418. }
  1419. static void HbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int maxLen)
  1420. {
  1421. /*--
  1422. Nodes and heap entries run from 1. Entry 0
  1423. for both the heap and nodes is a sentinel.
  1424. --*/
  1425. int nNodes, nHeap, n1, n2, j, k;
  1426. bool tooLong;
  1427. int[] heap = new int[BZip2Constants.MaximumAlphaSize + 2];
  1428. int[] weight = new int[BZip2Constants.MaximumAlphaSize * 2];
  1429. int[] parent = new int[BZip2Constants.MaximumAlphaSize * 2];
  1430. for (int i = 0; i < alphaSize; ++i) {
  1431. weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
  1432. }
  1433. while (true) {
  1434. nNodes = alphaSize;
  1435. nHeap = 0;
  1436. heap[0] = 0;
  1437. weight[0] = 0;
  1438. parent[0] = -2;
  1439. for (int i = 1; i <= alphaSize; ++i) {
  1440. parent[i] = -1;
  1441. nHeap++;
  1442. heap[nHeap] = i;
  1443. int zz = nHeap;
  1444. int tmp = heap[zz];
  1445. while (weight[tmp] < weight[heap[zz >> 1]]) {
  1446. heap[zz] = heap[zz >> 1];
  1447. zz >>= 1;
  1448. }
  1449. heap[zz] = tmp;
  1450. }
  1451. if (!(nHeap < (BZip2Constants.MaximumAlphaSize + 2))) {
  1452. Panic();
  1453. }
  1454. while (nHeap > 1) {
  1455. n1 = heap[1];
  1456. heap[1] = heap[nHeap];
  1457. nHeap--;
  1458. int zz = 1;
  1459. int yy = 0;
  1460. int tmp = heap[zz];
  1461. while (true) {
  1462. yy = zz << 1;
  1463. if (yy > nHeap) {
  1464. break;
  1465. }
  1466. if (yy < nHeap && weight[heap[yy + 1]] < weight[heap[yy]]) {
  1467. yy++;
  1468. }
  1469. if (weight[tmp] < weight[heap[yy]]) {
  1470. break;
  1471. }
  1472. heap[zz] = heap[yy];
  1473. zz = yy;
  1474. }
  1475. heap[zz] = tmp;
  1476. n2 = heap[1];
  1477. heap[1] = heap[nHeap];
  1478. nHeap--;
  1479. zz = 1;
  1480. yy = 0;
  1481. tmp = heap[zz];
  1482. while (true) {
  1483. yy = zz << 1;
  1484. if (yy > nHeap) {
  1485. break;
  1486. }
  1487. if (yy < nHeap && weight[heap[yy + 1]] < weight[heap[yy]]) {
  1488. yy++;
  1489. }
  1490. if (weight[tmp] < weight[heap[yy]]) {
  1491. break;
  1492. }
  1493. heap[zz] = heap[yy];
  1494. zz = yy;
  1495. }
  1496. heap[zz] = tmp;
  1497. nNodes++;
  1498. parent[n1] = parent[n2] = nNodes;
  1499. weight[nNodes] = (int)((weight[n1] & 0xffffff00) + (weight[n2] & 0xffffff00)) |
  1500. (int)(1 + (((weight[n1] & 0x000000ff) > (weight[n2] & 0x000000ff)) ? (weight[n1] & 0x000000ff) : (weight[n2] & 0x000000ff)));
  1501. parent[nNodes] = -1;
  1502. nHeap++;
  1503. heap[nHeap] = nNodes;
  1504. zz = nHeap;
  1505. tmp = heap[zz];
  1506. while (weight[tmp] < weight[heap[zz >> 1]]) {
  1507. heap[zz] = heap[zz >> 1];
  1508. zz >>= 1;
  1509. }
  1510. heap[zz] = tmp;
  1511. }
  1512. if (!(nNodes < (BZip2Constants.MaximumAlphaSize * 2))) {
  1513. Panic();
  1514. }
  1515. tooLong = false;
  1516. for (int i = 1; i <= alphaSize; ++i) {
  1517. j = 0;
  1518. k = i;
  1519. while (parent[k] >= 0) {
  1520. k = parent[k];
  1521. j++;
  1522. }
  1523. len[i - 1] = (char)j;
  1524. tooLong |= j > maxLen;
  1525. }
  1526. if (!tooLong) {
  1527. break;
  1528. }
  1529. for (int i = 1; i < alphaSize; ++i) {
  1530. j = weight[i] >> 8;
  1531. j = 1 + (j / 2);
  1532. weight[i] = j << 8;
  1533. }
  1534. }
  1535. }
  1536. static void HbAssignCodes(int[] code, char[] length, int minLen, int maxLen, int alphaSize)
  1537. {
  1538. int vec = 0;
  1539. for (int n = minLen; n <= maxLen; ++n) {
  1540. for (int i = 0; i < alphaSize; ++i) {
  1541. if (length[i] == n) {
  1542. code[i] = vec;
  1543. ++vec;
  1544. }
  1545. }
  1546. vec <<= 1;
  1547. }
  1548. }
  1549. static byte Med3(byte a, byte b, byte c)
  1550. {
  1551. byte t;
  1552. if (a > b) {
  1553. t = a;
  1554. a = b;
  1555. b = t;
  1556. }
  1557. if (b > c) {
  1558. t = b;
  1559. b = c;
  1560. c = t;
  1561. }
  1562. if (a > b) {
  1563. b = a;
  1564. }
  1565. return b;
  1566. }
  1567. struct StackElement
  1568. {
  1569. public int ll;
  1570. public int hh;
  1571. public int dd;
  1572. }
  1573. }
  1574. }