zdeflate.pas 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  1. Unit zDeflate;
  2. {$ifdef fpc}
  3. {$goto on}
  4. {$endif}
  5. { Orginal: deflate.h -- internal compression state
  6. deflate.c -- compress data using the deflation algorithm
  7. Copyright (C) 1995-1996 Jean-loup Gailly.
  8. Pascal tranlastion
  9. Copyright (C) 1998 by Jacques Nomssi Nzali
  10. For conditions of distribution and use, see copyright notice in readme.txt
  11. }
  12. { ALGORITHM
  13. The "deflation" process depends on being able to identify portions
  14. of the input text which are identical to earlier input (within a
  15. sliding window trailing behind the input currently being processed).
  16. The most straightforward technique turns out to be the fastest for
  17. most input files: try all possible matches and select the longest.
  18. The key feature of this algorithm is that insertions into the string
  19. dictionary are very simple and thus fast, and deletions are avoided
  20. completely. Insertions are performed at each input character, whereas
  21. string matches are performed only when the previous match ends. So it
  22. is preferable to spend more time in matches to allow very fast string
  23. insertions and avoid deletions. The matching algorithm for small
  24. strings is inspired from that of Rabin & Karp. A brute force approach
  25. is used to find longer strings when a small match has been found.
  26. A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  27. (by Leonid Broukhis).
  28. A previous version of this file used a more sophisticated algorithm
  29. (by Fiala and Greene) which is guaranteed to run in linear amortized
  30. time, but has a larger average cost, uses more memory and is patented.
  31. However the F&G algorithm may be faster for some highly redundant
  32. files if the parameter max_chain_length (described below) is too large.
  33. ACKNOWLEDGEMENTS
  34. The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  35. I found it in 'freeze' written by Leonid Broukhis.
  36. Thanks to many people for bug reports and testing.
  37. REFERENCES
  38. Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  39. Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  40. A description of the Rabin and Karp algorithm is given in the book
  41. "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  42. Fiala,E.R., and Greene,D.H.
  43. Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595}
  44. { $Id$ }
  45. interface
  46. {$I zconf.inc}
  47. uses
  48. zutil, zlib;
  49. function deflateInit_(strm : z_streamp;
  50. level : int;
  51. const version : string;
  52. stream_size : int) : int;
  53. function deflateInit (var strm : z_stream; level : int) : int;
  54. { Initializes the internal stream state for compression. The fields
  55. zalloc, zfree and opaque must be initialized before by the caller.
  56. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  57. use default allocation functions.
  58. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  59. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  60. all (the input data is simply copied a block at a time).
  61. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  62. compression (currently equivalent to level 6).
  63. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  64. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  65. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  66. with the version assumed by the caller (ZLIB_VERSION).
  67. msg is set to null if there is no error message. deflateInit does not
  68. perform any compression: this will be done by deflate(). }
  69. {EXPORT}
  70. function deflate (var strm : z_stream; flush : int) : int;
  71. { Performs one or both of the following actions:
  72. - Compress more input starting at next_in and update next_in and avail_in
  73. accordingly. If not all input can be processed (because there is not
  74. enough room in the output buffer), next_in and avail_in are updated and
  75. processing will resume at this point for the next call of deflate().
  76. - Provide more output starting at next_out and update next_out and avail_out
  77. accordingly. This action is forced if the parameter flush is non zero.
  78. Forcing flush frequently degrades the compression ratio, so this parameter
  79. should be set only when necessary (in interactive applications).
  80. Some output may be provided even if flush is not set.
  81. Before the call of deflate(), the application should ensure that at least
  82. one of the actions is possible, by providing more input and/or consuming
  83. more output, and updating avail_in or avail_out accordingly; avail_out
  84. should never be zero before the call. The application can consume the
  85. compressed output when it wants, for example when the output buffer is full
  86. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  87. and with zero avail_out, it must be called again after making room in the
  88. output buffer because there might be more output pending.
  89. If the parameter flush is set to Z_PARTIAL_FLUSH, the current compression
  90. block is terminated and flushed to the output buffer so that the
  91. decompressor can get all input data available so far. For method 9, a future
  92. variant on method 8, the current block will be flushed but not terminated.
  93. Z_SYNC_FLUSH has the same effect as partial flush except that the compressed
  94. output is byte aligned (the compressor can clear its internal bit buffer)
  95. and the current block is always terminated; this can be useful if the
  96. compressor has to be restarted from scratch after an interruption (in which
  97. case the internal state of the compressor may be lost).
  98. If flush is set to Z_FULL_FLUSH, the compression block is terminated, a
  99. special marker is output and the compression dictionary is discarded; this
  100. is useful to allow the decompressor to synchronize if one compressed block
  101. has been damaged (see inflateSync below). Flushing degrades compression and
  102. so should be used only when necessary. Using Z_FULL_FLUSH too often can
  103. seriously degrade the compression. If deflate returns with avail_out == 0,
  104. this function must be called again with the same value of the flush
  105. parameter and more output space (updated avail_out), until the flush is
  106. complete (deflate returns with non-zero avail_out).
  107. If the parameter flush is set to Z_FINISH, all pending input is processed,
  108. all pending output is flushed and deflate returns with Z_STREAM_END if there
  109. was enough output space; if deflate returns with Z_OK, this function must be
  110. called again with Z_FINISH and more output space (updated avail_out) but no
  111. more input data, until it returns with Z_STREAM_END or an error. After
  112. deflate has returned Z_STREAM_END, the only possible operations on the
  113. stream are deflateReset or deflateEnd.
  114. Z_FINISH can be used immediately after deflateInit if all the compression
  115. is to be done in a single step. In this case, avail_out must be at least
  116. 0.1% larger than avail_in plus 12 bytes. If deflate does not return
  117. Z_STREAM_END, then it must be called again as described above.
  118. deflate() may update data_type if it can make a good guess about
  119. the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
  120. binary. This field is only for information purposes and does not affect
  121. the compression algorithm in any manner.
  122. deflate() returns Z_OK if some progress has been made (more input
  123. processed or more output produced), Z_STREAM_END if all input has been
  124. consumed and all output has been produced (only when flush is set to
  125. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  126. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible. }
  127. function deflateEnd (var strm : z_stream) : int;
  128. { All dynamically allocated data structures for this stream are freed.
  129. This function discards any unprocessed input and does not flush any
  130. pending output.
  131. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  132. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  133. prematurely (some input or output was discarded). In the error case,
  134. msg may be set but then points to a static string (which must not be
  135. deallocated). }
  136. { Advanced functions }
  137. { The following functions are needed only in some special applications. }
  138. {EXPORT}
  139. function deflateInit2 (var strm : z_stream;
  140. level : int;
  141. method : int;
  142. windowBits : int;
  143. memLevel : int;
  144. strategy : int) : int;
  145. { This is another version of deflateInit with more compression options. The
  146. fields next_in, zalloc, zfree and opaque must be initialized before by
  147. the caller.
  148. The method parameter is the compression method. It must be Z_DEFLATED in
  149. this version of the library. (Method 9 will allow a 64K history buffer and
  150. partial block flushes.)
  151. The windowBits parameter is the base two logarithm of the window size
  152. (the size of the history buffer). It should be in the range 8..15 for this
  153. version of the library (the value 16 will be allowed for method 9). Larger
  154. values of this parameter result in better compression at the expense of
  155. memory usage. The default value is 15 if deflateInit is used instead.
  156. The memLevel parameter specifies how much memory should be allocated
  157. for the internal compression state. memLevel=1 uses minimum memory but
  158. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  159. for optimal speed. The default value is 8. See zconf.h for total memory
  160. usage as a function of windowBits and memLevel.
  161. The strategy parameter is used to tune the compression algorithm. Use the
  162. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  163. filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
  164. string match). Filtered data consists mostly of small values with a
  165. somewhat random distribution. In this case, the compression algorithm is
  166. tuned to compress them better. The effect of Z_FILTERED is to force more
  167. Huffman coding and less string matching; it is somewhat intermediate
  168. between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
  169. the compression ratio but not the correctness of the compressed output even
  170. if it is not set appropriately.
  171. If next_in is not null, the library will use this buffer to hold also
  172. some history information; the buffer must either hold the entire input
  173. data, or have at least 1<<(windowBits+1) bytes and be writable. If next_in
  174. is null, the library will allocate its own history buffer (and leave next_in
  175. null). next_out need not be provided here but must be provided by the
  176. application for the next call of deflate().
  177. If the history buffer is provided by the application, next_in must
  178. must never be changed by the application since the compressor maintains
  179. information inside this buffer from call to call; the application
  180. must provide more input only by increasing avail_in. next_in is always
  181. reset by the library in this case.
  182. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was
  183. not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as
  184. an invalid method). msg is set to null if there is no error message.
  185. deflateInit2 does not perform any compression: this will be done by
  186. deflate(). }
  187. {EXPORT}
  188. function deflateSetDictionary (var strm : z_stream;
  189. dictionary : pBytef; {const bytes}
  190. dictLength : uint) : int;
  191. { Initializes the compression dictionary (history buffer) from the given
  192. byte sequence without producing any compressed output. This function must
  193. be called immediately after deflateInit or deflateInit2, before any call
  194. of deflate. The compressor and decompressor must use exactly the same
  195. dictionary (see inflateSetDictionary).
  196. The dictionary should consist of strings (byte sequences) that are likely
  197. to be encountered later in the data to be compressed, with the most commonly
  198. used strings preferably put towards the end of the dictionary. Using a
  199. dictionary is most useful when the data to be compressed is short and
  200. can be predicted with good accuracy; the data can then be compressed better
  201. than with the default empty dictionary. In this version of the library,
  202. only the last 32K bytes of the dictionary are used.
  203. Upon return of this function, strm->adler is set to the Adler32 value
  204. of the dictionary; the decompressor may later use this value to determine
  205. which dictionary has been used by the compressor. (The Adler32 value
  206. applies to the whole dictionary even if only a subset of the dictionary is
  207. actually used by the compressor.)
  208. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  209. parameter is invalid (such as NULL dictionary) or the stream state
  210. is inconsistent (for example if deflate has already been called for this
  211. stream). deflateSetDictionary does not perform any compression: this will
  212. be done by deflate(). }
  213. {EXPORT}
  214. function deflateCopy (dest : z_streamp;
  215. source : z_streamp) : int;
  216. { Sets the destination stream as a complete copy of the source stream. If
  217. the source stream is using an application-supplied history buffer, a new
  218. buffer is allocated for the destination stream. The compressed output
  219. buffer is always application-supplied. It's the responsibility of the
  220. application to provide the correct values of next_out and avail_out for the
  221. next call of deflate.
  222. This function can be useful when several compression strategies will be
  223. tried, for example when there are several ways of pre-processing the input
  224. data with a filter. The streams that will be discarded should then be freed
  225. by calling deflateEnd. Note that deflateCopy duplicates the internal
  226. compression state which can be quite large, so this strategy is slow and
  227. can consume lots of memory.
  228. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  229. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  230. (such as zalloc being NULL). msg is left unchanged in both source and
  231. destination. }
  232. {EXPORT}
  233. function deflateReset (var strm : z_stream) : int;
  234. { This function is equivalent to deflateEnd followed by deflateInit,
  235. but does not free and reallocate all the internal compression state.
  236. The stream will keep the same compression level and any other attributes
  237. that may have been set by deflateInit2.
  238. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  239. stream state was inconsistent (such as zalloc or state being NIL). }
  240. {EXPORT}
  241. function deflateParams (var strm : z_stream; level : int; strategy : int) : int;
  242. { Dynamically update the compression level and compression strategy.
  243. This can be used to switch between compression and straight copy of
  244. the input data, or to switch to a different kind of input data requiring
  245. a different strategy. If the compression level is changed, the input
  246. available so far is compressed with the old level (and may be flushed);
  247. the new level will take effect only at the next call of deflate().
  248. Before the call of deflateParams, the stream state must be set as for
  249. a call of deflate(), since the currently available input may have to
  250. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  251. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  252. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  253. if strm->avail_out was zero. }
  254. const
  255. deflate_copyright : string = ' deflate 1.1.2 Copyright 1995-1998 Jean-loup Gailly ';
  256. { If you use the zlib library in a product, an acknowledgment is welcome
  257. in the documentation of your product. If for some reason you cannot
  258. include such an acknowledgment, I would appreciate that you keep this
  259. copyright string in the executable of your product. }
  260. implementation
  261. uses
  262. trees, adler;
  263. { ===========================================================================
  264. Function prototypes. }
  265. type
  266. block_state = (
  267. need_more, { block not completed, need more input or more output }
  268. block_done, { block flush performed }
  269. finish_started, { finish started, need only more output at next deflate }
  270. finish_done); { finish done, accept no more input or output }
  271. { Compression function. Returns the block state after the call. }
  272. type
  273. compress_func = function(var s : deflate_state; flush : int) : block_state;
  274. {local}
  275. procedure fill_window(var s : deflate_state); forward;
  276. {local}
  277. function deflate_stored(var s : deflate_state; flush : int) : block_state; far; forward;
  278. {local}
  279. function deflate_fast(var s : deflate_state; flush : int) : block_state; far; forward;
  280. {local}
  281. function deflate_slow(var s : deflate_state; flush : int) : block_state; far; forward;
  282. {local}
  283. procedure lm_init(var s : deflate_state); forward;
  284. {local}
  285. procedure putShortMSB(var s : deflate_state; b : uInt); forward;
  286. {local}
  287. procedure flush_pending (var strm : z_stream); forward;
  288. {local}
  289. function read_buf(strm : z_streamp;
  290. buf : pBytef;
  291. size : unsigned) : int; forward;
  292. {$ifdef ASMV}
  293. procedure match_init; { asm code initialization }
  294. function longest_match(var deflate_state; cur_match : IPos) : uInt; forward;
  295. {$else}
  296. {local}
  297. function longest_match(var s : deflate_state; cur_match : IPos) : uInt;
  298. forward;
  299. {$endif}
  300. {$ifdef DEBUG}
  301. {local}
  302. procedure check_match(var s : deflate_state;
  303. start, match : IPos;
  304. length : int); forward;
  305. {$endif}
  306. { ==========================================================================
  307. local data }
  308. const
  309. ZNIL = 0;
  310. { Tail of hash chains }
  311. const
  312. TOO_FAR = 4096;
  313. { Matches of length 3 are discarded if their distance exceeds TOO_FAR }
  314. const
  315. MIN_LOOKAHEAD = (MAX_MATCH+MIN_MATCH+1);
  316. { Minimum amount of lookahead, except at the end of the input file.
  317. See deflate.c for comments about the MIN_MATCH+1. }
  318. {macro MAX_DIST(var s : deflate_state) : uInt;
  319. begin
  320. MAX_DIST := (s.w_size - MIN_LOOKAHEAD);
  321. end;
  322. In order to simplify the code, particularly on 16 bit machines, match
  323. distances are limited to MAX_DIST instead of WSIZE. }
  324. { Values for max_lazy_match, good_match and max_chain_length, depending on
  325. the desired pack level (0..9). The values given below have been tuned to
  326. exclude worst case performance for pathological files. Better values may be
  327. found for specific files. }
  328. type
  329. config = record
  330. good_length : ush; { reduce lazy search above this match length }
  331. max_lazy : ush; { do not perform lazy search above this match length }
  332. nice_length : ush; { quit search above this match length }
  333. max_chain : ush;
  334. func : compress_func;
  335. end;
  336. {local}
  337. const
  338. configuration_table : array[0..10-1] of config = (
  339. { good lazy nice chain }
  340. {0} (good_length:0; max_lazy:0; nice_length:0; max_chain:0; func:deflate_stored), { store only }
  341. {1} (good_length:4; max_lazy:4; nice_length:8; max_chain:4; func:deflate_fast), { maximum speed, no lazy matches }
  342. {2} (good_length:4; max_lazy:5; nice_length:16; max_chain:8; func:deflate_fast),
  343. {3} (good_length:4; max_lazy:6; nice_length:32; max_chain:32; func:deflate_fast),
  344. {4} (good_length:4; max_lazy:4; nice_length:16; max_chain:16; func:deflate_slow), { lazy matches }
  345. {5} (good_length:8; max_lazy:16; nice_length:32; max_chain:32; func:deflate_slow),
  346. {6} (good_length:8; max_lazy:16; nice_length:128; max_chain:128; func:deflate_slow),
  347. {7} (good_length:8; max_lazy:32; nice_length:128; max_chain:256; func:deflate_slow),
  348. {8} (good_length:32; max_lazy:128; nice_length:258; max_chain:1024; func:deflate_slow),
  349. {9} (good_length:32; max_lazy:258; nice_length:258; max_chain:4096; func:deflate_slow)); { maximum compression }
  350. { Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  351. For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  352. meaning. }
  353. const
  354. EQUAL = 0;
  355. { result of memcmp for equal strings }
  356. { ==========================================================================
  357. Update a hash value with the given input byte
  358. IN assertion: all calls to to UPDATE_HASH are made with consecutive
  359. input characters, so that a running hash key can be computed from the
  360. previous key instead of complete recalculation each time.
  361. macro UPDATE_HASH(s,h,c)
  362. h := (( (h) shl s^.hash_shift) xor (c)) and s^.hash_mask;
  363. }
  364. { ===========================================================================
  365. Insert string str in the dictionary and set match_head to the previous head
  366. of the hash chain (the most recent string with same hash key). Return
  367. the previous length of the hash chain.
  368. If this file is compiled with -DFASTEST, the compression level is forced
  369. to 1, and no hash chains are maintained.
  370. IN assertion: all calls to to INSERT_STRING are made with consecutive
  371. input characters and the first MIN_MATCH bytes of str are valid
  372. (except for the last MIN_MATCH-1 bytes of the input file). }
  373. procedure INSERT_STRING(var s : deflate_state;
  374. str : uInt;
  375. var match_head : IPos);
  376. begin
  377. {$ifdef FASTEST}
  378. {UPDATE_HASH(s, s.ins_h, s.window[(str) + (MIN_MATCH-1)])}
  379. s.ins_h := ((s.ins_h shl s.hash_shift) xor
  380. (s.window^[(str) + (MIN_MATCH-1)])) and s.hash_mask;
  381. match_head := s.head[s.ins_h]
  382. s.head[s.ins_h] := Pos(str);
  383. {$else}
  384. {UPDATE_HASH(s, s.ins_h, s.window[(str) + (MIN_MATCH-1)])}
  385. s.ins_h := ((s.ins_h shl s.hash_shift) xor
  386. (s.window^[(str) + (MIN_MATCH-1)])) and s.hash_mask;
  387. match_head := s.head^[s.ins_h];
  388. s.prev^[(str) and s.w_mask] := match_head;
  389. s.head^[s.ins_h] := Pos(str);
  390. {$endif}
  391. end;
  392. { =========================================================================
  393. Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  394. prev[] will be initialized on the fly.
  395. macro CLEAR_HASH(s)
  396. s^.head[s^.hash_size-1] := ZNIL;
  397. zmemzero(pBytef(s^.head), unsigned(s^.hash_size-1)*sizeof(s^.head^[0]));
  398. }
  399. { ======================================================================== }
  400. function deflateInit2_(var strm : z_stream;
  401. level : int;
  402. method : int;
  403. windowBits : int;
  404. memLevel : int;
  405. strategy : int;
  406. const version : string;
  407. stream_size : int) : int;
  408. var
  409. s : deflate_state_ptr;
  410. noheader : int;
  411. overlay : pushfArray;
  412. { We overlay pending_buf and d_buf+l_buf. This works since the average
  413. output size for (length,distance) codes is <= 24 bits. }
  414. begin
  415. noheader := 0;
  416. if (version = '') or (version[1] <> ZLIB_VERSION[1]) or
  417. (stream_size <> sizeof(z_stream)) then
  418. begin
  419. deflateInit2_ := Z_VERSION_ERROR;
  420. exit;
  421. end;
  422. {
  423. if (strm = Z_NULL) then
  424. begin
  425. deflateInit2_ := Z_STREAM_ERROR;
  426. exit;
  427. end;
  428. }
  429. { SetLength(strm.msg, 255); }
  430. strm.msg := '';
  431. if not Assigned(strm.zalloc) then
  432. begin
  433. {$ifdef fpc}
  434. strm.zalloc := @zcalloc;
  435. {$else}
  436. strm.zalloc := zcalloc;
  437. {$endif}
  438. strm.opaque := voidpf(0);
  439. end;
  440. if not Assigned(strm.zfree) then
  441. {$ifdef fpc}
  442. strm.zfree := @zcfree;
  443. {$else}
  444. strm.zfree := zcfree;
  445. {$endif}
  446. if (level = Z_DEFAULT_COMPRESSION) then
  447. level := 6;
  448. {$ifdef FASTEST}
  449. level := 1;
  450. {$endif}
  451. if (windowBits < 0) then { undocumented feature: suppress zlib header }
  452. begin
  453. noheader := 1;
  454. windowBits := -windowBits;
  455. end;
  456. if (memLevel < 1) or (memLevel > MAX_MEM_LEVEL) or (method <> Z_DEFLATED)
  457. or (windowBits < 8) or (windowBits > 15) or (level < 0)
  458. or (level > 9) or (strategy < 0) or (strategy > Z_HUFFMAN_ONLY) then
  459. begin
  460. deflateInit2_ := Z_STREAM_ERROR;
  461. exit;
  462. end;
  463. s := deflate_state_ptr (ZALLOC(strm, 1, sizeof(deflate_state)));
  464. if (s = Z_NULL) then
  465. begin
  466. deflateInit2_ := Z_MEM_ERROR;
  467. exit;
  468. end;
  469. strm.state := pInternal_state(s);
  470. s^.strm := @strm;
  471. s^.noheader := noheader;
  472. s^.w_bits := windowBits;
  473. s^.w_size := 1 shl s^.w_bits;
  474. s^.w_mask := s^.w_size - 1;
  475. s^.hash_bits := memLevel + 7;
  476. s^.hash_size := 1 shl s^.hash_bits;
  477. s^.hash_mask := s^.hash_size - 1;
  478. s^.hash_shift := ((s^.hash_bits+MIN_MATCH-1) div MIN_MATCH);
  479. s^.window := pzByteArray (ZALLOC(strm, s^.w_size, 2*sizeof(Byte)));
  480. s^.prev := pzPosfArray (ZALLOC(strm, s^.w_size, sizeof(Pos)));
  481. s^.head := pzPosfArray (ZALLOC(strm, s^.hash_size, sizeof(Pos)));
  482. s^.lit_bufsize := 1 shl (memLevel + 6); { 16K elements by default }
  483. overlay := pushfArray (ZALLOC(strm, s^.lit_bufsize, sizeof(ush)+2));
  484. s^.pending_buf := pzByteArray (overlay);
  485. s^.pending_buf_size := ulg(s^.lit_bufsize) * (sizeof(ush)+Long(2));
  486. if (s^.window = Z_NULL) or (s^.prev = Z_NULL) or (s^.head = Z_NULL)
  487. or (s^.pending_buf = Z_NULL) then
  488. begin
  489. {ERR_MSG(Z_MEM_ERROR);}
  490. strm.msg := z_errmsg[z_errbase-Z_MEM_ERROR];
  491. deflateEnd (strm);
  492. deflateInit2_ := Z_MEM_ERROR;
  493. exit;
  494. end;
  495. s^.d_buf := pushfArray( @overlay^[s^.lit_bufsize div sizeof(ush)] );
  496. s^.l_buf := puchfArray( @s^.pending_buf^[(1+sizeof(ush))*s^.lit_bufsize] );
  497. s^.level := level;
  498. s^.strategy := strategy;
  499. s^.method := Byte(method);
  500. deflateInit2_ := deflateReset(strm);
  501. end;
  502. { ========================================================================= }
  503. function deflateInit2(var strm : z_stream;
  504. level : int;
  505. method : int;
  506. windowBits : int;
  507. memLevel : int;
  508. strategy : int) : int;
  509. { a macro }
  510. begin
  511. deflateInit2 := deflateInit2_(strm, level, method, windowBits,
  512. memLevel, strategy, ZLIB_VERSION, sizeof(z_stream));
  513. end;
  514. { ========================================================================= }
  515. function deflateInit_(strm : z_streamp;
  516. level : int;
  517. const version : string;
  518. stream_size : int) : int;
  519. begin
  520. if (strm = Z_NULL) then
  521. deflateInit_ := Z_STREAM_ERROR
  522. else
  523. deflateInit_ := deflateInit2_(strm^, level, Z_DEFLATED, MAX_WBITS,
  524. DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size);
  525. { To do: ignore strm^.next_in if we use it as window }
  526. end;
  527. { ========================================================================= }
  528. function deflateInit(var strm : z_stream; level : int) : int;
  529. { deflateInit is a macro to allow checking the zlib version
  530. and the compiler's view of z_stream: }
  531. begin
  532. deflateInit := deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS,
  533. DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, sizeof(z_stream));
  534. end;
  535. { ======================================================================== }
  536. function deflateSetDictionary (var strm : z_stream;
  537. dictionary : pBytef;
  538. dictLength : uInt) : int;
  539. var
  540. s : deflate_state_ptr;
  541. length : uInt;
  542. n : uInt;
  543. hash_head : IPos;
  544. var
  545. MAX_DIST : uInt; {macro}
  546. begin
  547. length := dictLength;
  548. hash_head := 0;
  549. if {(@strm = Z_NULL) or}
  550. (strm.state = Z_NULL) or (dictionary = Z_NULL)
  551. or (deflate_state_ptr(strm.state)^.status <> INIT_STATE) then
  552. begin
  553. deflateSetDictionary := Z_STREAM_ERROR;
  554. exit;
  555. end;
  556. s := deflate_state_ptr(strm.state);
  557. strm.adler := adler32(strm.adler, dictionary, dictLength);
  558. if (length < MIN_MATCH) then
  559. begin
  560. deflateSetDictionary := Z_OK;
  561. exit;
  562. end;
  563. MAX_DIST := (s^.w_size - MIN_LOOKAHEAD);
  564. if (length > MAX_DIST) then
  565. begin
  566. length := MAX_DIST;
  567. {$ifndef USE_DICT_HEAD}
  568. Inc(dictionary, dictLength - length); { use the tail of the dictionary }
  569. {$endif}
  570. end;
  571. zmemcpy( pBytef(s^.window), dictionary, length);
  572. s^.strstart := length;
  573. s^.block_start := long(length);
  574. { Insert all strings in the hash table (except for the last two bytes).
  575. s^.lookahead stays null, so s^.ins_h will be recomputed at the next
  576. call of fill_window. }
  577. s^.ins_h := s^.window^[0];
  578. {UPDATE_HASH(s, s^.ins_h, s^.window[1]);}
  579. s^.ins_h := ((s^.ins_h shl s^.hash_shift) xor (s^.window^[1]))
  580. and s^.hash_mask;
  581. for n := 0 to length - MIN_MATCH do
  582. begin
  583. INSERT_STRING(s^, n, hash_head);
  584. end;
  585. {if (hash_head <> 0) then
  586. hash_head := 0; - to make compiler happy }
  587. deflateSetDictionary := Z_OK;
  588. end;
  589. { ======================================================================== }
  590. function deflateReset (var strm : z_stream) : int;
  591. var
  592. s : deflate_state_ptr;
  593. begin
  594. if {(@strm = Z_NULL) or}
  595. (strm.state = Z_NULL)
  596. or (not Assigned(strm.zalloc)) or (not Assigned(strm.zfree)) then
  597. begin
  598. deflateReset := Z_STREAM_ERROR;
  599. exit;
  600. end;
  601. strm.total_out := 0;
  602. strm.total_in := 0;
  603. strm.msg := ''; { use zfree if we ever allocate msg dynamically }
  604. strm.data_type := Z_UNKNOWN;
  605. s := deflate_state_ptr(strm.state);
  606. s^.pending := 0;
  607. s^.pending_out := pBytef(s^.pending_buf);
  608. if (s^.noheader < 0) then
  609. begin
  610. s^.noheader := 0; { was set to -1 by deflate(..., Z_FINISH); }
  611. end;
  612. if s^.noheader <> 0 then
  613. s^.status := BUSY_STATE
  614. else
  615. s^.status := INIT_STATE;
  616. strm.adler := 1;
  617. s^.last_flush := Z_NO_FLUSH;
  618. _tr_init(s^);
  619. lm_init(s^);
  620. deflateReset := Z_OK;
  621. end;
  622. { ======================================================================== }
  623. function deflateParams(var strm : z_stream;
  624. level : int;
  625. strategy : int) : int;
  626. var
  627. s : deflate_state_ptr;
  628. func : compress_func;
  629. err : int;
  630. begin
  631. err := Z_OK;
  632. if {(@strm = Z_NULL) or} (strm.state = Z_NULL) then
  633. begin
  634. deflateParams := Z_STREAM_ERROR;
  635. exit;
  636. end;
  637. s := deflate_state_ptr(strm.state);
  638. if (level = Z_DEFAULT_COMPRESSION) then
  639. begin
  640. level := 6;
  641. end;
  642. if (level < 0) or (level > 9) or (strategy < 0)
  643. or (strategy > Z_HUFFMAN_ONLY) then
  644. begin
  645. deflateParams := Z_STREAM_ERROR;
  646. exit;
  647. end;
  648. func := configuration_table[s^.level].func;
  649. if (@func <> @configuration_table[level].func)
  650. and (strm.total_in <> 0) then
  651. begin
  652. { Flush the last buffer: }
  653. err := deflate(strm, Z_PARTIAL_FLUSH);
  654. end;
  655. if (s^.level <> level) then
  656. begin
  657. s^.level := level;
  658. s^.max_lazy_match := configuration_table[level].max_lazy;
  659. s^.good_match := configuration_table[level].good_length;
  660. s^.nice_match := configuration_table[level].nice_length;
  661. s^.max_chain_length := configuration_table[level].max_chain;
  662. end;
  663. s^.strategy := strategy;
  664. deflateParams := err;
  665. end;
  666. { =========================================================================
  667. Put a short in the pending buffer. The 16-bit value is put in MSB order.
  668. IN assertion: the stream state is correct and there is enough room in
  669. pending_buf. }
  670. {local}
  671. procedure putShortMSB (var s : deflate_state; b : uInt);
  672. begin
  673. s.pending_buf^[s.pending] := Byte(b shr 8);
  674. Inc(s.pending);
  675. s.pending_buf^[s.pending] := Byte(b and $ff);
  676. Inc(s.pending);
  677. end;
  678. { =========================================================================
  679. Flush as much pending output as possible. All deflate() output goes
  680. through this function so some applications may wish to modify it
  681. to avoid allocating a large strm^.next_out buffer and copying into it.
  682. (See also read_buf()). }
  683. {local}
  684. procedure flush_pending(var strm : z_stream);
  685. var
  686. len : unsigned;
  687. s : deflate_state_ptr;
  688. begin
  689. s := deflate_state_ptr(strm.state);
  690. len := s^.pending;
  691. if (len > strm.avail_out) then
  692. len := strm.avail_out;
  693. if (len = 0) then
  694. exit;
  695. zmemcpy(strm.next_out, s^.pending_out, len);
  696. Inc(strm.next_out, len);
  697. Inc(s^.pending_out, len);
  698. Inc(strm.total_out, len);
  699. Dec(strm.avail_out, len);
  700. Dec(s^.pending, len);
  701. if (s^.pending = 0) then
  702. begin
  703. s^.pending_out := pBytef(s^.pending_buf);
  704. end;
  705. end;
  706. { ========================================================================= }
  707. function deflate (var strm : z_stream; flush : int) : int;
  708. var
  709. old_flush : int; { value of flush param for previous deflate call }
  710. s : deflate_state_ptr;
  711. var
  712. header : uInt;
  713. level_flags : uInt;
  714. var
  715. bstate : block_state;
  716. begin
  717. if {(@strm = Z_NULL) or} (strm.state = Z_NULL)
  718. or (flush > Z_FINISH) or (flush < 0) then
  719. begin
  720. deflate := Z_STREAM_ERROR;
  721. exit;
  722. end;
  723. s := deflate_state_ptr(strm.state);
  724. if (strm.next_out = Z_NULL) or
  725. ((strm.next_in = Z_NULL) and (strm.avail_in <> 0)) or
  726. ((s^.status = FINISH_STATE) and (flush <> Z_FINISH)) then
  727. begin
  728. {ERR_RETURN(strm^, Z_STREAM_ERROR);}
  729. strm.msg := z_errmsg[z_errbase - Z_STREAM_ERROR];
  730. deflate := Z_STREAM_ERROR;
  731. exit;
  732. end;
  733. if (strm.avail_out = 0) then
  734. begin
  735. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  736. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  737. deflate := Z_BUF_ERROR;
  738. exit;
  739. end;
  740. s^.strm := @strm; { just in case }
  741. old_flush := s^.last_flush;
  742. s^.last_flush := flush;
  743. { Write the zlib header }
  744. if (s^.status = INIT_STATE) then
  745. begin
  746. header := (Z_DEFLATED + ((s^.w_bits-8) shl 4)) shl 8;
  747. level_flags := (s^.level-1) shr 1;
  748. if (level_flags > 3) then
  749. level_flags := 3;
  750. header := header or (level_flags shl 6);
  751. if (s^.strstart <> 0) then
  752. header := header or PRESET_DICT;
  753. Inc(header, 31 - (header mod 31));
  754. s^.status := BUSY_STATE;
  755. putShortMSB(s^, header);
  756. { Save the adler32 of the preset dictionary: }
  757. if (s^.strstart <> 0) then
  758. begin
  759. putShortMSB(s^, uInt(strm.adler shr 16));
  760. putShortMSB(s^, uInt(strm.adler and $ffff));
  761. end;
  762. strm.adler := long(1);
  763. end;
  764. { Flush as much pending output as possible }
  765. if (s^.pending <> 0) then
  766. begin
  767. flush_pending(strm);
  768. if (strm.avail_out = 0) then
  769. begin
  770. { Since avail_out is 0, deflate will be called again with
  771. more output space, but possibly with both pending and
  772. avail_in equal to zero. There won't be anything to do,
  773. but this is not an error situation so make sure we
  774. return OK instead of BUF_ERROR at next call of deflate: }
  775. s^.last_flush := -1;
  776. deflate := Z_OK;
  777. exit;
  778. end;
  779. { Make sure there is something to do and avoid duplicate consecutive
  780. flushes. For repeated and useless calls with Z_FINISH, we keep
  781. returning Z_STREAM_END instead of Z_BUFF_ERROR. }
  782. end
  783. else
  784. if (strm.avail_in = 0) and (flush <= old_flush)
  785. and (flush <> Z_FINISH) then
  786. begin
  787. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  788. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  789. deflate := Z_BUF_ERROR;
  790. exit;
  791. end;
  792. { User must not provide more input after the first FINISH: }
  793. if (s^.status = FINISH_STATE) and (strm.avail_in <> 0) then
  794. begin
  795. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  796. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  797. deflate := Z_BUF_ERROR;
  798. exit;
  799. end;
  800. { Start a new block or continue the current one. }
  801. if (strm.avail_in <> 0) or (s^.lookahead <> 0)
  802. or ((flush <> Z_NO_FLUSH) and (s^.status <> FINISH_STATE)) then
  803. begin
  804. bstate := configuration_table[s^.level].func(s^, flush);
  805. if (bstate = finish_started) or (bstate = finish_done) then
  806. s^.status := FINISH_STATE;
  807. if (bstate = need_more) or (bstate = finish_started) then
  808. begin
  809. if (strm.avail_out = 0) then
  810. s^.last_flush := -1; { avoid BUF_ERROR next call, see above }
  811. deflate := Z_OK;
  812. exit;
  813. { If flush != Z_NO_FLUSH && avail_out == 0, the next call
  814. of deflate should use the same flush parameter to make sure
  815. that the flush is complete. So we don't have to output an
  816. empty block here, this will be done at next call. This also
  817. ensures that for a very small output buffer, we emit at most
  818. one empty block. }
  819. end;
  820. if (bstate = block_done) then
  821. begin
  822. if (flush = Z_PARTIAL_FLUSH) then
  823. _tr_align(s^)
  824. else
  825. begin { FULL_FLUSH or SYNC_FLUSH }
  826. _tr_stored_block(s^, pcharf(NIL), Long(0), FALSE);
  827. { For a full flush, this empty block will be recognized
  828. as a special marker by inflate_sync(). }
  829. if (flush = Z_FULL_FLUSH) then
  830. begin
  831. {macro CLEAR_HASH(s);} { forget history }
  832. s^.head^[s^.hash_size-1] := ZNIL;
  833. zmemzero(pBytef(s^.head), unsigned(s^.hash_size-1)*sizeof(s^.head^[0]));
  834. end;
  835. end;
  836. flush_pending(strm);
  837. if (strm.avail_out = 0) then
  838. begin
  839. s^.last_flush := -1; { avoid BUF_ERROR at next call, see above }
  840. deflate := Z_OK;
  841. exit;
  842. end;
  843. end;
  844. end;
  845. {$IFDEF DEBUG}
  846. Assert(strm.avail_out > 0, 'bug2');
  847. {$ENDIF}
  848. if (flush <> Z_FINISH) then
  849. begin
  850. deflate := Z_OK;
  851. exit;
  852. end;
  853. if (s^.noheader <> 0) then
  854. begin
  855. deflate := Z_STREAM_END;
  856. exit;
  857. end;
  858. { Write the zlib trailer (adler32) }
  859. putShortMSB(s^, uInt(strm.adler shr 16));
  860. putShortMSB(s^, uInt(strm.adler and $ffff));
  861. flush_pending(strm);
  862. { If avail_out is zero, the application will call deflate again
  863. to flush the rest. }
  864. s^.noheader := -1; { write the trailer only once! }
  865. if s^.pending <> 0 then
  866. deflate := Z_OK
  867. else
  868. deflate := Z_STREAM_END;
  869. end;
  870. { ========================================================================= }
  871. function deflateEnd (var strm : z_stream) : int;
  872. var
  873. status : int;
  874. s : deflate_state_ptr;
  875. begin
  876. if {(@strm = Z_NULL) or} (strm.state = Z_NULL) then
  877. begin
  878. deflateEnd := Z_STREAM_ERROR;
  879. exit;
  880. end;
  881. s := deflate_state_ptr(strm.state);
  882. status := s^.status;
  883. if (status <> INIT_STATE) and (status <> BUSY_STATE) and
  884. (status <> FINISH_STATE) then
  885. begin
  886. deflateEnd := Z_STREAM_ERROR;
  887. exit;
  888. end;
  889. { Deallocate in reverse order of allocations: }
  890. TRY_FREE(strm, s^.pending_buf);
  891. TRY_FREE(strm, s^.head);
  892. TRY_FREE(strm, s^.prev);
  893. TRY_FREE(strm, s^.window);
  894. ZFREE(strm, s);
  895. strm.state := Z_NULL;
  896. if status = BUSY_STATE then
  897. deflateEnd := Z_DATA_ERROR
  898. else
  899. deflateEnd := Z_OK;
  900. end;
  901. { =========================================================================
  902. Copy the source state to the destination state.
  903. To simplify the source, this is not supported for 16-bit MSDOS (which
  904. doesn't have enough memory anyway to duplicate compression states). }
  905. { ========================================================================= }
  906. function deflateCopy (dest, source : z_streamp) : int;
  907. {$ifndef MAXSEG_64K}
  908. var
  909. ds : deflate_state_ptr;
  910. ss : deflate_state_ptr;
  911. overlay : pushfArray;
  912. {$endif}
  913. begin
  914. {$ifdef MAXSEG_64K}
  915. deflateCopy := Z_STREAM_ERROR;
  916. exit;
  917. {$else}
  918. if (source = Z_NULL) or (dest = Z_NULL) or (source^.state = Z_NULL) then
  919. begin
  920. deflateCopy := Z_STREAM_ERROR;
  921. exit;
  922. end;
  923. ss := deflate_state_ptr(source^.state);
  924. dest^ := source^;
  925. ds := deflate_state_ptr( ZALLOC(dest^, 1, sizeof(deflate_state)) );
  926. if (ds = Z_NULL) then
  927. begin
  928. deflateCopy := Z_MEM_ERROR;
  929. exit;
  930. end;
  931. dest^.state := pInternal_state(ds);
  932. ds^ := ss^;
  933. ds^.strm := dest;
  934. ds^.window := pzByteArray ( ZALLOC(dest^, ds^.w_size, 2*sizeof(Byte)) );
  935. ds^.prev := pzPosfArray ( ZALLOC(dest^, ds^.w_size, sizeof(Pos)) );
  936. ds^.head := pzPosfArray ( ZALLOC(dest^, ds^.hash_size, sizeof(Pos)) );
  937. overlay := pushfArray ( ZALLOC(dest^, ds^.lit_bufsize, sizeof(ush)+2) );
  938. ds^.pending_buf := pzByteArray ( overlay );
  939. if (ds^.window = Z_NULL) or (ds^.prev = Z_NULL) or (ds^.head = Z_NULL)
  940. or (ds^.pending_buf = Z_NULL) then
  941. begin
  942. deflateEnd (dest^);
  943. deflateCopy := Z_MEM_ERROR;
  944. exit;
  945. end;
  946. { following zmemcpy do not work for 16-bit MSDOS }
  947. zmemcpy(pBytef(ds^.window), pBytef(ss^.window), ds^.w_size * 2 * sizeof(Byte));
  948. zmemcpy(pBytef(ds^.prev), pBytef(ss^.prev), ds^.w_size * sizeof(Pos));
  949. zmemcpy(pBytef(ds^.head), pBytef(ss^.head), ds^.hash_size * sizeof(Pos));
  950. zmemcpy(pBytef(ds^.pending_buf), pBytef(ss^.pending_buf), uInt(ds^.pending_buf_size));
  951. ds^.pending_out := @ds^.pending_buf^[ptr2int(ss^.pending_out) - ptr2int(ss^.pending_buf)];
  952. ds^.d_buf := pushfArray (@overlay^[ds^.lit_bufsize div sizeof(ush)] );
  953. ds^.l_buf := puchfArray (@ds^.pending_buf^[(1+sizeof(ush))*ds^.lit_bufsize]);
  954. ds^.l_desc.dyn_tree := tree_ptr(@ds^.dyn_ltree);
  955. ds^.d_desc.dyn_tree := tree_ptr(@ds^.dyn_dtree);
  956. ds^.bl_desc.dyn_tree := tree_ptr(@ds^.bl_tree);
  957. deflateCopy := Z_OK;
  958. {$endif}
  959. end;
  960. { ===========================================================================
  961. Read a new buffer from the current input stream, update the adler32
  962. and total number of bytes read. All deflate() input goes through
  963. this function so some applications may wish to modify it to avoid
  964. allocating a large strm^.next_in buffer and copying from it.
  965. (See also flush_pending()). }
  966. {local}
  967. function read_buf(strm : z_streamp; buf : pBytef; size : unsigned) : int;
  968. var
  969. len : unsigned;
  970. begin
  971. len := strm^.avail_in;
  972. if (len > size) then
  973. len := size;
  974. if (len = 0) then
  975. begin
  976. read_buf := 0;
  977. exit;
  978. end;
  979. Dec(strm^.avail_in, len);
  980. if deflate_state_ptr(strm^.state)^.noheader = 0 then
  981. begin
  982. strm^.adler := adler32(strm^.adler, strm^.next_in, len);
  983. end;
  984. zmemcpy(buf, strm^.next_in, len);
  985. Inc(strm^.next_in, len);
  986. Inc(strm^.total_in, len);
  987. read_buf := int(len);
  988. end;
  989. { ===========================================================================
  990. Initialize the "longest match" routines for a new zlib stream }
  991. {local}
  992. procedure lm_init (var s : deflate_state);
  993. begin
  994. s.window_size := ulg( uLong(2)*s.w_size);
  995. {macro CLEAR_HASH(s);}
  996. s.head^[s.hash_size-1] := ZNIL;
  997. zmemzero(pBytef(s.head), unsigned(s.hash_size-1)*sizeof(s.head^[0]));
  998. { Set the default configuration parameters: }
  999. s.max_lazy_match := configuration_table[s.level].max_lazy;
  1000. s.good_match := configuration_table[s.level].good_length;
  1001. s.nice_match := configuration_table[s.level].nice_length;
  1002. s.max_chain_length := configuration_table[s.level].max_chain;
  1003. s.strstart := 0;
  1004. s.block_start := long(0);
  1005. s.lookahead := 0;
  1006. s.prev_length := MIN_MATCH-1;
  1007. s.match_length := MIN_MATCH-1;
  1008. s.match_available := FALSE;
  1009. s.ins_h := 0;
  1010. {$ifdef ASMV}
  1011. match_init; { initialize the asm code }
  1012. {$endif}
  1013. end;
  1014. { ===========================================================================
  1015. Set match_start to the longest match starting at the given string and
  1016. return its length. Matches shorter or equal to prev_length are discarded,
  1017. in which case the result is equal to prev_length and match_start is
  1018. garbage.
  1019. IN assertions: cur_match is the head of the hash chain for the current
  1020. string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1021. OUT assertion: the match length is not greater than s^.lookahead. }
  1022. {$ifndef ASMV}
  1023. { For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1024. match.S. The code will be functionally equivalent. }
  1025. {$ifndef FASTEST}
  1026. {local}
  1027. function longest_match(var s : deflate_state;
  1028. cur_match : IPos { current match }
  1029. ) : uInt;
  1030. label
  1031. nextstep;
  1032. var
  1033. chain_length : unsigned; { max hash chain length }
  1034. {register} scan : pBytef; { current string }
  1035. {register} match : pBytef; { matched string }
  1036. {register} len : int; { length of current match }
  1037. best_len : int; { best match length so far }
  1038. nice_match : int; { stop if match long enough }
  1039. limit : IPos;
  1040. prev : pzPosfArray;
  1041. wmask : uInt;
  1042. {$ifdef UNALIGNED_OK}
  1043. {register} strend : pBytef;
  1044. {register} scan_start : ush;
  1045. {register} scan_end : ush;
  1046. {$else}
  1047. {register} strend : pBytef;
  1048. {register} scan_end1 : Byte;
  1049. {register} scan_end : Byte;
  1050. {$endif}
  1051. var
  1052. MAX_DIST : uInt;
  1053. begin
  1054. chain_length := s.max_chain_length; { max hash chain length }
  1055. scan := @(s.window^[s.strstart]);
  1056. best_len := s.prev_length; { best match length so far }
  1057. nice_match := s.nice_match; { stop if match long enough }
  1058. MAX_DIST := s.w_size - MIN_LOOKAHEAD;
  1059. {In order to simplify the code, particularly on 16 bit machines, match
  1060. distances are limited to MAX_DIST instead of WSIZE. }
  1061. if s.strstart > IPos(MAX_DIST) then
  1062. limit := s.strstart - IPos(MAX_DIST)
  1063. else
  1064. limit := ZNIL;
  1065. { Stop when cur_match becomes <= limit. To simplify the code,
  1066. we prevent matches with the string of window index 0. }
  1067. prev := s.prev;
  1068. wmask := s.w_mask;
  1069. {$ifdef UNALIGNED_OK}
  1070. { Compare two bytes at a time. Note: this is not always beneficial.
  1071. Try with and without -DUNALIGNED_OK to check. }
  1072. strend := pBytef(@(s.window^[s.strstart + MAX_MATCH - 1]));
  1073. scan_start := pushf(scan)^;
  1074. scan_end := pushfArray(scan)^[best_len-1]; { fix }
  1075. {$else}
  1076. strend := pBytef(@(s.window^[s.strstart + MAX_MATCH]));
  1077. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1078. scan_end1 := pzByteArray(scan)^[best_len-1];
  1079. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1080. scan_end := pzByteArray(scan)^[best_len];
  1081. {$endif}
  1082. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1083. It is easy to get rid of this optimization if necessary. }
  1084. {$IFDEF DEBUG}
  1085. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1086. {$ENDIF}
  1087. { Do not waste too much time if we already have a good match: }
  1088. if (s.prev_length >= s.good_match) then
  1089. begin
  1090. chain_length := chain_length shr 2;
  1091. end;
  1092. { Do not look for matches beyond the end of the input. This is necessary
  1093. to make deflate deterministic. }
  1094. if (uInt(nice_match) > s.lookahead) then
  1095. nice_match := s.lookahead;
  1096. {$IFDEF DEBUG}
  1097. Assert(ulg(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1098. {$ENDIF}
  1099. repeat
  1100. {$IFDEF DEBUG}
  1101. Assert(cur_match < s.strstart, 'no future');
  1102. {$ENDIF}
  1103. match := @(s.window^[cur_match]);
  1104. { Skip to next match if the match length cannot increase
  1105. or if the match length is less than 2: }
  1106. {$undef DO_UNALIGNED_OK}
  1107. {$ifdef UNALIGNED_OK}
  1108. {$ifdef MAX_MATCH_IS_258}
  1109. {$define DO_UNALIGNED_OK}
  1110. {$endif}
  1111. {$endif}
  1112. {$ifdef DO_UNALIGNED_OK}
  1113. { This code assumes sizeof(unsigned short) = 2. Do not use
  1114. UNALIGNED_OK if your compiler uses a different size. }
  1115. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1116. if (pushfArray(match)^[best_len-1] <> scan_end) or
  1117. (pushf(match)^ <> scan_start) then
  1118. goto nextstep; {continue;}
  1119. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1120. { It is not necessary to compare scan[2] and match[2] since they are
  1121. always equal when the other bytes match, given that the hash keys
  1122. are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1123. strstart+3, +5, ... up to strstart+257. We check for insufficient
  1124. lookahead only every 4th comparison; the 128th check will be made
  1125. at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1126. necessary to put more guard bytes at the end of the window, or
  1127. to check more often for insufficient lookahead. }
  1128. {$IFDEF DEBUG}
  1129. Assert(pzByteArray(scan)^[2] = pzByteArray(match)^[2], 'scan[2]?');
  1130. {$ENDIF}
  1131. Inc(scan);
  1132. Inc(match);
  1133. repeat
  1134. Inc(scan,2); Inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1135. Inc(scan,2); Inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1136. Inc(scan,2); Inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1137. Inc(scan,2); Inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1138. until (ptr2int(scan) >= ptr2int(strend));
  1139. { The funny "do while" generates better code on most compilers }
  1140. { Here, scan <= window+strstart+257 }
  1141. {$IFDEF DEBUG}
  1142. Assert(ptr2int(scan) <=
  1143. ptr2int(@(s.window^[unsigned(s.window_size-1)])),
  1144. 'wild scan');
  1145. {$ENDIF}
  1146. if (scan^ = match^) then
  1147. Inc(scan);
  1148. len := (MAX_MATCH - 1) - int(ptr2int(strend)-ptr2int(scan));
  1149. scan := strend;
  1150. Dec(scan, (MAX_MATCH-1));
  1151. {$else} { UNALIGNED_OK }
  1152. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1153. if (pzByteArray(match)^[best_len] <> scan_end) or
  1154. (pzByteArray(match)^[best_len-1] <> scan_end1) or
  1155. (match^ <> scan^) then
  1156. goto nextstep; {continue;}
  1157. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1158. Inc(match);
  1159. if (match^ <> pzByteArray(scan)^[1]) then
  1160. goto nextstep; {continue;}
  1161. { The check at best_len-1 can be removed because it will be made
  1162. again later. (This heuristic is not always a win.)
  1163. It is not necessary to compare scan[2] and match[2] since they
  1164. are always equal when the other bytes match, given that
  1165. the hash keys are equal and that HASH_BITS >= 8. }
  1166. Inc(scan, 2);
  1167. Inc(match);
  1168. {$IFDEF DEBUG}
  1169. Assert( scan^ = match^, 'match[2]?');
  1170. {$ENDIF}
  1171. { We check for insufficient lookahead only every 8th comparison;
  1172. the 256th check will be made at strstart+258. }
  1173. repeat
  1174. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1175. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1176. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1177. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1178. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1179. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1180. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1181. Inc(scan); Inc(match); if (scan^ <> match^) then break;
  1182. until (ptr2int(scan) >= ptr2int(strend));
  1183. {$IFDEF DEBUG}
  1184. Assert(ptr2int(scan) <=
  1185. ptr2int(@(s.window^[unsigned(s.window_size-1)])),
  1186. 'wild scan');
  1187. {$ENDIF}
  1188. len := MAX_MATCH - int(ptr2int(strend) - ptr2int(scan));
  1189. scan := strend;
  1190. Dec(scan, MAX_MATCH);
  1191. {$endif} { UNALIGNED_OK }
  1192. if (len > best_len) then
  1193. begin
  1194. s.match_start := cur_match;
  1195. best_len := len;
  1196. if (len >= nice_match) then
  1197. break;
  1198. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1199. {$ifdef UNALIGNED_OK}
  1200. scan_end := pzByteArray(scan)^[best_len-1];
  1201. {$else}
  1202. scan_end1 := pzByteArray(scan)^[best_len-1];
  1203. scan_end := pzByteArray(scan)^[best_len];
  1204. {$endif}
  1205. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1206. end;
  1207. nextstep:
  1208. cur_match := prev^[cur_match and wmask];
  1209. Dec(chain_length);
  1210. until (cur_match <= limit) or (chain_length = 0);
  1211. if (uInt(best_len) <= s.lookahead) then
  1212. longest_match := uInt(best_len)
  1213. else
  1214. longest_match := s.lookahead;
  1215. end;
  1216. {$endif} { ASMV }
  1217. {$else} { FASTEST }
  1218. { ---------------------------------------------------------------------------
  1219. Optimized version for level = 1 only }
  1220. {local}
  1221. function longest_match(var s : deflate_state;
  1222. cur_match : IPos { current match }
  1223. ) : uInt;
  1224. var
  1225. {register} scan : pBytef; { current string }
  1226. {register} match : pBytef; { matched string }
  1227. {register} len : int; { length of current match }
  1228. {register} strend : pBytef;
  1229. begin
  1230. scan := @s.window^[s.strstart];
  1231. strend := @s.window^[s.strstart + MAX_MATCH];
  1232. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1233. It is easy to get rid of this optimization if necessary. }
  1234. {$IFDEF DEBUG}
  1235. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1236. Assert(ulg(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1237. Assert(cur_match < s.strstart, 'no future');
  1238. {$ENDIF}
  1239. match := s.window + cur_match;
  1240. { Return failure if the match length is less than 2: }
  1241. if (match[0] <> scan[0]) or (match[1] <> scan[1]) then
  1242. begin
  1243. longest_match := MIN_MATCH-1;
  1244. exit;
  1245. end;
  1246. { The check at best_len-1 can be removed because it will be made
  1247. again later. (This heuristic is not always a win.)
  1248. It is not necessary to compare scan[2] and match[2] since they
  1249. are always equal when the other bytes match, given that
  1250. the hash keys are equal and that HASH_BITS >= 8. }
  1251. scan += 2, match += 2;
  1252. Assert(scan^ = match^, 'match[2]?');
  1253. { We check for insufficient lookahead only every 8th comparison;
  1254. the 256th check will be made at strstart+258. }
  1255. repeat
  1256. Inc(scan); Inc(match); if scan^<>match^ then break;
  1257. Inc(scan); Inc(match); if scan^<>match^ then break;
  1258. Inc(scan); Inc(match); if scan^<>match^ then break;
  1259. Inc(scan); Inc(match); if scan^<>match^ then break;
  1260. Inc(scan); Inc(match); if scan^<>match^ then break;
  1261. Inc(scan); Inc(match); if scan^<>match^ then break;
  1262. Inc(scan); Inc(match); if scan^<>match^ then break;
  1263. Inc(scan); Inc(match); if scan^<>match^ then break;
  1264. until (ptr2int(scan) >= ptr2int(strend));
  1265. Assert(scan <= s.window+unsigned(s.window_size-1), 'wild scan');
  1266. len := MAX_MATCH - int(strend - scan);
  1267. if (len < MIN_MATCH) then
  1268. begin
  1269. return := MIN_MATCH - 1;
  1270. exit;
  1271. end;
  1272. s.match_start := cur_match;
  1273. if len <= s.lookahead then
  1274. longest_match := len
  1275. else
  1276. longest_match := s.lookahead;
  1277. end;
  1278. {$endif} { FASTEST }
  1279. {$ifdef DEBUG}
  1280. { ===========================================================================
  1281. Check that the match at match_start is indeed a match. }
  1282. {local}
  1283. procedure check_match(var s : deflate_state;
  1284. start, match : IPos;
  1285. length : int);
  1286. begin
  1287. exit;
  1288. { check that the match is indeed a match }
  1289. if (zmemcmp(pBytef(@s.window^[match]),
  1290. pBytef(@s.window^[start]), length) <> EQUAL) then
  1291. begin
  1292. WriteLn(' start ',start,', match ',match ,' length ', length);
  1293. repeat
  1294. Write(char(s.window^[match]), char(s.window^[start]));
  1295. Inc(match);
  1296. Inc(start);
  1297. Dec(length);
  1298. Until (length = 0);
  1299. z_error('invalid match');
  1300. end;
  1301. if (z_verbose > 1) then
  1302. begin
  1303. Write('\\[',start-match,',',length,']');
  1304. repeat
  1305. Write(char(s.window^[start]));
  1306. Inc(start);
  1307. Dec(length);
  1308. Until (length = 0);
  1309. end;
  1310. end;
  1311. {$endif}
  1312. { ===========================================================================
  1313. Fill the window when the lookahead becomes insufficient.
  1314. Updates strstart and lookahead.
  1315. IN assertion: lookahead < MIN_LOOKAHEAD
  1316. OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1317. At least one byte has been read, or avail_in = 0; reads are
  1318. performed for at least two bytes (required for the zip translate_eol
  1319. option -- not supported here). }
  1320. {local}
  1321. procedure fill_window(var s : deflate_state);
  1322. var
  1323. {register} n, m : unsigned;
  1324. {register} p : pPosf;
  1325. more : unsigned; { Amount of free space at the end of the window. }
  1326. wsize : uInt;
  1327. begin
  1328. wsize := s.w_size;
  1329. repeat
  1330. more := unsigned(s.window_size -ulg(s.lookahead) -ulg(s.strstart));
  1331. { Deal with !@#$% 64K limit: }
  1332. if (more = 0) and (s.strstart = 0) and (s.lookahead = 0) then
  1333. more := wsize
  1334. else
  1335. if (more = unsigned(-1)) then
  1336. begin
  1337. { Very unlikely, but possible on 16 bit machine if strstart = 0
  1338. and lookahead = 1 (input done one byte at time) }
  1339. Dec(more);
  1340. { If the window is almost full and there is insufficient lookahead,
  1341. move the upper half to the lower one to make room in the upper half.}
  1342. end
  1343. else
  1344. if (s.strstart >= wsize+ {MAX_DIST}wsize-MIN_LOOKAHEAD) then
  1345. begin
  1346. zmemcpy( pBytef(s.window), pBytef(@(s.window^[wsize])),
  1347. unsigned(wsize));
  1348. Dec(s.match_start, wsize);
  1349. Dec(s.strstart, wsize); { we now have strstart >= MAX_DIST }
  1350. Dec(s.block_start, long(wsize));
  1351. { Slide the hash table (could be avoided with 32 bit values
  1352. at the expense of memory usage). We slide even when level = 0
  1353. to keep the hash table consistent if we switch back to level > 0
  1354. later. (Using level 0 permanently is not an optimal usage of
  1355. zlib, so we don't care about this pathological case.) }
  1356. n := s.hash_size;
  1357. p := @s.head^[n];
  1358. repeat
  1359. Dec(p);
  1360. m := p^;
  1361. if (m >= wsize) then
  1362. p^ := Pos(m-wsize)
  1363. else
  1364. p^ := Pos(ZNIL);
  1365. Dec(n);
  1366. Until (n=0);
  1367. n := wsize;
  1368. {$ifndef FASTEST}
  1369. p := @s.prev^[n];
  1370. repeat
  1371. Dec(p);
  1372. m := p^;
  1373. if (m >= wsize) then
  1374. p^ := Pos(m-wsize)
  1375. else
  1376. p^:= Pos(ZNIL);
  1377. { If n is not on any hash chain, prev^[n] is garbage but
  1378. its value will never be used. }
  1379. Dec(n);
  1380. Until (n=0);
  1381. {$endif}
  1382. Inc(more, wsize);
  1383. end;
  1384. if (s.strm^.avail_in = 0) then
  1385. exit;
  1386. {* If there was no sliding:
  1387. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1388. * more == window_size - lookahead - strstart
  1389. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1390. * => more >= window_size - 2*WSIZE + 2
  1391. * In the BIG_MEM or MMAP case (not yet supported),
  1392. * window_size == input_size + MIN_LOOKAHEAD &&
  1393. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1394. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1395. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. }
  1396. {$IFDEF DEBUG}
  1397. Assert(more >= 2, 'more < 2');
  1398. {$ENDIF}
  1399. n := read_buf(s.strm, pBytef(@(s.window^[s.strstart + s.lookahead])),
  1400. more);
  1401. Inc(s.lookahead, n);
  1402. { Initialize the hash value now that we have some input: }
  1403. if (s.lookahead >= MIN_MATCH) then
  1404. begin
  1405. s.ins_h := s.window^[s.strstart];
  1406. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1407. s.ins_h := ((s.ins_h shl s.hash_shift) xor s.window^[s.strstart+1])
  1408. and s.hash_mask;
  1409. {$ifdef MIN_MATCH <> 3}
  1410. Call UPDATE_HASH() MIN_MATCH-3 more times
  1411. {$endif}
  1412. end;
  1413. { If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1414. but this is not important since only literal bytes will be emitted. }
  1415. until (s.lookahead >= MIN_LOOKAHEAD) or (s.strm^.avail_in = 0);
  1416. end;
  1417. { ===========================================================================
  1418. Flush the current block, with given end-of-file flag.
  1419. IN assertion: strstart is set to the end of the current match. }
  1420. procedure FLUSH_BLOCK_ONLY(var s : deflate_state; eof : boolean); {macro}
  1421. begin
  1422. if (s.block_start >= Long(0)) then
  1423. _tr_flush_block(s, pcharf(@s.window^[unsigned(s.block_start)]),
  1424. ulg(long(s.strstart) - s.block_start), eof)
  1425. else
  1426. _tr_flush_block(s, pcharf(Z_NULL),
  1427. ulg(long(s.strstart) - s.block_start), eof);
  1428. s.block_start := s.strstart;
  1429. flush_pending(s.strm^);
  1430. {$IFDEF DEBUG}
  1431. Tracev('[FLUSH]');
  1432. {$ENDIF}
  1433. end;
  1434. { Same but force premature exit if necessary.
  1435. macro FLUSH_BLOCK(var s : deflate_state; eof : boolean) : boolean;
  1436. var
  1437. result : block_state;
  1438. begin
  1439. FLUSH_BLOCK_ONLY(s, eof);
  1440. if (s.strm^.avail_out = 0) then
  1441. begin
  1442. if eof then
  1443. result := finish_started
  1444. else
  1445. result := need_more;
  1446. exit;
  1447. end;
  1448. end;
  1449. }
  1450. { ===========================================================================
  1451. Copy without compression as much as possible from the input stream, return
  1452. the current block state.
  1453. This function does not insert new strings in the dictionary since
  1454. uncompressible data is probably not useful. This function is used
  1455. only for the level=0 compression option.
  1456. NOTE: this function should be optimized to avoid extra copying from
  1457. window to pending_buf. }
  1458. {local}
  1459. function deflate_stored(var s : deflate_state; flush : int) : block_state;
  1460. { Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1461. to pending_buf_size, and each stored block has a 5 byte header: }
  1462. var
  1463. max_block_size : ulg;
  1464. max_start : ulg;
  1465. begin
  1466. max_block_size := $ffff;
  1467. if (max_block_size > s.pending_buf_size - 5) then
  1468. max_block_size := s.pending_buf_size - 5;
  1469. { Copy as much as possible from input to output: }
  1470. while TRUE do
  1471. begin
  1472. { Fill the window as much as possible: }
  1473. if (s.lookahead <= 1) then
  1474. begin
  1475. {$IFDEF DEBUG}
  1476. Assert( (s.strstart < s.w_size + {MAX_DIST}s.w_size-MIN_LOOKAHEAD) or
  1477. (s.block_start >= long(s.w_size)), 'slide too late');
  1478. {$ENDIF}
  1479. fill_window(s);
  1480. if (s.lookahead = 0) and (flush = Z_NO_FLUSH) then
  1481. begin
  1482. deflate_stored := need_more;
  1483. exit;
  1484. end;
  1485. if (s.lookahead = 0) then
  1486. break; { flush the current block }
  1487. end;
  1488. {$IFDEF DEBUG}
  1489. Assert(s.block_start >= long(0), 'block gone');
  1490. {$ENDIF}
  1491. Inc(s.strstart, s.lookahead);
  1492. s.lookahead := 0;
  1493. { Emit a stored block if pending_buf will be full: }
  1494. max_start := s.block_start + max_block_size;
  1495. if (s.strstart = 0) or (ulg(s.strstart) >= max_start) then
  1496. begin
  1497. { strstart = 0 is possible when wraparound on 16-bit machine }
  1498. s.lookahead := uInt(s.strstart - max_start);
  1499. s.strstart := uInt(max_start);
  1500. {FLUSH_BLOCK(s, FALSE);}
  1501. FLUSH_BLOCK_ONLY(s, FALSE);
  1502. if (s.strm^.avail_out = 0) then
  1503. begin
  1504. deflate_stored := need_more;
  1505. exit;
  1506. end;
  1507. end;
  1508. { Flush if we may have to slide, otherwise block_start may become
  1509. negative and the data will be gone: }
  1510. if (s.strstart - uInt(s.block_start) >= {MAX_DIST}
  1511. s.w_size-MIN_LOOKAHEAD) then
  1512. begin
  1513. {FLUSH_BLOCK(s, FALSE);}
  1514. FLUSH_BLOCK_ONLY(s, FALSE);
  1515. if (s.strm^.avail_out = 0) then
  1516. begin
  1517. deflate_stored := need_more;
  1518. exit;
  1519. end;
  1520. end;
  1521. end;
  1522. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1523. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1524. if (s.strm^.avail_out = 0) then
  1525. begin
  1526. if flush = Z_FINISH then
  1527. deflate_stored := finish_started
  1528. else
  1529. deflate_stored := need_more;
  1530. exit;
  1531. end;
  1532. if flush = Z_FINISH then
  1533. deflate_stored := finish_done
  1534. else
  1535. deflate_stored := block_done;
  1536. end;
  1537. { ===========================================================================
  1538. Compress as much as possible from the input stream, return the current
  1539. block state.
  1540. This function does not perform lazy evaluation of matches and inserts
  1541. new strings in the dictionary only for unmatched strings or for short
  1542. matches. It is used only for the fast compression options. }
  1543. {local}
  1544. function deflate_fast(var s : deflate_state; flush : int) : block_state;
  1545. var
  1546. hash_head : IPos; { head of the hash chain }
  1547. bflush : boolean; { set if current block must be flushed }
  1548. begin
  1549. hash_head := ZNIL;
  1550. while TRUE do
  1551. begin
  1552. { Make sure that we always have enough lookahead, except
  1553. at the end of the input file. We need MAX_MATCH bytes
  1554. for the next match, plus MIN_MATCH bytes to insert the
  1555. string following the next match. }
  1556. if (s.lookahead < MIN_LOOKAHEAD) then
  1557. begin
  1558. fill_window(s);
  1559. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1560. begin
  1561. deflate_fast := need_more;
  1562. exit;
  1563. end;
  1564. if (s.lookahead = 0) then
  1565. break; { flush the current block }
  1566. end;
  1567. { Insert the string window[strstart .. strstart+2] in the
  1568. dictionary, and set hash_head to the head of the hash chain: }
  1569. if (s.lookahead >= MIN_MATCH) then
  1570. begin
  1571. INSERT_STRING(s, s.strstart, hash_head);
  1572. end;
  1573. { Find the longest match, discarding those <= prev_length.
  1574. At this point we have always match_length < MIN_MATCH }
  1575. if (hash_head <> ZNIL) and
  1576. (s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD){MAX_DIST}) then
  1577. begin
  1578. { To simplify the code, we prevent matches with the string
  1579. of window index 0 (in particular we have to avoid a match
  1580. of the string with itself at the start of the input file). }
  1581. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1582. begin
  1583. s.match_length := longest_match (s, hash_head);
  1584. end;
  1585. { longest_match() sets match_start }
  1586. end;
  1587. if (s.match_length >= MIN_MATCH) then
  1588. begin
  1589. {$IFDEF DEBUG}
  1590. check_match(s, s.strstart, s.match_start, s.match_length);
  1591. {$ENDIF}
  1592. {_tr_tally_dist(s, s.strstart - s.match_start,
  1593. s.match_length - MIN_MATCH, bflush);}
  1594. bflush := _tr_tally(s, s.strstart - s.match_start,
  1595. s.match_length - MIN_MATCH);
  1596. Dec(s.lookahead, s.match_length);
  1597. { Insert new strings in the hash table only if the match length
  1598. is not too large. This saves time but degrades compression. }
  1599. {$ifndef FASTEST}
  1600. if (s.match_length <= s.max_insert_length)
  1601. and (s.lookahead >= MIN_MATCH) then
  1602. begin
  1603. Dec(s.match_length); { string at strstart already in hash table }
  1604. repeat
  1605. Inc(s.strstart);
  1606. INSERT_STRING(s, s.strstart, hash_head);
  1607. { strstart never exceeds WSIZE-MAX_MATCH, so there are
  1608. always MIN_MATCH bytes ahead. }
  1609. Dec(s.match_length);
  1610. until (s.match_length = 0);
  1611. Inc(s.strstart);
  1612. end
  1613. else
  1614. {$endif}
  1615. begin
  1616. Inc(s.strstart, s.match_length);
  1617. s.match_length := 0;
  1618. s.ins_h := s.window^[s.strstart];
  1619. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1620. s.ins_h := (( s.ins_h shl s.hash_shift) xor
  1621. s.window^[s.strstart+1]) and s.hash_mask;
  1622. if MIN_MATCH <> 3 then { the linker removes this }
  1623. begin
  1624. {Call UPDATE_HASH() MIN_MATCH-3 more times}
  1625. end;
  1626. { If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1627. matter since it will be recomputed at next deflate call. }
  1628. end;
  1629. end
  1630. else
  1631. begin
  1632. { No match, output a literal byte }
  1633. {$IFDEF DEBUG}
  1634. Tracevv(char(s.window^[s.strstart]));
  1635. {$ENDIF}
  1636. {_tr_tally_lit (s, 0, s.window^[s.strstart], bflush);}
  1637. bflush := _tr_tally (s, 0, s.window^[s.strstart]);
  1638. Dec(s.lookahead);
  1639. Inc(s.strstart);
  1640. end;
  1641. if bflush then
  1642. begin {FLUSH_BLOCK(s, FALSE);}
  1643. FLUSH_BLOCK_ONLY(s, FALSE);
  1644. if (s.strm^.avail_out = 0) then
  1645. begin
  1646. deflate_fast := need_more;
  1647. exit;
  1648. end;
  1649. end;
  1650. end;
  1651. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1652. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1653. if (s.strm^.avail_out = 0) then
  1654. begin
  1655. if flush = Z_FINISH then
  1656. deflate_fast := finish_started
  1657. else
  1658. deflate_fast := need_more;
  1659. exit;
  1660. end;
  1661. if flush = Z_FINISH then
  1662. deflate_fast := finish_done
  1663. else
  1664. deflate_fast := block_done;
  1665. end;
  1666. { ===========================================================================
  1667. Same as above, but achieves better compression. We use a lazy
  1668. evaluation for matches: a match is finally adopted only if there is
  1669. no better match at the next window position. }
  1670. {local}
  1671. function deflate_slow(var s : deflate_state; flush : int) : block_state;
  1672. var
  1673. hash_head : IPos; { head of hash chain }
  1674. bflush : boolean; { set if current block must be flushed }
  1675. var
  1676. max_insert : uInt;
  1677. begin
  1678. hash_head := ZNIL;
  1679. { Process the input block. }
  1680. while TRUE do
  1681. begin
  1682. { Make sure that we always have enough lookahead, except
  1683. at the end of the input file. We need MAX_MATCH bytes
  1684. for the next match, plus MIN_MATCH bytes to insert the
  1685. string following the next match. }
  1686. if (s.lookahead < MIN_LOOKAHEAD) then
  1687. begin
  1688. fill_window(s);
  1689. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1690. begin
  1691. deflate_slow := need_more;
  1692. exit;
  1693. end;
  1694. if (s.lookahead = 0) then
  1695. break; { flush the current block }
  1696. end;
  1697. { Insert the string window[strstart .. strstart+2] in the
  1698. dictionary, and set hash_head to the head of the hash chain: }
  1699. if (s.lookahead >= MIN_MATCH) then
  1700. begin
  1701. INSERT_STRING(s, s.strstart, hash_head);
  1702. end;
  1703. { Find the longest match, discarding those <= prev_length. }
  1704. s.prev_length := s.match_length;
  1705. s.prev_match := s.match_start;
  1706. s.match_length := MIN_MATCH-1;
  1707. if (hash_head <> ZNIL) and (s.prev_length < s.max_lazy_match) and
  1708. (s.strstart - hash_head <= {MAX_DIST}(s.w_size-MIN_LOOKAHEAD)) then
  1709. begin
  1710. { To simplify the code, we prevent matches with the string
  1711. of window index 0 (in particular we have to avoid a match
  1712. of the string with itself at the start of the input file). }
  1713. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1714. begin
  1715. s.match_length := longest_match (s, hash_head);
  1716. end;
  1717. { longest_match() sets match_start }
  1718. if (s.match_length <= 5) and ((s.strategy = Z_FILTERED) or
  1719. ((s.match_length = MIN_MATCH) and
  1720. (s.strstart - s.match_start > TOO_FAR))) then
  1721. begin
  1722. { If prev_match is also MIN_MATCH, match_start is garbage
  1723. but we will ignore the current match anyway. }
  1724. s.match_length := MIN_MATCH-1;
  1725. end;
  1726. end;
  1727. { If there was a match at the previous step and the current
  1728. match is not better, output the previous match: }
  1729. if (s.prev_length >= MIN_MATCH)
  1730. and (s.match_length <= s.prev_length) then
  1731. begin
  1732. max_insert := s.strstart + s.lookahead - MIN_MATCH;
  1733. { Do not insert strings in hash table beyond this. }
  1734. {$ifdef DEBUG}
  1735. check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  1736. {$endif}
  1737. {_tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1738. s->prev_length - MIN_MATCH, bflush);}
  1739. bflush := _tr_tally(s, s.strstart -1 - s.prev_match,
  1740. s.prev_length - MIN_MATCH);
  1741. { Insert in hash table all strings up to the end of the match.
  1742. strstart-1 and strstart are already inserted. If there is not
  1743. enough lookahead, the last two strings are not inserted in
  1744. the hash table. }
  1745. Dec(s.lookahead, s.prev_length-1);
  1746. Dec(s.prev_length, 2);
  1747. repeat
  1748. Inc(s.strstart);
  1749. if (s.strstart <= max_insert) then
  1750. begin
  1751. INSERT_STRING(s, s.strstart, hash_head);
  1752. end;
  1753. Dec(s.prev_length);
  1754. until (s.prev_length = 0);
  1755. s.match_available := FALSE;
  1756. s.match_length := MIN_MATCH-1;
  1757. Inc(s.strstart);
  1758. if (bflush) then {FLUSH_BLOCK(s, FALSE);}
  1759. begin
  1760. FLUSH_BLOCK_ONLY(s, FALSE);
  1761. if (s.strm^.avail_out = 0) then
  1762. begin
  1763. deflate_slow := need_more;
  1764. exit;
  1765. end;
  1766. end;
  1767. end
  1768. else
  1769. if (s.match_available) then
  1770. begin
  1771. { If there was no match at the previous position, output a
  1772. single literal. If there was a match but the current match
  1773. is longer, truncate the previous match to a single literal. }
  1774. {$IFDEF DEBUG}
  1775. Tracevv(char(s.window^[s.strstart-1]));
  1776. {$ENDIF}
  1777. bflush := _tr_tally (s, 0, s.window^[s.strstart-1]);
  1778. if bflush then
  1779. begin
  1780. FLUSH_BLOCK_ONLY(s, FALSE);
  1781. end;
  1782. Inc(s.strstart);
  1783. Dec(s.lookahead);
  1784. if (s.strm^.avail_out = 0) then
  1785. begin
  1786. deflate_slow := need_more;
  1787. exit;
  1788. end;
  1789. end
  1790. else
  1791. begin
  1792. { There is no previous match to compare with, wait for
  1793. the next step to decide. }
  1794. s.match_available := TRUE;
  1795. Inc(s.strstart);
  1796. Dec(s.lookahead);
  1797. end;
  1798. end;
  1799. {$IFDEF DEBUG}
  1800. Assert (flush <> Z_NO_FLUSH, 'no flush?');
  1801. {$ENDIF}
  1802. if (s.match_available) then
  1803. begin
  1804. {$IFDEF DEBUG}
  1805. Tracevv(char(s.window^[s.strstart-1]));
  1806. bflush :=
  1807. {$ENDIF}
  1808. _tr_tally (s, 0, s.window^[s.strstart-1]);
  1809. s.match_available := FALSE;
  1810. end;
  1811. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1812. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1813. if (s.strm^.avail_out = 0) then
  1814. begin
  1815. if flush = Z_FINISH then
  1816. deflate_slow := finish_started
  1817. else
  1818. deflate_slow := need_more;
  1819. exit;
  1820. end;
  1821. if flush = Z_FINISH then
  1822. deflate_slow := finish_done
  1823. else
  1824. deflate_slow := block_done;
  1825. end;
  1826. end.