    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one
    003 * or more contributor license agreements.  See the NOTICE file
    004 * distributed with this work for additional information
    005 * regarding copyright ownership.  The ASF licenses this file
    006 * to you under the Apache License, Version 2.0 (the
    007 * "License"); you may not use this file except in compliance
    008 * with the License.  You may obtain a copy of the License at
    009 *
    010 * http://www.apache.org/licenses/LICENSE-2.0
    011 *
    012 * Unless required by applicable law or agreed to in writing,
    013 * software distributed under the License is distributed on an
    014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    015 * KIND, either express or implied.  See the License for the
    016 * specific language governing permissions and limitations
    017 * under the License.
    018 */
    019package org.apache.commons.compress.compressors.bzip2;
    020
    021import java.io.IOException;
    022import java.io.OutputStream;
    023import java.util.Arrays;
    024
    025import org.apache.commons.compress.compressors.CompressorOutputStream;
    026
    027/**
    028 * An output stream that compresses into the BZip2 format into another stream.
    029 *
    030 * <p>
    031 * The compression requires large amounts of memory. Thus you should call the
    032 * {@link #close() close()} method as soon as possible, to force
    033 * {@code BZip2CompressorOutputStream} to release the allocated memory.
    034 * </p>
    035 *
    036 * <p> You can shrink the amount of allocated memory and maybe raise
    037 * the compression speed by choosing a lower blocksize, which in turn
    038 * may cause a lower compression ratio. You can avoid unnecessary
    039 * memory allocation by avoiding using a blocksize which is bigger
    040 * than the size of the input.  </p>
    041 *
    042 * <p> You can compute the memory usage for compressing by the
    043 * following formula: </p>
    044 *
    045 * <pre>
    046 * &lt;code&gt;400k + (9 * blocksize)&lt;/code&gt;.
    047 * </pre>
    048 *
    049 * <p> To get the memory required for decompression by {@link
    050 * BZip2CompressorInputStream} use </p>
    051 *
    052 * <pre>
    053 * &lt;code&gt;65k + (5 * blocksize)&lt;/code&gt;.
    054 * </pre>
    055 *
    056 * <table style="width:100%" border="1">
    057 * <caption>Memory usage by blocksize</caption>
    058 * <tr>
    059 * <th colspan="3">Memory usage by blocksize</th>
    060 * </tr>
    061 * <tr>
    062 * <th style="text-align: right">Blocksize</th> <th style="text-align: right">Compression<br>
    063 * memory usage</th> <th style="text-align: right">Decompression<br>
    064 * memory usage</th>
    065 * </tr>
    066 * <tr>
    067 * <td style="text-align: right">100k</td>
    068 * <td style="text-align: right">1300k</td>
    069 * <td style="text-align: right">565k</td>
    070 * </tr>
    071 * <tr>
    072 * <td style="text-align: right">200k</td>
    073 * <td style="text-align: right">2200k</td>
    074 * <td style="text-align: right">1065k</td>
    075 * </tr>
    076 * <tr>
    077 * <td style="text-align: right">300k</td>
    078 * <td style="text-align: right">3100k</td>
    079 * <td style="text-align: right">1565k</td>
    080 * </tr>
    081 * <tr>
    082 * <td style="text-align: right">400k</td>
    083 * <td style="text-align: right">4000k</td>
    084 * <td style="text-align: right">2065k</td>
    085 * </tr>
    086 * <tr>
    087 * <td style="text-align: right">500k</td>
    088 * <td style="text-align: right">4900k</td>
    089 * <td style="text-align: right">2565k</td>
    090 * </tr>
    091 * <tr>
    092 * <td style="text-align: right">600k</td>
    093 * <td style="text-align: right">5800k</td>
    094 * <td style="text-align: right">3065k</td>
    095 * </tr>
    096 * <tr>
    097 * <td style="text-align: right">700k</td>
    098 * <td style="text-align: right">6700k</td>
    099 * <td style="text-align: right">3565k</td>
    100 * </tr>
    101 * <tr>
    102 * <td style="text-align: right">800k</td>
    103 * <td style="text-align: right">7600k</td>
    104 * <td style="text-align: right">4065k</td>
    105 * </tr>
    106 * <tr>
    107 * <td style="text-align: right">900k</td>
    108 * <td style="text-align: right">8500k</td>
    109 * <td style="text-align: right">4565k</td>
    110 * </tr>
    111 * </table>
    112 *
    113 * <p>
    114 * For decompression {@code BZip2CompressorInputStream} allocates less memory if the
    115 * bzipped input is smaller than one block.
    116 * </p>
    117 *
    118 * <p>
    119 * Instances of this class are not threadsafe.
    120 * </p>
    121 *
    122 * <p>
    123 * TODO: Update to BZip2 1.0.1
    124 * </p>
    125 * @NotThreadSafe
    126 */
    127public class BZip2CompressorOutputStream extends CompressorOutputStream
    128    implements BZip2Constants {
    129
    130    static final class Data {
    131
    132        // with blockSize 900k
    133        /* maps unsigned byte => "does it occur in block" */
    134        final boolean[] inUse = new boolean[256]; // 256 byte
    135        final byte[] unseqToSeq = new byte[256]; // 256 byte
    136        final int[] mtfFreq = new int[MAX_ALPHA_SIZE]; // 1032 byte
    137        final byte[] selector = new byte[MAX_SELECTORS]; // 18002 byte
    138        final byte[] selectorMtf = new byte[MAX_SELECTORS]; // 18002 byte
    139
    140        final byte[] generateMTFValues_yy = new byte[256]; // 256 byte
    141        final byte[][] sendMTFValues_len = new byte[N_GROUPS][MAX_ALPHA_SIZE]; // 1548
    142        // byte
    143        final int[][] sendMTFValues_rfreq = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192
    144        // byte
    145        final int[] sendMTFValues_fave = new int[N_GROUPS]; // 24 byte
    146        final short[] sendMTFValues_cost = new short[N_GROUPS]; // 12 byte
    147        final int[][] sendMTFValues_code = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192
    148        // byte
    149        final byte[] sendMTFValues2_pos = new byte[N_GROUPS]; // 6 byte
    150        final boolean[] sentMTFValues4_inUse16 = new boolean[16]; // 16 byte
    151
    152        final int[] heap = new int[MAX_ALPHA_SIZE + 2]; // 1040 byte
    153        final int[] weight = new int[MAX_ALPHA_SIZE * 2]; // 2064 byte
    154        final int[] parent = new int[MAX_ALPHA_SIZE * 2]; // 2064 byte
    155
    156        // ------------
    157        // 333408 byte
    158
    159        /* holds the RLEd block of original data starting at index 1.
    160         * After sorting the last byte added to the buffer is at index
    161         * 0. */
    162        final byte[] block; // 900021 byte
    163        /* maps index in Burrows-Wheeler transformed block => index of
    164         * byte in original block */
    165        final int[] fmap; // 3600000 byte
    166        final char[] sfmap; // 3600000 byte
    167        // ------------
    168        // 8433529 byte
    169        // ============
    170
    171        /**
    172         * Index of original line in Burrows-Wheeler table.
    173         *
    174         * <p>This is the index in fmap that points to the last byte
    175         * of the original data.</p>
    176         */
    177        int origPtr;
    178
    179        Data(final int blockSize100k) {
    180            final int n = blockSize100k * BZip2Constants.BASEBLOCKSIZE;
    181            this.block = new byte[n + 1 + NUM_OVERSHOOT_BYTES];
    182            this.fmap = new int[n];
    183            this.sfmap = new char[2 * n];
    184        }
    185
    186    }
    187
    188    /**
    189     * The minimum supported blocksize {@code  == 1}.
    190     */
    191    public static final int MIN_BLOCKSIZE = 1;
    192
    193    /**
    194     * The maximum supported blocksize {@code  == 9}.
    195     */
    196    public static final int MAX_BLOCKSIZE = 9;
    197    private static final int GREATER_ICOST = 15;
    198
    199    private static final int LESSER_ICOST = 0;
    200
    201    /**
    202     * Chooses a blocksize based on the given length of the data to compress.
    203     *
    204     * @return The blocksize, between {@link #MIN_BLOCKSIZE} and
    205     *         {@link #MAX_BLOCKSIZE} both inclusive. For a negative
    206     *         {@code inputLength} this method returns {@code MAX_BLOCKSIZE}
    207     *         always.
    208     *
    209     * @param inputLength
    210     *            The length of the data which will be compressed by
    211     *            {@code BZip2CompressorOutputStream}.
    212     */
    213    public static int chooseBlockSize(final long inputLength) {
    214        return inputLength > 0 ? (int) Math
    215            .min(inputLength / 132000 + 1, 9) : MAX_BLOCKSIZE;
    216    }
    217
    218    private static void hbAssignCodes(final int[] code, final byte[] length,
    219                                      final int minLen, final int maxLen,
    220                                      final int alphaSize) {
    221        int vec = 0;
    222        for (int n = minLen; n <= maxLen; n++) {
    223            for (int i = 0; i < alphaSize; i++) {
    224                if ((length[i] & 0xff) == n) {
    225                    code[i] = vec;
    226                    vec++;
    227                }
    228            }
    229            vec <<= 1;
    230        }
    231    }
    232
    233    private static void hbMakeCodeLengths(final byte[] len, final int[] freq,
    234                                          final Data dat, final int alphaSize,
    235                                          final int maxLen) {
    236        /*
    237         * Nodes and heap entries run from 1. Entry 0 for both the heap and
    238         * nodes is a sentinel.
    239         */
    240        final int[] heap = dat.heap;
    241        final int[] weight = dat.weight;
    242        final int[] parent = dat.parent;
    243
    244        for (int i = alphaSize; --i >= 0;) {
    245            weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
    246        }
    247
    248        for (boolean tooLong = true; tooLong;) {
    249            tooLong = false;
    250
    251            int nNodes = alphaSize;
    252            int nHeap = 0;
    253            heap[0] = 0;
    254            weight[0] = 0;
    255            parent[0] = -2;
    256
    257            for (int i = 1; i <= alphaSize; i++) {
    258                parent[i] = -1;
    259                nHeap++;
    260                heap[nHeap] = i;
    261
    262                int zz = nHeap;
    263                final int tmp = heap[zz];
    264                while (weight[tmp] < weight[heap[zz >> 1]]) {
    265                    heap[zz] = heap[zz >> 1];
    266                    zz >>= 1;
    267                }
    268                heap[zz] = tmp;
    269            }
    270
    271            while (nHeap > 1) {
    272                final int n1 = heap[1];
    273                heap[1] = heap[nHeap];
    274                nHeap--;
    275
    276                int yy = 0;
    277                int zz = 1;
    278                int tmp = heap[1];
    279
    280                while (true) {
    281                    yy = zz << 1;
    282
    283                    if (yy > nHeap) {
    284                        break;
    285                    }
    286
    287                    if (yy < nHeap
    288                        && weight[heap[yy + 1]] < weight[heap[yy]]) {
    289                        yy++;
    290                    }
    291
    292                    if (weight[tmp] < weight[heap[yy]]) {
    293                        break;
    294                    }
    295
    296                    heap[zz] = heap[yy];
    297                    zz = yy;
    298                }
    299
    300                heap[zz] = tmp;
    301
    302                final int n2 = heap[1];
    303                heap[1] = heap[nHeap];
    304                nHeap--;
    305
    306                yy = 0;
    307                zz = 1;
    308                tmp = heap[1];
    309
    310                while (true) {
    311                    yy = zz << 1;
    312
    313                    if (yy > nHeap) {
    314                        break;
    315                    }
    316
    317                    if (yy < nHeap
    318                        && weight[heap[yy + 1]] < weight[heap[yy]]) {
    319                        yy++;
    320                    }
    321
    322                    if (weight[tmp] < weight[heap[yy]]) {
    323                        break;
    324                    }
    325
    326                    heap[zz] = heap[yy];
    327                    zz = yy;
    328                }
    329
    330                heap[zz] = tmp;
    331                nNodes++;
    332                parent[n1] = parent[n2] = nNodes;
    333
    334                final int weight_n1 = weight[n1];
    335                final int weight_n2 = weight[n2];
    336                weight[nNodes] = (weight_n1 & 0xffffff00)
    337                                  + (weight_n2 & 0xffffff00)
    338                    | 1 + Math.max(weight_n1 & 0x000000ff, weight_n2 & 0x000000ff);
    339
    340                parent[nNodes] = -1;
    341                nHeap++;
    342                heap[nHeap] = nNodes;
    343
    344                tmp = 0;
    345                zz = nHeap;
    346                tmp = heap[zz];
    347                final int weight_tmp = weight[tmp];
    348                while (weight_tmp < weight[heap[zz >> 1]]) {
    349                    heap[zz] = heap[zz >> 1];
    350                    zz >>= 1;
    351                }
    352                heap[zz] = tmp;
    353
    354            }
    355
    356            for (int i = 1; i <= alphaSize; i++) {
    357                int j = 0;
    358                int k = i;
    359
    360                for (int parent_k; (parent_k = parent[k]) >= 0;) {
    361                    k = parent_k;
    362                    j++;
    363                }
    364
    365                len[i - 1] = (byte) j;
    366                if (j > maxLen) {
    367                    tooLong = true;
    368                }
    369            }
    370
    371            if (tooLong) {
    372                for (int i = 1; i < alphaSize; i++) {
    373                    int j = weight[i] >> 8;
    374                    j = 1 + (j >> 1);
    375                    weight[i] = j << 8;
    376                }
    377            }
    378        }
    379    }
    380    /**
    381     * Index of the last char in the block, so the block size == last + 1.
    382     */
    383    private int last;
    384    /**
    385     * Always: in the range 0 .. 9. The current block size is 100000 * this
    386     * number.
    387     */
    388    private final int blockSize100k;
    389
    390    private int bsBuff;
    391
    392    private int bsLive;
    393
    394    private final CRC crc = new CRC();
    395    private int nInUse;
    396
    397    private int nMTF;
    398    private int currentChar = -1;
    399    private int runLength;
    400
    401    private int blockCRC;
    402    private int combinedCRC;
    403
    404    private final int allowableBlockSize;
    405    /**
    406     * All memory intensive stuff.
    407     */
    408    private Data data;
    409
    410    private BlockSort blockSorter;
    411
    412    private OutputStream out;
    413
    414    private volatile boolean closed;
    415
    416    /**
    417     * Constructs a new {@code BZip2CompressorOutputStream} with a blocksize of 900k.
    418     *
    419     * @param out
    420     *            the destination stream.
    421     *
    422     * @throws IOException
    423     *             if an I/O error occurs in the specified stream.
    424     * @throws NullPointerException
    425     *             if {@code out == null}.
    426     */
    427    public BZip2CompressorOutputStream(final OutputStream out)
    428        throws IOException {
    429        this(out, MAX_BLOCKSIZE);
    430    }
    431
    432    /**
    433     * Constructs a new {@code BZip2CompressorOutputStream} with specified blocksize.
    434     *
    435     * @param out
    436     *            the destination stream.
    437     * @param blockSize
    438     *            the blockSize as 100k units.
    439     *
    440     * @throws IOException
    441     *             if an I/O error occurs in the specified stream.
    442     * @throws IllegalArgumentException
    443     *             if {@code (blockSize &lt; 1) || (blockSize &gt; 9)}.
    444     * @throws NullPointerException
    445     *             if {@code out == null}.
    446     *
    447     * @see #MIN_BLOCKSIZE
    448     * @see #MAX_BLOCKSIZE
    449     */
    450    public BZip2CompressorOutputStream(final OutputStream out, final int blockSize) throws IOException {
    451        if (blockSize < 1) {
    452            throw new IllegalArgumentException("blockSize(" + blockSize + ") < 1");
    453        }
    454        if (blockSize > 9) {
    455            throw new IllegalArgumentException("blockSize(" + blockSize + ") > 9");
    456        }
    457
    458        this.blockSize100k = blockSize;
    459        this.out = out;
    460
    461        /* 20 is just a paranoia constant */
    462        this.allowableBlockSize = this.blockSize100k * BZip2Constants.BASEBLOCKSIZE - 20;
    463        init();
    464    }
    465
    466    private void blockSort() {
    467        blockSorter.blockSort(data, last);
    468    }
    469
    470
    471    private void bsFinishedWithStream() throws IOException {
    472        while (this.bsLive > 0) {
    473            final int ch = this.bsBuff >> 24;
    474            this.out.write(ch); // write 8-bit
    475            this.bsBuff <<= 8;
    476            this.bsLive -= 8;
    477        }
    478    }
    479
    480    private void bsPutInt(final int u) throws IOException {
    481        bsW(8, u >> 24 & 0xff);
    482        bsW(8, u >> 16 & 0xff);
    483        bsW(8, u >> 8 & 0xff);
    484        bsW(8, u & 0xff);
    485    }
    486
    487    private void bsPutUByte(final int c) throws IOException {
    488        bsW(8, c);
    489    }
    490
    491    private void bsW(final int n, final int v) throws IOException {
    492        final OutputStream outShadow = this.out;
    493        int bsLiveShadow = this.bsLive;
    494        int bsBuffShadow = this.bsBuff;
    495
    496        while (bsLiveShadow >= 8) {
    497            outShadow.write(bsBuffShadow >> 24); // write 8-bit
    498            bsBuffShadow <<= 8;
    499            bsLiveShadow -= 8;
    500        }
    501
    502        this.bsBuff = bsBuffShadow | v << 32 - bsLiveShadow - n;
    503        this.bsLive = bsLiveShadow + n;
    504    }
    505
    506    @Override
    507    public void close() throws IOException {
    508        if (!closed) {
    509            try (OutputStream outShadow = this.out) {
    510                finish();
    511            }
    512        }
    513    }
    514
    515    private void endBlock() throws IOException {
    516        this.blockCRC = this.crc.getFinalCRC();
    517        this.combinedCRC = this.combinedCRC << 1 | this.combinedCRC >>> 31;
    518        this.combinedCRC ^= this.blockCRC;
    519
    520        // empty block at end of file
    521        if (this.last == -1) {
    522            return;
    523        }
    524
    525        /* sort the block and establish posn of original string */
    526        blockSort();
    527
    528        /*
    529         * A 6-byte block header, the value chosen arbitrarily as 0x314159265359
    530         * :-). A 32 bit value does not really give a strong enough guarantee
    531         * that the value will not appear by chance in the compressed
    532         * data stream. Worst-case probability of this event, for a 900k block,
    533         * is about 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48
    534         * bits. For a compressed file of size 100Gb -- about 100000 blocks --
    535         * only a 48-bit marker will do. NB: normal compression/ decompression
    536         * doesn't rely on these statistical properties. They are only important
    537         * when trying to recover blocks from damaged files.
    538         */
    539        bsPutUByte(0x31);
    540        bsPutUByte(0x41);
    541        bsPutUByte(0x59);
    542        bsPutUByte(0x26);
    543        bsPutUByte(0x53);
    544        bsPutUByte(0x59);
    545
    546        /* Now the block's CRC, so it is in a known place. */
    547        bsPutInt(this.blockCRC);
    548
    549        /* Now a single bit indicating no randomisation. */
    550        bsW(1, 0);
    551
    552        /* Finally, block's contents proper. */
    553        moveToFrontCodeAndSend();
    554    }
    555
    556    private void endCompression() throws IOException {
    557        /*
    558         * Now another magic 48-bit number, 0x177245385090, to indicate the end
    559         * of the last block. (sqrt(pi), if you want to know. I did want to use
    560         * e, but it contains too much repetition -- 27 18 28 18 28 46 -- for me
    561         * to feel statistically comfortable. Call me paranoid.)
    562         */
    563        bsPutUByte(0x17);
    564        bsPutUByte(0x72);
    565        bsPutUByte(0x45);
    566        bsPutUByte(0x38);
    567        bsPutUByte(0x50);
    568        bsPutUByte(0x90);
    569
    570        bsPutInt(this.combinedCRC);
    571        bsFinishedWithStream();
    572    }
    573
    574    public void finish() throws IOException {
    575        if (!closed) {
    576            closed = true;
    577            try {
    578                if (this.runLength > 0) {
    579                    writeRun();
    580                }
    581                this.currentChar = -1;
    582                endBlock();
    583                endCompression();
    584            } finally {
    585                this.out = null;
    586                this.blockSorter = null;
    587                this.data = null;
    588            }
    589        }
    590    }
    591
    592    @Override
    593    public void flush() throws IOException {
    594        final OutputStream outShadow = this.out;
    595        if (outShadow != null) {
    596            outShadow.flush();
    597        }
    598    }
    599
    600    /*
    601     * Performs Move-To-Front on the Burrows-Wheeler transformed
    602     * buffer, storing the MTFed data in data.sfmap in RUNA/RUNB
    603     * run-length-encoded form.
    604     *
    605     * <p>Keeps track of byte frequencies in data.mtfFreq at the same time.</p>
    606     */
    607    private void generateMTFValues() {
    608        final int lastShadow = this.last;
    609        final Data dataShadow = this.data;
    610        final boolean[] inUse = dataShadow.inUse;
    611        final byte[] block = dataShadow.block;
    612        final int[] fmap = dataShadow.fmap;
    613        final char[] sfmap = dataShadow.sfmap;
    614        final int[] mtfFreq = dataShadow.mtfFreq;
    615        final byte[] unseqToSeq = dataShadow.unseqToSeq;
    616        final byte[] yy = dataShadow.generateMTFValues_yy;
    617
    618        // make maps
    619        int nInUseShadow = 0;
    620        for (int i = 0; i < 256; i++) {
    621            if (inUse[i]) {
    622                unseqToSeq[i] = (byte) nInUseShadow;
    623                nInUseShadow++;
    624            }
    625        }
    626        this.nInUse = nInUseShadow;
    627
    628        final int eob = nInUseShadow + 1;
    629
    630        Arrays.fill(mtfFreq, 0, eob + 1, 0);
    631
    632        for (int i = nInUseShadow; --i >= 0;) {
    633            yy[i] = (byte) i;
    634        }
    635
    636        int wr = 0;
    637        int zPend = 0;
    638
    639        for (int i = 0; i <= lastShadow; i++) {
    640            final byte ll_i = unseqToSeq[block[fmap[i]] & 0xff];
    641            byte tmp = yy[0];
    642            int j = 0;
    643
    644            while (ll_i != tmp) {
    645                j++;
    646                final byte tmp2 = tmp;
    647                tmp = yy[j];
    648                yy[j] = tmp2;
    649            }
    650            yy[0] = tmp;
    651
    652            if (j == 0) {
    653                zPend++;
    654            } else {
    655                if (zPend > 0) {
    656                    zPend--;
    657                    while (true) {
    658                        if ((zPend & 1) == 0) {
    659                            sfmap[wr] = RUNA;
    660                            wr++;
    661                            mtfFreq[RUNA]++;
    662                        } else {
    663                            sfmap[wr] = RUNB;
    664                            wr++;
    665                            mtfFreq[RUNB]++;
    666                        }
    667
    668                        if (zPend < 2) {
    669                            break;
    670                        }
    671                        zPend = zPend - 2 >> 1;
    672                    }
    673                    zPend = 0;
    674                }
    675                sfmap[wr] = (char) (j + 1);
    676                wr++;
    677                mtfFreq[j + 1]++;
    678            }
    679        }
    680
    681        if (zPend > 0) {
    682            zPend--;
    683            while (true) {
    684                if ((zPend & 1) == 0) {
    685                    sfmap[wr] = RUNA;
    686                    wr++;
    687                    mtfFreq[RUNA]++;
    688                } else {
    689                    sfmap[wr] = RUNB;
    690                    wr++;
    691                    mtfFreq[RUNB]++;
    692                }
    693
    694                if (zPend < 2) {
    695                    break;
    696                }
    697                zPend = zPend - 2 >> 1;
    698            }
    699        }
    700
    701        sfmap[wr] = (char) eob;
    702        mtfFreq[eob]++;
    703        this.nMTF = wr + 1;
    704    }
    705
    706    /**
    707     * Returns the blocksize parameter specified at construction time.
    708     * @return the blocksize parameter specified at construction time
    709     */
    710    public final int getBlockSize() {
    711        return this.blockSize100k;
    712    }
    713
    714    /**
    715     * Writes magic bytes like BZ on the first position of the stream
    716     * and bytes indicating the file-format, which is
    717     * huffmanized, followed by a digit indicating blockSize100k.
    718     * @throws IOException if the magic bytes could not been written
    719     */
    720    private void init() throws IOException {
    721        bsPutUByte('B');
    722        bsPutUByte('Z');
    723
    724        this.data = new Data(this.blockSize100k);
    725        this.blockSorter = new BlockSort(this.data);
    726
    727        // huffmanized magic bytes
    728        bsPutUByte('h');
    729        bsPutUByte('0' + this.blockSize100k);
    730
    731        this.combinedCRC = 0;
    732        initBlock();
    733    }
    734
    735    private void initBlock() {
    736        // blockNo++;
    737        this.crc.initializeCRC();
    738        this.last = -1;
    739        // ch = 0;
    740
    741        final boolean[] inUse = this.data.inUse;
    742        for (int i = 256; --i >= 0;) {
    743            inUse[i] = false;
    744        }
    745
    746    }
    747
    748    private void moveToFrontCodeAndSend() throws IOException {
    749        bsW(24, this.data.origPtr);
    750        generateMTFValues();
    751        sendMTFValues();
    752    }
    753
    754    private void sendMTFValues() throws IOException {
    755        final byte[][] len = this.data.sendMTFValues_len;
    756        final int alphaSize = this.nInUse + 2;
    757
    758        for (int t = N_GROUPS; --t >= 0;) {
    759            final byte[] len_t = len[t];
    760            for (int v = alphaSize; --v >= 0;) {
    761                len_t[v] = GREATER_ICOST;
    762            }
    763        }
    764
    765        /* Decide how many coding tables to use */
    766        // assert (this.nMTF > 0) : this.nMTF;
    767        final int nGroups = this.nMTF < 200 ? 2 : this.nMTF < 600 ? 3
    768            : this.nMTF < 1200 ? 4 : this.nMTF < 2400 ? 5 : 6;
    769
    770        /* Generate an initial set of coding tables */
    771        sendMTFValues0(nGroups, alphaSize);
    772
    773        /*
    774         * Iterate up to N_ITERS times to improve the tables.
    775         */
    776        final int nSelectors = sendMTFValues1(nGroups, alphaSize);
    777
    778        /* Compute MTF values for the selectors. */
    779        sendMTFValues2(nGroups, nSelectors);
    780
    781        /* Assign actual codes for the tables. */
    782        sendMTFValues3(nGroups, alphaSize);
    783
    784        /* Transmit the mapping table. */
    785        sendMTFValues4();
    786
    787        /* Now the selectors. */
    788        sendMTFValues5(nGroups, nSelectors);
    789
    790        /* Now the coding tables. */
    791        sendMTFValues6(nGroups, alphaSize);
    792
    793        /* And finally, the block data proper */
    794        sendMTFValues7();
    795    }
    796
    797    private void sendMTFValues0(final int nGroups, final int alphaSize) {
    798        final byte[][] len = this.data.sendMTFValues_len;
    799        final int[] mtfFreq = this.data.mtfFreq;
    800
    801        int remF = this.nMTF;
    802        int gs = 0;
    803
    804        for (int nPart = nGroups; nPart > 0; nPart--) {
    805            final int tFreq = remF / nPart;
    806            int ge = gs - 1;
    807            int aFreq = 0;
    808
    809            for (final int a = alphaSize - 1; aFreq < tFreq && ge < a;) {
    810                aFreq += mtfFreq[++ge];
    811            }
    812
    813            if (ge > gs && nPart != nGroups && nPart != 1
    814                && (nGroups - nPart & 1) != 0) {
    815                aFreq -= mtfFreq[ge--];
    816            }
    817
    818            final byte[] len_np = len[nPart - 1];
    819            for (int v = alphaSize; --v >= 0;) {
    820                if (v >= gs && v <= ge) {
    821                    len_np[v] = LESSER_ICOST;
    822                } else {
    823                    len_np[v] = GREATER_ICOST;
    824                }
    825            }
    826
    827            gs = ge + 1;
    828            remF -= aFreq;
    829        }
    830    }
    831
    832    private int sendMTFValues1(final int nGroups, final int alphaSize) {
    833        final Data dataShadow = this.data;
    834        final int[][] rfreq = dataShadow.sendMTFValues_rfreq;
    835        final int[] fave = dataShadow.sendMTFValues_fave;
    836        final short[] cost = dataShadow.sendMTFValues_cost;
    837        final char[] sfmap = dataShadow.sfmap;
    838        final byte[] selector = dataShadow.selector;
    839        final byte[][] len = dataShadow.sendMTFValues_len;
    840        final byte[] len_0 = len[0];
    841        final byte[] len_1 = len[1];
    842        final byte[] len_2 = len[2];
    843        final byte[] len_3 = len[3];
    844        final byte[] len_4 = len[4];
    845        final byte[] len_5 = len[5];
    846        final int nMTFShadow = this.nMTF;
    847
    848        int nSelectors = 0;
    849
    850        for (int iter = 0; iter < N_ITERS; iter++) {
    851            for (int t = nGroups; --t >= 0;) {
    852                fave[t] = 0;
    853                final int[] rfreqt = rfreq[t];
    854                for (int i = alphaSize; --i >= 0;) {
    855                    rfreqt[i] = 0;
    856                }
    857            }
    858
    859            nSelectors = 0;
    860
    861            for (int gs = 0; gs < this.nMTF;) {
    862                // Set group start & end marks.
    863
    864                // Calculate the cost of this group as coded by each of the
    865                // coding tables.
    866
    867                final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1);
    868
    869                final byte mask = (byte) 0xff;
    870                if (nGroups == N_GROUPS) {
    871                    // unrolled version of the else-block
    872
    873                    short cost0 = 0;
    874                    short cost1 = 0;
    875                    short cost2 = 0;
    876                    short cost3 = 0;
    877                    short cost4 = 0;
    878                    short cost5 = 0;
    879
    880                    for (int i = gs; i <= ge; i++) {
    881                        final int icv = sfmap[i];
    882                        cost0 += (short) (len_0[icv] & mask);
    883                        cost1 += (short) (len_1[icv] & mask);
    884                        cost2 += (short) (len_2[icv] & mask);
    885                        cost3 += (short) (len_3[icv] & mask);
    886                        cost4 += (short) (len_4[icv] & mask);
    887                        cost5 += (short) (len_5[icv] & mask);
    888                    }
    889
    890                    cost[0] = cost0;
    891                    cost[1] = cost1;
    892                    cost[2] = cost2;
    893                    cost[3] = cost3;
    894                    cost[4] = cost4;
    895                    cost[5] = cost5;
    896
    897                } else {
    898                    for (int t = nGroups; --t >= 0;) {
    899                        cost[t] = 0;
    900                    }
    901
    902                    for (int i = gs; i <= ge; i++) {
    903                        final int icv = sfmap[i];
    904                        for (int t = nGroups; --t >= 0;) {
    905                            cost[t] += (short) (len[t][icv] & mask);
    906                        }
    907                    }
    908                }
    909
    910                /*
    911                 * Find the coding table which is best for this group, and
    912                 * record its identity in the selector table.
    913                 */
    914                int bt = -1;
    915                for (int t = nGroups, bc = 999999999; --t >= 0;) {
    916                    final int cost_t = cost[t];
    917                    if (cost_t < bc) {
    918                        bc = cost_t;
    919                        bt = t;
    920                    }
    921                }
    922
    923                fave[bt]++;
    924                selector[nSelectors] = (byte) bt;
    925                nSelectors++;
    926
    927                /*
    928                 * Increment the symbol frequencies for the selected table.
    929                 */
    930                final int[] rfreq_bt = rfreq[bt];
    931                for (int i = gs; i <= ge; i++) {
    932                    rfreq_bt[sfmap[i]]++;
    933                }
    934
    935                gs = ge + 1;
    936            }
    937
    938            /*
    939             * Recompute the tables based on the accumulated frequencies.
    940             */
    941            for (int t = 0; t < nGroups; t++) {
    942                hbMakeCodeLengths(len[t], rfreq[t], this.data, alphaSize, 20);
    943            }
    944        }
    945
    946        return nSelectors;
    947    }
    948
    949    private void sendMTFValues2(final int nGroups, final int nSelectors) {
    950        // assert (nGroups < 8) : nGroups;
    951
    952        final Data dataShadow = this.data;
    953        final byte[] pos = dataShadow.sendMTFValues2_pos;
    954
    955        for (int i = nGroups; --i >= 0;) {
    956            pos[i] = (byte) i;
    957        }
    958
    959        for (int i = 0; i < nSelectors; i++) {
    960            final byte ll_i = dataShadow.selector[i];
    961            byte tmp = pos[0];
    962            int j = 0;
    963
    964            while (ll_i != tmp) {
    965                j++;
    966                final byte tmp2 = tmp;
    967                tmp = pos[j];
    968                pos[j] = tmp2;
    969            }
    970
    971            pos[0] = tmp;
    972            dataShadow.selectorMtf[i] = (byte) j;
    973        }
    974    }
    975
    976    private void sendMTFValues3(final int nGroups, final int alphaSize) {
    977        final int[][] code = this.data.sendMTFValues_code;
    978        final byte[][] len = this.data.sendMTFValues_len;
    979
    980        for (int t = 0; t < nGroups; t++) {
    981            int minLen = 32;
    982            int maxLen = 0;
    983            final byte[] len_t = len[t];
    984            for (int i = alphaSize; --i >= 0;) {
    985                final int l = len_t[i] & 0xff;
    986                if (l > maxLen) {
    987                    maxLen = l;
    988                }
    989                if (l < minLen) {
    990                    minLen = l;
    991                }
    992            }
    993
    994            // assert (maxLen <= 20) : maxLen;
    995            // assert (minLen >= 1) : minLen;
    996
    997            hbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize);
    998        }
    999    }
    1000
    1001    private void sendMTFValues4() throws IOException {
    1002        final boolean[] inUse = this.data.inUse;
    1003        final boolean[] inUse16 = this.data.sentMTFValues4_inUse16;
    1004
    1005        for (int i = 16; --i >= 0;) {
    1006            inUse16[i] = false;
    1007            final int i16 = i * 16;
    1008            for (int j = 16; --j >= 0;) {
    1009                if (inUse[i16 + j]) {
    1010                    inUse16[i] = true;
    1011                    break;
    1012                }
    1013            }
    1014        }
    1015
    1016        for (int i = 0; i < 16; i++) {
    1017            bsW(1, inUse16[i] ? 1 : 0);
    1018        }
    1019
    1020        final OutputStream outShadow = this.out;
    1021        int bsLiveShadow = this.bsLive;
    1022        int bsBuffShadow = this.bsBuff;
    1023
    1024        for (int i = 0; i < 16; i++) {
    1025            if (inUse16[i]) {
    1026                final int i16 = i * 16;
    1027                for (int j = 0; j < 16; j++) {
    1028                    // inlined: bsW(1, inUse[i16 + j] ? 1 : 0);
    1029                    while (bsLiveShadow >= 8) {
    1030                        outShadow.write(bsBuffShadow >> 24); // write 8-bit
    1031                        bsBuffShadow <<= 8;
    1032                        bsLiveShadow -= 8;
    1033                    }
    1034                    if (inUse[i16 + j]) {
    1035                        bsBuffShadow |= 1 << 32 - bsLiveShadow - 1;
    1036                    }
    1037                    bsLiveShadow++;
    1038                }
    1039            }
    1040        }
    1041
    1042        this.bsBuff = bsBuffShadow;
    1043        this.bsLive = bsLiveShadow;
    1044    }
    1045
    1046    private void sendMTFValues5(final int nGroups, final int nSelectors)
    1047        throws IOException {
    1048        bsW(3, nGroups);
    1049        bsW(15, nSelectors);
    1050
    1051        final OutputStream outShadow = this.out;
    1052        final byte[] selectorMtf = this.data.selectorMtf;
    1053
    1054        int bsLiveShadow = this.bsLive;
    1055        int bsBuffShadow = this.bsBuff;
    1056
    1057        for (int i = 0; i < nSelectors; i++) {
    1058            for (int j = 0, hj = selectorMtf[i] & 0xff; j < hj; j++) {
    1059                // inlined: bsW(1, 1);
    1060                while (bsLiveShadow >= 8) {
    1061                    outShadow.write(bsBuffShadow >> 24);
    1062                    bsBuffShadow <<= 8;
    1063                    bsLiveShadow -= 8;
    1064                }
    1065                bsBuffShadow |= 1 << 32 - bsLiveShadow - 1;
    1066                bsLiveShadow++;
    1067            }
    1068
    1069            // inlined: bsW(1, 0);
    1070            while (bsLiveShadow >= 8) {
    1071                outShadow.write(bsBuffShadow >> 24);
    1072                bsBuffShadow <<= 8;
    1073                bsLiveShadow -= 8;
    1074            }
    1075            // bsBuffShadow |= 0 << (32 - bsLiveShadow - 1);
    1076            bsLiveShadow++;
    1077        }
    1078
    1079        this.bsBuff = bsBuffShadow;
    1080        this.bsLive = bsLiveShadow;
    1081    }
    1082
    1083    private void sendMTFValues6(final int nGroups, final int alphaSize)
    1084        throws IOException {
    1085        final byte[][] len = this.data.sendMTFValues_len;
    1086        final OutputStream outShadow = this.out;
    1087
    1088        int bsLiveShadow = this.bsLive;
    1089        int bsBuffShadow = this.bsBuff;
    1090
    1091        for (int t = 0; t < nGroups; t++) {
    1092            final byte[] len_t = len[t];
    1093            int curr = len_t[0] & 0xff;
    1094
    1095            // inlined: bsW(5, curr);
    1096            while (bsLiveShadow >= 8) {
    1097                outShadow.write(bsBuffShadow >> 24); // write 8-bit
    1098                bsBuffShadow <<= 8;
    1099                bsLiveShadow -= 8;
    1100            }
    1101            bsBuffShadow |= curr << 32 - bsLiveShadow - 5;
    1102            bsLiveShadow += 5;
    1103
    1104            for (int i = 0; i < alphaSize; i++) {
    1105                final int lti = len_t[i] & 0xff;
    1106                while (curr < lti) {
    1107                    // inlined: bsW(2, 2);
    1108                    while (bsLiveShadow >= 8) {
    1109                        outShadow.write(bsBuffShadow >> 24); // write 8-bit
    1110                        bsBuffShadow <<= 8;
    1111                        bsLiveShadow -= 8;
    1112                    }
    1113                    bsBuffShadow |= 2 << 32 - bsLiveShadow - 2;
    1114                    bsLiveShadow += 2;
    1115
    1116                    curr++; /* 10 */
    1117                }
    1118
    1119                while (curr > lti) {
    1120                    // inlined: bsW(2, 3);
    1121                    while (bsLiveShadow >= 8) {
    1122                        outShadow.write(bsBuffShadow >> 24); // write 8-bit
    1123                        bsBuffShadow <<= 8;
    1124                        bsLiveShadow -= 8;
    1125                    }
    1126                    bsBuffShadow |= 3 << 32 - bsLiveShadow - 2;
    1127                    bsLiveShadow += 2;
    1128
    1129                    curr--; /* 11 */
    1130                }
    1131
    1132                // inlined: bsW(1, 0);
    1133                while (bsLiveShadow >= 8) {
    1134                    outShadow.write(bsBuffShadow >> 24); // write 8-bit
    1135                    bsBuffShadow <<= 8;
    1136                    bsLiveShadow -= 8;
    1137                }
    1138                // bsBuffShadow |= 0 << (32 - bsLiveShadow - 1);
    1139                bsLiveShadow++;
    1140            }
    1141        }
    1142
    1143        this.bsBuff = bsBuffShadow;
    1144        this.bsLive = bsLiveShadow;
    1145    }
    1146
    1147    private void sendMTFValues7() throws IOException {
    1148        final Data dataShadow = this.data;
    1149        final byte[][] len = dataShadow.sendMTFValues_len;
    1150        final int[][] code = dataShadow.sendMTFValues_code;
    1151        final OutputStream outShadow = this.out;
    1152        final byte[] selector = dataShadow.selector;
    1153        final char[] sfmap = dataShadow.sfmap;
    1154        final int nMTFShadow = this.nMTF;
    1155
    1156        int selCtr = 0;
    1157
    1158        int bsLiveShadow = this.bsLive;
    1159        int bsBuffShadow = this.bsBuff;
    1160
    1161        for (int gs = 0; gs < nMTFShadow;) {
    1162            final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1);
    1163            final int selector_selCtr = selector[selCtr] & 0xff;
    1164            final int[] code_selCtr = code[selector_selCtr];
    1165            final byte[] len_selCtr = len[selector_selCtr];
    1166
    1167            while (gs <= ge) {
    1168                final int sfmap_i = sfmap[gs];
    1169
    1170                //
    1171                // inlined: bsW(len_selCtr[sfmap_i] & 0xff,
    1172                // code_selCtr[sfmap_i]);
    1173                //
    1174                while (bsLiveShadow >= 8) {
    1175                    outShadow.write(bsBuffShadow >> 24);
    1176                    bsBuffShadow <<= 8;
    1177                    bsLiveShadow -= 8;
    1178                }
    1179                final int n = len_selCtr[sfmap_i] & 0xFF;
    1180                bsBuffShadow |= code_selCtr[sfmap_i] << 32 - bsLiveShadow - n;
    1181                bsLiveShadow += n;
    1182
    1183                gs++;
    1184            }
    1185
    1186            gs = ge + 1;
    1187            selCtr++;
    1188        }
    1189
    1190        this.bsBuff = bsBuffShadow;
    1191        this.bsLive = bsLiveShadow;
    1192    }
    1193
    1194    @Override
    1195    public void write(final byte[] buf, int offs, final int len)
    1196        throws IOException {
    1197        if (offs < 0) {
    1198            throw new IndexOutOfBoundsException("offs(" + offs + ") < 0.");
    1199        }
    1200        if (len < 0) {
    1201            throw new IndexOutOfBoundsException("len(" + len + ") < 0.");
    1202        }
    1203        if (offs + len > buf.length) {
    1204            throw new IndexOutOfBoundsException("offs(" + offs + ") + len("
    1205                                                + len + ") > buf.length("
    1206                                                + buf.length + ").");
    1207        }
    1208        if (closed) {
    1209            throw new IOException("Stream closed");
    1210        }
    1211
    1212        for (final int hi = offs + len; offs < hi;) {
    1213            write0(buf[offs++]);
    1214        }
    1215    }
    1216
    1217    @Override
    1218    public void write(final int b) throws IOException {
    1219        if (closed) {
    1220            throw new IOException("Closed");
    1221        }
    1222        write0(b);
    1223    }
    1224
    1225    /**
    1226     * Keeps track of the last bytes written and implicitly performs
    1227     * run-length encoding as the first step of the bzip2 algorithm.
    1228     */
    1229    private void write0(int b) throws IOException {
    1230        if (this.currentChar != -1) {
    1231            b &= 0xff;
    1232            if (this.currentChar == b) {
    1233                if (++this.runLength > 254) {
    1234                    writeRun();
    1235                    this.currentChar = -1;
    1236                    this.runLength = 0;
    1237                }
    1238                // else nothing to do
    1239            } else {
    1240                writeRun();
    1241                this.runLength = 1;
    1242                this.currentChar = b;
    1243            }
    1244        } else {
    1245            this.currentChar = b & 0xff;
    1246            this.runLength++;
    1247        }
    1248    }
    1249
    1250    /**
    1251     * Writes the current byte to the buffer, run-length encoding it
    1252     * if it has been repeated at least four times (the first step
    1253     * RLEs sequences of four identical bytes).
    1254     *
    1255     * <p>Flushes the current block before writing data if it is
    1256     * full.</p>
    1257     *
    1258     * <p>"write to the buffer" means adding to data.buffer starting
    1259     * two steps "after" this.last - initially starting at index 1
    1260     * (not 0) - and updating this.last to point to the last index
    1261     * written minus 1.</p>
    1262     */
    1263    private void writeRun() throws IOException {
    1264        final int lastShadow = this.last;
    1265
    1266        if (lastShadow < this.allowableBlockSize) {
    1267            final int currentCharShadow = this.currentChar;
    1268            final Data dataShadow = this.data;
    1269            dataShadow.inUse[currentCharShadow] = true;
    1270            final byte ch = (byte) currentCharShadow;
    1271
    1272            int runLengthShadow = this.runLength;
    1273            this.crc.updateCRC(currentCharShadow, runLengthShadow);
    1274
    1275            switch (runLengthShadow) {
    1276            case 1:
    1277                dataShadow.block[lastShadow + 2] = ch;
    1278                this.last = lastShadow + 1;
    1279                break;
    1280
    1281            case 2:
    1282                dataShadow.block[lastShadow + 2] = ch;
    1283                dataShadow.block[lastShadow + 3] = ch;
    1284                this.last = lastShadow + 2;
    1285                break;
    1286
    1287            case 3: {
    1288                final byte[] block = dataShadow.block;
    1289                block[lastShadow + 2] = ch;
    1290                block[lastShadow + 3] = ch;
    1291                block[lastShadow + 4] = ch;
    1292                this.last = lastShadow + 3;
    1293            }
    1294                break;
    1295
    1296            default: {
    1297                runLengthShadow -= 4;
    1298                dataShadow.inUse[runLengthShadow] = true;
    1299                final byte[] block = dataShadow.block;
    1300                block[lastShadow + 2] = ch;
    1301                block[lastShadow + 3] = ch;
    1302                block[lastShadow + 4] = ch;
    1303                block[lastShadow + 5] = ch;
    1304                block[lastShadow + 6] = (byte) runLengthShadow;
    1305                this.last = lastShadow + 5;
    1306            }
    1307                break;
    1308
    1309            }
    1310        } else {
    1311            endBlock();
    1312            initBlock();
    1313            writeRun();
    1314        }
    1315    }
    1316
    1317}