| 1 |
// Licensed to the .NET Foundation under one or more agreements. |
| 2 |
// The .NET Foundation licenses this file to you under the MIT license. |
| 3 |
// See the LICENSE.txt file in the directory for more information. |
| 4 |
// The Pascal translation by Alexander Koblov. |
| 5 |
|
| 6 |
unit HuffmanTree; |
| 7 |
|
| 8 |
{$mode ObjFPC}{$H+} |
| 9 |
|
| 10 |
interface |
| 11 |
|
| 12 |
uses |
| 13 |
Classes, SysUtils, Types, InputBuffer; |
| 14 |
|
| 15 |
type |
| 16 |
|
| 17 |
{ IHuffmanTree } |
| 18 |
|
| 19 |
IHuffmanTree = interface(IUnknown) |
| 20 |
['{83791289-1747-4815-AC47-B57A0A0C39C6}'] |
| 21 |
function GetNextSymbol(input: TInputBuffer): Integer; |
| 22 |
end; |
| 23 |
|
| 24 |
{ THuffmanTree } |
| 25 |
|
| 26 |
THuffmanTree = class(TInterfacedObject, IHuffmanTree) |
| 27 |
public |
| 28 |
const MAX_LITERAL_TREE_ELEMENTS = Integer(288); |
| 29 |
const MAX_DIST_TREE_ELEMENTS = Integer(32); |
| 30 |
const END_OF_BLOCK_CODE = Integer(256); |
| 31 |
const NUMBER_OF_CODE_LENGTH_TREE_ELEMENTS = Integer(19); |
| 32 |
private |
| 33 |
_tableBits: Integer; |
| 34 |
_table: TSmallIntDynArray; |
| 35 |
_left: TSmallIntDynArray; |
| 36 |
_right: TSmallIntDynArray; |
| 37 |
_codeLengthArray: TBytes; |
| 38 |
|
| 39 |
_tableMask: Integer; |
| 40 |
private |
| 41 |
_StaticLiteralLengthTree: THuffmanTree; static; |
| 42 |
_StaticDistanceTree: THuffmanTree; static; |
| 43 |
private |
| 44 |
class procedure CreateStaticTrees; |
| 45 |
class procedure FreeStaticTrees; |
| 46 |
// Generate the array contains huffman codes lengths for static huffman tree |
| 47 |
class function GetStaticLiteralTreeLength: TBytes; |
| 48 |
class function GetStaticDistanceTreeLength: TBytes; |
| 49 |
// Calculate the huffman code for each character based on the code length for each character. |
| 50 |
function CalculateHuffmanCode: TCardinalDynArray; |
| 51 |
procedure CreateTable; |
| 52 |
public |
| 53 |
class property StaticLiteralLengthTree: THuffmanTree read _StaticLiteralLengthTree; |
| 54 |
class property StaticDistanceTree: THuffmanTree read _StaticDistanceTree; |
| 55 |
public |
| 56 |
constructor Create(constref codeLengths: TBytes); |
| 57 |
// This function will try to get enough bits from input and try to decode the bits |
| 58 |
function GetNextSymbol(input: TInputBuffer): Integer; |
| 59 |
end; |
| 60 |
|
| 61 |
implementation |
| 62 |
|
| 63 |
// Reverse 'length' of the bits in code |
| 64 |
function BitReverse(code: Cardinal; length: Integer): Cardinal; |
| 65 |
begin |
| 66 |
Result := 0; |
| 67 |
|
| 68 |
Assert((length > 0) and (length <= 16), 'Invalid len'); |
| 69 |
repeat |
| 70 |
Result := Result or (code and 1); |
| 71 |
Result := Result << 1; |
| 72 |
code := code >> 1; |
| 73 |
Dec(length); |
| 74 |
until (length = 0); |
| 75 |
|
| 76 |
Result := Result >> 1; |
| 77 |
end; |
| 78 |
|
| 79 |
{ THuffmanTree } |
| 80 |
|
| 81 |
class procedure THuffmanTree.CreateStaticTrees; |
| 82 |
begin |
| 83 |
_StaticLiteralLengthTree:= THuffmanTree.Create(GetStaticLiteralTreeLength()); |
| 84 |
_StaticDistanceTree:= THuffmanTree.Create(GetStaticDistanceTreeLength()); |
| 85 |
_StaticLiteralLengthTree._AddRef; |
| 86 |
_StaticDistanceTree._AddRef; |
| 87 |
end; |
| 88 |
|
| 89 |
class procedure THuffmanTree.FreeStaticTrees; |
| 90 |
begin |
| 91 |
_StaticLiteralLengthTree._Release; |
| 92 |
_StaticDistanceTree._Release; |
| 93 |
end; |
| 94 |
|
| 95 |
class function THuffmanTree.GetStaticLiteralTreeLength: TBytes; |
| 96 |
var |
| 97 |
i: Integer; |
| 98 |
literalTreeLength: TBytes; |
| 99 |
begin |
| 100 |
SetLength(literalTreeLength, MAX_LITERAL_TREE_ELEMENTS); |
| 101 |
|
| 102 |
for i := 0 to 143 do |
| 103 |
begin |
| 104 |
literalTreeLength[i] := 8; |
| 105 |
end; |
| 106 |
|
| 107 |
for i := 144 to 255 do |
| 108 |
begin |
| 109 |
literalTreeLength[i] := 9; |
| 110 |
end; |
| 111 |
|
| 112 |
for i := 256 to 279 do |
| 113 |
begin |
| 114 |
literalTreeLength[i] := 7; |
| 115 |
end; |
| 116 |
|
| 117 |
for i := 280 to 287 do |
| 118 |
begin |
| 119 |
literalTreeLength[i] := 8; |
| 120 |
end; |
| 121 |
|
| 122 |
Result := literalTreeLength; |
| 123 |
end; |
| 124 |
|
| 125 |
class function THuffmanTree.GetStaticDistanceTreeLength: TBytes; |
| 126 |
var |
| 127 |
i: Integer; |
| 128 |
staticDistanceTreeLength: TBytes; |
| 129 |
begin |
| 130 |
SetLength(staticDistanceTreeLength, MAX_DIST_TREE_ELEMENTS); |
| 131 |
for i := 0 to Pred(MAX_DIST_TREE_ELEMENTS) do |
| 132 |
begin |
| 133 |
staticDistanceTreeLength[i] := 5; |
| 134 |
end; |
| 135 |
Result := staticDistanceTreeLength; |
| 136 |
end; |
| 137 |
|
| 138 |
function THuffmanTree.CalculateHuffmanCode: TCardinalDynArray; |
| 139 |
var |
| 140 |
i, bits: Integer; |
| 141 |
tempCode: Cardinal = 0; |
| 142 |
code: TCardinalDynArray; |
| 143 |
len, codeLength: Integer; |
| 144 |
bitLengthCount: TCardinalDynArray; |
| 145 |
nextCode: array[0..16] of Cardinal; |
| 146 |
begin |
| 147 |
SetLength(bitLengthCount, 17); |
| 148 |
SetLength(code, MAX_LITERAL_TREE_ELEMENTS); |
| 149 |
|
| 150 |
for i := 0 to High(_codeLengthArray) do |
| 151 |
begin |
| 152 |
codeLength := _codeLengthArray[i]; |
| 153 |
Inc(bitLengthCount[codeLength]); |
| 154 |
end; |
| 155 |
bitLengthCount[0] := 0; // clear count for length 0 |
| 156 |
|
| 157 |
for bits := 1 to 16 do |
| 158 |
begin |
| 159 |
tempCode := (tempCode + bitLengthCount[bits - 1]) << 1; |
| 160 |
nextCode[bits] := tempCode; |
| 161 |
end; |
| 162 |
|
| 163 |
for i := 0 to High(_codeLengthArray) do |
| 164 |
begin |
| 165 |
len := _codeLengthArray[i]; |
| 166 |
|
| 167 |
if (len > 0) then |
| 168 |
begin |
| 169 |
code[i] := BitReverse(nextCode[len], len); |
| 170 |
Inc(nextCode[len]); |
| 171 |
end; |
| 172 |
end; |
| 173 |
Result:= code; |
| 174 |
end; |
| 175 |
|
| 176 |
procedure THuffmanTree.CreateTable; |
| 177 |
var |
| 178 |
avail, value: Int16; |
| 179 |
increment, locs: Integer; |
| 180 |
array_: TSmallIntDynArray; |
| 181 |
codeArray: TCardinalDynArray; |
| 182 |
j, ch, len, start, index: Integer; |
| 183 |
overflowBits, codeBitMask: Integer; |
| 184 |
begin |
| 185 |
codeArray := CalculateHuffmanCode(); |
| 186 |
|
| 187 |
avail := Int16(Length(_codeLengthArray)); |
| 188 |
|
| 189 |
for ch := 0 to High(_codeLengthArray) do |
| 190 |
begin |
| 191 |
// length of this code |
| 192 |
len := _codeLengthArray[ch]; |
| 193 |
if (len > 0) then |
| 194 |
begin |
| 195 |
// start value (bit reversed) |
| 196 |
start := Integer(codeArray[ch]); |
| 197 |
|
| 198 |
if (len <= _tableBits) then |
| 199 |
begin |
| 200 |
// If a particular symbol is shorter than nine bits, |
| 201 |
// then that symbol's translation is duplicated |
| 202 |
// in all those entries that start with that symbol's bits. |
| 203 |
// For example, if the symbol is four bits, then it's duplicated |
| 204 |
// 32 times in a nine-bit table. If a symbol is nine bits long, |
| 205 |
// it appears in the table once. |
| 206 |
// |
| 207 |
// Make sure that in the loop below, code is always |
| 208 |
// less than table_size. |
| 209 |
// |
| 210 |
// On last iteration we store at array index: |
| 211 |
// initial_start_at + (locs-1)*increment |
| 212 |
// = initial_start_at + locs*increment - increment |
| 213 |
// = initial_start_at + (1 << tableBits) - increment |
| 214 |
// = initial_start_at + table_size - increment |
| 215 |
// |
| 216 |
// Therefore we must ensure: |
| 217 |
// initial_start_at + table_size - increment < table_size |
| 218 |
// or: initial_start_at < increment |
| 219 |
// |
| 220 |
increment := 1 << len; |
| 221 |
if (start >= increment) then |
| 222 |
begin |
| 223 |
raise Exception.Create('Deflate64: invalid Huffman data'); |
| 224 |
end; |
| 225 |
|
| 226 |
// Note the bits in the table are reverted. |
| 227 |
locs := 1 << (_tableBits - len); |
| 228 |
for j := 0 to Pred(locs) do |
| 229 |
begin |
| 230 |
_table[start] := Int16(ch); |
| 231 |
start += increment; |
| 232 |
end; |
| 233 |
end |
| 234 |
else |
| 235 |
begin |
| 236 |
// For any code which has length longer than num_elements, |
| 237 |
// build a binary tree. |
| 238 |
|
| 239 |
overflowBits := len - _tableBits; // the nodes we need to respent the data. |
| 240 |
codeBitMask := 1 << _tableBits; // mask to get current bit (the bits can't fit in the table) |
| 241 |
|
| 242 |
// the left, right table is used to repesent the |
| 243 |
// the rest bits. When we got the first part (number bits.) and look at |
| 244 |
// tbe table, we will need to follow the tree to find the real character. |
| 245 |
// This is in place to avoid bloating the table if there are |
| 246 |
// a few ones with long code. |
| 247 |
index := start and ((1 << _tableBits) - 1); |
| 248 |
array_ := _table; |
| 249 |
|
| 250 |
repeat |
| 251 |
value := array_[index]; |
| 252 |
|
| 253 |
if (value = 0) then |
| 254 |
begin |
| 255 |
// set up next pointer if this node is not used before. |
| 256 |
array_[index] := Int16(-avail); // use next available slot. |
| 257 |
value := Int16(-avail); |
| 258 |
Inc(avail); |
| 259 |
end; |
| 260 |
|
| 261 |
if (value > 0) then |
| 262 |
begin |
| 263 |
// prevent an IndexOutOfRangeException from array[index] |
| 264 |
raise Exception.Create('Deflate64: invalid Huffman data'); |
| 265 |
end; |
| 266 |
|
| 267 |
Assert( |
| 268 |
value < 0, |
| 269 |
'CreateTable: Only negative numbers are used for tree pointers!' |
| 270 |
); |
| 271 |
|
| 272 |
if ((start and codeBitMask) = 0) then |
| 273 |
begin |
| 274 |
// if current bit is 0, go change the left array |
| 275 |
array_ := _left; |
| 276 |
end |
| 277 |
else |
| 278 |
begin |
| 279 |
// if current bit is 1, set value in the right array |
| 280 |
array_ := _right; |
| 281 |
end; |
| 282 |
index := -value; // go to next node |
| 283 |
|
| 284 |
codeBitMask := codeBitMask << 1; |
| 285 |
Dec(overflowBits); |
| 286 |
until (overflowBits = 0); |
| 287 |
|
| 288 |
array_[index] := Int16(ch); |
| 289 |
end; |
| 290 |
end; |
| 291 |
end; |
| 292 |
end; |
| 293 |
|
| 294 |
constructor THuffmanTree.Create(constref codeLengths: TBytes); |
| 295 |
begin |
| 296 |
Assert( |
| 297 |
(Length(codeLengths) = MAX_LITERAL_TREE_ELEMENTS) |
| 298 |
or (Length(codeLengths) = MAX_DIST_TREE_ELEMENTS) |
| 299 |
or (Length(codeLengths) = NUMBER_OF_CODE_LENGTH_TREE_ELEMENTS), |
| 300 |
'we only expect three kinds of Length here' |
| 301 |
); |
| 302 |
_codeLengthArray := codeLengths; |
| 303 |
|
| 304 |
if (Length(_codeLengthArray) = MAX_LITERAL_TREE_ELEMENTS) then |
| 305 |
begin |
| 306 |
// bits for Literal/Length tree table |
| 307 |
_tableBits := 9; |
| 308 |
end |
| 309 |
else |
| 310 |
begin |
| 311 |
// bits for distance tree table and code length tree table |
| 312 |
_tableBits := 7; |
| 313 |
end; |
| 314 |
_tableMask := (1 << _tableBits) - 1; |
| 315 |
|
| 316 |
SetLength(_table, 1 << _tableBits); |
| 317 |
|
| 318 |
// I need to find proof that left and right array will always be |
| 319 |
// enough. I think they are. |
| 320 |
SetLength(_left, 2 * Length(_codeLengthArray)); |
| 321 |
SetLength(_right, 2 * Length(_codeLengthArray)); |
| 322 |
|
| 323 |
CreateTable(); |
| 324 |
end; |
| 325 |
|
| 326 |
function THuffmanTree.GetNextSymbol(input: TInputBuffer): Integer; |
| 327 |
var |
| 328 |
bitBuffer, mask: Cardinal; |
| 329 |
symbol, codeLength: Integer; |
| 330 |
begin |
| 331 |
// Try to load 16 bits into input buffer if possible and get the bitBuffer value. |
| 332 |
// If there aren't 16 bits available we will return all we have in the |
| 333 |
// input buffer. |
| 334 |
bitBuffer := input.TryLoad16Bits(); |
| 335 |
if (input.AvailableBits = 0) then |
| 336 |
begin // running out of input. |
| 337 |
Exit(-1); |
| 338 |
end; |
| 339 |
|
| 340 |
// decode an element |
| 341 |
symbol := _table[bitBuffer and _tableMask]; |
| 342 |
if (symbol < 0) then |
| 343 |
begin // this will be the start of the binary tree |
| 344 |
// navigate the tree |
| 345 |
mask := Cardinal(1) << _tableBits; |
| 346 |
repeat |
| 347 |
symbol := -symbol; |
| 348 |
if ((bitBuffer and mask) = 0) then |
| 349 |
begin |
| 350 |
symbol := _left[symbol]; |
| 351 |
end |
| 352 |
else |
| 353 |
begin |
| 354 |
symbol := _right[symbol]; |
| 355 |
end; |
| 356 |
|
| 357 |
mask := mask << 1; |
| 358 |
until (symbol >= 0); |
| 359 |
end; |
| 360 |
|
| 361 |
codeLength := _codeLengthArray[symbol]; |
| 362 |
|
| 363 |
// huffman code lengths must be at least 1 bit long |
| 364 |
if (codeLength <= 0) then |
| 365 |
begin |
| 366 |
raise Exception.Create('Deflate64: invalid Huffman data'); |
| 367 |
end; |
| 368 |
|
| 369 |
// |
| 370 |
// If this code is longer than the # bits we had in the bit buffer (i.e. |
| 371 |
// we read only part of the code), we can hit the entry in the table or the tree |
| 372 |
// for another symbol. However the length of another symbol will not match the |
| 373 |
// available bits count. |
| 374 |
if (codeLength > input.AvailableBits) then |
| 375 |
begin |
| 376 |
// We already tried to load 16 bits and maximum length is 15, |
| 377 |
// so this means we are running out of input. |
| 378 |
Exit(-1); |
| 379 |
end; |
| 380 |
|
| 381 |
input.SkipBits(codeLength); |
| 382 |
Result := symbol; |
| 383 |
end; |
| 384 |
|
| 385 |
initialization |
| 386 |
THuffmanTree.CreateStaticTrees; |
| 387 |
|
| 388 |
finalization |
| 389 |
THuffmanTree.FreeStaticTrees; |
| 390 |
|
| 391 |
end. |
| 392 |
|