Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1193 lines
43 KiB

  1. /* DEC/CMS REPLACEMENT HISTORY, Element TREES.C */
  2. /* *1 14-NOV-1996 10:26:31 ANIGBOGU "[113914]Functions to output deflated data using Huffman encoding" */
  3. /* DEC/CMS REPLACEMENT HISTORY, Element TREES.C */
  4. /* PRIVATE FILE
  5. ******************************************************************************
  6. **
  7. ** (c) Copyright Schlumberger Technology Corp., unpublished work, created 1996.
  8. **
  9. ** This computer program includes Confidential, Proprietary Information and is
  10. ** a Trade Secret of Schlumberger Technology Corp. All use, disclosure, and/or
  11. ** reproduction is prohibited unless authorized in writing by Schlumberger.
  12. ** All Rights Reserved.
  13. **
  14. ******************************************************************************
  15. **
  16. ** compress/trees.c
  17. **
  18. ** PURPOSE
  19. **
  20. ** Output deflated data using Huffman coding
  21. **
  22. ** DISCUSSION
  23. **
  24. ** The PKZIP "deflation" process uses several Huffman trees. The more
  25. ** common source values are represented by shorter bit sequences.
  26. **
  27. ** Each code tree is stored in the ZIP file in a compressed form
  28. ** which is itself a Huffman encoding of the lengths of
  29. ** all the code strings (in ascending order by source values).
  30. ** The actual code strings are reconstructed from the lengths in
  31. ** the UNZIP process, as described in the "application note"
  32. ** (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  33. **
  34. ** REFERENCES
  35. **
  36. ** Lynch, Thomas J.
  37. ** Data Compression: Techniques and Applications, pp. 53-55.
  38. ** Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
  39. **
  40. ** Storer, James A.
  41. ** Data Compression: Methods and Theory, pp. 49-50.
  42. ** Computer Science Press, 1988. ISBN 0-7167-8156-5.
  43. **
  44. ** Sedgewick, R.
  45. ** Algorithms, p290.
  46. ** Addison-Wesley, 1983. ISBN 0-201-06672-6.
  47. **
  48. ** INTERFACE
  49. **
  50. ** void InitMatchBuffer(void)
  51. ** Allocate the match buffer, initialize the various tables.
  52. **
  53. ** void TallyFrequencies(int Dist, int MatchLength, int Level, DeflateParam_t
  54. ** *Defl, CompParam_t *Comp);
  55. ** Save the match info and tally the frequency counts.
  56. **
  57. ** long FlushBlock(char *buf, ulg stored_len, int Eof,
  58. ** LocalBits_t *Bits, CompParam_t *Comp)
  59. ** Determine the best encoding for the current block: dynamic trees,
  60. ** static trees or store, and output the encoded block to the zip
  61. ** file. Returns the total compressed length for the file so far.
  62. **
  63. ** SPECIAL REQUIREMENTS & NOTES
  64. **
  65. ** AUTHOR
  66. **
  67. ** J. C. Anigbogu
  68. ** Austin Systems Center
  69. ** Nov 1996
  70. **
  71. ******************************************************************************
  72. */
  73. #include "comppriv.h"
  74. /* ===========================================================================
  75. * Constants
  76. */
  77. #define MAX_BITS 15
  78. /* All codes must not exceed MAX_BITS bits */
  79. #define MAX_BL_BITS 7
  80. /* Bit length codes must not exceed MAX_BL_BITS bits */
  81. #define LENGTH_CODES 29
  82. /* number of length codes, not counting the special END_BLOCK code */
  83. #define LITERALS 256
  84. /* number of literal bytes 0..255 */
  85. #define END_BLOCK 256
  86. /* end of block literal code */
  87. #define L_CODES (LITERALS+1+LENGTH_CODES)
  88. /* number of Literal or Length codes, including the END_BLOCK code */
  89. #define D_CODES 30
  90. /* number of distance codes */
  91. #define BL_CODES 19
  92. /* number of codes used to transfer the bit lengths */
  93. /* extra bits for each length code */
  94. static unsigned ExtraLBits[LENGTH_CODES] =
  95. {
  96. 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
  97. };
  98. /* extra bits for each distance code */
  99. static unsigned ExtraDBits[D_CODES] =
  100. {
  101. 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
  102. };
  103. /* extra bits for each bit length code */
  104. static unsigned ExtraBlBits[BL_CODES] =
  105. {
  106. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
  107. };
  108. #define LIT_BUFSIZE 0x8000
  109. #ifndef DIST_BUFSIZE
  110. # define DIST_BUFSIZE LIT_BUFSIZE
  111. #endif
  112. /* Sizes of match buffers for literals/lengths and distances. There are
  113. * 4 reasons for limiting LIT_BUFSIZE to 64K:
  114. * - frequencies can be kept in 16 bit counters
  115. * - if compression is not successful for the first block, all input data is
  116. * still in the window so we can still emit a stored block even when input
  117. * comes from standard input. (This can also be done for all blocks if
  118. * LIT_BUFSIZE is not greater than 32K.)
  119. * - if compression is not successful for a file smaller than 64K, we can
  120. * even emit a stored file instead of a stored block (saving 5 bytes).
  121. * - creating new Huffman trees less frequently may not provide fast
  122. * adaptation to changes in the input data statistics. (Take for
  123. * example a binary file with poorly compressible code followed by
  124. * a highly compressible string table.) Smaller buffer sizes give
  125. * fast adaptation but have of course the overhead of transmitting trees
  126. * more frequently.
  127. * - I can't count above 4
  128. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  129. * memory at the expense of compression). Some optimizations would be possible
  130. * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  131. */
  132. #define REP_3_6 16
  133. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  134. #define REPZ_3_10 17
  135. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  136. #define REPZ_11_138 18
  137. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  138. /* ===========================================================================
  139. * Local data
  140. */
  141. /* Data structure describing a single value and its code string. */
  142. typedef struct ValueCodeString
  143. {
  144. union
  145. {
  146. unsigned short Frequency; /* frequency count */
  147. unsigned short Code; /* bit string */
  148. } FrequencyCode;
  149. union
  150. {
  151. unsigned short Father; /* father node in Huffman tree */
  152. unsigned short Length; /* length of bit string */
  153. } FatherLength;
  154. } ValueCodeString_t;
  155. #define HEAP_SIZE (2*L_CODES+1)
  156. /* maximum heap size */
  157. static ValueCodeString_t DynLiteralTree[HEAP_SIZE]; /* literal and length tree */
  158. static ValueCodeString_t DynDistanceTree[2*D_CODES+1]; /* distance tree */
  159. static ValueCodeString_t StaticLiteralTree[L_CODES+2];
  160. /* The static literal tree. Since the bit lengths are imposed, there is no
  161. * need for the L_CODES extra codes used during heap construction. However
  162. * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  163. * below).
  164. */
  165. static ValueCodeString_t StaticDistanceTree[D_CODES];
  166. /* The static distance tree. (Actually a trivial tree since all codes use
  167. * 5 bits.)
  168. */
  169. static ValueCodeString_t BitLengthsTree[2*BL_CODES+1];
  170. /* Huffman tree for the bit lengths */
  171. typedef struct TreeDesc
  172. {
  173. ValueCodeString_t *DynamicTree; /* the dynamic tree */
  174. ValueCodeString_t *StaticTree; /* corresponding static tree or NULL */
  175. unsigned int *ExtraBits; /* extra bits for each code or NULL */
  176. int ExtraBase; /* base index for Extrabits */
  177. int Elements; /* max number of elements in the tree */
  178. int MaxLength; /* max bit length for the codes */
  179. int MaxCode; /* largest code with non zero frequency */
  180. } TreeDesc_t;
  181. static TreeDesc_t LengthDesc =
  182. {
  183. DynLiteralTree, StaticLiteralTree, ExtraLBits, LITERALS+1, L_CODES,
  184. MAX_BITS, 0
  185. };
  186. static TreeDesc_t DistanceDesc =
  187. {
  188. DynDistanceTree, StaticDistanceTree, ExtraDBits, 0, D_CODES, MAX_BITS, 0
  189. };
  190. static TreeDesc_t BitLengthsDesc =
  191. {
  192. BitLengthsTree, (ValueCodeString_t *)0, ExtraBlBits, 0, BL_CODES, MAX_BL_BITS, 0
  193. };
  194. static unsigned short BitLengthsCount[MAX_BITS+1];
  195. /* number of codes at each bit length for an optimal tree */
  196. static unsigned char BitLengthsOrder[BL_CODES] =
  197. {
  198. 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15
  199. };
  200. /* The lengths of the bit length codes are sent in order of decreasing
  201. * probability, to avoid transmitting the lengths for unused bit length codes.
  202. */
  203. static unsigned int Heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  204. static unsigned int HeapLength; /* number of elements in the heap */
  205. static unsigned int HeapMax; /* element of largest frequency */
  206. /* The sons of Heap[n] are Heap[2*n] and Heap[2*n+1]. Heap[0] is not used.
  207. * The same heap array is used to build all trees.
  208. */
  209. static unsigned char Depth[2*L_CODES+1];
  210. /* Depth of each subtree used as tie breaker for trees of equal frequency */
  211. static unsigned char LengthCode[MAX_MATCH-MIN_MATCH+1];
  212. /* length code for each normalized match length (0 == MIN_MATCH) */
  213. static unsigned char DistanceCode[512];
  214. /* distance codes. The first 256 values correspond to the distances
  215. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  216. * the 15 bit distances.
  217. */
  218. static int BaseLength[LENGTH_CODES];
  219. /* First normalized length for each code (0 = MIN_MATCH) */
  220. static unsigned int BaseDistance[D_CODES];
  221. /* First normalized distance for each code (0 = distance of 1) */
  222. /* unsigned char Input[LIT_BUFSIZE]; buffer for literals or lengths */
  223. /* unsigned short DistBuffer[DIST_BUFSIZE]; buffer for distances */
  224. static unsigned char FlagBuffer[(LIT_BUFSIZE/8)];
  225. /* FlagBuffer is a bit array distinguishing literals from lengths in
  226. * Input, thus indicating the presence or absence of a distance.
  227. */
  228. typedef struct LocalTree
  229. {
  230. unsigned int InputIndex; /* running index in Input */
  231. unsigned int DistIndex; /* running index in DistBuffer */
  232. unsigned int FlagIndex; /* running index in FlagBuffer */
  233. unsigned char Flags; /* current flags not yet saved in FlagBuffer */
  234. unsigned char FlagBit; /* current bit used in Flags */
  235. unsigned long OptimalLength; /* bit length of current block with optimal trees */
  236. unsigned long StaticLength; /* bit length of current block with static trees */
  237. unsigned long CompressedLength; /* total bit length of compressed file */
  238. unsigned long InputLength; /* total byte length of input file */
  239. } LocalTree_t;
  240. /* InputLength is for debugging only since we can get it by other means. */
  241. /* bits are filled in Flags starting at bit 0 (least significant).
  242. * Note: these flags are overkill in the current code since we don't
  243. * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  244. */
  245. static LocalTree_t Xtree;
  246. /* ===========================================================================
  247. * Local (static) routines in this file.
  248. */
  249. static void InitializeBlock(void);
  250. static void RestoreHeap(ValueCodeString_t *Tree, int Node);
  251. static void GenerateBitLengths(TreeDesc_t *Desc);
  252. static void GenerateCodes(ValueCodeString_t *Tree, int MaxCode);
  253. static void BuildTree(TreeDesc_t *Desc);
  254. static void ScanTree(ValueCodeString_t *Tree, int MaxCode);
  255. static void SendTree(ValueCodeString_t *Tree, int MaxCode,
  256. LocalBits_t *Bits, CompParam_t *Comp);
  257. static int BuildBitLengthsTree(void);
  258. static void SendAllTrees(int LCodes, int DCodes, int BlCodes,
  259. LocalBits_t *Bits, CompParam_t *Comp);
  260. static void CompressBlock(ValueCodeString_t *LTree, ValueCodeString_t *DTree,
  261. LocalBits_t *Bits, CompParam_t *Comp);
  262. #define SendCode(c, Tree, Bits, Comp) \
  263. SendBits(Tree[c].FrequencyCode.Code, Tree[c].FatherLength.Length, Bits, Comp)
  264. /* Send a code of the given tree. c and Tree must not have side effects */
  265. #define DistCode(Dist) \
  266. ((Dist) < 256 ? DistanceCode[Dist] : DistanceCode[256+((Dist)>>7)])
  267. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  268. * must not have side effects. DistanceCode[256] and DistanceCode[257] are never
  269. * used.
  270. */
  271. /* ===========================================================================
  272. * Allocate the match buffer, initialize the various tables
  273. */
  274. void
  275. InitMatchBuffer(
  276. void
  277. )
  278. {
  279. unsigned int Count; /* iterates over tree elements */
  280. int Bits; /* bit counter */
  281. int Length; /* length value */
  282. unsigned int Code; /* code value */
  283. unsigned int Dist; /* distance index */
  284. Xtree.CompressedLength = Xtree.InputLength = 0L;
  285. if (StaticDistanceTree[0].FatherLength.Length != 0)
  286. return; /* InitMatchBuffer already called */
  287. /* Initialize the mapping length (0..255) -> length code (0..28) */
  288. Length = 0;
  289. for (Code = 0; Code < LENGTH_CODES-1; Code++)
  290. {
  291. BaseLength[Code] = Length;
  292. for (Count = 0; Count < (unsigned int)(1<<ExtraLBits[Code]); Count++)
  293. {
  294. LengthCode[Length++] = (unsigned char)Code;
  295. }
  296. }
  297. Assert (Length == 256, "InitMatchBuffer: Length != 256");
  298. /* Note that the length 255 (match length 258) can be represented
  299. * in two different ways: code 284 + 5 bits or code 285, so we
  300. * overwrite LengthCode[255] to use the best encoding:
  301. */
  302. LengthCode[Length-1] = (unsigned char)Code;
  303. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  304. Dist = 0;
  305. for (Code = 0 ; Code < 16; Code++)
  306. {
  307. BaseDistance[Code] = Dist;
  308. for (Count = 0; Count < (unsigned int)(1<<ExtraDBits[Code]); Count++)
  309. {
  310. DistanceCode[Dist++] = (unsigned char)Code;
  311. }
  312. }
  313. Assert (Dist == 256, "InitMatchBuffer: Dist != 256");
  314. Dist >>= 7; /* from now on, all distances are divided by 128 */
  315. for ( ; Code < D_CODES; Code++)
  316. {
  317. BaseDistance[Code] = Dist << 7;
  318. for (Count = 0; Count < (unsigned int)(1<<(ExtraDBits[Code]-7)); Count++)
  319. {
  320. DistanceCode[256 + Dist++] = (unsigned char)Code;
  321. }
  322. }
  323. Assert (Dist == 256, "InitMatchBuffer: 256+Dist != 512");
  324. /* Construct the codes of the static literal tree */
  325. for (Bits = 0; Bits <= MAX_BITS; Bits++)
  326. BitLengthsCount[Bits] = 0;
  327. Count = 0;
  328. while (Count <= 143)
  329. {
  330. StaticLiteralTree[Count++].FatherLength.Length = 8;
  331. BitLengthsCount[8]++;
  332. }
  333. while (Count <= 255)
  334. {
  335. StaticLiteralTree[Count++].FatherLength.Length = 9;
  336. BitLengthsCount[9]++;
  337. }
  338. while (Count <= 279)
  339. {
  340. StaticLiteralTree[Count++].FatherLength.Length = 7;
  341. BitLengthsCount[7]++;
  342. }
  343. while (Count <= 287)
  344. {
  345. StaticLiteralTree[Count++].FatherLength.Length = 8;
  346. BitLengthsCount[8]++;
  347. }
  348. /* Codes 286 and 287 do not exist, but we must include them in the
  349. * tree construction to get a canonical Huffman tree (longest code
  350. * all ones)
  351. */
  352. GenerateCodes((ValueCodeString_t *)StaticLiteralTree, L_CODES+1);
  353. /* The static distance tree is trivial: */
  354. for (Count = 0; Count < D_CODES; Count++)
  355. {
  356. StaticDistanceTree[Count].FatherLength.Length = 5;
  357. StaticDistanceTree[Count].FrequencyCode.Code =
  358. (unsigned short)ReverseBits(Count, 5);
  359. }
  360. /* Initialize the first block of the first file: */
  361. InitializeBlock();
  362. }
  363. /* ===========================================================================
  364. * Initialize a new block.
  365. */
  366. static void
  367. InitializeBlock(
  368. void
  369. )
  370. {
  371. int Count; /* iterates over tree elements */
  372. /* Initialize the trees. */
  373. for (Count = 0; Count < L_CODES; Count++)
  374. DynLiteralTree[Count].FrequencyCode.Frequency = 0;
  375. for (Count = 0; Count < D_CODES; Count++)
  376. DynDistanceTree[Count].FrequencyCode.Frequency = 0;
  377. for (Count = 0; Count < BL_CODES; Count++)
  378. BitLengthsTree[Count].FrequencyCode.Frequency = 0;
  379. DynLiteralTree[END_BLOCK].FrequencyCode.Frequency = 1;
  380. Xtree.OptimalLength = Xtree.StaticLength = 0L;
  381. Xtree.InputIndex = Xtree.DistIndex = Xtree.FlagIndex = 0;
  382. Xtree.Flags = 0; Xtree.FlagBit = 1;
  383. }
  384. #define SMALLEST 1
  385. /* Index within the heap array of least frequent node in the Huffman tree */
  386. /* ===========================================================================
  387. * Remove the smallest element from the heap and recreate the heap with
  388. * one less element. Updates Heap and HeapLength.
  389. */
  390. #define RecreateHeap(Tree, Top) \
  391. {\
  392. Top = Heap[SMALLEST]; \
  393. Heap[SMALLEST] = Heap[HeapLength--]; \
  394. RestoreHeap(Tree, SMALLEST); \
  395. }
  396. /* ===========================================================================
  397. * Compares to subtrees, using the tree depth as tie breaker when
  398. * the subtrees have equal frequency. This minimizes the worst case length.
  399. */
  400. #define Smaller(Tree, Tmp1, Tmp2) \
  401. (Tree[Tmp1].FrequencyCode.Frequency < Tree[Tmp2].FrequencyCode.Frequency || \
  402. (Tree[Tmp1].FrequencyCode.Frequency == Tree[Tmp2].FrequencyCode.Frequency \
  403. && Depth[Tmp1] <= Depth[Tmp2]))
  404. /* ===========================================================================
  405. * Restore the heap property by moving down the tree starting at node Node,
  406. * exchanging a node with the smallest of its two sons if necessary, stopping
  407. * when the heap property is re-established (each father smaller than its
  408. * two sons).
  409. */
  410. static void
  411. RestoreHeap(
  412. ValueCodeString_t *Tree, /* the tree to restore */
  413. int Node /* node to move down */
  414. )
  415. {
  416. unsigned int Father = Heap[Node];
  417. unsigned int LeftSon = (unsigned int)Node << 1; /* left son of Node */
  418. while (LeftSon <= HeapLength)
  419. {
  420. /* Set LeftSon to the smallest of the two sons: */
  421. if (LeftSon < HeapLength && (unsigned int)Smaller(Tree, Heap[LeftSon+1], Heap[LeftSon]))
  422. LeftSon++;
  423. /* Exit if Father is smaller than both sons */
  424. if (Smaller(Tree, Father, Heap[LeftSon]))
  425. break;
  426. /* Exchange Father with the smallest son */
  427. Heap[Node] = Heap[LeftSon]; Node = (int)LeftSon;
  428. /* And continue down the tree, setting LeftSon to the left son of Node */
  429. LeftSon <<= 1;
  430. }
  431. Heap[Node] = Father;
  432. }
  433. /* ===========================================================================
  434. * Compute the optimal bit lengths for a tree and update the total bit length
  435. * for the current block.
  436. * IN assertion: the fields FrequencyCode.Frequency and FatherLength.Father are set, heap[HeapMax] and
  437. * above are the tree nodes sorted by increasing frequency.
  438. * OUT assertions: the field len is set to the optimal bit length, the
  439. * array BitLengthsCount contains the frequencies for each bit length.
  440. * The length OptimalLength is updated; StaticLength is also updated if stree is
  441. * not null.
  442. */
  443. static void
  444. GenerateBitLengths(
  445. TreeDesc_t *Desc /* the tree descriptor */
  446. )
  447. {
  448. ValueCodeString_t *Tree = Desc->DynamicTree;
  449. int *Extra = (int *)Desc->ExtraBits;
  450. int Base = Desc->ExtraBase;
  451. int MaxCode = Desc->MaxCode;
  452. int MaxLength = Desc->MaxLength;
  453. ValueCodeString_t *Stree = Desc->StaticTree;
  454. unsigned int HeapIndex; /* heap index */
  455. unsigned int Tmp1, Tmp2; /* iterate over the tree elements */
  456. int Bits; /* bit length */
  457. int Xbits; /* extra bits */
  458. unsigned short Frequency; /* frequency */
  459. int Overflow = 0; /* number of elements with bit length too large */
  460. for (Bits = 0; Bits <= MAX_BITS; Bits++)
  461. BitLengthsCount[Bits] = 0;
  462. /* In a first pass, compute the optimal bit lengths (which may
  463. * overflow in the case of the bit length tree).
  464. */
  465. Tree[Heap[HeapMax]].FatherLength.Length = 0; /* root of the heap */
  466. for (HeapIndex = HeapMax+1; HeapIndex < HEAP_SIZE; HeapIndex++)
  467. {
  468. Tmp1 = Heap[HeapIndex];
  469. Bits = Tree[Tree[Tmp1].FatherLength.Father].FatherLength.Length + 1;
  470. if (Bits > MaxLength)
  471. Bits = MaxLength, Overflow++;
  472. Tree[Tmp1].FatherLength.Length = (unsigned short)Bits;
  473. /* We overwrite tree[n].Dad which is no longer needed */
  474. if (Tmp1 > (unsigned int)MaxCode)
  475. continue; /* not a leaf node */
  476. BitLengthsCount[Bits]++;
  477. Xbits = 0;
  478. if (Tmp1 >= (unsigned int)Base)
  479. Xbits = (int)Extra[Tmp1-(unsigned int)Base];
  480. Frequency = Tree[Tmp1].FrequencyCode.Frequency;
  481. Xtree.OptimalLength += (unsigned long)(Frequency * (Bits + Xbits));
  482. if (Stree)
  483. Xtree.StaticLength += (unsigned long)(Frequency * (Stree[Tmp1].FatherLength.Length + Xbits));
  484. }
  485. if (Overflow == 0)
  486. return;
  487. /* This happens for example on obj2 and pic of the Calgary corpus */
  488. /* Find the first bit length which could increase: */
  489. do
  490. {
  491. Bits = MaxLength - 1;
  492. while (BitLengthsCount[Bits] == 0)
  493. Bits--;
  494. BitLengthsCount[Bits]--; /* move one leaf down the tree */
  495. BitLengthsCount[Bits+1] += 2; /* move one overflow item as its brother */
  496. BitLengthsCount[MaxLength]--;
  497. /* The brother of the overflow item also moves one step up,
  498. * but this does not affect BitLengthsCount[MaxLength]
  499. */
  500. Overflow -= 2;
  501. } while (Overflow > 0);
  502. /* Now recompute all bit lengths, scanning in increasing frequency.
  503. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  504. * lengths instead of fixing only the wrong ones. This idea is taken
  505. * from 'ar' written by Haruhiko Okumura.)
  506. */
  507. for (Bits = MaxLength; Bits != 0; Bits--)
  508. {
  509. Tmp1 = BitLengthsCount[Bits];
  510. while (Tmp1 != 0)
  511. {
  512. Tmp2 = Heap[--HeapIndex];
  513. if (Tmp2 > (unsigned int)MaxCode)
  514. continue;
  515. if (Tree[Tmp2].FatherLength.Length != (unsigned int) Bits)
  516. {
  517. Xtree.OptimalLength += (unsigned long)((long)Bits -
  518. (long)Tree[Tmp2].FatherLength.Length)*(long)Tree[Tmp2].FrequencyCode.Frequency;
  519. Tree[Tmp2].FatherLength.Length = (unsigned short)Bits;
  520. }
  521. Tmp1--;
  522. }
  523. }
  524. }
  525. /* ===========================================================================
  526. * Generate the codes for a given tree and bit counts (which need not be
  527. * optimal).
  528. * IN assertion: the array BitLengthsCount contains the bit length statistics for
  529. * the given tree and the field len is set for all tree elements.
  530. * OUT assertion: the field code is set for all tree elements of non
  531. * zero code length.
  532. */
  533. static void
  534. GenerateCodes(
  535. ValueCodeString_t *Tree, /* the tree to decorate */
  536. int MaxCode /* largest code with non zero frequency */
  537. )
  538. {
  539. unsigned short NextCode[MAX_BITS+1]; /* next code value for each bit length */
  540. unsigned short Code = 0; /* running code value */
  541. int BitIndex; /* bit index */
  542. int CodeIndex; /* code index */
  543. /* The distribution counts are first used to generate the code values
  544. * without bit reversal.
  545. */
  546. NextCode[0] = 0; /* For lint error 771 */
  547. for (BitIndex = 1; BitIndex <= MAX_BITS; BitIndex++)
  548. {
  549. NextCode[BitIndex] = Code = (unsigned short)((Code + BitLengthsCount[BitIndex-1]) << 1);
  550. }
  551. /* Check that the bit counts in BitLengthsCount are consistent. The last code
  552. * must be all ones.
  553. */
  554. Assert(Code + BitLengthsCount[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  555. "inconsistent bit counts");
  556. for (CodeIndex = 0; CodeIndex <= MaxCode; CodeIndex++)
  557. {
  558. int Length = Tree[CodeIndex].FatherLength.Length;
  559. if (Length == 0)
  560. continue;
  561. /* Now reverse the bits */
  562. Tree[CodeIndex].FrequencyCode.Code = (unsigned short)ReverseBits((unsigned int)NextCode[Length]++, Length);
  563. }
  564. }
  565. /* ===========================================================================
  566. * Construct one Huffman tree and assign the code bit strings and lengths.
  567. * Update the total bit length for the current block.
  568. * IN assertion: the field FrequencyCode.Frequency is set for all tree elements.
  569. * OUT assertions: the fields len and code are set to the optimal bit length
  570. * and corresponding code. The length OptimalLength is updated; StaticLength is
  571. * also updated if stree is not null. The field MaxCode is set.
  572. */
  573. static void
  574. BuildTree(
  575. TreeDesc_t *Desc /* the tree descriptor */
  576. )
  577. {
  578. ValueCodeString_t *Tree = Desc->DynamicTree;
  579. ValueCodeString_t *Stree = Desc->StaticTree;
  580. int Elements = Desc->Elements;
  581. unsigned int Tmp1, Tmp2; /* iterate over heap elements */
  582. int MaxCode = -1; /* largest code with non zero frequency */
  583. int Node = Elements; /* next internal node of the tree */
  584. /* Construct the initial heap, with least frequent element in
  585. * Heap[SMALLEST]. The sons of Heap[n] are Heap[2*n] and Heap[2*n+1].
  586. * Heap[0] is not used.
  587. */
  588. HeapLength = 0;
  589. HeapMax = HEAP_SIZE;
  590. for (Tmp1 = 0; Tmp1 < (unsigned int)Elements; Tmp1++)
  591. {
  592. if (Tree[Tmp1].FrequencyCode.Frequency != 0)
  593. {
  594. Heap[++HeapLength] = Tmp1;
  595. MaxCode = (int)Tmp1;
  596. Depth[Tmp1] = 0;
  597. }
  598. else
  599. {
  600. Tree[Tmp1].FatherLength.Length = 0;
  601. }
  602. }
  603. /* The pkzip format requires that at least one distance code exists,
  604. * and that at least one bit should be sent even if there is only one
  605. * possible code. So to avoid special checks later on we force at least
  606. * two codes of non zero frequency.
  607. */
  608. while (HeapLength < 2)
  609. {
  610. unsigned int New = Heap[++HeapLength] = (unsigned int)(MaxCode < 2 ? ++MaxCode : 0);
  611. Tree[New].FrequencyCode.Frequency = 1;
  612. Depth[New] = 0;
  613. Xtree.OptimalLength--;
  614. if (Stree)
  615. Xtree.StaticLength -= Stree[New].FatherLength.Length;
  616. /* new is 0 or 1 so it does not have extra bits */
  617. }
  618. Desc->MaxCode = MaxCode;
  619. /* The elements Heap[HeapLength/2+1 .. HeapLength] are leaves of the tree,
  620. * establish sub-heaps of increasing lengths:
  621. */
  622. for (Tmp1 = HeapLength/2; Tmp1 >= 1; Tmp1--)
  623. RestoreHeap(Tree, (int)Tmp1);
  624. /* Construct the Huffman tree by repeatedly combining the least two
  625. * frequent nodes.
  626. */
  627. do
  628. {
  629. RecreateHeap(Tree, Tmp1); /* Tmp1 = node of least frequency */
  630. Tmp2 = Heap[SMALLEST]; /* Tmp2 = node of next least frequency */
  631. Heap[--HeapMax] = Tmp1; /* keep the nodes sorted by frequency */
  632. Heap[--HeapMax] = Tmp2;
  633. /* Create a new node father of Tmp1 and Tmp2 */
  634. Tree[Node].FrequencyCode.Frequency = (unsigned short)(Tree[Tmp1].FrequencyCode.Frequency +
  635. Tree[Tmp2].FrequencyCode.Frequency);
  636. Depth[Node] = (unsigned char) (MAX(Depth[Tmp1], Depth[Tmp2]) + 1);
  637. Tree[Tmp1].FatherLength.Father = Tree[Tmp2].FatherLength.Father = (unsigned short)Node;
  638. /* and insert the new node in the Heap */
  639. Heap[SMALLEST] = (unsigned int)Node++;
  640. RestoreHeap(Tree, SMALLEST);
  641. } while (HeapLength >= 2);
  642. Heap[--HeapMax] = Heap[SMALLEST];
  643. /* At this point, the fields FrequencyCode.Frequency and FatherLength.Father are set. We can now
  644. * generate the bit lengths.
  645. */
  646. GenerateBitLengths((TreeDesc_t *)Desc);
  647. /* The field len is now set, we can generate the bit codes */
  648. GenerateCodes ((ValueCodeString_t *)Tree, MaxCode);
  649. }
  650. /* ===========================================================================
  651. * Scan a literal or distance tree to determine the frequencies of the codes
  652. * in the bit length tree. Updates OptimalLength to take into account the repeat
  653. * counts. (The contribution of the bit length codes will be added later
  654. * during the construction of BitLengthsTree.)
  655. */
  656. static void
  657. ScanTree(
  658. ValueCodeString_t *Tree, /* the tree to be scanned */
  659. int MaxCode /* and its largest code of non zero frequency */
  660. )
  661. {
  662. int Iter; /* iterates over all tree elements */
  663. int PrevLength = -1; /* last emitted length */
  664. int CurLength; /* length of current code */
  665. int NextLength = Tree[0].FatherLength.Length; /* length of next code */
  666. int Count = 0; /* repeat count of the current code */
  667. int MaxCount = 7; /* max repeat count */
  668. int MinCount = 4; /* min repeat count */
  669. if (NextLength == 0)
  670. {
  671. MaxCount = 138;
  672. MinCount = 3;
  673. }
  674. Tree[MaxCode+1].FatherLength.Length = (unsigned short)0xffff; /* guard */
  675. for (Iter = 0; Iter <= MaxCode; Iter++)
  676. {
  677. CurLength = NextLength;
  678. NextLength = Tree[Iter+1].FatherLength.Length;
  679. if (++Count < MaxCount && CurLength == NextLength)
  680. continue;
  681. else if (Count < MinCount)
  682. BitLengthsTree[CurLength].FrequencyCode.Frequency += (unsigned short)Count;
  683. else if (CurLength != 0)
  684. {
  685. if (CurLength != PrevLength)
  686. BitLengthsTree[CurLength].FrequencyCode.Frequency++;
  687. BitLengthsTree[REP_3_6].FrequencyCode.Frequency++;
  688. }
  689. else if (Count <= 10)
  690. BitLengthsTree[REPZ_3_10].FrequencyCode.Frequency++;
  691. else
  692. BitLengthsTree[REPZ_11_138].FrequencyCode.Frequency++;
  693. Count = 0;
  694. PrevLength = CurLength;
  695. if (NextLength == 0)
  696. {
  697. MaxCount = 13;
  698. MinCount = 3;
  699. }
  700. else if (CurLength == NextLength)
  701. {
  702. MaxCount = 6;
  703. MinCount = 3;
  704. }
  705. else
  706. {
  707. MaxCount = 7;
  708. MinCount = 4;
  709. }
  710. }
  711. }
  712. /* ===========================================================================
  713. * Send a literal or distance tree in compressed form, using the codes in
  714. * BitLengthsTree.
  715. */
  716. static void
  717. SendTree(
  718. ValueCodeString_t *Tree, /* the tree to be scanned */
  719. int MaxCode, /* and its largest code of non zero frequency */
  720. LocalBits_t *Bits,
  721. CompParam_t *Comp
  722. )
  723. {
  724. int Iter; /* iterates over all tree elements */
  725. int PrevLength = -1; /* last emitted length */
  726. int CurLength; /* length of current code */
  727. int NextLength = Tree[0].FatherLength.Length; /* length of next code */
  728. int Count = 0; /* repeat count of the current code */
  729. int MaxCount = 7; /* max repeat count */
  730. int MinCount = 4; /* min repeat count */
  731. /* tree[MaxCode+1].FatherLength.Length = -1; */ /* guard already set */
  732. if (NextLength == 0)
  733. {
  734. MaxCount = 138;
  735. MinCount = 3;
  736. }
  737. for (Iter = 0; Iter <= MaxCode; Iter++)
  738. {
  739. CurLength = NextLength;
  740. NextLength = Tree[Iter+1].FatherLength.Length;
  741. if (++Count < MaxCount && CurLength == NextLength)
  742. continue;
  743. else if (Count < MinCount)
  744. {
  745. do
  746. {
  747. SendCode(CurLength, BitLengthsTree, Bits, Comp);
  748. } while (--Count != 0);
  749. }
  750. else if (CurLength != 0)
  751. {
  752. if (CurLength != PrevLength)
  753. {
  754. SendCode(CurLength, BitLengthsTree, Bits, Comp);
  755. Count--;
  756. }
  757. Assert(Count >= 3 && Count <= 6, " 3_6?");
  758. SendCode(REP_3_6, BitLengthsTree, Bits, Comp);
  759. SendBits(Count-3, 2, Bits, Comp);
  760. }
  761. else if (Count <= 10)
  762. {
  763. SendCode(REPZ_3_10, BitLengthsTree, Bits, Comp);
  764. SendBits(Count-3, 3, Bits, Comp);
  765. }
  766. else
  767. {
  768. SendCode(REPZ_11_138, BitLengthsTree, Bits, Comp);
  769. SendBits(Count-11, 7, Bits, Comp);
  770. }
  771. Count = 0;
  772. PrevLength = CurLength;
  773. if (NextLength == 0)
  774. {
  775. MaxCount = 138;
  776. MinCount = 3;
  777. }
  778. else if (CurLength == NextLength)
  779. {
  780. MaxCount = 6;
  781. MinCount = 3;
  782. }
  783. else
  784. {
  785. MaxCount = 7;
  786. MinCount = 4;
  787. }
  788. }
  789. }
  790. /* ===========================================================================
  791. * Construct the Huffman tree for the bit lengths and return the index in
  792. * BitLengthsOrder of the last bit length code to send.
  793. */
  794. static int
  795. BuildBitLengthsTree(
  796. void
  797. )
  798. {
  799. int MaxIndex; /* index of last bit length code of non zero FrequencyCode.Frequency */
  800. /* Determine the bit length frequencies for literal and distance trees */
  801. ScanTree((ValueCodeString_t *)DynLiteralTree, LengthDesc.MaxCode);
  802. ScanTree((ValueCodeString_t *)DynDistanceTree, DistanceDesc.MaxCode);
  803. /* Build the bit length tree: */
  804. BuildTree((TreeDesc_t *)(&BitLengthsDesc));
  805. /* OptimalLength now includes the length of the tree representations, except
  806. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  807. */
  808. /* Determine the number of bit length codes to send. The pkzip format
  809. * requires that at least 4 bit length codes be sent. (appnote.txt says
  810. * 3 but the actual value used is 4.)
  811. */
  812. for (MaxIndex = BL_CODES-1; MaxIndex >= 3; MaxIndex--)
  813. {
  814. if (BitLengthsTree[BitLengthsOrder[MaxIndex]].FatherLength.Length != 0)
  815. break;
  816. }
  817. /* Update OptimalLength to include the bit length tree and counts */
  818. Xtree.OptimalLength += (unsigned long)(3*(MaxIndex+1) + 5+5+4);
  819. return MaxIndex;
  820. }
  821. /* ===========================================================================
  822. * Send the header for a block using dynamic Huffman trees: the counts, the
  823. * lengths of the bit length codes, the literal tree and the distance tree.
  824. * IN assertion: LCodes >= 257, DCodes >= 1, BlCodes >= 4.
  825. */
  826. static void
  827. SendAllTrees(
  828. int LCodes,
  829. int DCodes,
  830. int BlCodes, /* number of codes for each tree */
  831. LocalBits_t *Bits,
  832. CompParam_t *Comp
  833. )
  834. {
  835. int Rank; /* index in BitLengthsOrder */
  836. Assert (LCodes >= 257 && DCodes >= 1 && BlCodes >= 4,
  837. "not enough codes");
  838. Assert (LCodes <= L_CODES && DCodes <= D_CODES && BlCodes <= BL_CODES,
  839. "too many codes");
  840. SendBits(LCodes-257, 5, Bits, Comp); /* not +255 as stated in appnote.txt */
  841. SendBits(DCodes-1, 5, Bits, Comp);
  842. SendBits(BlCodes-4, 4, Bits, Comp); /* not -3 as stated in appnote.txt */
  843. for (Rank = 0; Rank < BlCodes; Rank++)
  844. {
  845. SendBits(BitLengthsTree[BitLengthsOrder[Rank]].FatherLength.Length, 3, Bits, Comp);
  846. }
  847. SendTree((ValueCodeString_t *)DynLiteralTree, LCodes-1, Bits, Comp);
  848. /* send the literal tree */
  849. SendTree((ValueCodeString_t *)DynDistanceTree, DCodes-1, Bits, Comp); /* send the distance tree */
  850. }
  851. /* ===========================================================================
  852. * Determine the best encoding for the current block: dynamic trees, static
  853. * trees or store, and output the encoded block to the zip buffer. This function
  854. * returns the total compressed length for the data so far.
  855. */
  856. unsigned long
  857. FlushBlock(
  858. char *Input, /* input block, or NULL if too old */
  859. unsigned long StoredLength, /* length of input block */
  860. int Eof, /* true if this is the last block for a buffer */
  861. LocalBits_t *Bits,
  862. CompParam_t *Comp
  863. )
  864. {
  865. unsigned long OptLengthb, StaticLengthb;
  866. /* OptLength and StaticLength in bytes */
  867. int MaxIndex; /* index of last bit length code of non zero FrequencyCode.Frequency */
  868. FlagBuffer[Xtree.FlagIndex] = Xtree.Flags; /* Save the flags for the last 8 items */
  869. /* Construct the literal and distance trees */
  870. BuildTree((TreeDesc_t *)(&LengthDesc));
  871. BuildTree((TreeDesc_t *)(&DistanceDesc));
  872. /* At this point, OptimalLength and StaticLength are the total bit lengths of
  873. * the compressed block data, excluding the tree representations.
  874. */
  875. /* Build the bit length tree for the above two trees, and get the index
  876. * in BitLengthsOrder of the last bit length code to send.
  877. */
  878. MaxIndex = BuildBitLengthsTree();
  879. /* Determine the best encoding. Compute first the block length in bytes */
  880. OptLengthb = (Xtree.OptimalLength+3+7)>>3;
  881. StaticLengthb = (Xtree.StaticLength+3+7)>>3;
  882. Xtree.InputLength += StoredLength; /* for debugging only */
  883. if (StaticLengthb <= OptLengthb)
  884. OptLengthb = StaticLengthb;
  885. /* If compression failed and this is the first and last block,
  886. * the whole buffer is transformed into a stored buffer:
  887. */
  888. if (StoredLength <= OptLengthb && Eof && Xtree.CompressedLength == 0L)
  889. {
  890. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  891. if (Input == (char *)0)
  892. return BLOCK_VANISHED;
  893. CopyBlock(Input, (unsigned int)StoredLength, 0, Bits, Comp);
  894. /* without header */
  895. Xtree.CompressedLength = StoredLength << 3;
  896. }
  897. else if (StoredLength+4 <= OptLengthb && Input != (char *)0)
  898. {
  899. /* 4: two words for the lengths */
  900. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  901. * Otherwise we can't have processed more than WSIZE input bytes since
  902. * the last block flush, because compression would have been
  903. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  904. * transform a block into a stored block.
  905. */
  906. SendBits((STORED_BLOCK<<1)+Eof, 3, Bits, Comp); /* send block type */
  907. Xtree.CompressedLength = (Xtree.CompressedLength + 3 + 7) & ~7L;
  908. Xtree.CompressedLength += (StoredLength + 4) << 3;
  909. CopyBlock(Input, (unsigned int)StoredLength, 1, Bits, Comp); /* with header */
  910. }
  911. else if (StaticLengthb == OptLengthb)
  912. {
  913. SendBits((STATIC_TREES<<1)+Eof, 3, Bits, Comp);
  914. CompressBlock((ValueCodeString_t *)StaticLiteralTree, (ValueCodeString_t *)StaticDistanceTree, Bits,
  915. Comp);
  916. Xtree.CompressedLength += 3 + Xtree.StaticLength;
  917. }
  918. else
  919. {
  920. SendBits((DYN_TREES<<1)+Eof, 3, Bits, Comp);
  921. SendAllTrees(LengthDesc.MaxCode+1, DistanceDesc.MaxCode+1,
  922. MaxIndex+1, Bits, Comp);
  923. CompressBlock((ValueCodeString_t *)DynLiteralTree, (ValueCodeString_t *)DynDistanceTree,
  924. Bits, Comp);
  925. Xtree.CompressedLength += 3 + Xtree.OptimalLength;
  926. }
  927. Assert (Xtree.CompressedLength == bits_sent, "bad compressed size");
  928. InitializeBlock();
  929. if (Eof)
  930. {
  931. Assert (Xtree.InputLength == Comp->InputSize, "bad input size");
  932. WindupBits(Bits, Comp);
  933. Xtree.CompressedLength += 7; /* align on byte boundary */
  934. }
  935. return Xtree.CompressedLength >> 3;
  936. }
  937. /* ===========================================================================
  938. * Save the match info and tally the frequency counts. Return true if
  939. * the current block must be flushed.
  940. */
  941. int
  942. TallyFrequencies(
  943. int Dist, /* distance of matched string */
  944. int LengthC, /* match length-MIN_MATCH or unmatched char (if dist==0) */
  945. int Level, /* compression level */
  946. DeflateParam_t *Defl,
  947. CompParam_t *Comp
  948. )
  949. {
  950. Comp->Input[Xtree.InputIndex++] = (unsigned char)LengthC;
  951. if (Dist == 0)
  952. {
  953. /* LengthC is the unmatched char */
  954. DynLiteralTree[LengthC].FrequencyCode.Frequency++;
  955. }
  956. else
  957. {
  958. /* Here, LengthC is the match length - MIN_MATCH */
  959. Dist--; /* dist = match distance - 1 */
  960. Assert((unsigned short)Dist < (unsigned short)MAX_DIST &&
  961. (unsigned short)LengthC <= (unsigned short)(MAX_MATCH-MIN_MATCH) &&
  962. (unsigned short)DistCode(Dist) < (unsigned short)D_CODES,
  963. "TallyFrequencies: bad match");
  964. DynLiteralTree[LengthCode[LengthC]+LITERALS+1].FrequencyCode.Frequency++;
  965. DynDistanceTree[DistCode((unsigned int)Dist)].FrequencyCode.Frequency++;
  966. Comp->DistBuffer[Xtree.DistIndex++] = (unsigned short)Dist;
  967. Xtree.Flags |= Xtree.FlagBit;
  968. }
  969. Xtree.FlagBit <<= 1;
  970. /* Output the flags if they fill a byte: */
  971. if ((Xtree.InputIndex & 7) == 0)
  972. {
  973. FlagBuffer[Xtree.FlagIndex++] = Xtree.Flags;
  974. Xtree.Flags = 0;
  975. Xtree.FlagBit = 1;
  976. }
  977. /* Try to guess if it is profitable to stop the current block here */
  978. if (Level > 2 && (Xtree.InputIndex & 0xfff) == 0)
  979. {
  980. /* Compute an upper bound for the compressed length */
  981. unsigned long OutLength = (unsigned long)Xtree.InputIndex*8L;
  982. unsigned long InLength = (unsigned long)((long)Defl->StringStart-Defl->BlockStart);
  983. int DCode;
  984. for (DCode = 0; DCode < D_CODES; DCode++)
  985. {
  986. OutLength += (unsigned long)(DynDistanceTree[DCode].FrequencyCode.Frequency*(5L+ExtraDBits[DCode]));
  987. }
  988. OutLength >>= 3;
  989. if (Xtree.DistIndex < Xtree.InputIndex/2 && OutLength < InLength/2)
  990. return 1;
  991. }
  992. return (Xtree.InputIndex == LIT_BUFSIZE-1 || Xtree.DistIndex == DIST_BUFSIZE);
  993. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  994. * on 16 bit machines and because stored blocks are restricted to
  995. * 64K-1 bytes.
  996. */
  997. }
  998. /* ===========================================================================
  999. * Send the block data compressed using the given Huffman trees
  1000. */
  1001. static void
  1002. CompressBlock(
  1003. ValueCodeString_t *LTree, /* literal tree */
  1004. ValueCodeString_t *DTree, /* distance tree */
  1005. LocalBits_t *Bits,
  1006. CompParam_t *Comp
  1007. )
  1008. {
  1009. unsigned int Distance; /* distance of matched string */
  1010. int MatchLength; /* match length or unmatched char (if Distance == 0) */
  1011. unsigned int InputIndex = 0; /* running index in Input */
  1012. unsigned int DistIndex = 0; /* running index in DistBuffer */
  1013. unsigned int FlagIndex = 0; /* running index in FlagBuffer */
  1014. unsigned char Flag = 0; /* current flags */
  1015. unsigned int Code; /* the code to send */
  1016. int Extra; /* number of extra bits to send */
  1017. if (Xtree.InputIndex != 0)
  1018. do
  1019. {
  1020. if ((InputIndex & 7) == 0)
  1021. Flag = FlagBuffer[FlagIndex++];
  1022. MatchLength = Comp->Input[InputIndex++];
  1023. if ((Flag & 1) == 0)
  1024. {
  1025. SendCode(MatchLength, LTree, Bits, Comp); /* send a literal byte */
  1026. }
  1027. else
  1028. {
  1029. /* Here, MatchLength is the match length - MIN_MATCH */
  1030. Code = LengthCode[MatchLength];
  1031. /* send the length code */
  1032. SendCode(Code + LITERALS + 1, LTree, Bits, Comp);
  1033. Extra = (int)ExtraLBits[Code];
  1034. if (Extra != 0)
  1035. {
  1036. MatchLength -= BaseLength[Code];
  1037. SendBits(MatchLength, Extra, Bits, Comp);
  1038. /* send the extra length bits */
  1039. }
  1040. Distance = Comp->DistBuffer[DistIndex++];
  1041. /* Here, Distance is the match distance - 1 */
  1042. Code = DistCode(Distance);
  1043. Assert (Code < D_CODES, "bad DistCode");
  1044. /* send the distance code */
  1045. SendCode((int)Code, DTree, Bits, Comp);
  1046. Extra = (int)ExtraDBits[Code];
  1047. if (Extra != 0)
  1048. {
  1049. Distance -= BaseDistance[Code];
  1050. SendBits((int)Distance, Extra, Bits, Comp);
  1051. /* send the extra distance bits */
  1052. }
  1053. } /* literal or match pair ? */
  1054. Flag >>= 1;
  1055. } while (InputIndex < Xtree.InputIndex);
  1056. SendCode(END_BLOCK, LTree, Bits, Comp);
  1057. }