-
Notifications
You must be signed in to change notification settings - Fork 20
/
rice.hpp
544 lines (441 loc) · 15.2 KB
/
rice.hpp
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// ================================================================================================
// -*- C++ -*-
// File: rice.hpp
// Author: Guilherme R. Lampert
// Created on: 05/03/17
// Brief: Rice encoding/decoding (named after Robert F. Rice), which is based on Golomb Coding.
// http://dmr.ath.cx/code/rice/
// https://en.wikipedia.org/wiki/Golomb_coding
// ================================================================================================
#ifndef RICE_HPP
#define RICE_HPP
#include <cstdint>
#include <cstdlib>
// If you provide a custom malloc(), you must also provide a custom free().
// Note: We never check RICE_MALLOC's return for null. A custom implementation
// should just abort with a fatal error if the program runs out of memory.
#ifndef RICE_MALLOC
#define RICE_MALLOC std::malloc
#define RICE_MFREE std::free
#endif // RICE_MALLOC
namespace rice
{
// ========================================================
// The default fatalError() function writes to stderr and aborts.
#ifndef RICE_ERROR
void fatalError(const char * message);
#define RICE_USING_DEFAULT_ERROR_HANDLER
#define RICE_ERROR(message) ::rice::fatalError(message)
#endif // RICE_ERROR
// ========================================================
// class Encoder:
// ========================================================
class Encoder final
{
public:
// No copy/assignment.
Encoder(const Encoder &) = delete;
Encoder & operator = (const Encoder &) = delete;
Encoder();
explicit Encoder(int initialSizeInBits, int growthGranularity = 2);
void encodeByte(int value, int KBits);
void writeKBitsWord(std::uint32_t KBits, int bitCount);
void appendBit(int bit);
static int computeCodeLength(int value, int KBits);
static int findBestKBits(const std::uint8_t * input, int inSizeBytes, int KBitsMax, int * outBestSizeBits);
int getByteCount() const;
int getBitCount() const;
const std::uint8_t * getBitStream() const;
void allocate(int bitsWanted);
void setGranularity(int growthGranularity);
std::uint8_t * release();
~Encoder();
private:
void internalInit();
static int nextPowerOfTwo(int num);
static std::uint8_t * allocBytes(int bytesWanted, std::uint8_t * oldPtr, int oldSize);
std::uint8_t * stream; // Growable buffer to store our bits. Heap allocated & owned by the class instance.
int bytesAllocated; // Current size of heap-allocated stream buffer *in bytes*.
int granularity; // Amount bytesAllocated multiplies by when auto-resizing in appendBit().
int currBytePos; // Current byte being written to, from 0 to bytesAllocated-1.
int nextBitPos; // Bit position within the current byte to access next. 0 to 7.
int numBitsWritten; // Number of bits in use from the stream buffer, not including byte-rounding padding.
};
// ========================================================
// class Decoder:
// ========================================================
class Decoder final
{
public:
// No copy/assignment.
Decoder(const Decoder &) = delete;
Decoder & operator = (const Decoder &) = delete;
Decoder(const Encoder & encoder);
Decoder(const std::uint8_t * encodedData, int encodedSizeBytes, int encodedSizeBits);
void reset();
bool readNextBit(int & bitOut);
int readKBitsWord(int bitCount);
int getByteCount() const { return sizeInBytes; }
int getBitCount() const { return sizeInBits; }
const std::uint8_t * getBitStream() const { return stream; }
private:
const std::uint8_t * stream; // Pointer to the external bit stream. Not owned by the reader.
const int sizeInBytes; // Size of the stream *in bytes*. Might include padding.
const int sizeInBits; // Size of the stream *in bits*, padding *not* include.
int currBytePos; // Current byte being read in the stream.
int nextBitPos; // Bit position within the current byte to access next. 0 to 7.
int numBitsRead; // Total bits read from the stream so far. Never includes byte-rounding padding.
};
// ========================================================
// easyEncode() / easyDecode():
// ========================================================
// Quick Rice data compression. Output compressed data is heap allocated
// with RICE_MALLOC() and should be later freed with RICE_MFREE().
void easyEncode(const std::uint8_t * uncompressed, int uncompressedSizeBytes,
std::uint8_t ** compressed, int * compressedSizeBytes, int * compressedSizeBits);
// Decompress back the output of easyEncode().
// The uncompressed output buffer is assumed to be big enough to hold the uncompressed data,
// if it happens to be smaller, the decoder will return a partial output and the return value
// of this function will be less than uncompressedSizeBytes.
int easyDecode(const std::uint8_t * compressed, int compressedSizeBytes, int compressedSizeBits,
std::uint8_t * uncompressed, int uncompressedSizeBytes);
} // namespace rice {}
// ================== End of header file ==================
#endif // RICE_HPP
// ================== End of header file ==================
// ================================================================================================
//
// Rice Encoder/Decoder Implementation
//
// ================================================================================================
#ifdef RICE_IMPLEMENTATION
#ifdef RICE_USING_DEFAULT_ERROR_HANDLER
#include <cstdio> // For the default error handler
#endif // RICE_USING_DEFAULT_ERROR_HANDLER
#include <cassert>
namespace rice
{
// ========================================================
#ifdef RICE_USING_DEFAULT_ERROR_HANDLER
// Prints a fatal error to stderr and aborts the process.
// This is the default method used by RICE_ERROR(), but
// you can override the macro to use other error handling
// mechanisms, such as C++ exceptions.
void fatalError(const char * const message)
{
std::fprintf(stderr, "Rice encoder/decoder error: %s\n", message);
std::abort();
}
#endif // RICE_USING_DEFAULT_ERROR_HANDLER
// ========================================================
// class Encoder:
// ========================================================
Encoder::Encoder()
{
// 8192 bits for a start (1024 bytes). It will resize if needed.
// Default granularity is 2.
internalInit();
allocate(8192);
}
Encoder::Encoder(const int initialSizeInBits, const int growthGranularity)
{
internalInit();
setGranularity(growthGranularity);
allocate(initialSizeInBits);
}
Encoder::~Encoder()
{
if (stream != nullptr)
{
RICE_MFREE(stream);
}
}
void Encoder::internalInit()
{
stream = nullptr;
bytesAllocated = 0;
granularity = 2;
currBytePos = 0;
nextBitPos = 0;
numBitsWritten = 0;
}
void Encoder::encodeByte(const int value, const int KBits)
{
const int m = 1 << KBits;
const int q = value / m;
// Write the quotient code (q 1 bits followed by a terminating 0)
for (int i = 0; i < q; ++i)
{
appendBit(1);
}
appendBit(0);
// Write the reminder (last k bits of the value)
for (int i = KBits - 1; i >= 0; i--)
{
appendBit((value >> i) & 1);
}
}
int Encoder::computeCodeLength(const int value, const int KBits)
{
const int m = 1 << KBits;
const int q = value / m;
return q + 1 + KBits;
}
int Encoder::findBestKBits(const std::uint8_t * input, const int inSizeBytes, const int KBitsMax, int * outBestSizeBits)
{
assert(input != nullptr);
assert(outBestSizeBits != nullptr);
int bestKBits = 0;
int bestSize = 0;
for (int k = 0; k <= KBitsMax; ++k)
{
int outputSize = 0;
for (int i = 0; i < inSizeBytes; ++i)
{
outputSize += computeCodeLength(input[i], k);
}
if (bestSize == 0 || outputSize < bestSize)
{
bestSize = outputSize;
bestKBits = k;
}
}
*outBestSizeBits = bestSize;
return bestKBits;
}
void Encoder::writeKBitsWord(const std::uint32_t KBits, const int bitCount)
{
assert(bitCount <= 32);
for (int b = 0; b < bitCount; ++b)
{
const std::uint32_t mask = std::uint32_t(1) << b;
const int bit = !!(KBits & mask);
appendBit(bit);
}
}
void Encoder::appendBit(const int bit)
{
const std::uint32_t mask = std::uint32_t(1) << nextBitPos;
stream[currBytePos] = (stream[currBytePos] & ~mask) | (-bit & mask);
++numBitsWritten;
if (++nextBitPos == 8)
{
nextBitPos = 0;
if (++currBytePos == bytesAllocated)
{
allocate(bytesAllocated * granularity * 8);
}
}
}
int Encoder::getByteCount() const
{
int usedBytes = numBitsWritten / 8;
int leftovers = numBitsWritten % 8;
if (leftovers != 0)
{
++usedBytes;
}
assert(usedBytes <= bytesAllocated);
return usedBytes;
}
int Encoder::getBitCount() const
{
return numBitsWritten;
}
const std::uint8_t * Encoder::getBitStream() const
{
return stream;
}
void Encoder::setGranularity(const int growthGranularity)
{
granularity = (growthGranularity >= 2) ? growthGranularity : 2;
}
std::uint8_t * Encoder::release()
{
std::uint8_t * oldPtr = stream;
internalInit();
return oldPtr;
}
void Encoder::allocate(int bitsWanted)
{
// Require at least a byte.
if (bitsWanted <= 0)
{
bitsWanted = 8;
}
// Round upwards if needed:
if ((bitsWanted % 8) != 0)
{
bitsWanted = nextPowerOfTwo(bitsWanted);
}
// We might already have the required count.
const int sizeInBytes = bitsWanted / 8;
if (sizeInBytes <= bytesAllocated)
{
return;
}
stream = allocBytes(sizeInBytes, stream, bytesAllocated);
bytesAllocated = sizeInBytes;
}
std::uint8_t * Encoder::allocBytes(const int bytesWanted, std::uint8_t * oldPtr, const int oldSize)
{
std::uint8_t * newMemory = static_cast<std::uint8_t *>(RICE_MALLOC(bytesWanted));
std::memset(newMemory, 0, bytesWanted);
if (oldPtr != nullptr)
{
std::memcpy(newMemory, oldPtr, oldSize);
RICE_MFREE(oldPtr);
}
return newMemory;
}
int Encoder::nextPowerOfTwo(int num)
{
--num;
for (std::size_t i = 1; i < sizeof(num) * 8; i <<= 1)
{
num = num | num >> i;
}
return ++num;
}
// ========================================================
// class Decoder:
// ========================================================
Decoder::Decoder(const Encoder & encoder)
: Decoder(encoder.getBitStream(), encoder.getByteCount(), encoder.getBitCount())
{
}
Decoder::Decoder(const std::uint8_t * encodedData, const int encodedSizeBytes, const int encodedSizeBits)
: stream(encodedData)
, sizeInBytes(encodedSizeBytes)
, sizeInBits(encodedSizeBits)
{
reset();
}
void Decoder::reset()
{
currBytePos = 0;
nextBitPos = 0;
numBitsRead = 0;
}
bool Decoder::readNextBit(int & bitOut)
{
if (numBitsRead >= sizeInBits)
{
return false; // We are done.
}
const std::uint32_t mask = std::uint32_t(1) << nextBitPos;
bitOut = !!(stream[currBytePos] & mask);
++numBitsRead;
if (++nextBitPos == 8)
{
nextBitPos = 0;
++currBytePos;
}
return true;
}
int Decoder::readKBitsWord(const int bitCount)
{
assert(bitCount <= 32);
std::uint32_t num = 0;
for (int b = 0; b < bitCount; ++b)
{
int bit;
if (!readNextBit(bit))
{
RICE_ERROR("Failed to read bits from stream! Unexpected end.");
break;
}
// Based on a "Stanford bit-hack":
// http://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
const std::uint32_t mask = std::uint32_t(1) << b;
num = (num & ~mask) | (-bit & mask);
}
return static_cast<int>(num);
}
// ========================================================
// easyEncode() implementation:
// ========================================================
void easyEncode(const std::uint8_t * uncompressed, const int uncompressedSizeBytes,
std::uint8_t ** compressed, int * compressedSizeBytes, int * compressedSizeBits)
{
if (uncompressed == nullptr || compressed == nullptr)
{
RICE_ERROR("rice::easyEncode(): Null data pointer(s)!");
return;
}
if (uncompressedSizeBytes <= 0 || compressedSizeBytes == nullptr || compressedSizeBits == nullptr)
{
RICE_ERROR("rice::easyEncode(): Bad in/out sizes!");
return;
}
// Do up to 8 passes to try finding the best K number of bits for the encoding.
int minCompressedBitSize;
const int KBits = Encoder::findBestKBits(uncompressed, uncompressedSizeBytes, 8, &minCompressedBitSize);
Encoder bitStreamEncoder(minCompressedBitSize);
// The decoder needs to know the number of bits we've used.
// Since the max is 8, we only need up to 4 bits for that.
bitStreamEncoder.writeKBitsWord(KBits, 4);
// Encode each byte of the input:
for (int b = 0; b < uncompressedSizeBytes; ++b)
{
bitStreamEncoder.encodeByte(uncompressed[b], KBits);
}
// Pass ownership of the compressed data buffer to the user pointer:
*compressedSizeBytes = bitStreamEncoder.getByteCount();
*compressedSizeBits = bitStreamEncoder.getBitCount();
*compressed = bitStreamEncoder.release();
}
// ========================================================
// easyDecode() implementation:
// ========================================================
int easyDecode(const std::uint8_t * compressed, const int compressedSizeBytes, const int compressedSizeBits,
std::uint8_t * uncompressed, const int uncompressedSizeBytes)
{
if (compressed == nullptr || uncompressed == nullptr)
{
RICE_ERROR("rice::easyDecode(): Null data pointer(s)!");
return 0;
}
if (compressedSizeBytes <= 0 || compressedSizeBits <= 0 || uncompressedSizeBytes <= 0)
{
RICE_ERROR("rice::easyDecode(): Bad in/out sizes!");
return 0;
}
Decoder bitStreamDecoder(compressed, compressedSizeBytes, compressedSizeBits);
// KBits word length is fixed to 4 bits.
const int KBits = bitStreamDecoder.readKBitsWord(4);
const int m = 1 << KBits;
int bytesDecoded = 0;
for (;;)
{
int q = 0;
int bit = 0;
// Reconstruct q:
while (bitStreamDecoder.readNextBit(bit) && (bit == 1))
{
++q;
}
// Reconstruct the remainder:
int value = m * q;
for (int i = KBits - 1; i >= 0; i--)
{
if (!bitStreamDecoder.readNextBit(bit))
{
RICE_ERROR("Failed to read bits from stream! Unexpected end.");
return bytesDecoded;
}
value = value | (bit << i);
}
*uncompressed++ = static_cast<std::uint8_t>(value);
bytesDecoded++;
if (bytesDecoded == uncompressedSizeBytes)
{
break; // Decompress buffer is full.
}
}
return bytesDecoded;
}
} // namespace rice {}
// ================ End of implementation =================
#endif // RICE_IMPLEMENTATION
// ================ End of implementation =================