-
Notifications
You must be signed in to change notification settings - Fork 15
/
FPAQCodec.go
353 lines (293 loc) · 8.95 KB
/
FPAQCodec.go
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
Copyright 2011-2017 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
you may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package entropy
import (
"encoding/binary"
"errors"
kanzi "github.com/flanglet/kanzi-go"
)
const (
_FPAQ_PSCALE = 1 << 16
)
// FPAQEncoder entropy encoder derived from fpaq0r by Matt Mahoney & Alexander Ratushnyak.
// See http://mattmahoney.net/dc/#fpaq0.
// Simple (and fast) adaptive order 0 entropy coder
type FPAQEncoder struct {
low uint64
high uint64
bitstream kanzi.OutputBitStream
disposed bool
buffer []byte
index int
probs [4][]int // probability of bit=1
p []int // pointer to current prob
ctxIdx byte // previous bits
}
// NewFPAQEncoder creates an instance of FPAQEncoder
func NewFPAQEncoder(bs kanzi.OutputBitStream) (*FPAQEncoder, error) {
if bs == nil {
return nil, errors.New("FPAQ codec: Invalid null bitstream parameter")
}
this := &FPAQEncoder{}
this.low = 0
this.high = _BINARY_ENTROPY_TOP
this.bitstream = bs
this.buffer = make([]byte, 0)
this.index = 0
this.ctxIdx = 1
this.p = this.probs[0]
for i := 0; i < 4; i++ {
this.probs[i] = make([]int, 256)
for j := range this.probs[0] {
this.probs[i][j] = _FPAQ_PSCALE >> 1
}
}
return this, nil
}
func (this *FPAQEncoder) encodeBit(bit byte, pIdx int) {
// Calculate interval split
// Written in a way to maximize accuracy of multiplication/division
split := (((this.high - this.low) >> 4) * uint64(this.p[pIdx]>>4)) >> 8
// Update probabilities
if bit == 0 {
this.low += (split + 1)
this.p[pIdx] -= (this.p[pIdx] >> 6)
} else {
this.high = this.low + split
this.p[pIdx] -= ((this.p[pIdx] - _FPAQ_PSCALE + 64) >> 6)
}
// Write unchanged first 32 bits to bitstream
for (this.low^this.high)>>24 == 0 {
this.flush()
}
}
// Write encodes the data provided into the bitstream. Return the number of byte
// written to the bitstream. Splits big blocks into chunks and encode the chunks
// byte by byte sequentially into the bitstream.
func (this *FPAQEncoder) Write(block []byte) (int, error) {
count := len(block)
if count > 1<<30 {
return -1, errors.New("FPAQ codec: Invalid block size parameter (max is 1<<30)")
}
startChunk := 0
end := count
length := count
if count >= 1<<26 {
// If the block is big (>=64MB), split the encoding to avoid allocating
// too much memory.
if count < 1<<29 {
length = count >> 3
} else {
length = count >> 4
}
} else if count < 64 {
length = 64
}
// Split block into chunks, read bit array from bitstream and decode chunk
for startChunk < end {
chunkSize := length
if startChunk+length >= end {
chunkSize = end - startChunk
}
if len(this.buffer) < (chunkSize + (chunkSize >> 3)) {
this.buffer = make([]byte, chunkSize+(chunkSize>>3))
}
this.index = 0
buf := block[startChunk : startChunk+chunkSize]
this.p = this.probs[0]
for _, val := range buf {
bits := int(val) + 256
this.encodeBit(val&0x80, 1)
this.encodeBit(val&0x40, bits>>7)
this.encodeBit(val&0x20, bits>>6)
this.encodeBit(val&0x10, bits>>5)
this.encodeBit(val&0x08, bits>>4)
this.encodeBit(val&0x04, bits>>3)
this.encodeBit(val&0x02, bits>>2)
this.encodeBit(val&0x01, bits>>1)
this.p = this.probs[val>>6]
}
WriteVarInt(this.bitstream, uint32(this.index))
this.bitstream.WriteArray(this.buffer, uint(8*this.index))
startChunk += chunkSize
if startChunk < end {
this.bitstream.WriteBits(this.low|_MASK_0_24, 56)
}
}
return count, nil
}
func (this *FPAQEncoder) flush() {
binary.BigEndian.PutUint32(this.buffer[this.index:], uint32(this.high>>24))
this.index += 4
this.low <<= 32
this.high = (this.high << 32) | _MASK_0_32
}
// BitStream returns the underlying bitstream
func (this *FPAQEncoder) BitStream() kanzi.OutputBitStream {
return this.bitstream
}
// Dispose must be called before getting rid of the entropy encoder
// This idempotent implmentation writes the last buffered bits into the
// bitstream.
func (this *FPAQEncoder) Dispose() {
if this.disposed == true {
return
}
this.disposed = true
this.bitstream.WriteBits(this.low|_MASK_0_24, 56)
}
// FPAQDecoder entropy decoder derived from fpaq0r by Matt Mahoney & Alexander Ratushnyak.
// See http://mattmahoney.net/dc/#fpaq0.
// Simple (and fast) adaptive order 0 entropy coder
type FPAQDecoder struct {
low uint64
high uint64
current uint64
initialized bool
bitstream kanzi.InputBitStream
buffer []byte
index int
probs [4][]int // probability of bit=1
p []int // pointer to current prob
ctx byte // previous bits
}
// NewFPAQDecoder creates an instance of FPAQDecoder
func NewFPAQDecoder(bs kanzi.InputBitStream) (*FPAQDecoder, error) {
if bs == nil {
return nil, errors.New("FPAQ codec: Invalid null bitstream parameter")
}
// Defer stream reading. We are creating the object, we should not do any I/O
this := &FPAQDecoder{}
this.low = 0
this.high = _BINARY_ENTROPY_TOP
this.bitstream = bs
this.buffer = make([]byte, 0)
this.index = 0
this.ctx = 1
this.p = this.probs[0]
for i := 0; i < 4; i++ {
this.probs[i] = make([]int, 256)
for j := range this.probs[0] {
this.probs[i][j] = _FPAQ_PSCALE >> 1
}
}
return this, nil
}
// Initialized returns true if Initialize() has been called at least once
func (this *FPAQDecoder) Initialized() bool {
return this.initialized
}
// Initialize initializes the decoder by prefetching the first bits
// and saving them into a buffer. This code is idempotent.
func (this *FPAQDecoder) Initialize() {
if this.initialized == true {
return
}
this.current = this.bitstream.ReadBits(56)
this.initialized = true
}
func (this *FPAQDecoder) decodeBit(pred int) byte {
// Calculate interval split
// Written in a way to maximize accuracy of multiplication/division
split := ((((this.high - this.low) >> 4) * uint64(pred)) >> 8) + this.low
var bit byte
// Update probabilities
if split >= this.current {
bit = 1
this.high = split
this.p[this.ctx] -= ((this.p[this.ctx] - _FPAQ_PSCALE + 64) >> 6)
this.ctx += (this.ctx + 1)
} else {
bit = 0
this.low = -^split
this.p[this.ctx] -= (this.p[this.ctx] >> 6)
this.ctx += this.ctx
}
// Read 32 bits from bitstream
for (this.low^this.high)>>24 == 0 {
this.read()
}
return bit
}
func (this *FPAQDecoder) read() {
this.low = (this.low << 32) & _MASK_0_56
this.high = ((this.high << 32) | _MASK_0_32) & _MASK_0_56
val := uint64(binary.BigEndian.Uint32(this.buffer[this.index:]))
this.current = ((this.current << 32) | val) & _MASK_0_56
this.index += 4
}
// Read decodes data from the bitstream and return it in the provided buffer.
// Return the number of bytes read from the bitstream.
// Splits big blocks into chunks and decode the chunks byte by byte sequentially from the bitstream.
func (this *FPAQDecoder) Read(block []byte) (int, error) {
count := len(block)
if count > 1<<30 {
return -1, errors.New("FPAQ codec: Invalid block size parameter (max is 1<<30)")
}
startChunk := 0
end := count
length := count
if count >= 1<<26 {
// If the block is big (>=64MB), split the decoding to avoid allocating
// too much memory.
if count < 1<<29 {
length = count >> 3
} else {
length = count >> 4
}
} else if count < 64 {
length = 64
}
// Split block into chunks, read bit array from bitstream and decode chunk
for startChunk < end {
chunkSize := length
if startChunk+length >= end {
chunkSize = end - startChunk
}
if len(this.buffer) < (chunkSize*9)>>3 {
this.buffer = make([]byte, (chunkSize*9)>>3)
}
szBytes := ReadVarInt(this.bitstream)
this.current = this.bitstream.ReadBits(56)
this.initialized = true
if szBytes != 0 {
this.bitstream.ReadArray(this.buffer, uint(8*szBytes))
}
this.index = 0
buf := block[startChunk : startChunk+chunkSize]
this.p = this.probs[0]
for i := range buf {
this.ctx = 1
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
this.decodeBit(this.p[this.ctx] >> 4)
buf[i] = byte(this.ctx)
this.p = this.probs[(this.ctx&0xFF)>>6]
}
startChunk += chunkSize
}
return count, nil
}
// BitStream returns the underlying bitstream
func (this *FPAQDecoder) BitStream() kanzi.InputBitStream {
return this.bitstream
}
// Dispose must be called before getting rid of the entropy decoder
// This implementation does nothing.
func (this *FPAQDecoder) Dispose() {
}