Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HuffmanEncoder.h « Huffman « Compress « 7zip - github.com/kornelski/7z.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c6b46a6a4b7c6cfab31731db82a49bd0ebfee713 (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
// Compression/HuffmanEncoder.h

#ifndef __COMPRESSION_HUFFMANENCODER_H
#define __COMPRESSION_HUFFMANENCODER_H

#include "../../../Common/Types.h"

namespace NCompression {
namespace NHuffman {

const int kNumBitsInLongestCode = 20;

struct CItem
{
  UInt32 Freq;
  UInt32 Code;
  UInt32 Dad;
  UInt32 Len;
};

class CEncoder
{
public:
  UInt32 m_NumSymbols; // number of symbols in adwSymbol

  CItem *m_Items;
  UInt32 *m_Heap;
  UInt32 m_HeapSize;
  Byte *m_Depth;
  const Byte *m_ExtraBits;
  UInt32 m_ExtraBase;
  UInt32 m_MaxLength;

  UInt32 m_HeapLength;
  UInt32 m_BitLenCounters[kNumBitsInLongestCode + 1];

  UInt32 RemoveSmallest();
  bool Smaller(int n, int m); 
  void DownHeap(UInt32 k);
  void GenerateBitLen(UInt32 maxCode, UInt32 heapMax);
  void GenerateCodes(UInt32 maxCode);
  
  UInt32 m_BlockBitLength;

  void Free();

public:

  CEncoder();
  ~CEncoder();
  bool Create(UInt32 numSymbols, const Byte *extraBits, 
      UInt32 extraBase, UInt32 maxLength);
  void StartNewBlock();

  void AddSymbol(UInt32 symbol) {  m_Items[symbol].Freq++; }

  void SetFreqs(const UInt32 *freqs);
  
  UInt32 GetPrice(const Byte *length) const 
  {  
    UInt32 price = 0;
    for (UInt32 i = 0; i < m_NumSymbols; i++)
    {
      price += length[i] * m_Items[i].Freq; 
      if (m_ExtraBits && i >= m_ExtraBase)
        price += m_ExtraBits[i - m_ExtraBase] * m_Items[i].Freq;
    }
    return price;
  };
  void SetFreq(UInt32 symbol, UInt32 value) {  m_Items[symbol].Freq = value; };

  void BuildTree(Byte *levels);
  UInt32 GetBlockBitLength() const { return m_BlockBitLength; }

  template <class TBitEncoder>
  void CodeOneValue(TBitEncoder *bitEncoder, UInt32 symbol)
    { bitEncoder->WriteBits(m_Items[symbol].Code, m_Items[symbol].Len); }

  void ReverseBits();
};

}}

#endif