zdeflate.pas 72 KB

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