huangcm
2025-09-01 53d8e046ac1bf2ebe94f671983e3d3be059df91a
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
 
#include "puffin/src/include/puffin/huffer.h"
 
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
 
#include "puffin/src/bit_writer.h"
#include "puffin/src/huffman_table.h"
#include "puffin/src/include/puffin/common.h"
#include "puffin/src/include/puffin/stream.h"
#include "puffin/src/logging.h"
#include "puffin/src/puff_data.h"
#include "puffin/src/puff_reader.h"
 
using std::string;
 
namespace puffin {
 
Huffer::Huffer() : dyn_ht_(new HuffmanTable()), fix_ht_(new HuffmanTable()) {}
 
Huffer::~Huffer() {}
 
bool Huffer::HuffDeflate(PuffReaderInterface* pr,
                         BitWriterInterface* bw) const {
  PuffData pd;
  HuffmanTable* cur_ht = nullptr;
  // If no bytes left for PuffReader to read, bail out.
  while (pr->BytesLeft() != 0) {
    TEST_AND_RETURN_FALSE(pr->GetNext(&pd));
 
    // The first data should be a metadata.
    TEST_AND_RETURN_FALSE(pd.type == PuffData::Type::kBlockMetadata);
    auto header = pd.block_metadata[0];
    auto final_bit = (header & 0x80) >> 7;
    auto type = (header & 0x60) >> 5;
    auto skipped_bits = header & 0x1F;
    DVLOG(2) << "Write block type: "
             << BlockTypeToString(static_cast<BlockType>(type));
 
    TEST_AND_RETURN_FALSE(bw->WriteBits(1, final_bit));
    TEST_AND_RETURN_FALSE(bw->WriteBits(2, type));
    switch (static_cast<BlockType>(type)) {
      case BlockType::kUncompressed:
        bw->WriteBoundaryBits(skipped_bits);
        TEST_AND_RETURN_FALSE(pr->GetNext(&pd));
        TEST_AND_RETURN_FALSE(pd.type != PuffData::Type::kLiteral);
 
        if (pd.type == PuffData::Type::kLiterals) {
          TEST_AND_RETURN_FALSE(bw->WriteBits(16, pd.length));
          TEST_AND_RETURN_FALSE(bw->WriteBits(16, ~pd.length));
          TEST_AND_RETURN_FALSE(bw->WriteBytes(pd.length, pd.read_fn));
          // Reading end of block, but don't write anything.
          TEST_AND_RETURN_FALSE(pr->GetNext(&pd));
          TEST_AND_RETURN_FALSE(pd.type == PuffData::Type::kEndOfBlock);
        } else if (pd.type == PuffData::Type::kEndOfBlock) {
          TEST_AND_RETURN_FALSE(bw->WriteBits(16, 0));
          TEST_AND_RETURN_FALSE(bw->WriteBits(16, ~0));
        } else {
          LOG(ERROR) << "Uncompressed block did not end properly!";
          return false;
        }
        // We have to read a new block.
        continue;
 
      case BlockType::kFixed:
        fix_ht_->BuildFixedHuffmanTable();
        cur_ht = fix_ht_.get();
        break;
 
      case BlockType::kDynamic:
        cur_ht = dyn_ht_.get();
        TEST_AND_RETURN_FALSE(dyn_ht_->BuildDynamicHuffmanTable(
            &pd.block_metadata[1], pd.length - 1, bw));
        break;
 
      default:
        LOG(ERROR) << "Invalid block compression type: "
                   << static_cast<int>(type);
        return false;
    }
 
    // We read literal or distrance/lengths until and end of block or end of
    // stream is reached.
    bool block_ended = false;
    while (!block_ended) {
      TEST_AND_RETURN_FALSE(pr->GetNext(&pd));
      switch (pd.type) {
        case PuffData::Type::kLiteral:
        case PuffData::Type::kLiterals: {
          auto write_literal = [&cur_ht, &bw](uint8_t literal) {
            uint16_t literal_huffman;
            size_t nbits;
            TEST_AND_RETURN_FALSE(
                cur_ht->LitLenHuffman(literal, &literal_huffman, &nbits));
            TEST_AND_RETURN_FALSE(bw->WriteBits(nbits, literal_huffman));
            return true;
          };
 
          if (pd.type == PuffData::Type::kLiteral) {
            TEST_AND_RETURN_FALSE(write_literal(pd.byte));
          } else {
            auto len = pd.length;
            while (len-- > 0) {
              uint8_t literal;
              pd.read_fn(&literal, 1);
              TEST_AND_RETURN_FALSE(write_literal(literal));
            }
          }
          break;
        }
        case PuffData::Type::kLenDist: {
          auto len = pd.length;
          auto dist = pd.distance;
          TEST_AND_RETURN_FALSE(len >= 3 && len <= 258);
 
          // Using a binary search here instead of the linear search may be (but
          // not necessarily) faster. Needs experiment to validate.
          size_t index = 0;
          while (len > kLengthBases[index]) {
            index++;
          }
          if (len < kLengthBases[index]) {
            index--;
          }
          auto extra_bits_len = kLengthExtraBits[index];
          uint16_t length_huffman;
          size_t nbits;
          TEST_AND_RETURN_FALSE(
              cur_ht->LitLenHuffman(index + 257, &length_huffman, &nbits));
 
          TEST_AND_RETURN_FALSE(bw->WriteBits(nbits, length_huffman));
 
          if (extra_bits_len > 0) {
            TEST_AND_RETURN_FALSE(
                bw->WriteBits(extra_bits_len, len - kLengthBases[index]));
          }
 
          // Same as above (binary search).
          index = 0;
          while (dist > kDistanceBases[index]) {
            index++;
          }
          if (dist < kDistanceBases[index]) {
            index--;
          }
          extra_bits_len = kDistanceExtraBits[index];
          uint16_t distance_huffman;
          TEST_AND_RETURN_FALSE(
              cur_ht->DistanceHuffman(index, &distance_huffman, &nbits));
 
          TEST_AND_RETURN_FALSE(bw->WriteBits(nbits, distance_huffman));
          if (extra_bits_len > 0) {
            TEST_AND_RETURN_FALSE(
                bw->WriteBits(extra_bits_len, dist - kDistanceBases[index]));
          }
          break;
        }
 
        case PuffData::Type::kEndOfBlock: {
          uint16_t eos_huffman;
          size_t nbits;
          TEST_AND_RETURN_FALSE(
              cur_ht->LitLenHuffman(256, &eos_huffman, &nbits));
          TEST_AND_RETURN_FALSE(bw->WriteBits(nbits, eos_huffman));
          block_ended = true;
          break;
        }
        case PuffData::Type::kBlockMetadata:
          LOG(ERROR) << "Not expecing a metadata!";
          return false;
 
        default:
          LOG(ERROR) << "Invalid block data type!";
          return false;
      }
    }
  }
 
  TEST_AND_RETURN_FALSE(bw->Flush());
  return true;
}
 
}  // namespace puffin