libUTL++
HuffmanEncoder.h
1 #pragma once
2 
4 
5 #include <libutl/Encoder.h>
6 
8 
9 UTL_NS_BEGIN;
10 
12 
34 
36 class HuffmanEncoder : public Encoder
37 {
39 
40 public:
51  Stream* stream,
52  bool owner,
53  uint_t numSymbols,
54  uint_t incLimit,
55  bool eob = false)
56  {
57  init();
58  start(mode, stream, owner, numSymbols, incLimit, eob);
59  }
60 
61  virtual size_t decode(byte_t* block, size_t num);
62 
64  inline uint_t decode();
65 
66  virtual size_t encode(const byte_t* block, size_t num);
67 
69  inline void encode(uint_t symbol);
70 
81  void start(uint_t mode,
82  Stream* stream,
83  bool owner,
84  uint_t numSymbols,
85  uint_t incLimit,
86  bool eob = false);
87 
88 protected:
89  virtual void clear();
90  virtual void finishEncoding();
91 
92 private:
93  void init();
94  void
95  deInit()
96  {
97  close();
98  }
99  void clearSelf();
100  void updateFreq(uint_t a, uint_t b);
101  void updateModel(uint_t symbol);
102  uint_t _numSymbols;
103  uint_t _incLimit;
104  uint_t _eob;
105  uint_t* _up;
106  uint_t* _freq;
107  uint_t* _left;
108  uint_t* _right;
109 };
110 
112 
113 void
114 HuffmanEncoder::encode(uint_t symbol)
115 {
116  uint_t a, sp = 0;
117  bool stack[64];
118  a = _numSymbols + symbol;
119  do
120  {
121  stack[sp++] = (_right[_up[a]] == a);
122  a = _up[a];
123  } while (a != 1);
124  do
125  {
126  _stream->putBit(stack[--sp]);
127  } while (sp > 0);
128  updateModel(symbol);
129 }
130 
132 
133 uint_t
134 HuffmanEncoder::decode()
135 {
136  uint_t a = 1;
137  do
138  {
139  if (_stream->getBit())
140  {
141  a = _right[a];
142  }
143  else
144  {
145  a = _left[a];
146  }
147  } while (a < _numSymbols);
148  a -= _numSymbols;
149  updateModel(a);
150  return a;
151 }
152 
154 
155 UTL_NS_END;
void deInit()
De-initialize UTL++.
Encoder/decoder abstraction.
Definition: Encoder.h:39
#define UTL_CLASS_DECL(DC, BC)
Declaration of standard UTL++ functionality for a non-template class.
Definition: macros.h:688
unsigned char byte_t
Unsigned character.
Definition: types.h:31
HuffmanEncoder(uint_t mode, Stream *stream, bool owner, uint_t numSymbols, uint_t incLimit, bool eob=false)
Constructor.
Adaptive Huffman coder.
unsigned int uint_t
Unsigned integer.
Definition: types.h:59
Stream I/O abstraction.
Definition: Stream.h:68
void init()
Initialize UTL++.