1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. /*
  18. * This package is based on the work done by Keiron Liddle, Aftex Software
  19. * <keiron@aftexsw.com> to whom the Ant project is very grateful for his
  20. * great code.
  21. */
  22. package org.apache.tools.bzip2;
  23. import java.io.OutputStream;
  24. import java.io.IOException;
  25. /**
  26. * An output stream that compresses into the BZip2 format (without the file
  27. * header chars) into another stream.
  28. *
  29. *
  30. * TODO: Update to BZip2 1.0.1
  31. */
  32. public class CBZip2OutputStream extends OutputStream implements BZip2Constants {
  33. protected static final int SETMASK = (1 << 21);
  34. protected static final int CLEARMASK = (~SETMASK);
  35. protected static final int GREATER_ICOST = 15;
  36. protected static final int LESSER_ICOST = 0;
  37. protected static final int SMALL_THRESH = 20;
  38. protected static final int DEPTH_THRESH = 10;
  39. /*
  40. If you are ever unlucky/improbable enough
  41. to get a stack overflow whilst sorting,
  42. increase the following constant and try
  43. again. In practice I have never seen the
  44. stack go above 27 elems, so the following
  45. limit seems very generous.
  46. */
  47. protected static final int QSORT_STACK_SIZE = 1000;
  48. private static void panic() {
  49. System.out.println("panic");
  50. //throw new CError();
  51. }
  52. private void makeMaps() {
  53. int i;
  54. nInUse = 0;
  55. for (i = 0; i < 256; i++) {
  56. if (inUse[i]) {
  57. seqToUnseq[nInUse] = (char) i;
  58. unseqToSeq[i] = (char) nInUse;
  59. nInUse++;
  60. }
  61. }
  62. }
  63. protected static void hbMakeCodeLengths(char[] len, int[] freq,
  64. int alphaSize, int maxLen) {
  65. /*
  66. Nodes and heap entries run from 1. Entry 0
  67. for both the heap and nodes is a sentinel.
  68. */
  69. int nNodes, nHeap, n1, n2, i, j, k;
  70. boolean tooLong;
  71. int[] heap = new int[MAX_ALPHA_SIZE + 2];
  72. int[] weight = new int[MAX_ALPHA_SIZE * 2];
  73. int[] parent = new int[MAX_ALPHA_SIZE * 2];
  74. for (i = 0; i < alphaSize; i++) {
  75. weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
  76. }
  77. while (true) {
  78. nNodes = alphaSize;
  79. nHeap = 0;
  80. heap[0] = 0;
  81. weight[0] = 0;
  82. parent[0] = -2;
  83. for (i = 1; i <= alphaSize; i++) {
  84. parent[i] = -1;
  85. nHeap++;
  86. heap[nHeap] = i;
  87. {
  88. int zz, tmp;
  89. zz = nHeap;
  90. tmp = heap[zz];
  91. while (weight[tmp] < weight[heap[zz >> 1]]) {
  92. heap[zz] = heap[zz >> 1];
  93. zz >>= 1;
  94. }
  95. heap[zz] = tmp;
  96. }
  97. }
  98. if (!(nHeap < (MAX_ALPHA_SIZE + 2))) {
  99. panic();
  100. }
  101. while (nHeap > 1) {
  102. n1 = heap[1];
  103. heap[1] = heap[nHeap];
  104. nHeap--;
  105. {
  106. int zz = 0, yy = 0, tmp = 0;
  107. zz = 1;
  108. tmp = heap[zz];
  109. while (true) {
  110. yy = zz << 1;
  111. if (yy > nHeap) {
  112. break;
  113. }
  114. if (yy < nHeap
  115. && weight[heap[yy + 1]] < weight[heap[yy]]) {
  116. yy++;
  117. }
  118. if (weight[tmp] < weight[heap[yy]]) {
  119. break;
  120. }
  121. heap[zz] = heap[yy];
  122. zz = yy;
  123. }
  124. heap[zz] = tmp;
  125. }
  126. n2 = heap[1];
  127. heap[1] = heap[nHeap];
  128. nHeap--;
  129. {
  130. int zz = 0, yy = 0, tmp = 0;
  131. zz = 1;
  132. tmp = heap[zz];
  133. while (true) {
  134. yy = zz << 1;
  135. if (yy > nHeap) {
  136. break;
  137. }
  138. if (yy < nHeap
  139. && weight[heap[yy + 1]] < weight[heap[yy]]) {
  140. yy++;
  141. }
  142. if (weight[tmp] < weight[heap[yy]]) {
  143. break;
  144. }
  145. heap[zz] = heap[yy];
  146. zz = yy;
  147. }
  148. heap[zz] = tmp;
  149. }
  150. nNodes++;
  151. parent[n1] = parent[n2] = nNodes;
  152. weight[nNodes] = ((weight[n1] & 0xffffff00)
  153. + (weight[n2] & 0xffffff00))
  154. | (1 + (((weight[n1] & 0x000000ff)
  155. > (weight[n2] & 0x000000ff))
  156. ? (weight[n1] & 0x000000ff)
  157. : (weight[n2] & 0x000000ff)));
  158. parent[nNodes] = -1;
  159. nHeap++;
  160. heap[nHeap] = nNodes;
  161. {
  162. int zz = 0, tmp = 0;
  163. zz = nHeap;
  164. tmp = heap[zz];
  165. while (weight[tmp] < weight[heap[zz >> 1]]) {
  166. heap[zz] = heap[zz >> 1];
  167. zz >>= 1;
  168. }
  169. heap[zz] = tmp;
  170. }
  171. }
  172. if (!(nNodes < (MAX_ALPHA_SIZE * 2))) {
  173. panic();
  174. }
  175. tooLong = false;
  176. for (i = 1; i <= alphaSize; i++) {
  177. j = 0;
  178. k = i;
  179. while (parent[k] >= 0) {
  180. k = parent[k];
  181. j++;
  182. }
  183. len[i - 1] = (char) j;
  184. if (j > maxLen) {
  185. tooLong = true;
  186. }
  187. }
  188. if (!tooLong) {
  189. break;
  190. }
  191. for (i = 1; i < alphaSize; i++) {
  192. j = weight[i] >> 8;
  193. j = 1 + (j / 2);
  194. weight[i] = j << 8;
  195. }
  196. }
  197. }
  198. /*
  199. index of the last char in the block, so
  200. the block size == last + 1.
  201. */
  202. int last;
  203. /*
  204. index in zptr[] of original string after sorting.
  205. */
  206. int origPtr;
  207. /*
  208. always: in the range 0 .. 9.
  209. The current block size is 100000 * this number.
  210. */
  211. int blockSize100k;
  212. boolean blockRandomised;
  213. int bytesOut;
  214. int bsBuff;
  215. int bsLive;
  216. CRC mCrc = new CRC();
  217. private boolean[] inUse = new boolean[256];
  218. private int nInUse;
  219. private char[] seqToUnseq = new char[256];
  220. private char[] unseqToSeq = new char[256];
  221. private char[] selector = new char[MAX_SELECTORS];
  222. private char[] selectorMtf = new char[MAX_SELECTORS];
  223. private char[] block;
  224. private int[] quadrant;
  225. private int[] zptr;
  226. private short[] szptr;
  227. private int[] ftab;
  228. private int nMTF;
  229. private int[] mtfFreq = new int[MAX_ALPHA_SIZE];
  230. /*
  231. * Used when sorting. If too many long comparisons
  232. * happen, we stop sorting, randomise the block
  233. * slightly, and try again.
  234. */
  235. private int workFactor;
  236. private int workDone;
  237. private int workLimit;
  238. private boolean firstAttempt;
  239. private int nBlocksRandomised;
  240. private int currentChar = -1;
  241. private int runLength = 0;
  242. public CBZip2OutputStream(OutputStream inStream) throws IOException {
  243. this(inStream, 9);
  244. }
  245. public CBZip2OutputStream(OutputStream inStream, int inBlockSize)
  246. throws IOException {
  247. block = null;
  248. quadrant = null;
  249. zptr = null;
  250. ftab = null;
  251. bsSetStream(inStream);
  252. workFactor = 50;
  253. if (inBlockSize > 9) {
  254. inBlockSize = 9;
  255. }
  256. if (inBlockSize < 1) {
  257. inBlockSize = 1;
  258. }
  259. blockSize100k = inBlockSize;
  260. allocateCompressStructures();
  261. initialize();
  262. initBlock();
  263. }
  264. /**
  265. *
  266. * modified by Oliver Merkel, 010128
  267. *
  268. */
  269. public void write(int bv) throws IOException {
  270. int b = (256 + bv) % 256;
  271. if (currentChar != -1) {
  272. if (currentChar == b) {
  273. runLength++;
  274. if (runLength > 254) {
  275. writeRun();
  276. currentChar = -1;
  277. runLength = 0;
  278. }
  279. } else {
  280. writeRun();
  281. runLength = 1;
  282. currentChar = b;
  283. }
  284. } else {
  285. currentChar = b;
  286. runLength++;
  287. }
  288. }
  289. private void writeRun() throws IOException {
  290. if (last < allowableBlockSize) {
  291. inUse[currentChar] = true;
  292. for (int i = 0; i < runLength; i++) {
  293. mCrc.updateCRC((char) currentChar);
  294. }
  295. switch (runLength) {
  296. case 1:
  297. last++;
  298. block[last + 1] = (char) currentChar;
  299. break;
  300. case 2:
  301. last++;
  302. block[last + 1] = (char) currentChar;
  303. last++;
  304. block[last + 1] = (char) currentChar;
  305. break;
  306. case 3:
  307. last++;
  308. block[last + 1] = (char) currentChar;
  309. last++;
  310. block[last + 1] = (char) currentChar;
  311. last++;
  312. block[last + 1] = (char) currentChar;
  313. break;
  314. default:
  315. inUse[runLength - 4] = true;
  316. last++;
  317. block[last + 1] = (char) currentChar;
  318. last++;
  319. block[last + 1] = (char) currentChar;
  320. last++;
  321. block[last + 1] = (char) currentChar;
  322. last++;
  323. block[last + 1] = (char) currentChar;
  324. last++;
  325. block[last + 1] = (char) (runLength - 4);
  326. break;
  327. }
  328. } else {
  329. endBlock();
  330. initBlock();
  331. writeRun();
  332. }
  333. }
  334. boolean closed = false;
  335. protected void finalize() throws Throwable {
  336. close();
  337. super.finalize();
  338. }
  339. public void close() throws IOException {
  340. if (closed) {
  341. return;
  342. }
  343. if (runLength > 0) {
  344. writeRun();
  345. }
  346. currentChar = -1;
  347. endBlock();
  348. endCompression();
  349. closed = true;
  350. super.close();
  351. bsStream.close();
  352. }
  353. public void flush() throws IOException {
  354. super.flush();
  355. bsStream.flush();
  356. }
  357. private int blockCRC, combinedCRC;
  358. private void initialize() throws IOException {
  359. bytesOut = 0;
  360. nBlocksRandomised = 0;
  361. /* Write `magic' bytes h indicating file-format == huffmanised,
  362. followed by a digit indicating blockSize100k.
  363. */
  364. bsPutUChar('h');
  365. bsPutUChar('0' + blockSize100k);
  366. combinedCRC = 0;
  367. }
  368. private int allowableBlockSize;
  369. private void initBlock() {
  370. // blockNo++;
  371. mCrc.initialiseCRC();
  372. last = -1;
  373. // ch = 0;
  374. for (int i = 0; i < 256; i++) {
  375. inUse[i] = false;
  376. }
  377. /* 20 is just a paranoia constant */
  378. allowableBlockSize = baseBlockSize * blockSize100k - 20;
  379. }
  380. private void endBlock() throws IOException {
  381. blockCRC = mCrc.getFinalCRC();
  382. combinedCRC = (combinedCRC << 1) | (combinedCRC >>> 31);
  383. combinedCRC ^= blockCRC;
  384. /* sort the block and establish posn of original string */
  385. doReversibleTransformation();
  386. /*
  387. A 6-byte block header, the value chosen arbitrarily
  388. as 0x314159265359 :-). A 32 bit value does not really
  389. give a strong enough guarantee that the value will not
  390. appear by chance in the compressed datastream. Worst-case
  391. probability of this event, for a 900k block, is about
  392. 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
  393. For a compressed file of size 100Gb -- about 100000 blocks --
  394. only a 48-bit marker will do. NB: normal compression/
  395. decompression do *not* rely on these statistical properties.
  396. They are only important when trying to recover blocks from
  397. damaged files.
  398. */
  399. bsPutUChar(0x31);
  400. bsPutUChar(0x41);
  401. bsPutUChar(0x59);
  402. bsPutUChar(0x26);
  403. bsPutUChar(0x53);
  404. bsPutUChar(0x59);
  405. /* Now the block's CRC, so it is in a known place. */
  406. bsPutint(blockCRC);
  407. /* Now a single bit indicating randomisation. */
  408. if (blockRandomised) {
  409. bsW(1, 1);
  410. nBlocksRandomised++;
  411. } else {
  412. bsW(1, 0);
  413. }
  414. /* Finally, block's contents proper. */
  415. moveToFrontCodeAndSend();
  416. }
  417. private void endCompression() throws IOException {
  418. /*
  419. Now another magic 48-bit number, 0x177245385090, to
  420. indicate the end of the last block. (sqrt(pi), if
  421. you want to know. I did want to use e, but it contains
  422. too much repetition -- 27 18 28 18 28 46 -- for me
  423. to feel statistically comfortable. Call me paranoid.)
  424. */
  425. bsPutUChar(0x17);
  426. bsPutUChar(0x72);
  427. bsPutUChar(0x45);
  428. bsPutUChar(0x38);
  429. bsPutUChar(0x50);
  430. bsPutUChar(0x90);
  431. bsPutint(combinedCRC);
  432. bsFinishedWithStream();
  433. }
  434. private void hbAssignCodes (int[] code, char[] length, int minLen,
  435. int maxLen, int alphaSize) {
  436. int n, vec, i;
  437. vec = 0;
  438. for (n = minLen; n <= maxLen; n++) {
  439. for (i = 0; i < alphaSize; i++) {
  440. if (length[i] == n) {
  441. code[i] = vec;
  442. vec++;
  443. }
  444. };
  445. vec <<= 1;
  446. }
  447. }
  448. private void bsSetStream(OutputStream f) {
  449. bsStream = f;
  450. bsLive = 0;
  451. bsBuff = 0;
  452. bytesOut = 0;
  453. }
  454. private void bsFinishedWithStream() throws IOException {
  455. while (bsLive > 0) {
  456. int ch = (bsBuff >> 24);
  457. try {
  458. bsStream.write(ch); // write 8-bit
  459. } catch (IOException e) {
  460. throw e;
  461. }
  462. bsBuff <<= 8;
  463. bsLive -= 8;
  464. bytesOut++;
  465. }
  466. }
  467. private void bsW(int n, int v) throws IOException {
  468. while (bsLive >= 8) {
  469. int ch = (bsBuff >> 24);
  470. try {
  471. bsStream.write(ch); // write 8-bit
  472. } catch (IOException e) {
  473. throw e;
  474. }
  475. bsBuff <<= 8;
  476. bsLive -= 8;
  477. bytesOut++;
  478. }
  479. bsBuff |= (v << (32 - bsLive - n));
  480. bsLive += n;
  481. }
  482. private void bsPutUChar(int c) throws IOException {
  483. bsW(8, c);
  484. }
  485. private void bsPutint(int u) throws IOException {
  486. bsW(8, (u >> 24) & 0xff);
  487. bsW(8, (u >> 16) & 0xff);
  488. bsW(8, (u >> 8) & 0xff);
  489. bsW(8, u & 0xff);
  490. }
  491. private void bsPutIntVS(int numBits, int c) throws IOException {
  492. bsW(numBits, c);
  493. }
  494. private void sendMTFValues() throws IOException {
  495. char len[][] = new char[N_GROUPS][MAX_ALPHA_SIZE];
  496. int v, t, i, j, gs, ge, totc, bt, bc, iter;
  497. int nSelectors = 0, alphaSize, minLen, maxLen, selCtr;
  498. int nGroups, nBytes;
  499. alphaSize = nInUse + 2;
  500. for (t = 0; t < N_GROUPS; t++) {
  501. for (v = 0; v < alphaSize; v++) {
  502. len[t][v] = (char) GREATER_ICOST;
  503. }
  504. }
  505. /* Decide how many coding tables to use */
  506. if (nMTF <= 0) {
  507. panic();
  508. }
  509. if (nMTF < 200) {
  510. nGroups = 2;
  511. } else if (nMTF < 600) {
  512. nGroups = 3;
  513. } else if (nMTF < 1200) {
  514. nGroups = 4;
  515. } else if (nMTF < 2400) {
  516. nGroups = 5;
  517. } else {
  518. nGroups = 6;
  519. }
  520. /* Generate an initial set of coding tables */ {
  521. int nPart, remF, tFreq, aFreq;
  522. nPart = nGroups;
  523. remF = nMTF;
  524. gs = 0;
  525. while (nPart > 0) {
  526. tFreq = remF / nPart;
  527. ge = gs - 1;
  528. aFreq = 0;
  529. while (aFreq < tFreq && ge < alphaSize - 1) {
  530. ge++;
  531. aFreq += mtfFreq[ge];
  532. }
  533. if (ge > gs && nPart != nGroups && nPart != 1
  534. && ((nGroups - nPart) % 2 == 1)) {
  535. aFreq -= mtfFreq[ge];
  536. ge--;
  537. }
  538. for (v = 0; v < alphaSize; v++) {
  539. if (v >= gs && v <= ge) {
  540. len[nPart - 1][v] = (char) LESSER_ICOST;
  541. } else {
  542. len[nPart - 1][v] = (char) GREATER_ICOST;
  543. }
  544. }
  545. nPart--;
  546. gs = ge + 1;
  547. remF -= aFreq;
  548. }
  549. }
  550. int[][] rfreq = new int[N_GROUPS][MAX_ALPHA_SIZE];
  551. int[] fave = new int[N_GROUPS];
  552. short[] cost = new short[N_GROUPS];
  553. /*
  554. Iterate up to N_ITERS times to improve the tables.
  555. */
  556. for (iter = 0; iter < N_ITERS; iter++) {
  557. for (t = 0; t < nGroups; t++) {
  558. fave[t] = 0;
  559. }
  560. for (t = 0; t < nGroups; t++) {
  561. for (v = 0; v < alphaSize; v++) {
  562. rfreq[t][v] = 0;
  563. }
  564. }
  565. nSelectors = 0;
  566. totc = 0;
  567. gs = 0;
  568. while (true) {
  569. /* Set group start & end marks. */
  570. if (gs >= nMTF) {
  571. break;
  572. }
  573. ge = gs + G_SIZE - 1;
  574. if (ge >= nMTF) {
  575. ge = nMTF - 1;
  576. }
  577. /*
  578. Calculate the cost of this group as coded
  579. by each of the coding tables.
  580. */
  581. for (t = 0; t < nGroups; t++) {
  582. cost[t] = 0;
  583. }
  584. if (nGroups == 6) {
  585. short cost0, cost1, cost2, cost3, cost4, cost5;
  586. cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0;
  587. for (i = gs; i <= ge; i++) {
  588. short icv = szptr[i];
  589. cost0 += len[0][icv];
  590. cost1 += len[1][icv];
  591. cost2 += len[2][icv];
  592. cost3 += len[3][icv];
  593. cost4 += len[4][icv];
  594. cost5 += len[5][icv];
  595. }
  596. cost[0] = cost0;
  597. cost[1] = cost1;
  598. cost[2] = cost2;
  599. cost[3] = cost3;
  600. cost[4] = cost4;
  601. cost[5] = cost5;
  602. } else {
  603. for (i = gs; i <= ge; i++) {
  604. short icv = szptr[i];
  605. for (t = 0; t < nGroups; t++) {
  606. cost[t] += len[t][icv];
  607. }
  608. }
  609. }
  610. /*
  611. Find the coding table which is best for this group,
  612. and record its identity in the selector table.
  613. */
  614. bc = 999999999;
  615. bt = -1;
  616. for (t = 0; t < nGroups; t++) {
  617. if (cost[t] < bc) {
  618. bc = cost[t];
  619. bt = t;
  620. }
  621. };
  622. totc += bc;
  623. fave[bt]++;
  624. selector[nSelectors] = (char) bt;
  625. nSelectors++;
  626. /*
  627. Increment the symbol frequencies for the selected table.
  628. */
  629. for (i = gs; i <= ge; i++) {
  630. rfreq[bt][szptr[i]]++;
  631. }
  632. gs = ge + 1;
  633. }
  634. /*
  635. Recompute the tables based on the accumulated frequencies.
  636. */
  637. for (t = 0; t < nGroups; t++) {
  638. hbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20);
  639. }
  640. }
  641. rfreq = null;
  642. fave = null;
  643. cost = null;
  644. if (!(nGroups < 8)) {
  645. panic();
  646. }
  647. if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / G_SIZE)))) {
  648. panic();
  649. }
  650. /* Compute MTF values for the selectors. */
  651. {
  652. char[] pos = new char[N_GROUPS];
  653. char ll_i, tmp2, tmp;
  654. for (i = 0; i < nGroups; i++) {
  655. pos[i] = (char) i;
  656. }
  657. for (i = 0; i < nSelectors; i++) {
  658. ll_i = selector[i];
  659. j = 0;
  660. tmp = pos[j];
  661. while (ll_i != tmp) {
  662. j++;
  663. tmp2 = tmp;
  664. tmp = pos[j];
  665. pos[j] = tmp2;
  666. }
  667. pos[0] = tmp;
  668. selectorMtf[i] = (char) j;
  669. }
  670. }
  671. int[][] code = new int[N_GROUPS][MAX_ALPHA_SIZE];
  672. /* Assign actual codes for the tables. */
  673. for (t = 0; t < nGroups; t++) {
  674. minLen = 32;
  675. maxLen = 0;
  676. for (i = 0; i < alphaSize; i++) {
  677. if (len[t][i] > maxLen) {
  678. maxLen = len[t][i];
  679. }
  680. if (len[t][i] < minLen) {
  681. minLen = len[t][i];
  682. }
  683. }
  684. if (maxLen > 20) {
  685. panic();
  686. }
  687. if (minLen < 1) {
  688. panic();
  689. }
  690. hbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize);
  691. }
  692. /* Transmit the mapping table. */
  693. {
  694. boolean[] inUse16 = new boolean[16];
  695. for (i = 0; i < 16; i++) {
  696. inUse16[i] = false;
  697. for (j = 0; j < 16; j++) {
  698. if (inUse[i * 16 + j]) {
  699. inUse16[i] = true;
  700. }
  701. }
  702. }
  703. nBytes = bytesOut;
  704. for (i = 0; i < 16; i++) {
  705. if (inUse16[i]) {
  706. bsW(1, 1);
  707. } else {
  708. bsW(1, 0);
  709. }
  710. }
  711. for (i = 0; i < 16; i++) {
  712. if (inUse16[i]) {
  713. for (j = 0; j < 16; j++) {
  714. if (inUse[i * 16 + j]) {
  715. bsW(1, 1);
  716. } else {
  717. bsW(1, 0);
  718. }
  719. }
  720. }
  721. }
  722. }
  723. /* Now the selectors. */
  724. nBytes = bytesOut;
  725. bsW (3, nGroups);
  726. bsW (15, nSelectors);
  727. for (i = 0; i < nSelectors; i++) {
  728. for (j = 0; j < selectorMtf[i]; j++) {
  729. bsW(1, 1);
  730. }
  731. bsW(1, 0);
  732. }
  733. /* Now the coding tables. */
  734. nBytes = bytesOut;
  735. for (t = 0; t < nGroups; t++) {
  736. int curr = len[t][0];
  737. bsW(5, curr);
  738. for (i = 0; i < alphaSize; i++) {
  739. while (curr < len[t][i]) {
  740. bsW(2, 2);
  741. curr++; /* 10 */
  742. }
  743. while (curr > len[t][i]) {
  744. bsW(2, 3);
  745. curr--; /* 11 */
  746. }
  747. bsW (1, 0);
  748. }
  749. }
  750. /* And finally, the block data proper */
  751. nBytes = bytesOut;
  752. selCtr = 0;
  753. gs = 0;
  754. while (true) {
  755. if (gs >= nMTF) {
  756. break;
  757. }
  758. ge = gs + G_SIZE - 1;
  759. if (ge >= nMTF) {
  760. ge = nMTF - 1;
  761. }
  762. for (i = gs; i <= ge; i++) {
  763. bsW(len[selector[selCtr]][szptr[i]],
  764. code[selector[selCtr]][szptr[i]]);
  765. }
  766. gs = ge + 1;
  767. selCtr++;
  768. }
  769. if (!(selCtr == nSelectors)) {
  770. panic();
  771. }
  772. }
  773. private void moveToFrontCodeAndSend () throws IOException {
  774. bsPutIntVS(24, origPtr);
  775. generateMTFValues();
  776. sendMTFValues();
  777. }
  778. private OutputStream bsStream;
  779. private void simpleSort(int lo, int hi, int d) {
  780. int i, j, h, bigN, hp;
  781. int v;
  782. bigN = hi - lo + 1;
  783. if (bigN < 2) {
  784. return;
  785. }
  786. hp = 0;
  787. while (incs[hp] < bigN) {
  788. hp++;
  789. }
  790. hp--;
  791. for (; hp >= 0; hp--) {
  792. h = incs[hp];
  793. i = lo + h;
  794. while (true) {
  795. /* copy 1 */
  796. if (i > hi) {
  797. break;
  798. }
  799. v = zptr[i];
  800. j = i;
  801. while (fullGtU(zptr[j - h] + d, v + d)) {
  802. zptr[j] = zptr[j - h];
  803. j = j - h;
  804. if (j <= (lo + h - 1)) {
  805. break;
  806. }
  807. }
  808. zptr[j] = v;
  809. i++;
  810. /* copy 2 */
  811. if (i > hi) {
  812. break;
  813. }
  814. v = zptr[i];
  815. j = i;
  816. while (fullGtU(zptr[j - h] + d, v + d)) {
  817. zptr[j] = zptr[j - h];
  818. j = j - h;
  819. if (j <= (lo + h - 1)) {
  820. break;
  821. }
  822. }
  823. zptr[j] = v;
  824. i++;
  825. /* copy 3 */
  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. if (workDone > workLimit && firstAttempt) {
  841. return;
  842. }
  843. }
  844. }
  845. }
  846. private void vswap(int p1, int p2, int n) {
  847. int temp = 0;
  848. while (n > 0) {
  849. temp = zptr[p1];
  850. zptr[p1] = zptr[p2];
  851. zptr[p2] = temp;
  852. p1++;
  853. p2++;
  854. n--;
  855. }
  856. }
  857. private char med3(char a, char b, char c) {
  858. char t;
  859. if (a > b) {
  860. t = a;
  861. a = b;
  862. b = t;
  863. }
  864. if (b > c) {
  865. t = b;
  866. b = c;
  867. c = t;
  868. }
  869. if (a > b) {
  870. b = a;
  871. }
  872. return b;
  873. }
  874. private static class StackElem {
  875. int ll;
  876. int hh;
  877. int dd;
  878. }
  879. private void qSort3(int loSt, int hiSt, int dSt) {
  880. int unLo, unHi, ltLo, gtHi, med, n, m;
  881. int sp, lo, hi, d;
  882. StackElem[] stack = new StackElem[QSORT_STACK_SIZE];
  883. for (int count = 0; count < QSORT_STACK_SIZE; count++) {
  884. stack[count] = new StackElem();
  885. }
  886. sp = 0;
  887. stack[sp].ll = loSt;
  888. stack[sp].hh = hiSt;
  889. stack[sp].dd = dSt;
  890. sp++;
  891. while (sp > 0) {
  892. if (sp >= QSORT_STACK_SIZE) {
  893. panic();
  894. }
  895. sp--;
  896. lo = stack[sp].ll;
  897. hi = stack[sp].hh;
  898. d = stack[sp].dd;
  899. if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) {
  900. simpleSort(lo, hi, d);
  901. if (workDone > workLimit && firstAttempt) {
  902. return;
  903. }
  904. continue;
  905. }
  906. med = med3(block[zptr[lo] + d + 1],
  907. block[zptr[hi ] + d + 1],
  908. block[zptr[(lo + hi) >> 1] + d + 1]);
  909. unLo = ltLo = lo;
  910. unHi = gtHi = hi;
  911. while (true) {
  912. while (true) {
  913. if (unLo > unHi) {
  914. break;
  915. }
  916. n = ((int) block[zptr[unLo] + d + 1]) - med;
  917. if (n == 0) {
  918. int temp = 0;
  919. temp = zptr[unLo];
  920. zptr[unLo] = zptr[ltLo];
  921. zptr[ltLo] = temp;
  922. ltLo++;
  923. unLo++;
  924. continue;
  925. };
  926. if (n > 0) {
  927. break;
  928. }
  929. unLo++;
  930. }
  931. while (true) {
  932. if (unLo > unHi) {
  933. break;
  934. }
  935. n = ((int) block[zptr[unHi] + d + 1]) - med;
  936. if (n == 0) {
  937. int temp = 0;
  938. temp = zptr[unHi];
  939. zptr[unHi] = zptr[gtHi];
  940. zptr[gtHi] = temp;
  941. gtHi--;
  942. unHi--;
  943. continue;
  944. };
  945. if (n < 0) {
  946. break;
  947. }
  948. unHi--;
  949. }
  950. if (unLo > unHi) {
  951. break;
  952. }
  953. int temp = 0;
  954. temp = zptr[unLo];
  955. zptr[unLo] = zptr[unHi];
  956. zptr[unHi] = temp;
  957. unLo++;
  958. unHi--;
  959. }
  960. if (gtHi < ltLo) {
  961. stack[sp].ll = lo;
  962. stack[sp].hh = hi;
  963. stack[sp].dd = d + 1;
  964. sp++;
  965. continue;
  966. }
  967. n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo);
  968. vswap(lo, unLo - n, n);
  969. m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi);
  970. vswap(unLo, hi - m + 1, m);
  971. n = lo + unLo - ltLo - 1;
  972. m = hi - (gtHi - unHi) + 1;
  973. stack[sp].ll = lo;
  974. stack[sp].hh = n;
  975. stack[sp].dd = d;
  976. sp++;
  977. stack[sp].ll = n + 1;
  978. stack[sp].hh = m - 1;
  979. stack[sp].dd = d + 1;
  980. sp++;
  981. stack[sp].ll = m;
  982. stack[sp].hh = hi;
  983. stack[sp].dd = d;
  984. sp++;
  985. }
  986. }
  987. private void mainSort() {
  988. int i, j, ss, sb;
  989. int[] runningOrder = new int[256];
  990. int[] copy = new int[256];
  991. boolean[] bigDone = new boolean[256];
  992. int c1, c2;
  993. int numQSorted;
  994. /*
  995. In the various block-sized structures, live data runs
  996. from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First,
  997. set up the overshoot area for block.
  998. */
  999. // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" );
  1000. for (i = 0; i < NUM_OVERSHOOT_BYTES; i++) {
  1001. block[last + i + 2] = block[(i % (last + 1)) + 1];
  1002. }
  1003. for (i = 0; i <= last + NUM_OVERSHOOT_BYTES; i++) {
  1004. quadrant[i] = 0;
  1005. }
  1006. block[0] = (char) (block[last + 1]);
  1007. if (last < 4000) {
  1008. /*
  1009. Use simpleSort(), since the full sorting mechanism
  1010. has quite a large constant overhead.
  1011. */
  1012. for (i = 0; i <= last; i++) {
  1013. zptr[i] = i;
  1014. }
  1015. firstAttempt = false;
  1016. workDone = workLimit = 0;
  1017. simpleSort(0, last, 0);
  1018. } else {
  1019. numQSorted = 0;
  1020. for (i = 0; i <= 255; i++) {
  1021. bigDone[i] = false;
  1022. }
  1023. for (i = 0; i <= 65536; i++) {
  1024. ftab[i] = 0;
  1025. }
  1026. c1 = block[0];
  1027. for (i = 0; i <= last; i++) {
  1028. c2 = block[i + 1];
  1029. ftab[(c1 << 8) + c2]++;
  1030. c1 = c2;
  1031. }
  1032. for (i = 1; i <= 65536; i++) {
  1033. ftab[i] += ftab[i - 1];
  1034. }
  1035. c1 = block[1];
  1036. for (i = 0; i < last; i++) {
  1037. c2 = block[i + 2];
  1038. j = (c1 << 8) + c2;
  1039. c1 = c2;
  1040. ftab[j]--;
  1041. zptr[ftab[j]] = i;
  1042. }
  1043. j = ((block[last + 1]) << 8) + (block[1]);
  1044. ftab[j]--;
  1045. zptr[ftab[j]] = last;
  1046. /*
  1047. Now ftab contains the first loc of every small bucket.
  1048. Calculate the running order, from smallest to largest
  1049. big bucket.
  1050. */
  1051. for (i = 0; i <= 255; i++) {
  1052. runningOrder[i] = i;
  1053. }
  1054. {
  1055. int vv;
  1056. int h = 1;
  1057. do {
  1058. h = 3 * h + 1;
  1059. }
  1060. while (h <= 256);
  1061. do {
  1062. h = h / 3;
  1063. for (i = h; i <= 255; i++) {
  1064. vv = runningOrder[i];
  1065. j = i;
  1066. while ((ftab[((runningOrder[j - h]) + 1) << 8]
  1067. - ftab[(runningOrder[j - h]) << 8])
  1068. > (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) {
  1069. runningOrder[j] = runningOrder[j - h];
  1070. j = j - h;
  1071. if (j <= (h - 1)) {
  1072. break;
  1073. }
  1074. }
  1075. runningOrder[j] = vv;
  1076. }
  1077. } while (h != 1);
  1078. }
  1079. /*
  1080. The main sorting loop.
  1081. */
  1082. for (i = 0; i <= 255; i++) {
  1083. /*
  1084. Process big buckets, starting with the least full.
  1085. */
  1086. ss = runningOrder[i];
  1087. /*
  1088. Complete the big bucket [ss] by quicksorting
  1089. any unsorted small buckets [ss, j]. Hopefully
  1090. previous pointer-scanning phases have already
  1091. completed many of the small buckets [ss, j], so
  1092. we don't have to sort them at all.
  1093. */
  1094. for (j = 0; j <= 255; j++) {
  1095. sb = (ss << 8) + j;
  1096. if (!((ftab[sb] & SETMASK) == SETMASK)) {
  1097. int lo = ftab[sb] & CLEARMASK;
  1098. int hi = (ftab[sb + 1] & CLEARMASK) - 1;
  1099. if (hi > lo) {
  1100. qSort3(lo, hi, 2);
  1101. numQSorted += (hi - lo + 1);
  1102. if (workDone > workLimit && firstAttempt) {
  1103. return;
  1104. }
  1105. }
  1106. ftab[sb] |= SETMASK;
  1107. }
  1108. }
  1109. /*
  1110. The ss big bucket is now done. Record this fact,
  1111. and update the quadrant descriptors. Remember to
  1112. update quadrants in the overshoot area too, if
  1113. necessary. The "if (i < 255)" test merely skips
  1114. this updating for the last bucket processed, since
  1115. updating for the last bucket is pointless.
  1116. */
  1117. bigDone[ss] = true;
  1118. if (i < 255) {
  1119. int bbStart = ftab[ss << 8] & CLEARMASK;
  1120. int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart;
  1121. int shifts = 0;
  1122. while ((bbSize >> shifts) > 65534) {
  1123. shifts++;
  1124. }
  1125. for (j = 0; j < bbSize; j++) {
  1126. int a2update = zptr[bbStart + j];
  1127. int qVal = (j >> shifts);
  1128. quadrant[a2update] = qVal;
  1129. if (a2update < NUM_OVERSHOOT_BYTES) {
  1130. quadrant[a2update + last + 1] = qVal;
  1131. }
  1132. }
  1133. if (!(((bbSize - 1) >> shifts) <= 65535)) {
  1134. panic();
  1135. }
  1136. }
  1137. /*
  1138. Now scan this big bucket so as to synthesise the
  1139. sorted order for small buckets [t, ss] for all t != ss.
  1140. */
  1141. for (j = 0; j <= 255; j++) {
  1142. copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
  1143. }
  1144. for (j = ftab[ss << 8] & CLEARMASK;
  1145. j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) {
  1146. c1 = block[zptr[j]];
  1147. if (!bigDone[c1]) {
  1148. zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
  1149. copy[c1]++;
  1150. }
  1151. }
  1152. for (j = 0; j <= 255; j++) {
  1153. ftab[(j << 8) + ss] |= SETMASK;
  1154. }
  1155. }
  1156. }
  1157. }
  1158. private void randomiseBlock() {
  1159. int i;
  1160. int rNToGo = 0;
  1161. int rTPos = 0;
  1162. for (i = 0; i < 256; i++) {
  1163. inUse[i] = false;
  1164. }
  1165. for (i = 0; i <= last; i++) {
  1166. if (rNToGo == 0) {
  1167. rNToGo = (char) rNums[rTPos];
  1168. rTPos++;
  1169. if (rTPos == 512) {
  1170. rTPos = 0;
  1171. }
  1172. }
  1173. rNToGo--;
  1174. block[i + 1] ^= ((rNToGo == 1) ? 1 : 0);
  1175. // handle 16 bit signed numbers
  1176. block[i + 1] &= 0xFF;
  1177. inUse[block[i + 1]] = true;
  1178. }
  1179. }
  1180. private void doReversibleTransformation() {
  1181. int i;
  1182. workLimit = workFactor * last;
  1183. workDone = 0;
  1184. blockRandomised = false;
  1185. firstAttempt = true;
  1186. mainSort();
  1187. if (workDone > workLimit && firstAttempt) {
  1188. randomiseBlock();
  1189. workLimit = workDone = 0;
  1190. blockRandomised = true;
  1191. firstAttempt = false;
  1192. mainSort();
  1193. }
  1194. origPtr = -1;
  1195. for (i = 0; i <= last; i++) {
  1196. if (zptr[i] == 0) {
  1197. origPtr = i;
  1198. break;
  1199. }
  1200. };
  1201. if (origPtr == -1) {
  1202. panic();
  1203. }
  1204. }
  1205. private boolean fullGtU(int i1, int i2) {
  1206. int k;
  1207. char c1, c2;
  1208. int s1, s2;
  1209. c1 = block[i1 + 1];
  1210. c2 = block[i2 + 1];
  1211. if (c1 != c2) {
  1212. return (c1 > c2);
  1213. }
  1214. i1++;
  1215. i2++;
  1216. c1 = block[i1 + 1];
  1217. c2 = block[i2 + 1];
  1218. if (c1 != c2) {
  1219. return (c1 > c2);
  1220. }
  1221. i1++;
  1222. i2++;
  1223. c1 = block[i1 + 1];
  1224. c2 = block[i2 + 1];
  1225. if (c1 != c2) {
  1226. return (c1 > c2);
  1227. }
  1228. i1++;
  1229. i2++;
  1230. c1 = block[i1 + 1];
  1231. c2 = block[i2 + 1];
  1232. if (c1 != c2) {
  1233. return (c1 > c2);
  1234. }
  1235. i1++;
  1236. i2++;
  1237. c1 = block[i1 + 1];
  1238. c2 = block[i2 + 1];
  1239. if (c1 != c2) {
  1240. return (c1 > c2);
  1241. }
  1242. i1++;
  1243. i2++;
  1244. c1 = block[i1 + 1];
  1245. c2 = block[i2 + 1];
  1246. if (c1 != c2) {
  1247. return (c1 > c2);
  1248. }
  1249. i1++;
  1250. i2++;
  1251. k = last + 1;
  1252. do {
  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. c1 = block[i1 + 1];
  1290. c2 = block[i2 + 1];
  1291. if (c1 != c2) {
  1292. return (c1 > c2);
  1293. }
  1294. s1 = quadrant[i1];
  1295. s2 = quadrant[i2];
  1296. if (s1 != s2) {
  1297. return (s1 > s2);
  1298. }
  1299. i1++;
  1300. i2++;
  1301. if (i1 > last) {
  1302. i1 -= last;
  1303. i1--;
  1304. };
  1305. if (i2 > last) {
  1306. i2 -= last;
  1307. i2--;
  1308. };
  1309. k -= 4;
  1310. workDone++;
  1311. } while (k >= 0);
  1312. return false;
  1313. }
  1314. /*
  1315. Knuth's increments seem to work better
  1316. than Incerpi-Sedgewick here. Possibly
  1317. because the number of elems to sort is
  1318. usually small, typically <= 20.
  1319. */
  1320. private int[] incs = {1, 4, 13, 40, 121, 364, 1093, 3280,
  1321. 9841, 29524, 88573, 265720,
  1322. 797161, 2391484};
  1323. private void allocateCompressStructures () {
  1324. int n = baseBlockSize * blockSize100k;
  1325. block = new char[(n + 1 + NUM_OVERSHOOT_BYTES)];
  1326. quadrant = new int[(n + NUM_OVERSHOOT_BYTES)];
  1327. zptr = new int[n];
  1328. ftab = new int[65537];
  1329. if (block == null || quadrant == null || zptr == null
  1330. || ftab == null) {
  1331. //int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537;
  1332. //compressOutOfMemory ( totalDraw, n );
  1333. }
  1334. /*
  1335. The back end needs a place to store the MTF values
  1336. whilst it calculates the coding tables. We could
  1337. put them in the zptr array. However, these values
  1338. will fit in a short, so we overlay szptr at the
  1339. start of zptr, in the hope of reducing the number
  1340. of cache misses induced by the multiple traversals
  1341. of the MTF values when calculating coding tables.
  1342. Seems to improve compression speed by about 1%.
  1343. */
  1344. // szptr = zptr;
  1345. szptr = new short[2 * n];
  1346. }
  1347. private void generateMTFValues() {
  1348. char[] yy = new char[256];
  1349. int i, j;
  1350. char tmp;
  1351. char tmp2;
  1352. int zPend;
  1353. int wr;
  1354. int EOB;
  1355. makeMaps();
  1356. EOB = nInUse + 1;
  1357. for (i = 0; i <= EOB; i++) {
  1358. mtfFreq[i] = 0;
  1359. }
  1360. wr = 0;
  1361. zPend = 0;
  1362. for (i = 0; i < nInUse; i++) {
  1363. yy[i] = (char) i;
  1364. }
  1365. for (i = 0; i <= last; i++) {
  1366. char ll_i;
  1367. ll_i = unseqToSeq[block[zptr[i]]];
  1368. j = 0;
  1369. tmp = yy[j];
  1370. while (ll_i != tmp) {
  1371. j++;
  1372. tmp2 = tmp;
  1373. tmp = yy[j];
  1374. yy[j] = tmp2;
  1375. };
  1376. yy[0] = tmp;
  1377. if (j == 0) {
  1378. zPend++;
  1379. } else {
  1380. if (zPend > 0) {
  1381. zPend--;
  1382. while (true) {
  1383. switch (zPend % 2) {
  1384. case 0:
  1385. szptr[wr] = (short) RUNA;
  1386. wr++;
  1387. mtfFreq[RUNA]++;
  1388. break;
  1389. case 1:
  1390. szptr[wr] = (short) RUNB;
  1391. wr++;
  1392. mtfFreq[RUNB]++;
  1393. break;
  1394. };
  1395. if (zPend < 2) {
  1396. break;
  1397. }
  1398. zPend = (zPend - 2) / 2;
  1399. };
  1400. zPend = 0;
  1401. }
  1402. szptr[wr] = (short) (j + 1);
  1403. wr++;
  1404. mtfFreq[j + 1]++;
  1405. }
  1406. }
  1407. if (zPend > 0) {
  1408. zPend--;
  1409. while (true) {
  1410. switch (zPend % 2) {
  1411. case 0:
  1412. szptr[wr] = (short) RUNA;
  1413. wr++;
  1414. mtfFreq[RUNA]++;
  1415. break;
  1416. case 1:
  1417. szptr[wr] = (short) RUNB;
  1418. wr++;
  1419. mtfFreq[RUNB]++;
  1420. break;
  1421. }
  1422. if (zPend < 2) {
  1423. break;
  1424. }
  1425. zPend = (zPend - 2) / 2;
  1426. }
  1427. }
  1428. szptr[wr] = (short) EOB;
  1429. wr++;
  1430. mtfFreq[EOB]++;
  1431. nMTF = wr;
  1432. }
  1433. }