ZLib.pas 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 <cosmint@cs.ubbcluj.ro> }
  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.5';
  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. {$L adler32.obj}
  158. {$L compress.obj}
  159. {$L crc32.obj}
  160. {$L deflate.obj}
  161. {$L infback.obj}
  162. {$L inffast.obj}
  163. {$L inflate.obj}
  164. {$L inftrees.obj}
  165. {$L trees.obj}
  166. {$L uncompr.obj}
  167. {$L zutil.obj}
  168. procedure adler32; external;
  169. procedure compressBound; external;
  170. procedure crc32; external;
  171. procedure deflateInit2_; external;
  172. procedure deflateParams; external;
  173. function _malloc(Size: Integer): Pointer; cdecl;
  174. begin
  175. Result := AllocMem(Size);
  176. end;
  177. procedure _free(Block: Pointer); cdecl;
  178. begin
  179. FreeMem(Block);
  180. end;
  181. procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
  182. begin
  183. FillChar(P^, count, B);
  184. end;
  185. procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
  186. begin
  187. Move(source^, dest^, count);
  188. end;
  189. // deflate compresses data
  190. function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
  191. recsize: Integer): Integer; external;
  192. function deflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  193. function deflateEnd(var strm: TZStreamRec): Integer; external;
  194. // inflate decompresses data
  195. function inflateInit_(var strm: TZStreamRec; version: PChar;
  196. recsize: Integer): Integer; external;
  197. function inflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  198. function inflateEnd(var strm: TZStreamRec): Integer; external;
  199. function inflateReset(var strm: TZStreamRec): Integer; external;
  200. function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
  201. begin
  202. // GetMem(Result, Items*Size);
  203. Result := AllocMem(Items * Size);
  204. end;
  205. procedure zlibFreeMem(AppData, Block: Pointer); cdecl;
  206. begin
  207. FreeMem(Block);
  208. end;
  209. {function zlibCheck(code: Integer): Integer;
  210. begin
  211. Result := code;
  212. if code < 0 then
  213. raise EZlibError.Create('error'); //!!
  214. end;}
  215. function CCheck(code: Integer): Integer;
  216. begin
  217. Result := code;
  218. if code < 0 then
  219. raise ECompressionError.Create('error'); //!!
  220. end;
  221. function DCheck(code: Integer): Integer;
  222. begin
  223. Result := code;
  224. if code < 0 then
  225. raise EDecompressionError.Create('error'); //!!
  226. end;
  227. procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
  228. out OutBuf: Pointer; out OutBytes: Integer);
  229. var
  230. strm: TZStreamRec;
  231. P: Pointer;
  232. begin
  233. FillChar(strm, sizeof(strm), 0);
  234. strm.zalloc := zlibAllocMem;
  235. strm.zfree := zlibFreeMem;
  236. OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255;
  237. GetMem(OutBuf, OutBytes);
  238. try
  239. strm.next_in := InBuf;
  240. strm.avail_in := InBytes;
  241. strm.next_out := OutBuf;
  242. strm.avail_out := OutBytes;
  243. CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm)));
  244. try
  245. while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do
  246. begin
  247. P := OutBuf;
  248. Inc(OutBytes, 256);
  249. ReallocMem(OutBuf, OutBytes);
  250. strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  251. strm.avail_out := 256;
  252. end;
  253. finally
  254. CCheck(deflateEnd(strm));
  255. end;
  256. ReallocMem(OutBuf, strm.total_out);
  257. OutBytes := strm.total_out;
  258. except
  259. FreeMem(OutBuf);
  260. raise
  261. end;
  262. end;
  263. procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
  264. OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
  265. var
  266. strm: TZStreamRec;
  267. P: Pointer;
  268. BufInc: Integer;
  269. begin
  270. FillChar(strm, sizeof(strm), 0);
  271. strm.zalloc := zlibAllocMem;
  272. strm.zfree := zlibFreeMem;
  273. BufInc := (InBytes + 255) and not 255;
  274. if OutEstimate = 0 then
  275. OutBytes := BufInc
  276. else
  277. OutBytes := OutEstimate;
  278. GetMem(OutBuf, OutBytes);
  279. try
  280. strm.next_in := InBuf;
  281. strm.avail_in := InBytes;
  282. strm.next_out := OutBuf;
  283. strm.avail_out := OutBytes;
  284. DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
  285. try
  286. while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do
  287. begin
  288. P := OutBuf;
  289. Inc(OutBytes, BufInc);
  290. ReallocMem(OutBuf, OutBytes);
  291. strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  292. strm.avail_out := BufInc;
  293. end;
  294. finally
  295. DCheck(inflateEnd(strm));
  296. end;
  297. ReallocMem(OutBuf, strm.total_out);
  298. OutBytes := strm.total_out;
  299. except
  300. FreeMem(OutBuf);
  301. raise
  302. end;
  303. end;
  304. procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
  305. const OutBuf: Pointer; BufSize: Integer);
  306. var
  307. strm: TZStreamRec;
  308. begin
  309. FillChar(strm, sizeof(strm), 0);
  310. strm.zalloc := zlibAllocMem;
  311. strm.zfree := zlibFreeMem;
  312. strm.next_in := InBuf;
  313. strm.avail_in := InBytes;
  314. strm.next_out := OutBuf;
  315. strm.avail_out := BufSize;
  316. DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
  317. try
  318. if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then
  319. raise EZlibError.CreateRes(@sTargetBufferTooSmall);
  320. finally
  321. DCheck(inflateEnd(strm));
  322. end;
  323. end;
  324. // TCustomZlibStream
  325. constructor TCustomZLibStream.Create(Strm: TStream);
  326. begin
  327. inherited Create;
  328. FStrm := Strm;
  329. FStrmPos := Strm.Position;
  330. FZRec.zalloc := zlibAllocMem;
  331. FZRec.zfree := zlibFreeMem;
  332. end;
  333. procedure TCustomZLibStream.Progress(Sender: TObject);
  334. begin
  335. if Assigned(FOnProgress) then FOnProgress(Sender);
  336. end;
  337. // TCompressionStream
  338. constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel;
  339. Dest: TStream);
  340. const
  341. Levels: array [TCompressionLevel] of ShortInt =
  342. (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION);
  343. begin
  344. inherited Create(Dest);
  345. FZRec.next_out := FBuffer;
  346. FZRec.avail_out := sizeof(FBuffer);
  347. CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec)));
  348. end;
  349. destructor TCompressionStream.Destroy;
  350. begin
  351. FZRec.next_in := nil;
  352. FZRec.avail_in := 0;
  353. try
  354. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  355. while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END)
  356. and (FZRec.avail_out = 0) do
  357. begin
  358. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  359. FZRec.next_out := FBuffer;
  360. FZRec.avail_out := sizeof(FBuffer);
  361. end;
  362. if FZRec.avail_out < sizeof(FBuffer) then
  363. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out);
  364. finally
  365. deflateEnd(FZRec);
  366. end;
  367. inherited Destroy;
  368. end;
  369. function TCompressionStream.Read(var Buffer; Count: Longint): Longint;
  370. begin
  371. raise ECompressionError.CreateRes(@sInvalidStreamOp);
  372. end;
  373. function TCompressionStream.Write(const Buffer; Count: Longint): Longint;
  374. begin
  375. FZRec.next_in := @Buffer;
  376. FZRec.avail_in := Count;
  377. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  378. while (FZRec.avail_in > 0) do
  379. begin
  380. CCheck(deflate(FZRec, 0));
  381. if FZRec.avail_out = 0 then
  382. begin
  383. FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  384. FZRec.next_out := FBuffer;
  385. FZRec.avail_out := sizeof(FBuffer);
  386. FStrmPos := FStrm.Position;
  387. Progress(Self);
  388. end;
  389. end;
  390. Result := Count;
  391. end;
  392. function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  393. begin
  394. if (Offset = 0) and (Origin = soFromCurrent) then
  395. Result := FZRec.total_in
  396. else
  397. raise ECompressionError.CreateRes(@sInvalidStreamOp);
  398. end;
  399. function TCompressionStream.GetCompressionRate: Single;
  400. begin
  401. if FZRec.total_in = 0 then
  402. Result := 0
  403. else
  404. Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0;
  405. end;
  406. // TDecompressionStream
  407. constructor TDecompressionStream.Create(Source: TStream);
  408. begin
  409. inherited Create(Source);
  410. FZRec.next_in := FBuffer;
  411. FZRec.avail_in := 0;
  412. DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec)));
  413. end;
  414. destructor TDecompressionStream.Destroy;
  415. begin
  416. FStrm.Seek(-FZRec.avail_in, 1);
  417. inflateEnd(FZRec);
  418. inherited Destroy;
  419. end;
  420. function TDecompressionStream.Read(var Buffer; Count: Longint): Longint;
  421. begin
  422. FZRec.next_out := @Buffer;
  423. FZRec.avail_out := Count;
  424. if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  425. while (FZRec.avail_out > 0) do
  426. begin
  427. if FZRec.avail_in = 0 then
  428. begin
  429. FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer));
  430. if FZRec.avail_in = 0 then
  431. begin
  432. Result := Count - FZRec.avail_out;
  433. Exit;
  434. end;
  435. FZRec.next_in := FBuffer;
  436. FStrmPos := FStrm.Position;
  437. Progress(Self);
  438. end;
  439. CCheck(inflate(FZRec, 0));
  440. end;
  441. Result := Count;
  442. end;
  443. function TDecompressionStream.Write(const Buffer; Count: Longint): Longint;
  444. begin
  445. raise EDecompressionError.CreateRes(@sInvalidStreamOp);
  446. end;
  447. function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  448. var
  449. I: Integer;
  450. Buf: array [0..4095] of Char;
  451. begin
  452. if (Offset = 0) and (Origin = soFromBeginning) then
  453. begin
  454. DCheck(inflateReset(FZRec));
  455. FZRec.next_in := FBuffer;
  456. FZRec.avail_in := 0;
  457. FStrm.Position := 0;
  458. FStrmPos := 0;
  459. end
  460. else if ( (Offset >= 0) and (Origin = soFromCurrent)) or
  461. ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then
  462. begin
  463. if Origin = soFromBeginning then Dec(Offset, FZRec.total_out);
  464. if Offset > 0 then
  465. begin
  466. for I := 1 to Offset div sizeof(Buf) do
  467. ReadBuffer(Buf, sizeof(Buf));
  468. ReadBuffer(Buf, Offset mod sizeof(Buf));
  469. end;
  470. end
  471. else
  472. raise EDecompressionError.CreateRes(@sInvalidStreamOp);
  473. Result := FZRec.total_out;
  474. end;
  475. end.