ZLib.pas 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. {*******************************************************}
  2. { }
  3. { Borland Delphi Supplemental Components }
  4. { ZLIB Data Compression Interface Unit }
  5. { }
  6. { Copyright (c) 1997,99 Borland Corporation }
  7. { }
  8. {*******************************************************}
  9. { Updated for zlib 1.2.x by Cosmin Truta <[email protected]> }
  10. unit ZLib;
  11. interface
  12. uses SysUtils, Classes;
  13. type
  14. TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
  15. TFree = procedure (AppData, Block: Pointer); cdecl;
  16. // Internal structure. Ignore.
  17. TZStreamRec = packed record
  18. next_in: PChar; // next input byte
  19. avail_in: Integer; // number of bytes available at next_in
  20. total_in: Longint; // total nb of input bytes read so far
  21. next_out: PChar; // next output byte should be put here
  22. avail_out: Integer; // remaining free space at next_out
  23. total_out: Longint; // total nb of bytes output so far
  24. msg: PChar; // last error message, NULL if no error
  25. internal: Pointer; // not visible by applications
  26. zalloc: TAlloc; // used to allocate the internal state
  27. zfree: TFree; // used to free the internal state
  28. AppData: Pointer; // private data object passed to zalloc and zfree
  29. data_type: Integer; // best guess about the data type: ascii or binary
  30. adler: Longint; // adler32 value of the uncompressed data
  31. reserved: Longint; // reserved for future use
  32. end;
  33. // Abstract ancestor class
  34. TCustomZlibStream = class(TStream)
  35. private
  36. FStrm: TStream;
  37. FStrmPos: Integer;
  38. FOnProgress: TNotifyEvent;
  39. FZRec: TZStreamRec;
  40. FBuffer: array [Word] of Char;
  41. protected
  42. procedure Progress(Sender: TObject); dynamic;
  43. property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
  44. constructor Create(Strm: TStream);
  45. end;
  46. { TCompressionStream compresses data on the fly as data is written to it, and
  47. stores the compressed data to another stream.
  48. TCompressionStream is write-only and strictly sequential. Reading from the
  49. stream will raise an exception. Using Seek to move the stream pointer
  50. will raise an exception.
  51. Output data is cached internally, written to the output stream only when
  52. the internal output buffer is full. All pending output data is flushed
  53. when the stream is destroyed.
  54. The Position property returns the number of uncompressed bytes of
  55. data that have been written to the stream so far.
  56. CompressionRate returns the on-the-fly percentage by which the original
  57. data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100
  58. If raw data size = 100 and compressed data size = 25, the CompressionRate
  59. is 75%
  60. The OnProgress event is called each time the output buffer is filled and
  61. written to the output stream. This is useful for updating a progress
  62. indicator when you are writing a large chunk of data to the compression
  63. stream in a single call.}
  64. TCompressionLevel = (clNone, clFastest, clDefault, clMax);
  65. TCompressionStream = class(TCustomZlibStream)
  66. private
  67. function GetCompressionRate: Single;
  68. public
  69. constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream);
  70. destructor Destroy; override;
  71. function Read(var Buffer; Count: Longint): Longint; override;
  72. function Write(const Buffer; Count: Longint): Longint; override;
  73. function Seek(Offset: Longint; Origin: Word): Longint; override;
  74. property CompressionRate: Single read GetCompressionRate;
  75. property OnProgress;
  76. end;
  77. { TDecompressionStream decompresses data on the fly as data is read from it.
  78. Compressed data comes from a separate source stream. TDecompressionStream
  79. is read-only and unidirectional; you can seek forward in the stream, but not
  80. backwards. The special case of setting the stream position to zero is
  81. allowed. Seeking forward decompresses data until the requested position in
  82. the uncompressed data has been reached. Seeking backwards, seeking relative
  83. to the end of the stream, requesting the size of the stream, and writing to
  84. the stream will raise an exception.
  85. The Position property returns the number of bytes of uncompressed data that
  86. have been read from the stream so far.
  87. The OnProgress event is called each time the internal input buffer of
  88. compressed data is exhausted and the next block is read from the input stream.
  89. This is useful for updating a progress indicator when you are reading a
  90. large chunk of data from the decompression stream in a single call.}
  91. TDecompressionStream = class(TCustomZlibStream)
  92. public
  93. constructor Create(Source: TStream);
  94. destructor Destroy; override;
  95. function Read(var Buffer; Count: Longint): Longint; override;
  96. function Write(const Buffer; Count: Longint): Longint; override;
  97. function Seek(Offset: Longint; Origin: Word): Longint; override;
  98. property OnProgress;
  99. end;
  100. { CompressBuf compresses data, buffer to buffer, in one call.
  101. In: InBuf = ptr to compressed data
  102. InBytes = number of bytes in InBuf
  103. Out: OutBuf = ptr to newly allocated buffer containing decompressed data
  104. OutBytes = number of bytes in OutBuf }
  105. procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
  106. out OutBuf: Pointer; out OutBytes: Integer);
  107. { DecompressBuf decompresses data, buffer to buffer, in one call.
  108. In: InBuf = ptr to compressed data
  109. InBytes = number of bytes in InBuf
  110. OutEstimate = zero, or est. size of the decompressed data
  111. Out: OutBuf = ptr to newly allocated buffer containing decompressed data
  112. OutBytes = number of bytes in OutBuf }
  113. procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
  114. OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
  115. { DecompressToUserBuf decompresses data, buffer to buffer, in one call.
  116. In: InBuf = ptr to compressed data
  117. InBytes = number of bytes in InBuf
  118. Out: OutBuf = ptr to user-allocated buffer to contain decompressed data
  119. BufSize = number of bytes in OutBuf }
  120. procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
  121. const OutBuf: Pointer; BufSize: Integer);
  122. const
  123. zlib_version = '1.2.3';
  124. type
  125. EZlibError = class(Exception);
  126. ECompressionError = class(EZlibError);
  127. EDecompressionError = class(EZlibError);
  128. implementation
  129. uses ZLibConst;
  130. const
  131. Z_NO_FLUSH = 0;
  132. Z_PARTIAL_FLUSH = 1;
  133. Z_SYNC_FLUSH = 2;
  134. Z_FULL_FLUSH = 3;
  135. Z_FINISH = 4;
  136. Z_OK = 0;
  137. Z_STREAM_END = 1;
  138. Z_NEED_DICT = 2;
  139. Z_ERRNO = (-1);
  140. Z_STREAM_ERROR = (-2);
  141. Z_DATA_ERROR = (-3);
  142. Z_MEM_ERROR = (-4);
  143. Z_BUF_ERROR = (-5);
  144. Z_VERSION_ERROR = (-6);
  145. Z_NO_COMPRESSION = 0;
  146. Z_BEST_SPEED = 1;
  147. Z_BEST_COMPRESSION = 9;
  148. Z_DEFAULT_COMPRESSION = (-1);
  149. Z_FILTERED = 1;
  150. Z_HUFFMAN_ONLY = 2;
  151. Z_RLE = 3;
  152. Z_DEFAULT_STRATEGY = 0;
  153. Z_BINARY = 0;
  154. Z_ASCII = 1;
  155. Z_UNKNOWN = 2;
  156. Z_DEFLATED = 8;
  157. {$IFNDEF VCL_XE2_OR_ABOVE}
  158. {$L adler32.obj}
  159. {$L compress.obj}
  160. {$L crc32.obj}
  161. {$L deflate.obj}
  162. {$L infback.obj}
  163. {$L inffast.obj}
  164. {$L inflate.obj}
  165. {$L inftrees.obj}
  166. {$L trees.obj}
  167. {$L uncompr.obj}
  168. {$L zutil.obj}
  169. {$ELSE}
  170. {$IFDEF WIN32}
  171. {$L i386-Win32-ZLib\adler32.obj}
  172. {$L i386-Win32-ZLib\compress.obj}
  173. {$L i386-Win32-ZLib\crc32.obj}
  174. {$L i386-Win32-ZLib\deflate.obj}
  175. {$L i386-Win32-ZLib\infback.obj}
  176. {$L i386-Win32-ZLib\inffast.obj}
  177. {$L i386-Win32-ZLib\inflate.obj}
  178. {$L i386-Win32-ZLib\inftrees.obj}
  179. {$L i386-Win32-ZLib\trees.obj}
  180. {$L i386-Win32-ZLib\uncompr.obj}
  181. {$L i386-Win32-ZLib\zlibudec.obj} // undecorated stubs which are not needed for x64 compilation
  182. {$L i386-Win32-ZLib\zutil.obj}
  183. {$ENDIF}
  184. {$IFDEF WIN64}
  185. {$L x86_64-Win64-ZLib\adler32.obj}
  186. {$L x86_64-Win64-ZLib\compress.obj}
  187. {$L x86_64-Win64-ZLib\crc32.obj}
  188. {$L x86_64-Win64-ZLib\deflate.obj}
  189. {$L x86_64-Win64-ZLib\infback.obj}
  190. {$L x86_64-Win64-ZLib\inffast.obj}
  191. {$L x86_64-Win64-ZLib\inflate.obj}
  192. {$L x86_64-Win64-ZLib\inftrees.obj}
  193. {$L x86_64-Win64-ZLib\trees.obj}
  194. {$L x86_64-Win64-ZLib\uncompr.obj}
  195. {$L x86_64-Win64-ZLib\zutil.obj}
  196. {$ENDIF}
  197. {$ENDIF}
  198. procedure adler32; external;
  199. procedure compressBound; external;
  200. procedure crc32; external;
  201. procedure deflateInit2_; external;
  202. procedure deflateParams; external;
  203. function _malloc(Size: Integer): Pointer; cdecl;
  204. begin
  205. Result := AllocMem(Size);
  206. end;
  207. procedure _free(Block: Pointer); cdecl;
  208. begin
  209. FreeMem(Block);
  210. end;
  211. procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
  212. begin
  213. FillChar(P^, count, B);
  214. end;
  215. procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
  216. begin
  217. Move(source^, dest^, count);
  218. end;
  219. // deflate compresses data
  220. function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
  221. recsize: Integer): Integer; external;
  222. function deflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  223. function deflateEnd(var strm: TZStreamRec): Integer; external;
  224. // inflate decompresses data
  225. function inflateInit_(var strm: TZStreamRec; version: PChar;
  226. recsize: Integer): Integer; external;
  227. function inflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  228. function inflateEnd(var strm: TZStreamRec): Integer; external;
  229. function inflateReset(var strm: TZStreamRec): Integer; external;
  230. function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
  231. begin
  232. // GetMem(Result, Items*Size);
  233. Result := AllocMem(Items * Size);
  234. end;
  235. procedure zlibFreeMem(AppData, Block: Pointer); cdecl;
  236. begin
  237. FreeMem(Block);
  238. end;
  239. {function zlibCheck(code: Integer): Integer;
  240. begin
  241. Result := code;
  242. if code < 0 then
  243. raise EZlibError.Create('error'); //!!
  244. end;}
  245. function CCheck(code: Integer): Integer;
  246. begin
  247. Result := code;
  248. if code < 0 then
  249. raise ECompressionError.Create('error'); //!!
  250. end;
  251. function DCheck(code: Integer): Integer;
  252. begin
  253. Result := code;
  254. if code < 0 then
  255. raise EDecompressionError.Create('error'); //!!
  256. end;
  257. procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
  258. out OutBuf: Pointer; out OutBytes: Integer);
  259. var
  260. strm: TZStreamRec;
  261. P: Pointer;
  262. begin
  263. FillChar(strm, sizeof(strm), 0);
  264. strm.zalloc := zlibAllocMem;
  265. strm.zfree := zlibFreeMem;
  266. OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255;
  267. GetMem(OutBuf, OutBytes);
  268. try
  269. strm.next_in := InBuf;
  270. strm.avail_in := InBytes;
  271. strm.next_out := OutBuf;
  272. strm.avail_out := OutBytes;
  273. CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm)));
  274. try
  275. while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do
  276. begin
  277. P := OutBuf;
  278. Inc(OutBytes, 256);
  279. ReallocMem(OutBuf, OutBytes);
  280. strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  281. strm.avail_out := 256;
  282. end;
  283. finally
  284. CCheck(deflateEnd(strm));
  285. end;
  286. ReallocMem(OutBuf, strm.total_out);
  287. OutBytes := strm.total_out;
  288. except
  289. FreeMem(OutBuf);
  290. raise;
  291. end;
  292. end;
  293. procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
  294. OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
  295. var
  296. strm: TZStreamRec;
  297. P: Pointer;
  298. BufInc: Integer;
  299. begin
  300. FillChar(strm, sizeof(strm), 0);
  301. strm.zalloc := zlibAllocMem;
  302. strm.zfree := zlibFreeMem;
  303. BufInc := (InBytes + 255) and not 255;
  304. if OutEstimate = 0 then
  305. OutBytes := BufInc
  306. else
  307. OutBytes := OutEstimate;
  308. GetMem(OutBuf, OutBytes);
  309. try
  310. strm.next_in := InBuf;
  311. strm.avail_in := InBytes;
  312. strm.next_out := OutBuf;
  313. strm.avail_out := OutBytes;
  314. DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
  315. try
  316. while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do
  317. begin
  318. P := OutBuf;
  319. Inc(OutBytes, BufInc);
  320. ReallocMem(OutBuf, OutBytes);
  321. strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  322. strm.avail_out := BufInc;
  323. end;
  324. finally
  325. DCheck(inflateEnd(strm));
  326. end;
  327. ReallocMem(OutBuf, strm.total_out);
  328. OutBytes := strm.total_out;
  329. except
  330. FreeMem(OutBuf);
  331. raise;
  332. end;
  333. end;
  334. procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
  335. const OutBuf: Pointer; BufSize: Integer);
  336. var
  337. strm: TZStreamRec;
  338. begin
  339. FillChar(strm, sizeof(strm), 0);
  340. strm.zalloc := zlibAllocMem;
  341. strm.zfree := zlibFreeMem;
  342. strm.next_in := InBuf;
  343. strm.avail_in := InBytes;
  344. strm.next_out := OutBuf;
  345. strm.avail_out := BufSize;
  346. DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
  347. try
  348. if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then
  349. raise EZlibError.CreateRes(@sTargetBufferTooSmall);
  350. finally
  351. DCheck(inflateEnd(strm));
  352. end;
  353. end;
  354. // TCustomZlibStream
  355. constructor TCustomZLibStream.Create(Strm: TStream);
  356. begin
  357. inherited Create;
  358. FStrm := Strm;
  359. FStrmPos := Strm.Position;
  360. FZRec.zalloc := zlibAllocMem;
  361. FZRec.zfree := zlibFreeMem;
  362. end;
  363. procedure TCustomZLibStream.Progress(Sender: TObject);
  364. begin
  365. if Assigned(FOnProgress) then FOnProgress(Sender);
  366. end;
  367. // TCompressionStream
  368. constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel;
  369. Dest: TStream);
  370. const
  371. Levels: array [TCompressionLevel] of ShortInt =
  372. (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION);
  373. begin
  374. inherited Create(Dest);
  375. FZRec.next_out := FBuffer;
  376. FZRec.avail_out := sizeof(FBuffer);
  377. CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec)));
  378. end;
  379. destructor TCompressionStream.Destroy;
  380. begin
  381. FZRec.next_in := nil;
  382. FZRec.avail_in := 0;
  383. try
  384. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  385. while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END)
  386. and (FZRec.avail_out = 0) do
  387. begin
  388. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  389. FZRec.next_out := FBuffer;
  390. FZRec.avail_out := sizeof(FBuffer);
  391. end;
  392. if FZRec.avail_out < sizeof(FBuffer) then
  393. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out);
  394. finally
  395. deflateEnd(FZRec);
  396. end;
  397. inherited Destroy;
  398. end;
  399. function TCompressionStream.Read(var Buffer; Count: Longint): Longint;
  400. begin
  401. raise ECompressionError.CreateRes(@sInvalidStreamOp);
  402. end;
  403. function TCompressionStream.Write(const Buffer; Count: Longint): Longint;
  404. begin
  405. FZRec.next_in := @Buffer;
  406. FZRec.avail_in := Count;
  407. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  408. while (FZRec.avail_in > 0) do
  409. begin
  410. CCheck(deflate(FZRec, 0));
  411. if FZRec.avail_out = 0 then
  412. begin
  413. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  414. FZRec.next_out := FBuffer;
  415. FZRec.avail_out := sizeof(FBuffer);
  416. FStrmPos := FStrm.Position;
  417. Progress(Self);
  418. end;
  419. end;
  420. Result := Count;
  421. end;
  422. function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  423. begin
  424. if (Offset = 0) and (Origin = soFromCurrent) then
  425. Result := FZRec.total_in
  426. else
  427. raise ECompressionError.CreateRes(@sInvalidStreamOp);
  428. end;
  429. function TCompressionStream.GetCompressionRate: Single;
  430. begin
  431. if FZRec.total_in = 0 then
  432. Result := 0
  433. else
  434. Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0;
  435. end;
  436. // TDecompressionStream
  437. constructor TDecompressionStream.Create(Source: TStream);
  438. begin
  439. inherited Create(Source);
  440. FZRec.next_in := FBuffer;
  441. FZRec.avail_in := 0;
  442. DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec)));
  443. end;
  444. destructor TDecompressionStream.Destroy;
  445. begin
  446. FStrm.Seek(-FZRec.avail_in, 1);
  447. inflateEnd(FZRec);
  448. inherited Destroy;
  449. end;
  450. function TDecompressionStream.Read(var Buffer; Count: Longint): Longint;
  451. begin
  452. FZRec.next_out := @Buffer;
  453. FZRec.avail_out := Count;
  454. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  455. while (FZRec.avail_out > 0) do
  456. begin
  457. if FZRec.avail_in = 0 then
  458. begin
  459. FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer));
  460. if FZRec.avail_in = 0 then
  461. begin
  462. Result := Count - FZRec.avail_out;
  463. Exit;
  464. end;
  465. FZRec.next_in := FBuffer;
  466. FStrmPos := FStrm.Position;
  467. Progress(Self);
  468. end;
  469. CCheck(inflate(FZRec, 0));
  470. end;
  471. Result := Count;
  472. end;
  473. function TDecompressionStream.Write(const Buffer; Count: Longint): Longint;
  474. begin
  475. raise EDecompressionError.CreateRes(@sInvalidStreamOp);
  476. end;
  477. function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  478. var
  479. I: Integer;
  480. Buf: array [0..4095] of Char;
  481. begin
  482. if (Offset = 0) and (Origin = soFromBeginning) then
  483. begin
  484. DCheck(inflateReset(FZRec));
  485. FZRec.next_in := FBuffer;
  486. FZRec.avail_in := 0;
  487. FStrm.Position := 0;
  488. FStrmPos := 0;
  489. end
  490. else if ( (Offset >= 0) and (Origin = soFromCurrent)) or
  491. ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then
  492. begin
  493. if Origin = soFromBeginning then Dec(Offset, FZRec.total_out);
  494. if Offset > 0 then
  495. begin
  496. for I := 1 to Offset div sizeof(Buf) do
  497. ReadBuffer(Buf, sizeof(Buf));
  498. ReadBuffer(Buf, Offset mod sizeof(Buf));
  499. end;
  500. end
  501. else
  502. raise EDecompressionError.CreateRes(@sInvalidStreamOp);
  503. Result := FZRec.total_out;
  504. end;
  505. end.