about summary refs log tree commit diff
path: root/src/engine/shared/huffman.h
blob: 0edc36c64c15498002f9d562fde1db5b1e096949 (plain)
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
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com.                */
#ifndef ENGINE_SHARED_HUFFMAN_H
#define ENGINE_SHARED_HUFFMAN_H



class CHuffman
{
	enum
	{
		HUFFMAN_EOF_SYMBOL = 256,

		HUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1,
		HUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1,
		
		HUFFMAN_LUTBITS = 10,
		HUFFMAN_LUTSIZE = (1<<HUFFMAN_LUTBITS),
		HUFFMAN_LUTMASK = (HUFFMAN_LUTSIZE-1)
	};

	struct CNode
	{
		// symbol
		unsigned m_Bits;
		unsigned m_NumBits;

		// don't use pointers for this. shorts are smaller so we can fit more data into the cache
		unsigned short m_aLeafs[2];

		// what the symbol represents
		unsigned char m_Symbol;
	};

	CNode m_aNodes[HUFFMAN_MAX_NODES];
	CNode *m_apDecodeLut[HUFFMAN_LUTSIZE];
	CNode *m_pStartNode;
	int m_NumNodes;
	
	void Setbits_r(CNode *pNode, int Bits, unsigned Depth);
	void ConstructTree(const unsigned *pFrequencies);
	
public:
	/*
		Function: huffman_init
			Inits the compressor/decompressor.

		Parameters:
			huff - Pointer to the state to init
			frequencies - A pointer to an array of 256 entries of the frequencies of the bytes

		Remarks:
			- Does no allocation what so ever.
			- You don't have to call any cleanup functions when you are done with it
	*/
	void Init(const unsigned *pFrequencies);

	/*
		Function: huffman_compress
			Compresses a buffer and outputs a compressed buffer.

		Parameters:
			huff - Pointer to the huffman state
			input - Buffer to compress
			input_size - Size of the buffer to compress
			output - Buffer to put the compressed data into
			output_size - Size of the output buffer

		Returns:
			Returns the size of the compressed data. Negative value on failure.
	*/
	int Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize);

	/*
		Function: huffman_decompress
			Decompresses a buffer

		Parameters:
			huff - Pointer to the huffman state
			input - Buffer to decompress
			input_size - Size of the buffer to decompress
			output - Buffer to put the uncompressed data into
			output_size - Size of the output buffer

		Returns:
			Returns the size of the uncompressed data. Negative value on failure.
	*/
	int Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize);
	
};
#endif // __HUFFMAN_HEADER__