(HuffmanCompression): classes utilizing Huffman compression.

This commit is contained in:
morkt
2018-01-02 06:43:41 +04:00
parent 92a133fd52
commit 1a8b0d8b4a
2 changed files with 140 additions and 81 deletions

View File

@@ -153,87 +153,6 @@ namespace GameRes.Formats
}
}
public class HuffmanDecoder
{
byte[] m_src;
byte[] m_dst;
ushort[] lhs = new ushort[512];
ushort[] rhs = new ushort[512];
ushort token = 256;
int m_input_pos;
int m_remaining;
int m_cached_bits;
int m_cache;
public HuffmanDecoder (byte[] src, int index, int length, byte[] dst)
{
m_src = src;
m_dst = dst;
m_input_pos = index;
m_remaining = length;
m_cached_bits = 0;
m_cache = 0;
}
public HuffmanDecoder (byte[] src, byte[] dst) : this (src, 0, src.Length, dst)
{
}
public byte[] Unpack ()
{
int dst = 0;
token = 256;
ushort v3 = CreateTree();
while (dst < m_dst.Length)
{
ushort symbol = v3;
while ( symbol >= 0x100u )
{
if ( 0 != GetBits (1) )
symbol = rhs[symbol];
else
symbol = lhs[symbol];
}
m_dst[dst++] = (byte)symbol;
}
return m_dst;
}
ushort CreateTree()
{
if ( 0 != GetBits (1) )
{
ushort v = token++;
lhs[v] = CreateTree();
rhs[v] = CreateTree();
return v;
}
else
{
return (ushort)GetBits (8);
}
}
uint GetBits (int n)
{
while (n > m_cached_bits)
{
if (0 == m_remaining)
throw new ApplicationException ("Invalid huffman-compressed stream");
int v = m_src[m_input_pos++];
--m_remaining;
m_cache = v | (m_cache << 8);
m_cached_bits += 8;
}
uint mask = (uint)m_cache;
m_cached_bits -= n;
m_cache &= ~(-1 << m_cached_bits);
return (uint)(((-1 << m_cached_bits) & mask) >> m_cached_bits);
}
}
/// <summary>
/// Create stream in TGA format from the given image pixels.
/// </summary>