zdeflate.pas 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  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) : cardinal; 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 ZLIB_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. INSERT_STRING(s^, n, hash_head);
  574. {if (hash_head <> 0) then
  575. hash_head := 0; - to make compiler happy }
  576. deflateSetDictionary := Z_OK;
  577. end;
  578. { ======================================================================== }
  579. function deflateReset (var strm : z_stream) : integer;
  580. var
  581. s : deflate_state_ptr;
  582. begin
  583. if {(@strm = Z_NULL) or}
  584. (strm.state = nil) then
  585. begin
  586. deflateReset := Z_STREAM_ERROR;
  587. exit;
  588. end;
  589. strm.total_out := 0;
  590. strm.total_in := 0;
  591. strm.msg := ''; { use zfree if we ever allocate msg dynamically }
  592. strm.data_type := Z_UNKNOWN;
  593. s := deflate_state_ptr(strm.state);
  594. s^.pending := 0;
  595. s^.pending_out := Pbyte(s^.pending_buf);
  596. if (s^.noheader < 0) then
  597. begin
  598. s^.noheader := 0; { was set to -1 by deflate(..., Z_FINISH); }
  599. end;
  600. if s^.noheader <> 0 then
  601. s^.status := BUSY_STATE
  602. else
  603. s^.status := INIT_STATE;
  604. strm.adler := 1;
  605. s^.last_flush := Z_NO_FLUSH;
  606. _tr_init(s^);
  607. lm_init(s^);
  608. deflateReset := Z_OK;
  609. end;
  610. { ======================================================================== }
  611. function deflateParams(var strm : z_stream;
  612. level : integer;
  613. strategy : integer) : integer;
  614. var
  615. s : deflate_state_ptr;
  616. func : compress_func;
  617. err : integer;
  618. begin
  619. err := Z_OK;
  620. if {(@strm = Z_NULL) or} (strm.state = Z_NULL) then
  621. begin
  622. deflateParams := Z_STREAM_ERROR;
  623. exit;
  624. end;
  625. s := deflate_state_ptr(strm.state);
  626. if (level = Z_DEFAULT_COMPRESSION) then
  627. begin
  628. level := 6;
  629. end;
  630. if (level < 0) or (level > 9) or (strategy < 0)
  631. or (strategy > Z_HUFFMAN_ONLY) then
  632. begin
  633. deflateParams := Z_STREAM_ERROR;
  634. exit;
  635. end;
  636. func := configuration_table[s^.level].func;
  637. if (@func <> @configuration_table[level].func)
  638. and (strm.total_in <> 0) then
  639. begin
  640. { Flush the last buffer: }
  641. err := deflate(strm, Z_PARTIAL_FLUSH);
  642. end;
  643. if (s^.level <> level) then
  644. begin
  645. s^.level := level;
  646. s^.max_lazy_match := configuration_table[level].max_lazy;
  647. s^.good_match := configuration_table[level].good_length;
  648. s^.nice_match := configuration_table[level].nice_length;
  649. s^.max_chain_length := configuration_table[level].max_chain;
  650. end;
  651. s^.strategy := strategy;
  652. deflateParams := err;
  653. end;
  654. { =========================================================================
  655. Put a short in the pending buffer. The 16-bit value is put in MSB order.
  656. IN assertion: the stream state is correct and there is enough room in
  657. pending_buf. }
  658. {local}
  659. procedure putShortMSB (var s : deflate_state; b : cardinal);
  660. begin
  661. s.pending_buf^[s.pending] := Byte(b shr 8);
  662. inc(s.pending);
  663. s.pending_buf^[s.pending] := Byte(b and $ff);
  664. inc(s.pending);
  665. end;
  666. { =========================================================================
  667. Flush as much pending output as possible. All deflate() output goes
  668. through this function so some applications may wish to modify it
  669. to avoid allocating a large strm^.next_out buffer and copying into it.
  670. (See also read_buf()). }
  671. {local}
  672. procedure flush_pending(var strm : z_stream);
  673. var
  674. len : cardinal;
  675. s : deflate_state_ptr;
  676. begin
  677. s := deflate_state_ptr(strm.state);
  678. len := s^.pending;
  679. if (len > strm.avail_out) then
  680. len := strm.avail_out;
  681. if (len = 0) then
  682. exit;
  683. move(s^.pending_out^,strm.next_out^,len);
  684. inc(strm.next_out, len);
  685. inc(s^.pending_out, len);
  686. inc(strm.total_out, len);
  687. dec(strm.avail_out, len);
  688. dec(s^.pending, len);
  689. if (s^.pending = 0) then
  690. begin
  691. s^.pending_out := Pbyte(s^.pending_buf);
  692. end;
  693. end;
  694. { ========================================================================= }
  695. function deflate (var strm : z_stream; flush : integer) : integer;
  696. var
  697. old_flush : integer; { value of flush param for previous deflate call }
  698. s : deflate_state_ptr;
  699. var
  700. header : cardinal;
  701. level_flags : cardinal;
  702. var
  703. bstate : block_state;
  704. begin
  705. if {(@strm = Z_NULL) or} (strm.state = Z_NULL)
  706. or (flush > Z_FINISH) or (flush < 0) then
  707. begin
  708. deflate := Z_STREAM_ERROR;
  709. exit;
  710. end;
  711. s := deflate_state_ptr(strm.state);
  712. if (strm.next_out = Z_NULL) or
  713. ((strm.next_in = Z_NULL) and (strm.avail_in <> 0)) or
  714. ((s^.status = FINISH_STATE) and (flush <> Z_FINISH)) then
  715. begin
  716. {ERR_RETURN(strm^, Z_STREAM_ERROR);}
  717. strm.msg := z_errmsg[z_errbase - Z_STREAM_ERROR];
  718. deflate := Z_STREAM_ERROR;
  719. exit;
  720. end;
  721. if (strm.avail_out = 0) then
  722. begin
  723. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  724. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  725. deflate := Z_BUF_ERROR;
  726. exit;
  727. end;
  728. s^.strm := @strm; { just in case }
  729. old_flush := s^.last_flush;
  730. s^.last_flush := flush;
  731. { Write the zlib header }
  732. if (s^.status = INIT_STATE) then
  733. begin
  734. header := (Z_DEFLATED + ((s^.w_bits-8) shl 4)) shl 8;
  735. level_flags := (s^.level-1) shr 1;
  736. if (level_flags > 3) then
  737. level_flags := 3;
  738. header := header or (level_flags shl 6);
  739. if (s^.strstart <> 0) then
  740. header := header or PRESET_DICT;
  741. inc(header, 31 - (header mod 31));
  742. s^.status := BUSY_STATE;
  743. putShortMSB(s^, header);
  744. { Save the adler32 of the preset dictionary: }
  745. if (s^.strstart <> 0) then
  746. begin
  747. putShortMSB(s^, cardinal(strm.adler shr 16));
  748. putShortMSB(s^, cardinal(strm.adler and $ffff));
  749. end;
  750. strm.adler := longint(1);
  751. end;
  752. { Flush as much pending output as possible }
  753. if (s^.pending <> 0) then
  754. begin
  755. flush_pending(strm);
  756. if (strm.avail_out = 0) then
  757. begin
  758. { Since avail_out is 0, deflate will be called again with
  759. more output space, but possibly with both pending and
  760. avail_in equal to zero. There won't be anything to do,
  761. but this is not an error situation so make sure we
  762. return OK instead of BUF_ERROR at next call of deflate: }
  763. s^.last_flush := -1;
  764. deflate := Z_OK;
  765. exit;
  766. end;
  767. { Make sure there is something to do and avoid duplicate consecutive
  768. flushes. For repeated and useless calls with Z_FINISH, we keep
  769. returning Z_STREAM_END instead of Z_BUFF_ERROR. }
  770. end
  771. else
  772. if (strm.avail_in = 0) and (flush <= old_flush)
  773. and (flush <> Z_FINISH) then
  774. begin
  775. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  776. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  777. deflate := Z_BUF_ERROR;
  778. exit;
  779. end;
  780. { User must not provide more input after the first FINISH: }
  781. if (s^.status = FINISH_STATE) and (strm.avail_in <> 0) then
  782. begin
  783. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  784. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  785. deflate := Z_BUF_ERROR;
  786. exit;
  787. end;
  788. { Start a new block or continue the current one. }
  789. if (strm.avail_in <> 0) or (s^.lookahead <> 0)
  790. or ((flush <> Z_NO_FLUSH) and (s^.status <> FINISH_STATE)) then
  791. begin
  792. bstate := configuration_table[s^.level].func(s^, flush);
  793. if (bstate = finish_started) or (bstate = finish_done) then
  794. s^.status := FINISH_STATE;
  795. if (bstate = need_more) or (bstate = finish_started) then
  796. begin
  797. if (strm.avail_out = 0) then
  798. s^.last_flush := -1; { avoid BUF_ERROR next call, see above }
  799. deflate := Z_OK;
  800. exit;
  801. { If flush != Z_NO_FLUSH && avail_out == 0, the next call
  802. of deflate should use the same flush parameter to make sure
  803. that the flush is complete. So we don't have to output an
  804. empty block here, this will be done at next call. This also
  805. ensures that for a very small output buffer, we emit at most
  806. one empty block. }
  807. end;
  808. if (bstate = block_done) then
  809. begin
  810. if (flush = Z_PARTIAL_FLUSH) then
  811. _tr_align(s^)
  812. else
  813. begin { FULL_FLUSH or SYNC_FLUSH }
  814. _tr_stored_block(s^, Pchar(NIL), longint(0), FALSE);
  815. { For a full flush, this empty block will be recognized
  816. as a special marker by inflate_sync(). }
  817. if (flush = Z_FULL_FLUSH) then
  818. begin
  819. {macro CLEAR_HASH(s);} { forget history }
  820. s^.head^[s^.hash_size-1] := ZNIL;
  821. fillchar(Pbyte(s^.head)^,cardinal(s^.hash_size-1)*sizeof(s^.head^[0]),0);
  822. end;
  823. end;
  824. flush_pending(strm);
  825. if (strm.avail_out = 0) then
  826. begin
  827. s^.last_flush := -1; { avoid BUF_ERROR at next call, see above }
  828. deflate := Z_OK;
  829. exit;
  830. end;
  831. end;
  832. end;
  833. {$IFDEF ZLIB_DEBUG}
  834. Assert(strm.avail_out > 0, 'bug2');
  835. {$ENDIF}
  836. if (flush <> Z_FINISH) then
  837. begin
  838. deflate := Z_OK;
  839. exit;
  840. end;
  841. if (s^.noheader <> 0) then
  842. begin
  843. deflate := Z_STREAM_END;
  844. exit;
  845. end;
  846. { Write the zlib trailer (adler32) }
  847. putShortMSB(s^, cardinal(strm.adler shr 16));
  848. putShortMSB(s^, cardinal(strm.adler and $ffff));
  849. flush_pending(strm);
  850. { If avail_out is zero, the application will call deflate again
  851. to flush the rest. }
  852. s^.noheader := -1; { write the trailer only once! }
  853. if s^.pending <> 0 then
  854. deflate := Z_OK
  855. else
  856. deflate := Z_STREAM_END;
  857. end;
  858. { ========================================================================= }
  859. function deflateEnd (var strm : z_stream) : integer;
  860. var
  861. status : integer;
  862. s : deflate_state_ptr;
  863. begin
  864. if {(@strm = Z_NULL) or} (strm.state = Z_NULL) then
  865. begin
  866. deflateEnd := Z_STREAM_ERROR;
  867. exit;
  868. end;
  869. s := deflate_state_ptr(strm.state);
  870. status := s^.status;
  871. if (status <> INIT_STATE) and (status <> BUSY_STATE) and
  872. (status <> FINISH_STATE) then
  873. begin
  874. deflateEnd := Z_STREAM_ERROR;
  875. exit;
  876. end;
  877. { Deallocate in reverse order of allocations: }
  878. TRY_FREE(strm, s^.pending_buf);
  879. TRY_FREE(strm, s^.head);
  880. TRY_FREE(strm, s^.prev);
  881. TRY_FREE(strm, s^.window);
  882. ZFREE(strm, s);
  883. strm.state := Z_NULL;
  884. if status = BUSY_STATE then
  885. deflateEnd := Z_DATA_ERROR
  886. else
  887. deflateEnd := Z_OK;
  888. end;
  889. { =========================================================================
  890. Copy the source state to the destination state.
  891. To simplify the source, this is not supported for 16-bit MSDOS (which
  892. doesn't have enough memory anyway to duplicate compression states). }
  893. { ========================================================================= }
  894. function deflateCopy (dest, source : z_streamp) : integer;
  895. {$ifndef MAXSEG_64K}
  896. var
  897. ds : deflate_state_ptr;
  898. ss : deflate_state_ptr;
  899. overlay : Pwordarray;
  900. {$endif}
  901. begin
  902. {$ifdef MAXSEG_64K}
  903. deflateCopy := Z_STREAM_ERROR;
  904. exit;
  905. {$else}
  906. if (source = Z_NULL) or (dest = Z_NULL) or (source^.state = Z_NULL) then
  907. begin
  908. deflateCopy := Z_STREAM_ERROR;
  909. exit;
  910. end;
  911. ss := deflate_state_ptr(source^.state);
  912. dest^ := source^;
  913. ds := deflate_state_ptr( ZALLOC(dest^, 1, sizeof(deflate_state)) );
  914. if (ds = Z_NULL) then
  915. begin
  916. deflateCopy := Z_MEM_ERROR;
  917. exit;
  918. end;
  919. dest^.state := pInternal_state(ds);
  920. ds^ := ss^;
  921. ds^.strm := dest;
  922. ds^.window := Pbytearray ( ZALLOC(dest^, ds^.w_size, 2*sizeof(Byte)) );
  923. ds^.prev := pzPosfArray ( ZALLOC(dest^, ds^.w_size, sizeof(Pos)) );
  924. ds^.head := pzPosfArray ( ZALLOC(dest^, ds^.hash_size, sizeof(Pos)) );
  925. overlay := Pwordarray ( ZALLOC(dest^, ds^.lit_bufsize, sizeof(word)+2) );
  926. ds^.pending_buf := Pbytearray ( overlay );
  927. if (ds^.window = Z_NULL) or (ds^.prev = Z_NULL) or (ds^.head = Z_NULL)
  928. or (ds^.pending_buf = Z_NULL) then
  929. begin
  930. deflateEnd (dest^);
  931. deflateCopy := Z_MEM_ERROR;
  932. exit;
  933. end;
  934. move(Pbyte(ss^.window)^,Pbyte(ds^.window)^,ds^.w_size * 2 * sizeof(byte));
  935. move(Pbyte(ss^.prev)^,Pbyte(ds^.prev)^,ds^.w_size * sizeof(pos));
  936. move(Pbyte(ss^.head)^,Pbyte(ds^.head)^,ds^.hash_size * sizeof(pos));
  937. move(Pbyte(ss^.pending_buf)^,Pbyte(ds^.pending_buf)^,cardinal(ds^.pending_buf_size));
  938. ds^.pending_out := @ds^.pending_buf^[ptrint(ss^.pending_out) - ptrint(ss^.pending_buf)];
  939. ds^.d_buf := Pwordarray(@overlay^[ds^.lit_bufsize div sizeof(word)] );
  940. ds^.l_buf := Pbytearray(@ds^.pending_buf^[(1+sizeof(word))*ds^.lit_bufsize]);
  941. ds^.l_desc.dyn_tree := tree_ptr(@ds^.dyn_ltree);
  942. ds^.d_desc.dyn_tree := tree_ptr(@ds^.dyn_dtree);
  943. ds^.bl_desc.dyn_tree := tree_ptr(@ds^.bl_tree);
  944. deflateCopy := Z_OK;
  945. {$endif}
  946. end;
  947. { ===========================================================================
  948. Read a new buffer from the current input stream, update the adler32
  949. and total number of bytes read. All deflate() input goes through
  950. this function so some applications may wish to modify it to avoid
  951. allocating a large strm^.next_in buffer and copying from it.
  952. (See also flush_pending()). }
  953. {local}
  954. function read_buf(strm:z_streamp;buf:Pbyte;size:cardinal):cardinal;
  955. var len:cardinal;
  956. begin
  957. len:=strm^.avail_in;
  958. if len>size then
  959. len:=size;
  960. dec(strm^.avail_in, len);
  961. if len<>0 then
  962. begin
  963. if deflate_state_ptr(strm^.state)^.noheader=0 then
  964. strm^.adler:=adler32(strm^.adler,strm^.next_in,len);
  965. move(strm^.next_in^,buf^,len);
  966. inc(strm^.next_in,len);
  967. inc(strm^.total_in,len);
  968. end;
  969. read_buf:=len;
  970. end;
  971. { ===========================================================================
  972. Initialize the "longest match" routines for a new zlib stream }
  973. {local}
  974. procedure lm_init (var s : deflate_state);
  975. begin
  976. s.window_size := longint( 2*s.w_size);
  977. {macro CLEAR_HASH(s);}
  978. s.head^[s.hash_size-1] := ZNIL;
  979. fillchar(Pbyte(s.head)^, cardinal(s.hash_size-1)*sizeof(s.head^[0]),0);
  980. { Set the default configuration parameters: }
  981. s.max_lazy_match := configuration_table[s.level].max_lazy;
  982. s.good_match := configuration_table[s.level].good_length;
  983. s.nice_match := configuration_table[s.level].nice_length;
  984. s.max_chain_length := configuration_table[s.level].max_chain;
  985. s.strstart := 0;
  986. s.block_start := longint(0);
  987. s.lookahead := 0;
  988. s.prev_length := MIN_MATCH-1;
  989. s.match_length := MIN_MATCH-1;
  990. s.match_available := FALSE;
  991. s.ins_h := 0;
  992. {$ifdef ASMV}
  993. match_init; { initialize the asm code }
  994. {$endif}
  995. end;
  996. { ===========================================================================
  997. Set match_start to the longest match starting at the given string and
  998. return its length. Matches shorter or equal to prev_length are discarded,
  999. in which case the result is equal to prev_length and match_start is
  1000. garbage.
  1001. IN assertions: cur_match is the head of the hash chain for the current
  1002. string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1003. OUT assertion: the match length is not greater than s^.lookahead. }
  1004. {$ifndef ASMV}
  1005. { For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1006. match.S. The code will be functionally equivalent. }
  1007. {$ifndef FASTEST}
  1008. {local}
  1009. function longest_match(var s : deflate_state;
  1010. cur_match : IPos { current match }
  1011. ) : cardinal;
  1012. label
  1013. nextstep;
  1014. var
  1015. chain_length : cardinal; { max hash chain length }
  1016. {register} scan : Pbyte; { current string }
  1017. {register} match : Pbyte; { matched string }
  1018. {register} len : integer; { length of current match }
  1019. best_len : integer; { best match length so far }
  1020. nice_match : integer; { stop if match longint enough }
  1021. limit : IPos;
  1022. prev : pzPosfArray;
  1023. wmask : cardinal;
  1024. {$ifdef UNALIGNED_OK}
  1025. {register} strend : Pbyte;
  1026. {register} scan_start : word;
  1027. {register} scan_end : word;
  1028. {$else}
  1029. {register} strend : Pbyte;
  1030. {register} scan_end1 : Byte;
  1031. {register} scan_end : Byte;
  1032. {$endif}
  1033. var
  1034. MAX_DIST : cardinal;
  1035. begin
  1036. chain_length := s.max_chain_length; { max hash chain length }
  1037. scan := @(s.window^[s.strstart]);
  1038. best_len := s.prev_length; { best match length so far }
  1039. nice_match := s.nice_match; { stop if match longint enough }
  1040. MAX_DIST := s.w_size - MIN_LOOKAHEAD;
  1041. {In order to simplify the code, particularly on 16 bit machines, match
  1042. distances are limited to MAX_DIST instead of WSIZE. }
  1043. if s.strstart > IPos(MAX_DIST) then
  1044. limit := s.strstart - IPos(MAX_DIST)
  1045. else
  1046. limit := ZNIL;
  1047. { Stop when cur_match becomes <= limit. To simplify the code,
  1048. we prevent matches with the string of window index 0. }
  1049. prev := s.prev;
  1050. wmask := s.w_mask;
  1051. {$ifdef UNALIGNED_OK}
  1052. { Compare two bytes at a time. Note: this is not always beneficial.
  1053. Try with and without -DUNALIGNED_OK to check. }
  1054. strend := Pbyte(@(s.window^[s.strstart + MAX_MATCH - 1]));
  1055. scan_start := pushf(scan)^;
  1056. scan_end := Pwordarray(scan)^[best_len-1]; { fix }
  1057. {$else}
  1058. strend := Pbyte(@(s.window^[s.strstart + MAX_MATCH]));
  1059. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1060. scan_end1 := Pbytearray(scan)^[best_len-1];
  1061. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1062. scan_end := Pbytearray(scan)^[best_len];
  1063. {$endif}
  1064. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1065. It is easy to get rid of this optimization if necessary. }
  1066. {$IFDEF ZLIB_DEBUG}
  1067. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1068. {$ENDIF}
  1069. { Do not waste too much time if we already have a good match: }
  1070. if (s.prev_length >= s.good_match) then
  1071. begin
  1072. chain_length := chain_length shr 2;
  1073. end;
  1074. { Do not look for matches beyond the end of the input. This is necessary
  1075. to make deflate deterministic. }
  1076. if (cardinal(nice_match) > s.lookahead) then
  1077. nice_match := s.lookahead;
  1078. {$IFDEF ZLIB_DEBUG}
  1079. Assert(longint(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1080. {$ENDIF}
  1081. repeat
  1082. {$IFDEF ZLIB_DEBUG}
  1083. Assert(cur_match < s.strstart, 'no future');
  1084. {$ENDIF}
  1085. match := @(s.window^[cur_match]);
  1086. { Skip to next match if the match length cannot increase
  1087. or if the match length is less than 2: }
  1088. {$undef DO_UNALIGNED_OK}
  1089. {$ifdef UNALIGNED_OK}
  1090. {$ifdef MAX_MATCH_IS_258}
  1091. {$define DO_UNALIGNED_OK}
  1092. {$endif}
  1093. {$endif}
  1094. {$ifdef DO_UNALIGNED_OK}
  1095. { This code assumes sizeof(cardinal short) = 2. Do not use
  1096. UNALIGNED_OK if your compiler uses a different size. }
  1097. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1098. if (pushfArray(match)^[best_len-1] <> scan_end) or
  1099. (pushf(match)^ <> scan_start) then
  1100. goto nextstep; {continue;}
  1101. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1102. { It is not necessary to compare scan[2] and match[2] since they are
  1103. always equal when the other bytes match, given that the hash keys
  1104. are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1105. strstart+3, +5, ... up to strstart+257. We check for insufficient
  1106. lookahead only every 4th comparison; the 128th check will be made
  1107. at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1108. necessary to put more guard bytes at the end of the window, or
  1109. to check more often for insufficient lookahead. }
  1110. {$IFDEF ZLIB_DEBUG}
  1111. Assert(pzByteArray(scan)^[2] = pzByteArray(match)^[2], 'scan[2]?');
  1112. {$ENDIF}
  1113. inc(scan);
  1114. inc(match);
  1115. repeat
  1116. inc(scan,2); inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1117. inc(scan,2); inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1118. inc(scan,2); inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1119. inc(scan,2); inc(match,2); if (pushf(scan)^<>pushf(match)^) then break;
  1120. until (ptrint(scan) >= ptrint(strend));
  1121. { The funny "do while" generates better code on most compilers }
  1122. { Here, scan <= window+strstart+257 }
  1123. {$IFDEF ZLIB_DEBUG}
  1124. {$ifopt R+} {$define RangeCheck} {$endif} {$R-}
  1125. Assert(ptrint(scan) <=
  1126. ptrint(@(s.window^[cardinal(s.window_size-1)])),
  1127. 'wild scan');
  1128. {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}
  1129. {$ENDIF}
  1130. if (scan^ = match^) then
  1131. inc(scan);
  1132. len := (MAX_MATCH - 1) - integer(ptrint(strend)) + integer(ptrint(scan));
  1133. scan := strend;
  1134. dec(scan, (MAX_MATCH-1));
  1135. {$else} { UNALIGNED_OK }
  1136. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1137. if (Pbytearray(match)^[best_len] <> scan_end) or
  1138. (Pbytearray(match)^[best_len-1] <> scan_end1) or
  1139. (match^ <> scan^) then
  1140. goto nextstep; {continue;}
  1141. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1142. inc(match);
  1143. if (match^ <> Pbytearray(scan)^[1]) then
  1144. goto nextstep; {continue;}
  1145. { The check at best_len-1 can be removed because it will be made
  1146. again later. (This heuristic is not always a win.)
  1147. It is not necessary to compare scan[2] and match[2] since they
  1148. are always equal when the other bytes match, given that
  1149. the hash keys are equal and that HASH_BITS >= 8. }
  1150. inc(scan, 2);
  1151. inc(match);
  1152. {$IFDEF ZLIB_DEBUG}
  1153. Assert( scan^ = match^, 'match[2]?');
  1154. {$ENDIF}
  1155. { We check for insufficient lookahead only every 8th comparison;
  1156. the 256th check will be made at strstart+258. }
  1157. repeat
  1158. inc(scan); inc(match); if (scan^ <> match^) then break;
  1159. inc(scan); inc(match); if (scan^ <> match^) then break;
  1160. inc(scan); inc(match); if (scan^ <> match^) then break;
  1161. inc(scan); inc(match); if (scan^ <> match^) then break;
  1162. inc(scan); inc(match); if (scan^ <> match^) then break;
  1163. inc(scan); inc(match); if (scan^ <> match^) then break;
  1164. inc(scan); inc(match); if (scan^ <> match^) then break;
  1165. inc(scan); inc(match); if (scan^ <> match^) then break;
  1166. until (ptrint(scan) >= ptrint(strend));
  1167. {$IFDEF ZLIB_DEBUG}
  1168. Assert(ptrint(scan) <=
  1169. ptrint(@(s.window^[cardinal(s.window_size-1)])),
  1170. 'wild scan');
  1171. {$ENDIF}
  1172. len := MAX_MATCH - integer(ptrint(strend) - ptrint(scan));
  1173. scan := strend;
  1174. dec(scan, MAX_MATCH);
  1175. {$endif} { UNALIGNED_OK }
  1176. if (len > best_len) then
  1177. begin
  1178. s.match_start := cur_match;
  1179. best_len := len;
  1180. if (len >= nice_match) then
  1181. break;
  1182. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1183. {$ifdef UNALIGNED_OK}
  1184. scan_end := Pbytearray(scan)^[best_len-1];
  1185. {$else}
  1186. scan_end1 := Pbytearray(scan)^[best_len-1];
  1187. scan_end := Pbytearray(scan)^[best_len];
  1188. {$endif}
  1189. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1190. end;
  1191. nextstep:
  1192. cur_match := prev^[cur_match and wmask];
  1193. dec(chain_length);
  1194. until (cur_match <= limit) or (chain_length = 0);
  1195. if (cardinal(best_len) <= s.lookahead) then
  1196. longest_match := cardinal(best_len)
  1197. else
  1198. longest_match := s.lookahead;
  1199. end;
  1200. {$endif} { ASMV }
  1201. {$else} { FASTEST }
  1202. { ---------------------------------------------------------------------------
  1203. Optimized version for level = 1 only }
  1204. {local}
  1205. function longest_match(var s : deflate_state;
  1206. cur_match : IPos { current match }
  1207. ) : cardinal;
  1208. var
  1209. {register} scan : Pbyte; { current string }
  1210. {register} match : Pbyte; { matched string }
  1211. {register} len : integer; { length of current match }
  1212. {register} strend : Pbyte;
  1213. begin
  1214. scan := @s.window^[s.strstart];
  1215. strend := @s.window^[s.strstart + MAX_MATCH];
  1216. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1217. It is easy to get rid of this optimization if necessary. }
  1218. {$IFDEF ZLIB_DEBUG}
  1219. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1220. Assert(longint(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1221. Assert(cur_match < s.strstart, 'no future');
  1222. {$ENDIF}
  1223. match := s.window + cur_match;
  1224. { Return failure if the match length is less than 2: }
  1225. if (match[0] <> scan[0]) or (match[1] <> scan[1]) then
  1226. begin
  1227. longest_match := MIN_MATCH-1;
  1228. exit;
  1229. end;
  1230. { The check at best_len-1 can be removed because it will be made
  1231. again later. (This heuristic is not always a win.)
  1232. It is not necessary to compare scan[2] and match[2] since they
  1233. are always equal when the other bytes match, given that
  1234. the hash keys are equal and that HASH_BITS >= 8. }
  1235. scan += 2, match += 2;
  1236. Assert(scan^ = match^, 'match[2]?');
  1237. { We check for insufficient lookahead only every 8th comparison;
  1238. the 256th check will be made at strstart+258. }
  1239. repeat
  1240. inc(scan); inc(match); if scan^<>match^ then break;
  1241. inc(scan); inc(match); if scan^<>match^ then break;
  1242. inc(scan); inc(match); if scan^<>match^ then break;
  1243. inc(scan); inc(match); if scan^<>match^ then break;
  1244. inc(scan); inc(match); if scan^<>match^ then break;
  1245. inc(scan); inc(match); if scan^<>match^ then break;
  1246. inc(scan); inc(match); if scan^<>match^ then break;
  1247. inc(scan); inc(match); if scan^<>match^ then break;
  1248. until (ptrint(scan) >= ptrint(strend));
  1249. Assert(scan <= s.window+cardinal(s.window_size-1), 'wild scan');
  1250. len := MAX_MATCH - integer(strend - scan);
  1251. if (len < MIN_MATCH) then
  1252. begin
  1253. return := MIN_MATCH - 1;
  1254. exit;
  1255. end;
  1256. s.match_start := cur_match;
  1257. if len <= s.lookahead then
  1258. longest_match := len
  1259. else
  1260. longest_match := s.lookahead;
  1261. end;
  1262. {$endif} { FASTEST }
  1263. {$ifdef ZLIB_DEBUG}
  1264. { ===========================================================================
  1265. Check that the match at match_start is indeed a match. }
  1266. {local}
  1267. procedure check_match(var s : deflate_state;
  1268. start, match : IPos;
  1269. length : integer);
  1270. begin
  1271. exit;
  1272. { check that the match is indeed a match }
  1273. if (zmemcmp(Pbyte(@s.window^[match]),
  1274. Pbyte(@s.window^[start]), length) <> EQUAL) then
  1275. begin
  1276. WriteLn(' start ',start,', match ',match ,' length ', length);
  1277. repeat
  1278. Write(char(s.window^[match]), char(s.window^[start]));
  1279. inc(match);
  1280. inc(start);
  1281. dec(length);
  1282. Until (length = 0);
  1283. z_error('invalid match');
  1284. end;
  1285. if (z_verbose > 1) then
  1286. begin
  1287. Write('\\[',start-match,',',length,']');
  1288. repeat
  1289. Write(char(s.window^[start]));
  1290. inc(start);
  1291. dec(length);
  1292. Until (length = 0);
  1293. end;
  1294. end;
  1295. {$endif}
  1296. { ===========================================================================
  1297. Fill the window when the lookahead becomes insufficient.
  1298. Updates strstart and lookahead.
  1299. IN assertion: lookahead < MIN_LOOKAHEAD
  1300. OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1301. At least one byte has been read, or avail_in = 0; reads are
  1302. performed for at least two bytes (required for the zip translate_eol
  1303. option -- not supported here). }
  1304. {local}
  1305. procedure fill_window(var s : deflate_state);
  1306. var
  1307. {register} n, m : cardinal;
  1308. {register} p : pPosf;
  1309. more : cardinal; { Amount of free space at the end of the window. }
  1310. wsize : cardinal;
  1311. begin
  1312. wsize := s.w_size;
  1313. repeat
  1314. more := cardinal(s.window_size -longint(s.lookahead) -longint(s.strstart));
  1315. { Deal with !@#$% 64K limit: }
  1316. if (more = 0) and (s.strstart = 0) and (s.lookahead = 0) then
  1317. more := wsize
  1318. else
  1319. if (more = cardinal(-1)) then
  1320. begin
  1321. { Very unlikely, but possible on 16 bit machine if strstart = 0
  1322. and lookahead = 1 (input done one byte at time) }
  1323. dec(more);
  1324. { If the window is almost full and there is insufficient lookahead,
  1325. move the upper half to the lower one to make room in the upper half.}
  1326. end
  1327. else
  1328. if (s.strstart >= wsize+ {MAX_DIST}(wsize-MIN_LOOKAHEAD)) then
  1329. begin
  1330. move(s.window^[wsize],Pbyte(s.window)^,wsize);
  1331. dec(s.match_start, wsize);
  1332. dec(s.strstart, wsize); { we now have strstart >= MAX_DIST }
  1333. dec(s.block_start, longint(wsize));
  1334. { Slide the hash table (could be avoided with 32 bit values
  1335. at the expense of memory usage). We slide even when level = 0
  1336. to keep the hash table consistent if we switch back to level > 0
  1337. later. (Using level 0 permanently is not an optimal usage of
  1338. zlib, so we don't care about this pathological case.) }
  1339. n := s.hash_size;
  1340. p := @s.head^[n];
  1341. repeat
  1342. dec(p);
  1343. m := p^;
  1344. if (m >= wsize) then
  1345. p^ := Pos(m-wsize)
  1346. else
  1347. p^ := Pos(ZNIL);
  1348. dec(n);
  1349. Until (n=0);
  1350. n := wsize;
  1351. {$ifndef FASTEST}
  1352. p := @s.prev^[n];
  1353. repeat
  1354. dec(p);
  1355. m := p^;
  1356. if (m >= wsize) then
  1357. p^ := Pos(m-wsize)
  1358. else
  1359. p^:= Pos(ZNIL);
  1360. { If n is not on any hash chain, prev^[n] is garbage but
  1361. its value will never be used. }
  1362. dec(n);
  1363. Until (n=0);
  1364. {$endif}
  1365. inc(more, wsize);
  1366. end;
  1367. if (s.strm^.avail_in = 0) then
  1368. exit;
  1369. {* If there was no sliding:
  1370. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1371. * more == window_size - lookahead - strstart
  1372. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1373. * => more >= window_size - 2*WSIZE + 2
  1374. * In the BIG_MEM or MMAP case (not yet supported),
  1375. * window_size == input_size + MIN_LOOKAHEAD &&
  1376. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1377. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1378. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. }
  1379. {$IFDEF ZLIB_DEBUG}
  1380. Assert(more >= 2, 'more < 2');
  1381. {$ENDIF}
  1382. n := read_buf(s.strm, Pbyte(@(s.window^[s.strstart + s.lookahead])),
  1383. more);
  1384. inc(s.lookahead, n);
  1385. { Initialize the hash value now that we have some input: }
  1386. if (s.lookahead >= MIN_MATCH) then
  1387. begin
  1388. s.ins_h := s.window^[s.strstart];
  1389. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1390. s.ins_h := ((s.ins_h shl s.hash_shift) xor s.window^[s.strstart+1])
  1391. and s.hash_mask;
  1392. {$ifdef MIN_MATCH <> 3}
  1393. Call UPDATE_HASH() MIN_MATCH-3 more times
  1394. {$endif}
  1395. end;
  1396. { If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1397. but this is not important since only literal bytes will be emitted. }
  1398. until (s.lookahead >= MIN_LOOKAHEAD) or (s.strm^.avail_in = 0);
  1399. end;
  1400. { ===========================================================================
  1401. Flush the current block, with given end-of-file flag.
  1402. IN assertion: strstart is set to the end of the current match. }
  1403. procedure FLUSH_BLOCK_ONLY(var s : deflate_state; eof : boolean); {macro}
  1404. begin
  1405. if (s.block_start >= 0) then
  1406. _tr_flush_block(s, Pchar(@s.window^[cardinal(s.block_start)]),
  1407. longint(longint(s.strstart) - s.block_start), eof)
  1408. else
  1409. _tr_flush_block(s, nil,
  1410. longint(longint(s.strstart) - s.block_start), eof);
  1411. s.block_start := s.strstart;
  1412. flush_pending(s.strm^);
  1413. {$IFDEF ZLIB_DEBUG}
  1414. Tracev('[FLUSH]');
  1415. {$ENDIF}
  1416. end;
  1417. { Same but force premature exit if necessary.
  1418. macro FLUSH_BLOCK(var s : deflate_state; eof : boolean) : boolean;
  1419. var
  1420. result : block_state;
  1421. begin
  1422. FLUSH_BLOCK_ONLY(s, eof);
  1423. if (s.strm^.avail_out = 0) then
  1424. begin
  1425. if eof then
  1426. result := finish_started
  1427. else
  1428. result := need_more;
  1429. exit;
  1430. end;
  1431. end;
  1432. }
  1433. { ===========================================================================
  1434. Copy without compression as much as possible from the input stream, return
  1435. the current block state.
  1436. This function does not insert new strings in the dictionary since
  1437. uncompressible data is probably not useful. This function is used
  1438. only for the level=0 compression option.
  1439. NOTE: this function should be optimized to avoid extra copying from
  1440. window to pending_buf. }
  1441. {local}
  1442. function deflate_stored(var s : deflate_state; flush : integer) : block_state;
  1443. { Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1444. to pending_buf_size, and each stored block has a 5 byte header: }
  1445. var
  1446. max_block_size : longint;
  1447. max_start : longint;
  1448. begin
  1449. max_block_size := $ffff;
  1450. if (max_block_size > s.pending_buf_size - 5) then
  1451. max_block_size := s.pending_buf_size - 5;
  1452. { Copy as much as possible from input to output: }
  1453. while TRUE do
  1454. begin
  1455. { Fill the window as much as possible: }
  1456. if (s.lookahead <= 1) then
  1457. begin
  1458. {$IFDEF ZLIB_DEBUG}
  1459. Assert( (s.strstart < s.w_size + {MAX_DIST}s.w_size-MIN_LOOKAHEAD) or
  1460. (s.block_start >= longint(s.w_size)), 'slide too late');
  1461. {$ENDIF}
  1462. fill_window(s);
  1463. if (s.lookahead = 0) and (flush = Z_NO_FLUSH) then
  1464. begin
  1465. deflate_stored := need_more;
  1466. exit;
  1467. end;
  1468. if (s.lookahead = 0) then
  1469. break; { flush the current block }
  1470. end;
  1471. {$IFDEF ZLIB_DEBUG}
  1472. Assert(s.block_start >= 0, 'block gone');
  1473. {$ENDIF}
  1474. inc(s.strstart, s.lookahead);
  1475. s.lookahead := 0;
  1476. { Emit a stored block if pending_buf will be full: }
  1477. max_start := s.block_start + max_block_size;
  1478. if (s.strstart = 0) or (longint(s.strstart) >= max_start) then
  1479. begin
  1480. { strstart = 0 is possible when wraparound on 16-bit machine }
  1481. s.lookahead := cardinal(s.strstart) - cardinal(max_start);
  1482. s.strstart := cardinal(max_start);
  1483. {FLUSH_BLOCK(s, FALSE);}
  1484. FLUSH_BLOCK_ONLY(s, FALSE);
  1485. if (s.strm^.avail_out = 0) then
  1486. begin
  1487. deflate_stored := need_more;
  1488. exit;
  1489. end;
  1490. end;
  1491. { Flush if we may have to slide, otherwise block_start may become
  1492. negative and the data will be gone: }
  1493. if (s.strstart - cardinal(s.block_start) >= {MAX_DIST}
  1494. s.w_size-MIN_LOOKAHEAD) then
  1495. begin
  1496. {FLUSH_BLOCK(s, FALSE);}
  1497. FLUSH_BLOCK_ONLY(s, FALSE);
  1498. if (s.strm^.avail_out = 0) then
  1499. begin
  1500. deflate_stored := need_more;
  1501. exit;
  1502. end;
  1503. end;
  1504. end;
  1505. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1506. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1507. if (s.strm^.avail_out = 0) then
  1508. begin
  1509. if flush = Z_FINISH then
  1510. deflate_stored := finish_started
  1511. else
  1512. deflate_stored := need_more;
  1513. exit;
  1514. end;
  1515. if flush = Z_FINISH then
  1516. deflate_stored := finish_done
  1517. else
  1518. deflate_stored := block_done;
  1519. end;
  1520. { ===========================================================================
  1521. Compress as much as possible from the input stream, return the current
  1522. block state.
  1523. This function does not perform lazy evaluation of matches and inserts
  1524. new strings in the dictionary only for unmatched strings or for short
  1525. matches. It is used only for the fast compression options. }
  1526. {local}
  1527. function deflate_fast(var s : deflate_state; flush : integer) : block_state;
  1528. var
  1529. hash_head : IPos; { head of the hash chain }
  1530. bflush : boolean; { set if current block must be flushed }
  1531. begin
  1532. hash_head := ZNIL;
  1533. while TRUE do
  1534. begin
  1535. { Make sure that we always have enough lookahead, except
  1536. at the end of the input file. We need MAX_MATCH bytes
  1537. for the next match, plus MIN_MATCH bytes to insert the
  1538. string following the next match. }
  1539. if (s.lookahead < MIN_LOOKAHEAD) then
  1540. begin
  1541. fill_window(s);
  1542. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1543. begin
  1544. deflate_fast := need_more;
  1545. exit;
  1546. end;
  1547. if (s.lookahead = 0) then
  1548. break; { flush the current block }
  1549. end;
  1550. { Insert the string window[strstart .. strstart+2] in the
  1551. dictionary, and set hash_head to the head of the hash chain: }
  1552. if (s.lookahead >= MIN_MATCH) then
  1553. INSERT_STRING(s, s.strstart, hash_head);
  1554. { Find the longest match, discarding those <= prev_length.
  1555. At this point we have always match_length < MIN_MATCH }
  1556. if (hash_head <> ZNIL) and
  1557. (s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD){MAX_DIST}) then
  1558. begin
  1559. { To simplify the code, we prevent matches with the string
  1560. of window index 0 (in particular we have to avoid a match
  1561. of the string with itself at the start of the input file). }
  1562. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1563. begin
  1564. s.match_length := longest_match (s, hash_head);
  1565. end;
  1566. { longest_match() sets match_start }
  1567. end;
  1568. if (s.match_length >= MIN_MATCH) then
  1569. begin
  1570. {$IFDEF ZLIB_DEBUG}
  1571. check_match(s, s.strstart, s.match_start, s.match_length);
  1572. {$ENDIF}
  1573. {_tr_tally_dist(s, s.strstart - s.match_start,
  1574. s.match_length - MIN_MATCH, bflush);}
  1575. bflush := _tr_tally(s, s.strstart - s.match_start,
  1576. s.match_length - MIN_MATCH);
  1577. dec(s.lookahead, s.match_length);
  1578. { Insert new strings in the hash table only if the match length
  1579. is not too large. This saves time but degrades compression. }
  1580. {$ifndef FASTEST}
  1581. if (s.match_length <= s.max_insert_length)
  1582. and (s.lookahead >= MIN_MATCH) then
  1583. begin
  1584. dec(s.match_length); { string at strstart already in hash table }
  1585. repeat
  1586. inc(s.strstart);
  1587. INSERT_STRING(s, s.strstart, hash_head);
  1588. { strstart never exceeds WSIZE-MAX_MATCH, so there are
  1589. always MIN_MATCH bytes ahead. }
  1590. dec(s.match_length);
  1591. until (s.match_length = 0);
  1592. inc(s.strstart);
  1593. end
  1594. else
  1595. {$endif}
  1596. begin
  1597. inc(s.strstart, s.match_length);
  1598. s.match_length := 0;
  1599. s.ins_h := s.window^[s.strstart];
  1600. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1601. s.ins_h := (( s.ins_h shl s.hash_shift) xor
  1602. s.window^[s.strstart+1]) and s.hash_mask;
  1603. if MIN_MATCH <> 3 then { the linker removes this }
  1604. begin
  1605. {Call UPDATE_HASH() MIN_MATCH-3 more times}
  1606. end;
  1607. { If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1608. matter since it will be recomputed at next deflate call. }
  1609. end;
  1610. end
  1611. else
  1612. begin
  1613. { No match, output a literal byte }
  1614. {$IFDEF ZLIB_DEBUG}
  1615. Tracevv(char(s.window^[s.strstart]));
  1616. {$ENDIF}
  1617. {_tr_tally_lit (s, 0, s.window^[s.strstart], bflush);}
  1618. bflush := _tr_tally (s, 0, s.window^[s.strstart]);
  1619. dec(s.lookahead);
  1620. inc(s.strstart);
  1621. end;
  1622. if bflush then
  1623. begin {FLUSH_BLOCK(s, FALSE);}
  1624. FLUSH_BLOCK_ONLY(s, FALSE);
  1625. if (s.strm^.avail_out = 0) then
  1626. begin
  1627. deflate_fast := need_more;
  1628. exit;
  1629. end;
  1630. end;
  1631. end;
  1632. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1633. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1634. if (s.strm^.avail_out = 0) then
  1635. begin
  1636. if flush = Z_FINISH then
  1637. deflate_fast := finish_started
  1638. else
  1639. deflate_fast := need_more;
  1640. exit;
  1641. end;
  1642. if flush = Z_FINISH then
  1643. deflate_fast := finish_done
  1644. else
  1645. deflate_fast := block_done;
  1646. end;
  1647. { ===========================================================================
  1648. Same as above, but achieves better compression. We use a lazy
  1649. evaluation for matches: a match is finally adopted only if there is
  1650. no better match at the next window position. }
  1651. {local}
  1652. function deflate_slow(var s : deflate_state; flush : integer) : block_state;
  1653. var
  1654. hash_head : IPos; { head of hash chain }
  1655. bflush : boolean; { set if current block must be flushed }
  1656. var
  1657. max_insert : cardinal;
  1658. begin
  1659. hash_head := ZNIL;
  1660. { Process the input block. }
  1661. repeat
  1662. { Make sure that we always have enough lookahead, except
  1663. at the end of the input file. We need MAX_MATCH bytes
  1664. for the next match, plus MIN_MATCH bytes to insert the
  1665. string following the next match. }
  1666. if (s.lookahead < MIN_LOOKAHEAD) then
  1667. begin
  1668. fill_window(s);
  1669. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1670. begin
  1671. deflate_slow := need_more;
  1672. exit;
  1673. end;
  1674. if s.lookahead=0 then
  1675. break; { flush the current block }
  1676. end;
  1677. { Insert the string window[strstart .. strstart+2] in the
  1678. dictionary, and set hash_head to the head of the hash chain: }
  1679. if (s.lookahead >= MIN_MATCH) then
  1680. INSERT_STRING(s, s.strstart, hash_head);
  1681. { Find the longest match, discarding those <= prev_length. }
  1682. s.prev_length := s.match_length;
  1683. s.prev_match := s.match_start;
  1684. s.match_length := MIN_MATCH-1;
  1685. if (hash_head <> ZNIL) and (s.prev_length < s.max_lazy_match) and
  1686. (s.strstart - hash_head <= {MAX_DIST}(s.w_size-MIN_LOOKAHEAD)) then
  1687. begin
  1688. { To simplify the code, we prevent matches with the string
  1689. of window index 0 (in particular we have to avoid a match
  1690. of the string with itself at the start of the input file). }
  1691. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1692. s.match_length := longest_match (s, hash_head);
  1693. { longest_match() sets match_start }
  1694. if (s.match_length <= 5) and ((s.strategy = Z_FILTERED) or
  1695. ((s.match_length = MIN_MATCH) and
  1696. (s.strstart - s.match_start > TOO_FAR))) then
  1697. begin
  1698. { If prev_match is also MIN_MATCH, match_start is garbage
  1699. but we will ignore the current match anyway. }
  1700. s.match_length := MIN_MATCH-1;
  1701. end;
  1702. end;
  1703. { If there was a match at the previous step and the current
  1704. match is not better, output the previous match: }
  1705. if (s.prev_length>=MIN_MATCH) and (s.match_length<=s.prev_length) then
  1706. begin
  1707. max_insert := s.strstart + s.lookahead - MIN_MATCH;
  1708. { Do not insert strings in hash table beyond this. }
  1709. {$ifdef ZLIB_DEBUG}
  1710. check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  1711. {$endif}
  1712. {_tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1713. s->prev_length - MIN_MATCH, bflush);}
  1714. bflush := _tr_tally(s, s.strstart -1 - s.prev_match,
  1715. s.prev_length - MIN_MATCH);
  1716. { Insert in hash table all strings up to the end of the match.
  1717. strstart-1 and strstart are already inserted. If there is not
  1718. enough lookahead, the last two strings are not inserted in
  1719. the hash table. }
  1720. {$ifdef ZLIB_DEBUG}
  1721. if s.lookahead<s.prev_length-1 then
  1722. runerror(255);
  1723. {$endif}
  1724. dec(s.lookahead, s.prev_length-1);
  1725. dec(s.prev_length, 2);
  1726. repeat
  1727. inc(s.strstart);
  1728. if s.strstart<=max_insert then
  1729. INSERT_STRING(s, s.strstart, hash_head);
  1730. dec(s.prev_length);
  1731. until s.prev_length = 0;
  1732. s.match_available := false;
  1733. s.match_length := MIN_MATCH-1;
  1734. inc(s.strstart);
  1735. if bflush then {FLUSH_BLOCK(s, FALSE);}
  1736. begin
  1737. FLUSH_BLOCK_ONLY(s,false);
  1738. if s.strm^.avail_out=0 then
  1739. begin
  1740. deflate_slow := need_more;
  1741. exit;
  1742. end;
  1743. end;
  1744. end
  1745. else
  1746. if s.match_available then
  1747. begin
  1748. { If there was no match at the previous position, output a
  1749. single literal. If there was a match but the current match
  1750. is longer, truncate the previous match to a single literal. }
  1751. {$IFDEF ZLIB_DEBUG}
  1752. Tracevv(char(s.window^[s.strstart-1]));
  1753. {$ENDIF}
  1754. bflush := _tr_tally (s, 0, s.window^[s.strstart-1]);
  1755. if bflush then
  1756. FLUSH_BLOCK_ONLY(s, FALSE);
  1757. inc(s.strstart);
  1758. {$ifdef ZLIB_DEBUG}
  1759. if s.lookahead=0 then
  1760. runerror(255);
  1761. {$endif}
  1762. dec(s.lookahead);
  1763. if (s.strm^.avail_out = 0) then
  1764. begin
  1765. deflate_slow := need_more;
  1766. exit;
  1767. end;
  1768. end
  1769. else
  1770. begin
  1771. { There is no previous match to compare with, wait for
  1772. the next step to decide. }
  1773. s.match_available := TRUE;
  1774. inc(s.strstart);
  1775. {$ifdef ZLIB_DEBUG}
  1776. if s.lookahead=0 then
  1777. runerror(255);
  1778. {$endif}
  1779. dec(s.lookahead);
  1780. end;
  1781. until false;
  1782. {$IFDEF ZLIB_DEBUG}
  1783. Assert (flush <> Z_NO_FLUSH, 'no flush?');
  1784. {$ENDIF}
  1785. if (s.match_available) then
  1786. begin
  1787. {$IFDEF ZLIB_DEBUG}
  1788. Tracevv(char(s.window^[s.strstart-1]));
  1789. bflush :=
  1790. {$ENDIF}
  1791. _tr_tally (s, 0, s.window^[s.strstart-1]);
  1792. s.match_available := FALSE;
  1793. end;
  1794. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1795. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1796. if (s.strm^.avail_out = 0) then
  1797. begin
  1798. if flush = Z_FINISH then
  1799. deflate_slow := finish_started
  1800. else
  1801. deflate_slow := need_more;
  1802. exit;
  1803. end;
  1804. if flush = Z_FINISH then
  1805. deflate_slow := finish_done
  1806. else
  1807. deflate_slow := block_done;
  1808. end;
  1809. end.