-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathrcencoder.cpp
61 lines (55 loc) · 1.04 KB
/
rcencoder.cpp
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
#include <cstddef>
#include "rcencoder.h"
// finalize encoder
void RCencoder::finish()
{
put(4);
flush();
}
// encode a bit s
void RCencoder::encode(bool s)
{
range >>= 1;
if (s)
low += range;
normalize();
}
// encode a symbol s using probability modeling
void RCencoder::encode(uint s, RCmodel* rm)
{
uint l, r;
rm->encode(s, l, r);
rm->normalize(range);
low += range * l;
range *= r;
normalize();
}
// encode a number s : 0 <= s < 2^n <= 2^16
void RCencoder::encode_shift(uint s, uint n)
{
range >>= n;
low += range * s;
normalize();
}
// encode a number s : 0 <= s < n <= 2^16
void RCencoder::encode_ratio(uint s, uint n)
{
range /= n;
low += range * s;
normalize();
}
// normalize the range and output data
void RCencoder::normalize()
{
while (!((low ^ (low + range)) >> 24)) {
// top 8 bits are fixed; output them
put(1);
range <<= 8;
}
if (!(range >> 16)) {
// top 8 bits are not fixed but range is small;
// fudge range to avoid carry and output 16 bits
put(2);
range = -low;
}
}