KASKADE 7 development version
Loading...
Searching...
No Matches
prefixcoder.hh
Go to the documentation of this file.
1#ifndef PREFIXCODER__HH
2#define PREFIXCODER__HH
3
4#include <cassert>
5#include <cstddef>
6#include <cstdint>
7#include <unordered_map>
8#include <variant>
9#include <vector>
10
11#include "alphabet.hh"
12
18// template <class State>
19// using CodeBook = std::vector<std::pair<State,int>>;
20
21template <class State, class Symbol>
22using CodeBook = std::vector<std::pair<Symbol, std::pair<State,int>>>;
23
24
25// /**
26// * \ingroup entropycoding
27// * \brief Creates a code book for a fixed-length code of minimal size.
28// *
29// * Each symbol is assigned a code of \f$ \lceil \log_2 n \rceil \f$ bits,
30// * where \f$ n\f$ is the size of the alphabet.
31// * \param nSymbols the size \f$ n \f$ of the alphabet.
32// */
33// template <class State=uint64_t>
34// CodeBook<State> uniformCodeBook(int nSymbols);
35
44// template <class State=uint64_t, class Freq>
45// CodeBook<State> huffmanCodeBook(Frequencies<Freq> const& p);
46template <class State, class Freq, class Symbol>
48//-------------------------------------------------------------------------------------------------
49//-------------------------------------------------------------------------------------------------
50
51template <class Symbol, class State_=uint64_t>
53{
54 // Converting symbols (integers 0,...,n-1) to code words is easy, by building a lookup
55 // table.
56 //
57 // In contrast, converting codes to symbols is not trivial since (i) the length of the
58 // current code word is unknown and needs to be inferred from the prefix property and
59 // (ii) the code words interpreted as integers are just a few numbers in a potentially
60 // large range - the more squeezed their probability distribution is, i.e. the larger
61 // the maximum code word length compared to the entropy, the larger is the range of
62 // integers where code words need to be found.
63 //
64 // When interpreting the next m bits of the message as an integer, where m is the maximum
65 // code word length, there are essentially two ways to handle this: (i) sorting the code
66 // words and doing a binary search or (ii) creating a lookup table mapping code words (and
67 // following arbitrary bits of the rest of the message) of length m to the symbols.
68 //
69 // The first option incurs a small but significant arithmetic effort *per symbol* decoded,
70 // and leads to a bad decoding performance. The second option is fast if the code is well
71 // balanced with small m and thus a small lookup table (of 2^m entries). If m is large, say
72 // m>20, then accessing the lookup table will lead to frequent cache misses, and reduce the
73 // decoding performance considerably (encode 1GB/s, decode 50MB/s has been observed for m=23).
74 //
75 // Here, we take a hybrid approach, by storing the symbols (and code lengths) in a tree of
76 // arity 256. Thus, the range 0,...,2^m-1 in which code words (and following arbitrary bits)
77 // are found, is subdivided into 256 bins. If a bin is covered completely by the numbers with
78 // a particular code word in the most significant bits, no further subdivision is needed, and
79 // the symbol can be found in the root node of the tree by simple lookup using the topmost
80 // 8 bits of the code. This is the frequent case, since short code words occur frequently.
81 //
82 // This tree, called the symbol book, is represented with nodes as std::variant holding
83 // either the final data (symbol,code length) or a std::vector of length 256 subdividing
84 // the range further.
85
86 struct SymbolEntry;
87 using SymbolBook = std::vector<SymbolEntry>;
88 struct SymbolEntry
89 {
90 std::variant<std::monostate, std::pair<Symbol,int>, SymbolBook> data;
91 };
92
93public:
94 using State = State_;
95
97 : codebook(std::move(codebook_))
98 {
99 assert(!codebook.empty());
100
101 // Extract the maximum lenght of any code word.
102 maxLength = 0;
103 for (auto const& [symbol, codeinfo] : codebook)
104 maxLength = std::max(maxLength, codeinfo.second);
105
106 // Create the symbol book. The root node is just a vector with 256 bins.
107 // Each code word c of length n is entered into the code book, associating
108 // it with symbol and code length.
109 symbolBook.resize(256);
110 for (auto const& [symbol, codeinfo] : codebook)
111 {
112 State c = codeinfo.first;
113 int n = codeinfo.second;
114 enter(symbolBook, c, n, std::pair(symbol, n));
115 }
116 }
117
121 int maxLen() const
122 {
123 return maxLength;
124 }
125
130 std::pair<State,int> code(Symbol s) const
131 {
132 auto it = std::find_if(codebook.begin(), codebook.end(),
133 [&](auto const& p) { return p.first == s; });
134 assert(it != codebook.end());
135 return it->second;
136 }
137
141 bool hasSymbol(Symbol s) const
142 {
143 return std::any_of(codebook.begin(), codebook.end(),
144 [&](auto const& p) { return p.first == s; });
145 }
146
151 std::pair<Symbol,int> symbol(State code) const
152 {
153 return lookup(symbolBook,code);
154 }
155
156 void printCodebook() const {
157 // std::cout << "Codebook contents (" << codebook.size() << " entries):\n";
158 for (auto const& [symbol, codepair] : codebook) {
159 std::cout << " Symbol: " << static_cast<int>(symbol)
160 << ", Code: " << codepair.first
161 << ", Length: " << codepair.second << '\n';
162 }
163 }
164
165private:
167 int maxLength;
168 SymbolBook symbolBook;
169
170 // Enter a code word c of length n into the symbol book. The code word has to be
171 // right aligned, i.e. occupying the least significant bits.
172 static void enter(SymbolBook& symbolBook, State c, int n, std::pair<Symbol,int> value)
173 {
174 if (n<=8) // a code word of up to 8 bit - it covers one (or more) full slots.
175 {
176 // Shift the code word such that it covers the most significant bits of a single byte
177 // (which is the range used for the lookup table in the tree node).
178 int const cShift = c<<(8-n);
179
180 // Enter the value into each slot that is covered by the symbol, i.e. for any number
181 // where the most significant bits coincide with the given code words.
182 for (int i=0; i<(1<<(8-n)); ++i)
183 symbolBook[cShift+i].data = value;
184 }
185 else // a code word of more than 8 bit, which covers only part of a full slot.
186 {
187 // Extract the eight most significant bits of the code word, and use them for looking
188 // up the bin in which the symbol will end up.
189 int const cShift = c>>(n-8);
190 auto& var = symbolBook[cShift].data;
191
192 // If the bin is not yet initialized, create a new node lookup table. This is necessary,
193 // since the code word is *longer* than 8 bits, such that its range covers only part
194 // of a bin - this needs to be subdivided.
195 assert(var.index() != 1);
196 if (var.index() == 0) // no recursive entry yet
197 var = SymbolBook(256);
198 assert(var.index() == 2);
199
200 // Extract the remaining code word bits following after the first 8, and use
201 // them for entering the data into the newly created lookup table.
202 State mask = ((State)1 << (n-8)) - 1;
203 enter(std::get<2>(var),c&mask,n-8,value);
204 }
205 }
206
207 // Find symbol and code word length from given code. The current symbol's code is
208 // left-aligned, i.e. contained in the most significant bits of the given code.
209 static std::pair<Symbol,int> lookup(SymbolBook const& symbolBook, State code)
210 {
211 // Extract the 8 most significant bits and use them to look up the bin in the table.
212 int cShift = code>>(8*sizeof(State)-8);
213 auto const& var = symbolBook[cShift].data;
214
215 // If the bin contains just the data we are looking for, return it.
216 // Otherwise, we remove the already processed eight bits and search
217 // for the data in the lookup table that is contained in the bin.
218 if (var.index()==1) // found the value
219 return std::get<1>(var);
220 else
221 {
222 assert(var.index()==2);
223 return lookup(std::get<2>(var),code<<8);
224 }
225 }
226};
227
228
229//-------------------------------------------------------------------------------------------------
230//-------------------------------------------------------------------------------------------------
231
232//-------------------------------------------------------------------------------------------------
233//-------------------------------------------------------------------------------------------------
234
259template <class Symbol, class OIter, class Output, class State=uint64_t>
261{
262 static int const outputDigits = 8*sizeof(Output);
263 static int const stateDigits = 8*sizeof(State);
264 //static_assert(stateDigits > outputDigits);
265
266public:
267 PrefixEncoder(OIter out_)
268 : out(out_)
269 {}
270
276 {
277 // The decoder is eager, i.e. it reads as many message bits as fit into
278 // the state, such that also the longest possible code word is completely
279 // read before trying to extract the symbol.
280 for (int i=0; i<sizeof(State)/sizeof(Output); ++i)
281 {
282 *out = static_cast<Output>(state>>(stateDigits-outputDigits));
283 state <<= outputDigits;
284 }
285 }
286
291 void push_back(Symbol s, PrefixCode<Symbol,State> const& code)
292 {
293 // The encoder maintains the message as a left-justified bitstream,
294 // i.e. it occupies the most significant bits of the state.
295
296 // Get a new codeword for the given symbol and append it to the message.
297 auto [c,n] = code.code(s);
298 push_back(c,n);
299 }
300
313 void push_back(State c, int n)
314 {
315 assert(0<=length && n+length<=stateDigits);
316
317 // append the code word to the
318 // end of the message (i.e. at the lower significant end of state).
319 length += n;
320 state |= static_cast<State>(c) << (stateDigits-length);
321
322 // Push as many of the leading (most significant) bits to the output,
323 // to make room for the next code word.
324 while (length > outputDigits)
325 {
326 *out++ = static_cast<Output>(state>>(stateDigits-outputDigits));
327 state <<= outputDigits;
328 length -= outputDigits;
329 }
330 }
331
332private:
333 OIter out;
334 State state = 0;
335 int length = 0;
336};
337
338//-------------------------------------------------------------------------------------------------
339
365template <class Symbol, class IIter, class Input=typename std::iterator_traits<IIter>::value_type, class State=size_t>
367{
368 static int const inputDigits = 8*sizeof(Input);
369 static int const stateDigits = 8*sizeof(State);
370 //static_assert(stateDigits > inputDigits);
371
372public:
373 PrefixDecoder(IIter in_)
374 : in(in_)
375 {}
376
382 {
383 // The decoder maintains the head of the (remaining) message left-justified in
384 // the state, i.e. in the most significant bits.
385
386 // Read as much of the remaining message as fits into state.
387 fill();
388
389 // Extract the symbol and the code word's length.
390 auto [s,n] = code.symbol(state);
391
392 // Remove the code word from the state by shifting it out to the left.
393 assert(n<=length);
394 length -= n;
395 state <<= n;
396
397 return s;
398 }
399
407 State pop_front(int n)
408 {
409 fill();
410
411 assert(n<=length);
412 State c = state >> (stateDigits - n);
413
414 // Remove the code word from the state by shifting it out to the left.
415 length -= n;
416 state <<= n;
417 return c;
418 }
419
420private:
421 IIter in;
422 State state = 0;
423 int length = 0;
424
425 void fill()
426 {
427 // Eager read: Read as many bits of the encoded message as possible into the state,
428 // such that also the longest possible code word can be decoded.
429 // In principle, we could read only until length>=code.maxLen(), which could
430 // save reading a few bytes at the end of the message (which can be of interest for
431 // short messages). But since the code is provided at run time only, and for each
432 // symbol individually, maxLen() needs to be looked up for every symbol again,
433 // and this sacrifices performance.
434 while (length < stateDigits-inputDigits)
435 {
436 state |= static_cast<State>(*in++) << (stateDigits-inputDigits-length);
437 length += inputDigits;
438 }
439 }
440};
441
442
443//-------------------------------------------------------------------------------------------------
444
451template <class Symbol>
453{
454public:
455 HuffmanCodec() = default;
456
457 template <class Freq>
459 {
460 build(f);
461 }
462
463 template <class Freq>
465
466 template <class OutputByte>
467 void encode(std::vector<Symbol> const& symbols, std::vector<OutputByte>& out) const;
468
469 template <class InputByte>
470 std::vector<Symbol> decode(std::vector<InputByte> const& data, std::size_t symbolCount) const;
471
472 bool hasSymbol(Symbol s) const
473 {
474 return codes.find(s) != codes.end();
475 }
476
477 std::unordered_map<Symbol, std::vector<uint8_t>> const& codeTable() const
478 {
479 return codes;
480 }
481
482private:
483 struct Node
484 {
485 int left = -1;
486 int right = -1;
487 Symbol symbol{};
488 bool leaf = false;
489 };
490
491 std::vector<Node> nodes;
492 std::unordered_map<Symbol, std::vector<uint8_t>> codes;
493 int root = -1;
494};
495
496//-------------------------------------------------------------------------------------------------
497
498#endif
HuffmanCodec()=default
void build(Frequencies< Freq, Symbol > const &f)
void encode(std::vector< Symbol > const &symbols, std::vector< OutputByte > &out) const
HuffmanCodec(Frequencies< Freq, Symbol > const &f)
bool hasSymbol(Symbol s) const
std::vector< Symbol > decode(std::vector< InputByte > const &data, std::size_t symbolCount) const
std::unordered_map< Symbol, std::vector< uint8_t > > const & codeTable() const
void printCodebook() const
std::pair< Symbol, int > symbol(State code) const
For an encoded message fraction of bits ( being the maximum code length), return the pair of symbo...
PrefixCode(CodeBook< State, Symbol > &&codebook_)
State_ State
int maxLen() const
Returns the maximum length of any codeword (in bits).
bool hasSymbol(Symbol s) const
Checks whether the given symbol exists in the codebook.
std::pair< State, int > code(Symbol s) const
For a symbol , return the pair of code word (in the least significant bits) and code length .
Symbol pop_front(PrefixCode< Symbol, State > const &code)
Extract a symbol from the head of the remaining encoded message.
State pop_front(int n)
Extract a code word of given length from the head of the remaining encoded message.
PrefixDecoder(IIter in_)
~PrefixEncoder()
Flushes the remaining state, i.e. writes the rest of the encoded message to the output.
void push_back(State c, int n)
Appends a given codeword directly.
PrefixEncoder(OIter out_)
void push_back(Symbol s, PrefixCode< Symbol, State > const &code)
Appends a symbol to the encoded message.
std::vector< std::pair< Symbol, std::pair< State, int > > > CodeBook
The type of a code book - a map from symbols to codes and their lengths.
CodeBook< State, Symbol > huffmanCodeBook(Frequencies< Freq, Symbol > const &f)
Creates a code book for a fixed-length code of minimal size.