rangecoder.cpp

// Range coder
// 
// Simplified code as example for the range coding.
//
// by feyd//godX.de
 
#include <stdint.h>
#include <vector>
#include <stdio.h>
#include <string.h>
#include <math.h>
 
class CRangeCoder
{
public:
    CRangeCoder(int nRangeBits=31) : 
        m_nRangeMax(1<<nRangeBits), m_nRangeMin(1<<(nRangeBits-1)), 
        m_nRange(1<<nRangeBits), m_nValue(0),
        m_nCarry(0), m_nCarryPos(0), m_nBitCount(0) {}
    virtual ~CRangeCoder() {}
 
    void AddCode(uint32_t nCode, uint32_t nMax)
    {
        uint32_t nBase = (m_nRange/nMax)*nCode;
        m_nValue += nBase;
        if(m_nValue>=m_nRangeMax) // Overflow
        {
            m_nValue %= m_nRangeMax;
            m_nCarry++;
        }
    }
 
    uint32_t GetCode(uint32_t nMax)
    {
        return m_nValue/(m_nRange/nMax);
    }
 
    void CommitRangeWrite(uint32_t nRange, uint32_t nMax)
    {
        m_nRange = (m_nRange/nMax)*nRange;
        while(m_nRange<=m_nRangeMin) // Range underflow -> normalize
        {
            AddOutput(m_nValue/m_nRangeMin);
            m_nValue %= m_nRangeMin;
            m_nValue <<= 1;
            m_nRange <<= 1;
        }
    }
 
    void CommitRangeRead(uint32_t nBase, uint32_t nRange, uint32_t nMax)
    {
        m_nValue -= (m_nRange/nMax)*nBase;
        m_nRange = (m_nRange/nMax)*nRange;
        while(m_nRange<=m_nRangeMin) // Range underflow -> normalize
        {
            // Load next bit here
            m_nValue <<= 1;
            m_nRange <<= 1;
        }
    }
 
    void CarryOutput()
    {
        if(m_nCarryPos==0)
            return;
 
        m_nCarryPos--;
        printf("%d", (m_nCarry>>m_nCarryPos)&1);
        m_nBitCount++;
        if((m_nBitCount&3)==0)
            printf(" ");
    }
 
    void AddOutput(uint32_t nValue)
    {
        if(m_nCarryPos==32)
            CarryOutput();
        m_nCarry <<= 1;
        m_nCarry |= nValue;
        m_nCarryPos++;
    }
 
    void Flush()
    {
        // Commit unsaved range  
        uint32_t nRange = m_nRange;
        while(nRange!=m_nRangeMax)
        {
            CommitRangeWrite(1, 2);
            if(nRange>=m_nRangeMin)
                break;
            nRange <<= 8;
        }
 
        // Write out all bits in buffer
        while(m_nCarryPos>0)
            CarryOutput();
    }
 
    int GetBitCount() const { return m_nBitCount; }
private:
    uint32_t m_nRangeMax;
    uint32_t m_nRangeMin;
    uint32_t m_nRange;
    uint32_t m_nValue;
    uint32_t m_nCarry;
    int m_nCarryPos;
    int m_nBitCount;
};
 
class CHistogram
{
    struct Histogram
    {
        int nBase;
        int nCount;
    };
 
public:
    CHistogram(CRangeCoder* pRangeCoder, size_t nSymbols) : 
        m_nSymbols(nSymbols), m_histogram(nSymbols), 
        m_pRangeCoder(pRangeCoder), m_nMax(0) {}
    virtual ~CHistogram() {}
 
    void Build(const std::vector<int>& codes)
    {
        // Clear histogram
        for(size_t n=0; n<m_histogram.size(); n++)
        {
            m_histogram[n].nBase = 0;
            m_histogram[n].nCount = 0;
        }
 
        // Build histogram
        for(size_t n=0; n<codes.size(); n++)
        {
            if(codes[n]>=(int)m_nSymbols)
            {
                printf("Error not enough symbols\r\n");
                return;
            }
            m_histogram[codes[n]].nCount++;
        }
 
        // Build bases
        m_nMax = 0;
        for(size_t n=0; n<m_histogram.size(); n++)
        {
            m_histogram[n].nBase = m_nMax;
            m_nMax += m_histogram[n].nCount;
        }
    }
 
    void Encode(const std::vector<int>& codes)
    {
        printf(" Encoded:\r\n   ");
        float fSymbolSizeIn = log((float)m_nSymbols)/log(2.0f);
        for(size_t n=0; n<codes.size(); n++)
        {
            m_pRangeCoder->AddCode(m_histogram[codes[n]].nBase, m_nMax);
            m_pRangeCoder->CommitRangeWrite(m_histogram[codes[n]].nCount, m_nMax);
        }
        m_pRangeCoder->Flush();
 
        printf("\r\n\r\n");
        int nBitsOut = m_pRangeCoder->GetBitCount();
        printf(" Bits in: %.0fx%d=%.0f Bits out: %d = %3.3f bits/code entropy\r\n", fSymbolSizeIn, (int)codes.size(), fSymbolSizeIn*(float)codes.size(), nBitsOut, (float)nBitsOut/(float)codes.size());
 
        // Theoretical entropy
        int nMaxCount = 0;
        for(size_t n=0; n<m_nSymbols; n++)
            nMaxCount+=m_histogram[n].nCount;
 
        float fBits = 0;
        for(size_t n=0; n<m_nSymbols; n++)
        {       
            if(m_histogram[n].nCount==0)
                continue;
 
            fBits += (float)m_histogram[n].nCount*(log((float)m_histogram[n].nCount/(float)nMaxCount)/-log(2.0f));
        }
        printf(" Theoretical lower bound for entropy is: %3.3f bits = %3.3f bits/code\r\n", fBits, fBits/(float)codes.size());
    }
 
    void Print()
    {
        printf(" Tables:\r\n");
        for(size_t n=0; n<m_nSymbols; n++)
        {
            if(m_histogram[n].nCount==0)
                continue;
            printf(" %5d (%c). %d", (int)n, (n<32 || n>=128)?'.':(char)n, m_histogram[n].nCount);
            printf("\r\n");
        }
        printf("\r\n");
    }
 
protected:
    size_t m_nSymbols;
    std::vector<Histogram> m_histogram;
    CRangeCoder* m_pRangeCoder;
    int m_nMax;
};
 
// Application entry point (from libc)
int main(int argc, const char* argv[])
{
    printf("Range coder test...\r\n\r\n");
 
    if(argc<2)
    {
        printf("Not enough parameters.\r\n");
        return -1;
    }
    std::vector<int> codes;
    for(size_t n=0; n<strlen(argv[1]); n++)
        codes.push_back(argv[1][n]);
 
    CRangeCoder rangeOut;
    CHistogram histogram(&rangeOut, 256); 
 
    histogram.Build(codes);
    histogram.Print();
    histogram.Encode(codes);
 
    return 0;
}
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