BZip2OutputStream.cs 42 KB

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