aboutsummaryrefslogtreecommitdiff
path: root/java/org/brotli/dec/BitReader.java
blob: 99839874d1b4459a83fdbc8668f2421af79af646 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/* Copyright 2015 Google Inc. All Rights Reserved.

   Distributed under MIT license.
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/

package org.brotli.dec;

import java.io.IOException;
import java.io.InputStream;

/**
 * Bit reading helpers.
 */
final class BitReader {

  /**
   * Input byte buffer, consist of a ring-buffer and a "slack" region where bytes from the start of
   * the ring-buffer are copied.
   */
  private static final int BUF_SIZE = IntReader.CAPACITY << 2;
  private static final int READ_SIZE = BUF_SIZE - 64;

  private final IntReader intReader = new IntReader();
  private final byte[] shadowBuffer = new byte[BUF_SIZE];

  private InputStream input;

  /**
   * Input stream is finished.
   */
  private boolean endOfStreamReached;

  /**
   * Pre-fetched bits.
   */
  long accumulator;

  /**
   * Current bit-reading position in accumulator.
   */
  int bitOffset;

  /**
   * Number of 32-bit integers available for reading.
   */
  private int available;

  /* Number of bytes in unfinished "int" item. */
  private int tailBytes = 0;

  /**
   * Fills up the input buffer.
   *
   * <p> No-op if there are at least 36 bytes present after current position.
   *
   * <p> After encountering the end of the input stream, 64 additional zero bytes are copied to the
   * buffer.
   */
  // TODO: Split to check and read; move read outside of decoding loop.
  static void readMoreInput(BitReader br) {
    if (br.available > 9) {
      return;
    }
    if (br.endOfStreamReached) {
      if (br.available > 4) {
        return;
      }
      throw new BrotliRuntimeException("No more input");
    }
    int readOffset = IntReader.position(br.intReader) << 2;
    int bytesRead = READ_SIZE - readOffset;
    System.arraycopy(br.shadowBuffer, readOffset, br.shadowBuffer, 0, bytesRead);
    try {
      while (bytesRead < READ_SIZE) {
        int len = br.input.read(br.shadowBuffer, bytesRead, READ_SIZE - bytesRead);
        if (len == -1) {
          br.endOfStreamReached = true;
          Utils.fillWithZeroes(br.shadowBuffer, bytesRead, 64);
          bytesRead += 64;
          br.tailBytes = bytesRead & 3;
          break;
        }
        bytesRead += len;
      }
    } catch (IOException e) {
      throw new BrotliRuntimeException("Failed to read input", e);
    }
    IntReader.reload(br.intReader, br.shadowBuffer, 0, bytesRead >> 2);
    br.available = bytesRead >> 2;
  }

  static void checkHealth(BitReader br) {
    if (!br.endOfStreamReached) {
      return;
    }
    /* When end of stream is reached, we "borrow" up to 64 zeroes to bit reader.
     * If compressed stream is valid, then borrowed zeroes should remain unused. */
    int unusedBytes = (br.available << 2) + ((64 - br.bitOffset) >> 3);
    int borrowedBytes = 64 - br.tailBytes;
    if (unusedBytes != borrowedBytes) {
      throw new BrotliRuntimeException("Read after end");
    }
  }

  /**
   * Advances the Read buffer by 5 bytes to make room for reading next 24 bits.
   */
  static void fillBitWindow(BitReader br) {
    if (br.bitOffset >= 32) {
      br.accumulator = ((long) IntReader.read(br.intReader) << 32) | (br.accumulator >>> 32);
      br.bitOffset -= 32;
      br.available--;
    }
  }

  /**
   * Reads the specified number of bits from Read Buffer.
   */
  static int readBits(BitReader br, int n) {
    fillBitWindow(br);
    int val = (int) (br.accumulator >>> br.bitOffset) & ((1 << n) - 1);
    br.bitOffset += n;
    return val;
  }

  /**
   * Initialize bit reader.
   *
   * <p> Initialisation turns bit reader to a ready state. Also a number of bytes is prefetched to
   * accumulator. Because of that this method may block until enough data could be read from input.
   *
   * @param br BitReader POJO
   * @param input data source
   */
  static void init(BitReader br, InputStream input) {
    if (br.input != null) {
      throw new IllegalStateException("Bit reader already has associated input stream");
    }
    br.input = input;
    br.accumulator = 0;
    IntReader.setPosition(br.intReader, READ_SIZE >> 2);
    br.bitOffset = 64;
    br.available = 0;
    br.endOfStreamReached = false;
    readMoreInput(br);
    /* This situation is impossible in current implementation. */
    if (br.available == 0) {
      throw new BrotliRuntimeException("Can't initialize reader");
    }
    fillBitWindow(br);
    fillBitWindow(br);
  }

  static void close(BitReader br) throws IOException {
    InputStream is = br.input;
    br.input = null;
    if (is != null) {
      is.close();
    }
  }

  static void jumpToByteBoundary(BitReader br) {
    int padding = (64 - br.bitOffset) & 7;
    if (padding != 0) {
      int paddingBits = BitReader.readBits(br, padding);
      if (paddingBits != 0) {
        throw new BrotliRuntimeException("Corrupted padding bits ");
      }
    }
  }

}