24 #ifndef COMMON_HUFFMAN_H 25 #define COMMON_HUFFMAN_H 27 #include "common/array.h" 28 #include "common/list.h" 29 #include "common/types.h" 45 inline uint32 REVERSEBITS(uint32 x) {
46 x = (((x & ~0x55555555) >> 1) | ((x & 0x55555555) << 1));
47 x = (((x & ~0x33333333) >> 2) | ((x & 0x33333333) << 2));
48 x = (((x & ~0x0F0F0F0F) >> 4) | ((x & 0x0F0F0F0F) << 4));
49 x = (((x & ~0x00FF00FF) >> 8) | ((x & 0x00FF00FF) << 8));
51 return((x >> 16) | (x << 16));
58 template<
class BITSTREAM>
69 Huffman(uint8 maxLength, uint32 codeCount,
const uint32 *codes,
const uint8 *lengths,
const uint32 *symbols =
nullptr);
79 Symbol(uint32 c, uint32 s) : code(c), symbol(s) {}
93 PrefixEntry() : length(0xFF) {}
96 static const uint8 _prefixTableBits = 8;
97 PrefixEntry _prefixTable[1 << _prefixTableBits];
100 template <
class BITSTREAM>
102 assert(codeCount > 0);
108 for (uint32 i = 0; i < codeCount; i++)
109 maxLength =
MAX(maxLength, lengths[i]);
111 assert(maxLength <= 32);
114 _codes.resize(
MAX(maxLength - _prefixTableBits, 0));
116 for (uint i = 0; i < codeCount; i++) {
117 uint8 length = lengths[i];
120 uint32 symbol = symbols ? symbols[i] : i;
122 if (length <= _prefixTableBits) {
126 if (BITSTREAM::isMSB2LSB()) {
127 startIndex = codes[i] << (_prefixTableBits - length);
129 startIndex = REVERSEBITS(codes[i]) >> (32 - _prefixTableBits);
132 uint32 endIndex = startIndex | ((1 << (_prefixTableBits - length)) - 1);
134 for (uint32 j = startIndex; j <= endIndex; j++) {
135 uint32 index = BITSTREAM::isMSB2LSB() ? j : REVERSEBITS(j) >> (32 - _prefixTableBits);
136 _prefixTable[index].symbol = symbol;
137 _prefixTable[index].length = length;
141 _codes[lengths[i] - 1 - _prefixTableBits].push_back(Symbol(codes[i], symbol));
146 template <
class BITSTREAM>
148 uint32 code = bits.peekBits(_prefixTableBits);
150 uint8 length = _prefixTable[code].length;
152 if (length != 0xFF) {
154 return _prefixTable[code].symbol;
156 bits.skip(_prefixTableBits);
158 for (uint32 i = 0; i < _codes.size(); i++) {
159 bits.addBit(code, i + _prefixTableBits);
162 if (code == cCode->code)
163 return cCode->symbol;
167 error(
"Unknown Huffman code");
175 #endif // COMMON_HUFFMAN_H
uint32 getSymbol(BITSTREAM &bits) const
Definition: huffman.h:147
Huffman(uint8 maxLength, uint32 codeCount, const uint32 *codes, const uint8 *lengths, const uint32 *symbols=nullptr)
Definition: huffman.h:101
Definition: algorithm.h:29
void NORETURN_PRE error(MSVC_PRINTF const char *s,...) GCC_PRINTF(1
Definition: list_intern.h:48
T MAX(T a, T b)
Definition: util.h:62