1 // Compress/RangeCoder/RangeCoder.h
3 #ifndef __COMPRESS_RANGECODER_H
4 #define __COMPRESS_RANGECODER_H
6 #include "../../Common/InBuffer.h"
7 #include "../../Common/OutBuffer.h"
10 namespace NRangeCoder {
12 const int kNumTopBits = 24;
13 const UInt32 kTopValue = (1 << kNumTopBits);
23 bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); }
25 void SetStream(ISequentialOutStream *stream) { Stream.SetStream(stream); }
38 for(int i = 0; i < 5; i++)
42 HRESULT FlushStream() { return Stream.Flush(); }
44 void ReleaseStream() { Stream.ReleaseStream(); }
46 void Encode(UInt32 start, UInt32 size, UInt32 total)
48 Low += start * (Range /= total);
50 while (Range < kTopValue)
59 if ((UInt32)Low < (UInt32)0xFF000000 || (int)(Low >> 32) != 0)
64 Stream.WriteByte((Byte)(temp + (Byte)(Low >> 32)));
67 while(--_cacheSize != 0);
68 _cache = (Byte)((UInt32)Low >> 24);
71 Low = (UInt32)Low << 8;
74 void EncodeDirectBits(UInt32 value, int numTotalBits)
76 for (int i = numTotalBits - 1; i >= 0; i--)
79 if (((value >> i) & 1) == 1)
81 if (Range < kTopValue)
89 void EncodeBit(UInt32 size0, UInt32 numTotalBits, UInt32 symbol)
91 UInt32 newBound = (Range >> numTotalBits) * size0;
99 while (Range < kTopValue)
106 UInt64 GetProcessedSize() { return Stream.GetProcessedSize() + _cacheSize + 4; }
115 bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); }
119 while (Range < kTopValue)
121 Code = (Code << 8) | Stream.ReadByte();
126 void SetStream(ISequentialInStream *stream) { Stream.SetStream(stream); }
132 for(int i = 0; i < 5; i++)
133 Code = (Code << 8) | Stream.ReadByte();
136 void ReleaseStream() { Stream.ReleaseStream(); }
138 UInt32 GetThreshold(UInt32 total)
140 return (Code) / ( Range /= total);
143 void Decode(UInt32 start, UInt32 size)
145 Code -= start * Range;
150 UInt32 DecodeDirectBits(int numTotalBits)
152 UInt32 range = Range;
155 for (int i = numTotalBits; i != 0; i--)
166 UInt32 t = (code - range) >> 31;
167 code -= range & (t - 1);
168 result = (result << 1) | (1 - t);
170 if (range < kTopValue)
172 code = (code << 8) | Stream.ReadByte();
181 UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits)
183 UInt32 newBound = (Range >> numTotalBits) * size0;
200 UInt64 GetProcessedSize() {return Stream.GetProcessedSize(); }