-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmeticEncoder.java
More file actions
61 lines (39 loc) · 1.37 KB
/
Copy pathArithmeticEncoder.java
File metadata and controls
61 lines (39 loc) · 1.37 KB
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
package nayuki.arithcode;
import java.io.IOException;
public final class ArithmeticEncoder extends ArithmeticCoderBase {
private BitOutputStream output;
// Number of saved underflow bits. This value can grow without bound, so a truly correct implementation would use a BigInteger.
private int underflow;
// Creates an arithmetic coding encoder.
public ArithmeticEncoder(BitOutputStream out) {
super();
if (out == null)
throw new NullPointerException();
output = out;
underflow = 0;
}
// Encodes a symbol.
public void write(FrequencyTable freq, int symbol) throws IOException {
write(new CheckedFrequencyTable(freq), symbol);
}
// Encodes a symbol.
public void write(CheckedFrequencyTable freq, int symbol) throws IOException {
update(freq, symbol);
}
// Must be called at the end of the stream of input symbols, otherwise the output data cannot be decoded properly.
public void finish() throws IOException {
output.write((byte)1);
}
protected void shift() throws IOException {
int bit = (int)(low >>> (STATE_SIZE - 1));
output.write((byte)bit);
// Write out saved underflow bits
for (; underflow > 0; underflow--)
output.write((byte)(bit ^ 1));
}
protected void underflow() throws IOException {
if (underflow == Integer.MAX_VALUE)
throw new RuntimeException("Maximum underflow reached");
underflow++;
}
}