Debian Codegraph @

plugins/wcx/zip/src/inflate64/inflatermanaged.pas

raw
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 InflaterManaged;
7
8 {$mode ObjFPC}{$H+}
9
10 interface
11
12 uses
13 Classes, SysUtils, OutputWindow, InputBuffer, HuffmanTree;
14
15 type
16
17 TBlockType =
18 (
19 Uncompressed = 0,
20 Static = 1,
21 Dynamic = 2
22 );
23
24 // Do not rearrange the enum values.
25 TInflaterState =
26 (
27 ReadingHeader = 0, // Only applies to GZIP
28
29 ReadingBFinal = 2, // About to read bfinal bit
30 ReadingBType = 3, // About to read blockType bits
31
32 ReadingNumLitCodes = 4, // About to read # literal codes
33 ReadingNumDistCodes = 5, // About to read # dist codes
34 ReadingNumCodeLengthCodes = 6, // About to read # code length codes
35 ReadingCodeLengthCodes = 7, // In the middle of reading the code length codes
36 ReadingTreeCodesBefore = 8, // In the middle of reading tree codes (loop top)
37 ReadingTreeCodesAfter = 9, // In the middle of reading tree codes (extension; code > 15)
38
39 DecodeTop = 10, // About to decode a literal (char/match) in a compressed block
40 HaveInitialLength = 11, // Decoding a match, have the literal code (base length)
41 HaveFullLength = 12, // Ditto, now have the full match length (incl. extra length bits)
42 HaveDistCode = 13, // Ditto, now have the distance code also, need extra dist bits
43
44 //* uncompressed blocks */
45 UncompressedAligning = 15,
46 UncompressedByte1 = 16,
47 UncompressedByte2 = 17,
48 UncompressedByte3 = 18,
49 UncompressedByte4 = 19,
50 DecodingUncompressed = 20,
51
52 // These three apply only to GZIP
53 StartReadingFooter = 21, // (Initialisation for reading footer)
54 ReadingFooter = 22,
55 VerifyingFooter = 23,
56
57 Done = 24 // Finished
58 );
59
60 type
61
62 { TInflaterManaged }
63
64 TInflaterManaged = class
65 private
66 _output: TOutputWindow;
67 _input: TInputBuffer;
68 _literalLengthTree: IHuffmanTree;
69 _distanceTree: IHuffmanTree;
70
71 _state: TInflaterState;
72
73 _bfinal: Integer;
74 _blockType: TBlockType;
75
76 // uncompressed block
77 _blockLengthBuffer: array[0..3] of Byte;
78 _blockLength: Integer;
79
80 // compressed block
81 _length: Integer;
82 _distanceCode: Integer;
83 _extraBits: Integer;
84
85 _loopCounter: Integer;
86 _literalLengthCodeCount: Integer;
87 _distanceCodeCount: Integer;
88 _codeLengthCodeCount: Integer;
89 _codeArraySize: Integer;
90 _lengthCode: Integer;
91
92 _codeList: TBytes; // temporary array to store the code length for literal/Length and distance
93 _codeLengthTreeCodeLength: TBytes;
94 _deflate64: Boolean;
95 _codeLengthTree: IHuffmanTree;
96 private
97 procedure Reset;
98 function Decode: Boolean;
99 function DecodeUncompressedBlock(out endOfBlock: Boolean): Boolean;
100 function DecodeBlock(out endOfBlockCodeSeen: Boolean): Boolean;
101 function DecodeDynamicBlockHeader: Boolean;
102 public
103 constructor Create(deflate64: Boolean);
104 destructor Destroy; override;
105 procedure SetInput(inputBytes: PByte; offset, length: Integer);
106 function Finished: Boolean;
107 function AvailableOutput: Integer;
108 function Inflate(bytes: PByte; offset, length: Integer): Integer;
109 end;
110
111 implementation
112
113 const
114 // Extra bits for length code 257 - 285.
115 S_EXTRA_LENGTH_BITS: array[0..28] of Byte =
116 (
117 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3,
118 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 16
119 );
120
121 // The base length for length code 257 - 285.
122 // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits)
123 S_LENGTH_BASE: array[0..28] of Integer =
124 (
125 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51,
126 59, 67, 83, 99, 115, 131, 163, 195, 227, 3
127 );
128
129 // The base distance for distance code 0 - 31
130 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits)
131 S_DISTANCE_BASE_POSITION: array[0..31] of Integer =
132 (
133 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
134 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153
135 );
136
137 // code lengths for code length alphabet is stored in following order
138 S_CODE_ORDER: array[0..18] of Byte = (16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
139
140 S_STATIC_DISTANCE_TREE_TABLE: array[0..31] of Byte =
141 (
142 $00, $10, $08, $18, $04, $14, $0c, $1c, $02, $12, $0a, $1a,
143 $06, $16, $0e, $1e, $01, $11, $09, $19, $05, $15, $0d, $1d,
144 $03, $13, $0b, $1b, $07, $17, $0f, $1f
145 );
146
147 { TInflaterManaged }
148
149 procedure TInflaterManaged.Reset;
150 begin
151 _state := TInflaterState.ReadingBFinal; // start by reading BFinal bit
152 end;
153
154 function TInflaterManaged.Decode: Boolean;
155 var
156 eob: Boolean = false;
157 begin
158 result := false;
159
160 if (Finished()) then
161 begin
162 Exit(true);
163 end;
164
165 if (_state = TInflaterState.ReadingBFinal) then
166 begin
167 // reading bfinal bit
168 // Need 1 bit
169 if (not _input.EnsureBitsAvailable(1)) then
170 begin
171 Exit(false);
172 end;
173
174 _bfinal := _input.GetBits(1);
175 _state := TInflaterState.ReadingBType;
176 end;
177
178 if (_state = TInflaterState.ReadingBType) then
179 begin
180 // Need 2 bits
181 if (not _input.EnsureBitsAvailable(2)) then
182 begin
183 _state := TInflaterState.ReadingBType;
184 Exit(false);
185 end;
186
187 _blockType := TBlockType(_input.GetBits(2));
188
189 if (_blockType = TBlockType.Dynamic) then
190 begin
191 _state := TInflaterState.ReadingNumLitCodes;
192 end
193 else if (_blockType = TBlockType.Static) then
194 begin
195 _literalLengthTree := THuffmanTree.StaticLiteralLengthTree;
196 _distanceTree := THuffmanTree.StaticDistanceTree;
197 _state := TInflaterState.DecodeTop;
198 end
199 else if (_blockType = TBlockType.Uncompressed) then
200 begin
201 _state := TInflaterState.UncompressedAligning;
202 end
203 else
204 begin
205 raise Exception.Create('Deflate64: unknown block type');
206 end;
207 end;
208
209 if (_blockType = TBlockType.Dynamic) then
210 begin
211 if (_state < TInflaterState.DecodeTop) then
212 begin
213 // we are reading the header
214 result := DecodeDynamicBlockHeader();
215 end
216 else
217 begin
218 result := DecodeBlock(eob); // this can returns true when output is full
219 end;
220 end
221 else if (_blockType = TBlockType.Static) then
222 begin
223 result := DecodeBlock(eob);
224 end
225 else if (_blockType = TBlockType.Uncompressed) then
226 begin
227 result := DecodeUncompressedBlock(eob);
228 end
229 else
230 begin
231 raise Exception.Create('Deflate64: unknown block type');
232 end;
233
234 //
235 // If we reached the end of the block and the block we were decoding had
236 // bfinal=1 (final block)
237 //
238 if (eob and (_bfinal <> 0)) then
239 begin
240 _state := TInflaterState.Done;
241 end;
242 end;
243
244 function TInflaterManaged.DecodeUncompressedBlock(out endOfBlock: Boolean
245 ): Boolean;
246 var
247 bits, bytesCopied: Integer;
248 blockLengthComplement: Integer;
249 begin
250 endOfBlock := false;
251 while (true) do
252 begin
253 case (_state) of
254 TInflaterState.UncompressedAligning: // initial state when calling this function
255 begin
256 // we must skip to a byte boundary
257 _input.SkipToByteBoundary();
258 _state := TInflaterState.UncompressedByte1;
259 Continue;
260 end;
261 TInflaterState.UncompressedByte1, // decoding block length
262 TInflaterState.UncompressedByte2,
263 TInflaterState.UncompressedByte3,
264 TInflaterState.UncompressedByte4:
265 begin
266 bits := _input.GetBits(8);
267 if (bits < 0) then
268 begin
269 Exit(false);
270 end;
271
272 _blockLengthBuffer[Integer(_state) - Integer(TInflaterState.UncompressedByte1)] := byte(bits);
273 if (_state = TInflaterState.UncompressedByte4) then
274 begin
275 _blockLength := _blockLengthBuffer[0] + (_blockLengthBuffer[1] * 256);
276 blockLengthComplement :=
277 _blockLengthBuffer[2] + (_blockLengthBuffer[3] * 256);
278
279 // make sure complement matches
280 if (UInt16(_blockLength) <> UInt16((not blockLengthComplement))) then
281 begin
282 raise Exception.Create('Deflate64: invalid block length');
283 end;
284 end;
285
286 Inc(_state);
287 end;
288
289 TInflaterState.DecodingUncompressed: // copying block data
290 begin
291 // Directly copy bytes from input to output.
292 bytesCopied := _output.CopyFrom(_input, _blockLength);
293 _blockLength -= bytesCopied;
294
295 if (_blockLength = 0) then
296 begin
297 // Done with this block, need to re-init bit buffer for next block
298 _state := TInflaterState.ReadingBFinal;
299 endOfBlock := true;
300 Exit(true);
301 end;
302
303 // We can fail to copy all bytes for two reasons:
304 // Running out of Input
305 // running out of free space in output window
306 if (_output.FreeBytes = 0) then
307 begin
308 Exit(true);
309 end;
310
311 Exit(false);
312 end;
313 else begin
314 //*Fail*/
315 Assert(false, 'check why we are here!');
316 raise Exception.Create('Deflate64: unknown state');
317 end;
318 end;
319 end;
320 end;
321
322 function TInflaterManaged.DecodeBlock(out endOfBlockCodeSeen: Boolean): Boolean;
323 var
324 freeBytes, symbol, bits, offset: Integer;
325 begin
326 endOfBlockCodeSeen := false;
327
328 freeBytes := _output.FreeBytes; // it is a little bit faster than frequently accessing the property
329 while (freeBytes > 65536) do
330 begin
331 // With Deflate64 we can have up to a 64kb length, so we ensure at least that much space is available
332 // in the OutputWindow to avoid overwriting previous unflushed output data.
333 case (_state) of
334
335 TInflaterState.DecodeTop:
336 begin
337 // decode an element from the literal tree
338
339 // TODO: optimize this!!!
340 symbol := _literalLengthTree.GetNextSymbol(_input);
341 if (symbol < 0) then
342 begin
343 // running out of input
344 Exit(false);
345 end;
346
347 if (symbol < 256) then
348 begin
349 // literal
350 _output.Write(Byte(symbol));
351 Dec(freeBytes);
352 end
353 else if (symbol = 256) then
354 begin
355 // end of block
356 endOfBlockCodeSeen := true;
357 // Reset state
358 _state := TInflaterState.ReadingBFinal;
359 Exit(true);
360 end
361 else
362 begin
363 // length/distance pair
364 symbol -= 257; // length code started at 257
365 if (symbol < 8) then
366 begin
367 symbol += 3; // match length = 3,4,5,6,7,8,9,10
368 _extraBits := 0;
369 end
370 else if ((not _deflate64) and (symbol = 28)) then
371 begin
372 // extra bits for code 285 is 0
373 symbol := 258; // code 285 means length 258
374 _extraBits := 0;
375 end
376 else
377 begin
378 if (symbol < 0) or (symbol >= Length(S_EXTRA_LENGTH_BITS)) then
379 begin
380 raise Exception.Create('Deflate64: invalid data');
381 end;
382 _extraBits := S_EXTRA_LENGTH_BITS[symbol];
383 Assert(_extraBits <> 0, 'We handle other cases separately!');
384 end;
385 _length := symbol;
386 _state := TInflaterState.HaveInitialLength;
387 Continue;
388 end;
389 end;
390
391 TInflaterState.HaveInitialLength:
392 begin
393 if (_extraBits > 0) then
394 begin
395 _state := TInflaterState.HaveInitialLength;
396 bits := _input.GetBits(_extraBits);
397 if (bits < 0) then
398 begin
399 Exit(false);
400 end;
401
402 if (_length < 0) or (_length >= Length(S_LENGTH_BASE)) then
403 begin
404 raise Exception.Create('Deflate64: invalid data');
405 end;
406 _length := S_LENGTH_BASE[_length] + bits;
407 end;
408 _state := TInflaterState.HaveFullLength;
409 Continue;
410 end;
411
412
413 TInflaterState.HaveFullLength:
414 begin
415 if (_blockType = TBlockType.Dynamic) then
416 begin
417 _distanceCode := _distanceTree.GetNextSymbol(_input);
418 end
419 else
420 begin
421 // get distance code directly for static block
422 _distanceCode := _input.GetBits(5);
423 if (_distanceCode >= 0) then
424 begin
425 _distanceCode := S_STATIC_DISTANCE_TREE_TABLE[_distanceCode];
426 end;
427 end;
428
429 if (_distanceCode < 0) then
430 begin
431 // running out input
432 Exit(false);
433 end;
434
435 _state := TInflaterState.HaveDistCode;
436 Continue;
437 end;
438
439 TInflaterState.HaveDistCode:
440 begin
441 // To avoid a table lookup we note that for distanceCode > 3,
442 // extra_bits = (distanceCode-2) >> 1
443 if (_distanceCode > 3) then
444 begin
445 _extraBits := (_distanceCode - 2) >> 1;
446 bits := _input.GetBits(_extraBits);
447 if (bits < 0) then
448 begin
449 Exit(false);
450 end;
451 offset := S_DISTANCE_BASE_POSITION[_distanceCode] + bits;
452 end
453 else
454 begin
455 offset := _distanceCode + 1;
456 end;
457
458 _output.WriteLengthDistance(_length, offset);
459 freeBytes -= _length;
460 _state := TInflaterState.DecodeTop;
461 end;
462
463 else begin
464 //*Fail*/
465 Assert(false, 'check why we are here!');
466 raise Exception.Create('Deflate64: unknown state');
467 end;
468 end;
469 end;
470
471 Result := true;
472 end;
473
474 function TInflaterManaged.DecodeDynamicBlockHeader: Boolean;
475 var
476 i, j, bits, repeatCount, previousCode: Integer;
477 literalTreeCodeLength, distanceTreeCodeLength: TBytes;
478 begin
479 while (True) do
480 begin
481 case (_state) of
482
483 TInflaterState.ReadingNumLitCodes:
484 begin
485 _literalLengthCodeCount := _input.GetBits(5);
486 if (_literalLengthCodeCount < 0) then
487 begin
488 Exit(false);
489 end;
490 _literalLengthCodeCount += 257;
491 _state := TInflaterState.ReadingNumDistCodes;
492 Continue;
493 end;
494
495 TInflaterState.ReadingNumDistCodes:
496 begin
497 _distanceCodeCount := _input.GetBits(5);
498 if (_distanceCodeCount < 0) then
499 begin
500 Exit(false);
501 end;
502 _distanceCodeCount += 1;
503 _state := TInflaterState.ReadingNumCodeLengthCodes;
504 Continue;
505 end;
506
507 TInflaterState.ReadingNumCodeLengthCodes:
508 begin
509 _codeLengthCodeCount := _input.GetBits(4);
510 if (_codeLengthCodeCount < 0) then
511 begin
512 Exit(false);
513 end;
514 _codeLengthCodeCount += 4;
515 _loopCounter := 0;
516 _state := TInflaterState.ReadingCodeLengthCodes;
517 Continue;
518 end;
519
520 TInflaterState.ReadingCodeLengthCodes:
521 begin
522 while (_loopCounter < _codeLengthCodeCount) do
523 begin
524 bits := _input.GetBits(3);
525 if (bits < 0) then
526 begin
527 Exit(false);
528 end;
529 _codeLengthTreeCodeLength[S_CODE_ORDER[_loopCounter]] := Byte(bits);
530 Inc(_loopCounter);
531 end;
532
533 for i := _codeLengthCodeCount to High(S_CODE_ORDER) do
534 begin
535 _codeLengthTreeCodeLength[S_CODE_ORDER[i]] := 0;
536 end;
537
538 // create huffman tree for code length
539 _codeLengthTree := THuffmanTree.Create(_codeLengthTreeCodeLength);
540 _codeArraySize := _literalLengthCodeCount + _distanceCodeCount;
541 _loopCounter := 0; // reset loop count
542
543 _state := TInflaterState.ReadingTreeCodesBefore;
544 Continue;
545 end;
546
547 TInflaterState.ReadingTreeCodesBefore,
548 TInflaterState.ReadingTreeCodesAfter:
549 begin
550 while (_loopCounter < _codeArraySize) do
551 begin
552 if (_state = TInflaterState.ReadingTreeCodesBefore) then
553 begin
554 _lengthCode := _codeLengthTree.GetNextSymbol(_input);
555 if (_lengthCode < 0) then
556 begin
557 Exit(false);
558 end;
559 end;
560
561 // The alphabet for code lengths is as follows:
562 // 0 - 15: Represent code lengths of 0 - 15
563 // 16: Copy the previous code length 3 - 6 times.
564 // The next 2 bits indicate repeat length
565 // (0 = 3, ... , 3 = 6)
566 // Example: Codes 8, 16 (+2 bits 11),
567 // 16 (+2 bits 10) will expand to
568 // 12 code lengths of 8 (1 + 6 + 5)
569 // 17: Repeat a code length of 0 for 3 - 10 times.
570 // (3 bits of length)
571 // 18: Repeat a code length of 0 for 11 - 138 times
572 // (7 bits of length)
573 if (_lengthCode <= 15) then
574 begin
575 _codeList[_loopCounter] := Byte(_lengthCode);
576 Inc(_loopCounter);
577 end
578 else
579 begin
580 if (_lengthCode = 16) then
581 begin
582 if (not _input.EnsureBitsAvailable(2)) then
583 begin
584 _state := TInflaterState.ReadingTreeCodesAfter;
585 Exit(false);
586 end;
587
588 if (_loopCounter = 0) then
589 begin
590 // can't have "prev code" on first code
591 raise Exception(EmptyStr);
592 end;
593
594 previousCode := _codeList[_loopCounter - 1];
595 repeatCount := _input.GetBits(2) + 3;
596
597 if (_loopCounter + repeatCount > _codeArraySize) then
598 begin
599 raise Exception(EmptyStr);
600 end;
601
602 for j := 0 to Pred(repeatCount) do
603 begin
604 _codeList[_loopCounter] := previousCode;
605 Inc(_loopCounter);
606 end;
607 end
608 else if (_lengthCode = 17) then
609 begin
610 if (not _input.EnsureBitsAvailable(3)) then
611 begin
612 _state := TInflaterState.ReadingTreeCodesAfter;
613 Exit(false);
614 end;
615
616 repeatCount := _input.GetBits(3) + 3;
617
618 if (_loopCounter + repeatCount > _codeArraySize) then
619 begin
620 raise Exception(EmptyStr);
621 end;
622
623 for j := 0 to Pred(repeatCount) do
624 begin
625 _codeList[_loopCounter] := 0;
626 Inc(_loopCounter);
627 end;
628 end
629 else
630 begin
631 // code == 18
632 if (not _input.EnsureBitsAvailable(7)) then
633 begin
634 _state := TInflaterState.ReadingTreeCodesAfter;
635 Exit(false);
636 end;
637
638 repeatCount := _input.GetBits(7) + 11;
639
640 if (_loopCounter + repeatCount > _codeArraySize) then
641 begin
642 raise Exception(EmptyStr);
643 end;
644
645 for j := 0 to Pred(repeatCount) do
646 begin
647 _codeList[_loopCounter] := 0;
648 Inc(_loopCounter);
649 end;
650 end;
651 end;
652 _state := TInflaterState.ReadingTreeCodesBefore; // we want to read the next code.
653 end;
654 end;
655
656 else
657 //*Fail*/
658 Assert(false, 'check why we are here!');
659 raise Exception.Create('Deflate64: unknown state');
660 end;
661 Break;
662 end;
663
664 SetLength(literalTreeCodeLength, THuffmanTree.MAX_LITERAL_TREE_ELEMENTS);
665 SetLength(distanceTreeCodeLength, THuffmanTree.MAX_DIST_TREE_ELEMENTS);
666
667 // Create literal and distance tables
668 Move(_codeList[0], literalTreeCodeLength[0], _literalLengthCodeCount);
669 Move(_codeList[_literalLengthCodeCount], distanceTreeCodeLength[0], _distanceCodeCount);
670
671 // Make sure there is an end-of-block code, otherwise how could we ever end?
672 if (literalTreeCodeLength[THuffmanTree.END_OF_BLOCK_CODE] = 0) then
673 begin
674 raise Exception(EmptyStr);
675 end;
676
677 _literalLengthTree := THuffmanTree.Create(literalTreeCodeLength);
678 _distanceTree := THuffmanTree.Create(distanceTreeCodeLength);
679 _state := TInflaterState.DecodeTop;
680 Result := true;
681 end;
682
683 constructor TInflaterManaged.Create(deflate64: Boolean);
684 begin
685 _output := TOutputWindow.Create;
686 _input := TInputBuffer.Create;
687
688 SetLength(_codeList, THuffmanTree.MAX_LITERAL_TREE_ELEMENTS + THuffmanTree.MAX_DIST_TREE_ELEMENTS);
689
690 SetLength(_codeLengthTreeCodeLength, THuffmanTree.NUMBER_OF_CODE_LENGTH_TREE_ELEMENTS);
691 _deflate64 := deflate64;
692
693 Reset();
694 end;
695
696 destructor TInflaterManaged.Destroy;
697 begin
698 inherited Destroy;
699 _output.Free;
700 _input.Free;
701 end;
702
703 procedure TInflaterManaged.SetInput(inputBytes: PByte; offset, length: Integer);
704 begin
705 _input.SetInput(inputBytes, offset, length); // append the bytes
706 end;
707
708 function TInflaterManaged.Finished: Boolean;
709 begin
710 Result := (_state = TInflaterState.Done) or (_state = TInflaterState.VerifyingFooter);
711 end;
712
713 function TInflaterManaged.AvailableOutput: Integer;
714 begin
715 Result := _output.AvailableBytes;
716 end;
717
718 function TInflaterManaged.Inflate(bytes: PByte; offset, length: Integer): Integer;
719 var
720 copied: Integer;
721 count: Integer = 0;
722 begin
723 // copy bytes from output to outputbytes if we have available bytes
724 // if buffer is not filled up. keep decoding until no input are available
725 // if decodeBlock returns false. Throw an exception.
726 repeat
727 copied := _output.CopyTo(bytes, offset, length);
728 if (copied > 0) then
729 begin
730 offset += copied;
731 count += copied;
732 length -= copied;
733 end;
734
735 if (length = 0) then
736 begin // filled in the bytes array
737 break;
738 end;
739 // Decode will return false when more input is needed
740 until not ((not Finished() and Decode()));
741
742 Result := count;
743 end;
744
745 end.
746