deflate.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <flate.h>
  4. typedef struct Chain Chain;
  5. typedef struct Chains Chains;
  6. typedef struct Dyncode Dyncode;
  7. typedef struct Huff Huff;
  8. typedef struct LZblock LZblock;
  9. typedef struct LZstate LZstate;
  10. enum
  11. {
  12. /*
  13. * deflate format paramaters
  14. */
  15. DeflateUnc = 0, /* uncompressed block */
  16. DeflateFix = 1, /* fixed huffman codes */
  17. DeflateDyn = 2, /* dynamic huffman codes */
  18. DeflateEob = 256, /* end of block code in lit/len book */
  19. DeflateMaxBlock = 64*1024-1, /* maximum size of uncompressed block */
  20. DeflateMaxExp = 10, /* maximum expansion for a block */
  21. LenStart = 257, /* start of length codes in litlen */
  22. Nlitlen = 288, /* number of litlen codes */
  23. Noff = 30, /* number of offset codes */
  24. Nclen = 19, /* number of codelen codes */
  25. MaxOff = 32*1024,
  26. MinMatch = 3, /* shortest match possible */
  27. MaxMatch = 258, /* longest match possible */
  28. /*
  29. * huffman code paramaters
  30. */
  31. MaxLeaf = Nlitlen,
  32. MaxHuffBits = 16, /* max bits in a huffman code */
  33. ChainMem = 2 * (MaxHuffBits - 1) * MaxHuffBits,
  34. /*
  35. * coding of the lz parse
  36. */
  37. LenFlag = 1 << 3,
  38. LenShift = 4, /* leaves enough space for MinMatchMaxOff */
  39. MaxLitRun = LenFlag - 1,
  40. /*
  41. * internal lz paramaters
  42. */
  43. DeflateOut = 4096, /* output buffer size */
  44. BlockSize = 8192, /* attempted input read quanta */
  45. DeflateBlock = DeflateMaxBlock & ~(BlockSize - 1),
  46. MinMatchMaxOff = 4096, /* max profitable offset for small match;
  47. * assumes 8 bits for len, 5+10 for offset
  48. * DONT CHANGE WITHOUT CHANGING LZPARSE CONSTANTS
  49. */
  50. HistSlop = 512, /* must be at lead MaxMatch */
  51. HistBlock = 64*1024,
  52. HistSize = HistBlock + HistSlop,
  53. HashLog = 13,
  54. HashSize = 1<<HashLog,
  55. MaxOffCode = 256, /* biggest offset looked up in direct table */
  56. EstLitBits = 8,
  57. EstLenBits = 4,
  58. EstOffBits = 5,
  59. };
  60. /*
  61. * knuth vol. 3 multiplicative hashing
  62. * each byte x chosen according to rules
  63. * 1/4 < x < 3/10, 1/3 x < < 3/7, 4/7 < x < 2/3, 7/10 < x < 3/4
  64. * with reasonable spread between the bytes & their complements
  65. *
  66. * the 3 byte value appears to be as almost good as the 4 byte value,
  67. * and might be faster on some machines
  68. */
  69. /*
  70. #define hashit(c) (((ulong)(c) * 0x6b43a9) >> (24 - HashLog))
  71. */
  72. #define hashit(c) ((((ulong)(c) & 0xffffff) * 0x6b43a9b5) >> (32 - HashLog))
  73. /*
  74. * lempel-ziv style compression state
  75. */
  76. struct LZstate
  77. {
  78. uchar hist[HistSize];
  79. ulong pos; /* current location in history buffer */
  80. ulong avail; /* data available after pos */
  81. int eof;
  82. ushort hash[HashSize]; /* hash chains */
  83. ushort nexts[MaxOff];
  84. int now; /* pos in hash chains */
  85. int dot; /* dawn of time in history */
  86. int prevlen; /* lazy matching state */
  87. int prevoff;
  88. int maxcheck; /* compressor tuning */
  89. uchar obuf[DeflateOut];
  90. uchar *out; /* current position in the output buffer */
  91. uchar *eout;
  92. ulong bits; /* bit shift register */
  93. int nbits;
  94. int rbad; /* got an error reading the buffer */
  95. int wbad; /* got an error writing the buffer */
  96. int (*w)(void*, void*, int);
  97. void *wr;
  98. ulong totr; /* total input size */
  99. ulong totw; /* total output size */
  100. int debug;
  101. };
  102. struct LZblock
  103. {
  104. ushort parse[DeflateMaxBlock / 2 + 1];
  105. int lastv; /* value being constucted for parse */
  106. ulong litlencount[Nlitlen];
  107. ulong offcount[Noff];
  108. ushort *eparse; /* limit for parse table */
  109. int bytes; /* consumed from the input */
  110. int excost; /* cost of encoding extra len & off bits */
  111. };
  112. /*
  113. * huffman code table
  114. */
  115. struct Huff
  116. {
  117. short bits; /* length of the code */
  118. ushort encode; /* the code */
  119. };
  120. /*
  121. * encoding of dynamic huffman trees
  122. */
  123. struct Dyncode
  124. {
  125. int nlit;
  126. int noff;
  127. int nclen;
  128. int ncode;
  129. Huff codetab[Nclen];
  130. uchar codes[Nlitlen+Noff];
  131. uchar codeaux[Nlitlen+Noff];
  132. };
  133. static int deflateb(LZstate *lz, LZblock *lzb, void *rr, int (*r)(void*, void*, int));
  134. static int lzcomp(LZstate*, LZblock*, uchar*, ushort*, int finish);
  135. static void wrblock(LZstate*, int, ushort*, ushort*, Huff*, Huff*);
  136. static int bitcost(Huff*, ulong*, int);
  137. static int huffcodes(Dyncode*, Huff*, Huff*);
  138. static void wrdyncode(LZstate*, Dyncode*);
  139. static void lzput(LZstate*, ulong bits, int nbits);
  140. static void lzflushbits(LZstate*);
  141. static void lzflush(LZstate *lz);
  142. static void lzwrite(LZstate *lz, void *buf, int n);
  143. static int hufftabinit(Huff*, int, ulong*, int);
  144. static int mkgzprecode(Huff*, ulong *, int, int);
  145. static int mkprecode(Huff*, ulong *, int, int, ulong*);
  146. static void nextchain(Chains*, int);
  147. static void leafsort(ulong*, ushort*, int, int);
  148. /* conversion from len to code word */
  149. static int lencode[MaxMatch];
  150. /*
  151. * conversion from off to code word
  152. * off <= MaxOffCode ? offcode[off] : bigoffcode[off >> 7]
  153. */
  154. static int offcode[MaxOffCode];
  155. static int bigoffcode[256];
  156. /* litlen code words LenStart-285 extra bits */
  157. static int litlenbase[Nlitlen-LenStart];
  158. static int litlenextra[Nlitlen-LenStart] =
  159. {
  160. /* 257 */ 0, 0, 0,
  161. /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
  162. /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
  163. /* 280 */ 4, 5, 5, 5, 5, 0, 0, 0
  164. };
  165. /* offset code word extra bits */
  166. static int offbase[Noff];
  167. static int offextra[] =
  168. {
  169. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  170. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  171. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  172. 0, 0,
  173. };
  174. /* order code lengths */
  175. static int clenorder[Nclen] =
  176. {
  177. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  178. };
  179. /* static huffman tables */
  180. static Huff litlentab[Nlitlen];
  181. static Huff offtab[Noff];
  182. static Huff hofftab[Noff];
  183. /* bit reversal for brain dead endian swap in huffman codes */
  184. static uchar revtab[256];
  185. static ulong nlits;
  186. static ulong nmatches;
  187. int
  188. deflateinit(void)
  189. {
  190. ulong bitcount[MaxHuffBits];
  191. int i, j, ci, n;
  192. /* byte reverse table */
  193. for(i=0; i<256; i++)
  194. for(j=0; j<8; j++)
  195. if(i & (1<<j))
  196. revtab[i] |= 0x80 >> j;
  197. /* static Litlen bit lengths */
  198. for(i=0; i<144; i++)
  199. litlentab[i].bits = 8;
  200. for(i=144; i<256; i++)
  201. litlentab[i].bits = 9;
  202. for(i=256; i<280; i++)
  203. litlentab[i].bits = 7;
  204. for(i=280; i<Nlitlen; i++)
  205. litlentab[i].bits = 8;
  206. memset(bitcount, 0, sizeof(bitcount));
  207. bitcount[8] += 144 - 0;
  208. bitcount[9] += 256 - 144;
  209. bitcount[7] += 280 - 256;
  210. bitcount[8] += Nlitlen - 280;
  211. if(!hufftabinit(litlentab, Nlitlen, bitcount, 9))
  212. return FlateInternal;
  213. /* static offset bit lengths */
  214. for(i = 0; i < Noff; i++)
  215. offtab[i].bits = 5;
  216. memset(bitcount, 0, sizeof(bitcount));
  217. bitcount[5] = Noff;
  218. if(!hufftabinit(offtab, Noff, bitcount, 5))
  219. return FlateInternal;
  220. bitcount[0] = 0;
  221. bitcount[1] = 0;
  222. if(!mkgzprecode(hofftab, bitcount, 2, MaxHuffBits))
  223. return FlateInternal;
  224. /* conversion tables for lens & offs to codes */
  225. ci = 0;
  226. for(i = LenStart; i < 286; i++){
  227. n = ci + (1 << litlenextra[i - LenStart]);
  228. litlenbase[i - LenStart] = ci;
  229. for(; ci < n; ci++)
  230. lencode[ci] = i;
  231. }
  232. /* patch up special case for len MaxMatch */
  233. lencode[MaxMatch-MinMatch] = 285;
  234. litlenbase[285-LenStart] = MaxMatch-MinMatch;
  235. ci = 0;
  236. for(i = 0; i < 16; i++){
  237. n = ci + (1 << offextra[i]);
  238. offbase[i] = ci;
  239. for(; ci < n; ci++)
  240. offcode[ci] = i;
  241. }
  242. ci = ci >> 7;
  243. for(; i < 30; i++){
  244. n = ci + (1 << (offextra[i] - 7));
  245. offbase[i] = ci << 7;
  246. for(; ci < n; ci++)
  247. bigoffcode[ci] = i;
  248. }
  249. return FlateOk;
  250. }
  251. static void
  252. deflatereset(LZstate *lz, int level, int debug)
  253. {
  254. memset(lz->nexts, 0, sizeof lz->nexts);
  255. memset(lz->hash, 0, sizeof lz->hash);
  256. lz->totr = 0;
  257. lz->totw = 0;
  258. lz->pos = 0;
  259. lz->avail = 0;
  260. lz->out = lz->obuf;
  261. lz->eout = &lz->obuf[DeflateOut];
  262. lz->prevlen = MinMatch - 1;
  263. lz->prevoff = 0;
  264. lz->now = MaxOff + 1;
  265. lz->dot = lz->now;
  266. lz->bits = 0;
  267. lz->nbits = 0;
  268. lz->maxcheck = (1 << level);
  269. lz->maxcheck -= lz->maxcheck >> 2;
  270. if(lz->maxcheck < 2)
  271. lz->maxcheck = 2;
  272. else if(lz->maxcheck > 1024)
  273. lz->maxcheck = 1024;
  274. lz->debug = debug;
  275. }
  276. int
  277. deflate(void *wr, int (*w)(void*, void*, int), void *rr, int (*r)(void*, void*, int), int level, int debug)
  278. {
  279. LZstate *lz;
  280. LZblock *lzb;
  281. int ok;
  282. lz = malloc(sizeof *lz + sizeof *lzb);
  283. if(lz == nil)
  284. return FlateNoMem;
  285. lzb = (LZblock*)&lz[1];
  286. deflatereset(lz, level, debug);
  287. lz->w = w;
  288. lz->wr = wr;
  289. lz->wbad = 0;
  290. lz->rbad = 0;
  291. lz->eof = 0;
  292. ok = FlateOk;
  293. while(!lz->eof || lz->avail){
  294. ok = deflateb(lz, lzb, rr, r);
  295. if(ok != FlateOk)
  296. break;
  297. }
  298. if(ok == FlateOk && lz->rbad)
  299. ok = FlateInputFail;
  300. if(ok == FlateOk && lz->wbad)
  301. ok = FlateOutputFail;
  302. free(lz);
  303. return ok;
  304. }
  305. static int
  306. deflateb(LZstate *lz, LZblock *lzb, void *rr, int (*r)(void*, void*, int))
  307. {
  308. Dyncode dyncode, hdyncode;
  309. Huff dlitlentab[Nlitlen], dofftab[Noff], hlitlentab[Nlitlen];
  310. ulong litcount[Nlitlen];
  311. long nunc, ndyn, nfix, nhuff;
  312. uchar *slop, *hslop;
  313. ulong ep;
  314. int i, n, m, mm, nslop;
  315. memset(lzb->litlencount, 0, sizeof lzb->litlencount);
  316. memset(lzb->offcount, 0, sizeof lzb->offcount);
  317. lzb->litlencount[DeflateEob]++;
  318. lzb->bytes = 0;
  319. lzb->eparse = lzb->parse;
  320. lzb->lastv = 0;
  321. lzb->excost = 0;
  322. slop = &lz->hist[lz->pos];
  323. n = lz->avail;
  324. while(n < DeflateBlock && (!lz->eof || lz->avail)){
  325. /*
  326. * fill the buffer as much as possible,
  327. * while leaving room for MaxOff history behind lz->pos,
  328. * and not reading more than we can handle.
  329. *
  330. * make sure we read at least HistSlop bytes.
  331. */
  332. if(!lz->eof){
  333. ep = lz->pos + lz->avail;
  334. if(ep >= HistBlock)
  335. ep -= HistBlock;
  336. m = HistBlock - MaxOff - lz->avail;
  337. if(m > HistBlock - n)
  338. m = HistBlock - n;
  339. if(m > (HistBlock + HistSlop) - ep)
  340. m = (HistBlock + HistSlop) - ep;
  341. if(m & ~(BlockSize - 1))
  342. m &= ~(BlockSize - 1);
  343. /*
  344. * be nice to the caller: stop reads that are too small.
  345. * can only get here when we've already filled the buffer some
  346. */
  347. if(m < HistSlop){
  348. if(!m || !lzb->bytes)
  349. return FlateInternal;
  350. break;
  351. }
  352. mm = (*r)(rr, &lz->hist[ep], m);
  353. if(mm > 0){
  354. /*
  355. * wrap data to end if we're read it from the beginning
  356. * this way, we don't have to wrap searches.
  357. *
  358. * wrap reads past the end to the beginning.
  359. * this way, we can guarantee minimum size reads.
  360. */
  361. if(ep < HistSlop)
  362. memmove(&lz->hist[ep + HistBlock], &lz->hist[ep], HistSlop - ep);
  363. else if(ep + mm > HistBlock)
  364. memmove(&lz->hist[0], &lz->hist[HistBlock], ep + mm - HistBlock);
  365. lz->totr += mm;
  366. n += mm;
  367. lz->avail += mm;
  368. }else{
  369. if(mm < 0)
  370. lz->rbad = 1;
  371. lz->eof = 1;
  372. }
  373. }
  374. ep = lz->pos + lz->avail;
  375. if(ep > HistSize)
  376. ep = HistSize;
  377. if(lzb->bytes + ep - lz->pos > DeflateMaxBlock)
  378. ep = lz->pos + DeflateMaxBlock - lzb->bytes;
  379. m = lzcomp(lz, lzb, &lz->hist[ep], lzb->eparse, lz->eof);
  380. lzb->bytes += m;
  381. lz->pos = (lz->pos + m) & (HistBlock - 1);
  382. lz->avail -= m;
  383. }
  384. if(lzb->lastv)
  385. *lzb->eparse++ = lzb->lastv;
  386. if(lzb->eparse > lzb->parse + nelem(lzb->parse))
  387. return FlateInternal;
  388. nunc = lzb->bytes;
  389. if(!mkgzprecode(dlitlentab, lzb->litlencount, Nlitlen, MaxHuffBits)
  390. || !mkgzprecode(dofftab, lzb->offcount, Noff, MaxHuffBits))
  391. return FlateInternal;
  392. ndyn = huffcodes(&dyncode, dlitlentab, dofftab);
  393. if(ndyn < 0)
  394. return FlateInternal;
  395. ndyn += bitcost(dlitlentab, lzb->litlencount, Nlitlen)
  396. + bitcost(dofftab, lzb->offcount, Noff)
  397. + lzb->excost;
  398. memset(litcount, 0, sizeof litcount);
  399. nslop = nunc;
  400. if(nslop > &lz->hist[HistSize] - slop)
  401. nslop = &lz->hist[HistSize] - slop;
  402. for(i = 0; i < nslop; i++)
  403. litcount[slop[i]]++;
  404. hslop = &lz->hist[HistSlop - nslop];
  405. for(; i < nunc; i++)
  406. litcount[hslop[i]]++;
  407. litcount[DeflateEob]++;
  408. if(!mkgzprecode(hlitlentab, litcount, Nlitlen, MaxHuffBits))
  409. return FlateInternal;
  410. nhuff = huffcodes(&hdyncode, hlitlentab, hofftab);
  411. if(nhuff < 0)
  412. return FlateInternal;
  413. nhuff += bitcost(hlitlentab, litcount, Nlitlen);
  414. nfix = bitcost(litlentab, lzb->litlencount, Nlitlen)
  415. + bitcost(offtab, lzb->offcount, Noff)
  416. + lzb->excost;
  417. lzput(lz, lz->eof && !lz->avail, 1);
  418. if(lz->debug){
  419. fprint(2, "block: bytes=%lud entries=%ld extra bits=%d\n\tuncompressed=%lud fixed=%lud dynamic=%lud huffman=%lud\n",
  420. nunc, lzb->eparse - lzb->parse, lzb->excost, (nunc + 4) * 8, nfix, ndyn, nhuff);
  421. fprint(2, "\tnlit=%lud matches=%lud eof=%d\n", nlits, nmatches, lz->eof && !lz->avail);
  422. }
  423. if((nunc + 4) * 8 < ndyn && (nunc + 4) * 8 < nfix && (nunc + 4) * 8 < nhuff){
  424. lzput(lz, DeflateUnc, 2);
  425. lzflushbits(lz);
  426. lzput(lz, nunc & 0xff, 8);
  427. lzput(lz, (nunc >> 8) & 0xff, 8);
  428. lzput(lz, ~nunc & 0xff, 8);
  429. lzput(lz, (~nunc >> 8) & 0xff, 8);
  430. lzflush(lz);
  431. lzwrite(lz, slop, nslop);
  432. lzwrite(lz, &lz->hist[HistSlop], nunc - nslop);
  433. }else if(ndyn < nfix && ndyn < nhuff){
  434. lzput(lz, DeflateDyn, 2);
  435. wrdyncode(lz, &dyncode);
  436. wrblock(lz, slop - lz->hist, lzb->parse, lzb->eparse, dlitlentab, dofftab);
  437. lzput(lz, dlitlentab[DeflateEob].encode, dlitlentab[DeflateEob].bits);
  438. }else if(nhuff < nfix){
  439. lzput(lz, DeflateDyn, 2);
  440. wrdyncode(lz, &hdyncode);
  441. m = 0;
  442. for(i = nunc; i > MaxLitRun; i -= MaxLitRun)
  443. lzb->parse[m++] = MaxLitRun;
  444. lzb->parse[m++] = i;
  445. wrblock(lz, slop - lz->hist, lzb->parse, lzb->parse + m, hlitlentab, hofftab);
  446. lzput(lz, hlitlentab[DeflateEob].encode, hlitlentab[DeflateEob].bits);
  447. }else{
  448. lzput(lz, DeflateFix, 2);
  449. wrblock(lz, slop - lz->hist, lzb->parse, lzb->eparse, litlentab, offtab);
  450. lzput(lz, litlentab[DeflateEob].encode, litlentab[DeflateEob].bits);
  451. }
  452. if(lz->eof && !lz->avail){
  453. lzflushbits(lz);
  454. lzflush(lz);
  455. }
  456. return FlateOk;
  457. }
  458. static void
  459. lzwrite(LZstate *lz, void *buf, int n)
  460. {
  461. int nw;
  462. if(n && lz->w){
  463. nw = (*lz->w)(lz->wr, buf, n);
  464. if(nw != n){
  465. lz->w = nil;
  466. lz->wbad = 1;
  467. }else
  468. lz->totw += n;
  469. }
  470. }
  471. static void
  472. lzflush(LZstate *lz)
  473. {
  474. lzwrite(lz, lz->obuf, lz->out - lz->obuf);
  475. lz->out = lz->obuf;
  476. }
  477. static void
  478. lzput(LZstate *lz, ulong bits, int nbits)
  479. {
  480. bits = (bits << lz->nbits) | lz->bits;
  481. for(nbits += lz->nbits; nbits >= 8; nbits -= 8){
  482. *lz->out++ = bits;
  483. if(lz->out == lz->eout)
  484. lzflush(lz);
  485. bits >>= 8;
  486. }
  487. lz->bits = bits;
  488. lz->nbits = nbits;
  489. }
  490. static void
  491. lzflushbits(LZstate *lz)
  492. {
  493. if(lz->nbits)
  494. lzput(lz, 0, 8 - (lz->nbits & 7));
  495. }
  496. /*
  497. * write out a block of n samples,
  498. * given lz encoding and counts for huffman tables
  499. */
  500. static void
  501. wrblock(LZstate *out, int litoff, ushort *soff, ushort *eoff, Huff *litlentab, Huff *offtab)
  502. {
  503. ushort *off;
  504. int i, run, offset, lit, len, c;
  505. if(out->debug > 2){
  506. for(off = soff; off < eoff; ){
  507. offset = *off++;
  508. run = offset & MaxLitRun;
  509. if(run){
  510. for(i = 0; i < run; i++){
  511. lit = out->hist[litoff & (HistBlock - 1)];
  512. litoff++;
  513. fprint(2, "\tlit %.2ux %c\n", lit, lit);
  514. }
  515. if(!(offset & LenFlag))
  516. continue;
  517. len = offset >> LenShift;
  518. offset = *off++;
  519. }else if(offset & LenFlag){
  520. len = offset >> LenShift;
  521. offset = *off++;
  522. }else{
  523. len = 0;
  524. offset >>= LenShift;
  525. }
  526. litoff += len + MinMatch;
  527. fprint(2, "\t<%d, %d>\n", offset + 1, len + MinMatch);
  528. }
  529. }
  530. for(off = soff; off < eoff; ){
  531. offset = *off++;
  532. run = offset & MaxLitRun;
  533. if(run){
  534. for(i = 0; i < run; i++){
  535. lit = out->hist[litoff & (HistBlock - 1)];
  536. litoff++;
  537. lzput(out, litlentab[lit].encode, litlentab[lit].bits);
  538. }
  539. if(!(offset & LenFlag))
  540. continue;
  541. len = offset >> LenShift;
  542. offset = *off++;
  543. }else if(offset & LenFlag){
  544. len = offset >> LenShift;
  545. offset = *off++;
  546. }else{
  547. len = 0;
  548. offset >>= LenShift;
  549. }
  550. litoff += len + MinMatch;
  551. c = lencode[len];
  552. lzput(out, litlentab[c].encode, litlentab[c].bits);
  553. c -= LenStart;
  554. if(litlenextra[c])
  555. lzput(out, len - litlenbase[c], litlenextra[c]);
  556. if(offset < MaxOffCode)
  557. c = offcode[offset];
  558. else
  559. c = bigoffcode[offset >> 7];
  560. lzput(out, offtab[c].encode, offtab[c].bits);
  561. if(offextra[c])
  562. lzput(out, offset - offbase[c], offextra[c]);
  563. }
  564. }
  565. /*
  566. * look for the longest, closest string which matches
  567. * the next prefix. the clever part here is looking for
  568. * a string 1 longer than the previous best match.
  569. *
  570. * follows the recommendation of limiting number of chains
  571. * which are checked. this appears to be the best heuristic.
  572. */
  573. static int
  574. lzmatch(int now, int then, uchar *p, uchar *es, ushort *nexts, uchar *hist, int runlen, int check, int *m)
  575. {
  576. uchar *s, *t;
  577. int ml, off, last;
  578. ml = check;
  579. if(runlen >= 8)
  580. check >>= 2;
  581. *m = 0;
  582. if(p + runlen >= es)
  583. return runlen;
  584. last = 0;
  585. for(; check-- > 0; then = nexts[then & (MaxOff-1)]){
  586. off = (ushort)(now - then);
  587. if(off <= last || off > MaxOff)
  588. break;
  589. s = p + runlen;
  590. t = hist + (((p - hist) - off) & (HistBlock-1));
  591. t += runlen;
  592. for(; s >= p; s--){
  593. if(*s != *t)
  594. goto matchloop;
  595. t--;
  596. }
  597. /*
  598. * we have a new best match.
  599. * extend it to it's maximum length
  600. */
  601. t += runlen + 2;
  602. s += runlen + 2;
  603. for(; s < es; s++){
  604. if(*s != *t)
  605. break;
  606. t++;
  607. }
  608. runlen = s - p;
  609. *m = off - 1;
  610. if(s == es || runlen > ml)
  611. break;
  612. matchloop:;
  613. last = off;
  614. }
  615. return runlen;
  616. }
  617. static int
  618. lzcomp(LZstate *lz, LZblock *lzb, uchar *ep, ushort *parse, int finish)
  619. {
  620. ulong cont, excost, *litlencount, *offcount;
  621. uchar *p, *q, *s, *es;
  622. ushort *nexts, *hash;
  623. int v, i, h, runlen, n, now, then, m, prevlen, prevoff, maxdefer;
  624. litlencount = lzb->litlencount;
  625. offcount = lzb->offcount;
  626. nexts = lz->nexts;
  627. hash = lz->hash;
  628. now = lz->now;
  629. p = &lz->hist[lz->pos];
  630. if(lz->prevlen != MinMatch - 1)
  631. p++;
  632. /*
  633. * hash in the links for any hanging link positions,
  634. * and calculate the hash for the current position.
  635. */
  636. n = MinMatch;
  637. if(n > ep - p)
  638. n = ep - p;
  639. cont = 0;
  640. for(i = 0; i < n - 1; i++){
  641. m = now - ((MinMatch-1) - i);
  642. if(m < lz->dot)
  643. continue;
  644. s = lz->hist + (((p - lz->hist) - (now - m)) & (HistBlock-1));
  645. cont = (s[0] << 16) | (s[1] << 8) | s[2];
  646. h = hashit(cont);
  647. prevoff = 0;
  648. for(then = hash[h]; ; then = nexts[then & (MaxOff-1)]){
  649. v = (ushort)(now - then);
  650. if(v <= prevoff || v >= (MinMatch-1) - i)
  651. break;
  652. prevoff = v;
  653. }
  654. if(then == (ushort)m)
  655. continue;
  656. nexts[m & (MaxOff-1)] = hash[h];
  657. hash[h] = m;
  658. }
  659. for(i = 0; i < n; i++)
  660. cont = (cont << 8) | p[i];
  661. /*
  662. * now must point to the index in the nexts array
  663. * corresponding to p's position in the history
  664. */
  665. prevlen = lz->prevlen;
  666. prevoff = lz->prevoff;
  667. maxdefer = lz->maxcheck >> 2;
  668. excost = 0;
  669. v = lzb->lastv;
  670. for(;;){
  671. es = p + MaxMatch;
  672. if(es > ep){
  673. if(!finish || p >= ep)
  674. break;
  675. es = ep;
  676. }
  677. h = hashit(cont);
  678. runlen = lzmatch(now, hash[h], p, es, nexts, lz->hist, prevlen, lz->maxcheck, &m);
  679. /*
  680. * back out of small matches too far in the past
  681. */
  682. if(runlen == MinMatch && m >= MinMatchMaxOff){
  683. runlen = MinMatch - 1;
  684. m = 0;
  685. }
  686. /*
  687. * record the encoding and increment counts for huffman trees
  688. * if we get a match, defer selecting it until we check for
  689. * a longer match at the next position.
  690. */
  691. if(prevlen >= runlen && prevlen != MinMatch - 1){
  692. /*
  693. * old match at least as good; use that one
  694. */
  695. n = prevlen - MinMatch;
  696. if(v || n){
  697. *parse++ = v | LenFlag | (n << LenShift);
  698. *parse++ = prevoff;
  699. }else
  700. *parse++ = prevoff << LenShift;
  701. v = 0;
  702. n = lencode[n];
  703. litlencount[n]++;
  704. excost += litlenextra[n - LenStart];
  705. if(prevoff < MaxOffCode)
  706. n = offcode[prevoff];
  707. else
  708. n = bigoffcode[prevoff >> 7];
  709. offcount[n]++;
  710. excost += offextra[n];
  711. runlen = prevlen - 1;
  712. prevlen = MinMatch - 1;
  713. nmatches++;
  714. }else if(runlen == MinMatch - 1){
  715. /*
  716. * no match; just put out the literal
  717. */
  718. if(++v == MaxLitRun){
  719. *parse++ = v;
  720. v = 0;
  721. }
  722. litlencount[*p]++;
  723. nlits++;
  724. runlen = 1;
  725. }else{
  726. if(prevlen != MinMatch - 1){
  727. /*
  728. * longer match now. output previous literal,
  729. * update current match, and try again
  730. */
  731. if(++v == MaxLitRun){
  732. *parse++ = v;
  733. v = 0;
  734. }
  735. litlencount[p[-1]]++;
  736. nlits++;
  737. }
  738. prevoff = m;
  739. if(runlen < maxdefer){
  740. prevlen = runlen;
  741. runlen = 1;
  742. }else{
  743. n = runlen - MinMatch;
  744. if(v || n){
  745. *parse++ = v | LenFlag | (n << LenShift);
  746. *parse++ = prevoff;
  747. }else
  748. *parse++ = prevoff << LenShift;
  749. v = 0;
  750. n = lencode[n];
  751. litlencount[n]++;
  752. excost += litlenextra[n - LenStart];
  753. if(prevoff < MaxOffCode)
  754. n = offcode[prevoff];
  755. else
  756. n = bigoffcode[prevoff >> 7];
  757. offcount[n]++;
  758. excost += offextra[n];
  759. prevlen = MinMatch - 1;
  760. nmatches++;
  761. }
  762. }
  763. /*
  764. * update the hash for the newly matched data
  765. * this is constructed so the link for the old
  766. * match in this position must be at the end of a chain,
  767. * and will expire when this match is added, ie it will
  768. * never be examined by the match loop.
  769. * add to the hash chain only if we have the real hash data.
  770. */
  771. for(q = p + runlen; p != q; p++){
  772. if(p + MinMatch <= ep){
  773. h = hashit(cont);
  774. nexts[now & (MaxOff-1)] = hash[h];
  775. hash[h] = now;
  776. if(p + MinMatch < ep)
  777. cont = (cont << 8) | p[MinMatch];
  778. }
  779. now++;
  780. }
  781. }
  782. /*
  783. * we can just store away the lazy state and
  784. * pick it up next time. the last block will have finish set
  785. * so we won't have any pending matches
  786. * however, we need to correct for how much we've encoded
  787. */
  788. if(prevlen != MinMatch - 1)
  789. p--;
  790. lzb->excost += excost;
  791. lzb->eparse = parse;
  792. lzb->lastv = v;
  793. lz->now = now;
  794. lz->prevlen = prevlen;
  795. lz->prevoff = prevoff;
  796. return p - &lz->hist[lz->pos];
  797. }
  798. /*
  799. * make up the dynamic code tables, and return the number of bits
  800. * needed to transmit them.
  801. */
  802. static int
  803. huffcodes(Dyncode *dc, Huff *littab, Huff *offtab)
  804. {
  805. Huff *codetab;
  806. uchar *codes, *codeaux;
  807. ulong codecount[Nclen], excost;
  808. int i, n, m, v, c, nlit, noff, ncode, nclen;
  809. codetab = dc->codetab;
  810. codes = dc->codes;
  811. codeaux = dc->codeaux;
  812. /*
  813. * trim the sizes of the tables
  814. */
  815. for(nlit = Nlitlen; nlit > 257 && littab[nlit-1].bits == 0; nlit--)
  816. ;
  817. for(noff = Noff; noff > 1 && offtab[noff-1].bits == 0; noff--)
  818. ;
  819. /*
  820. * make the code-length code
  821. */
  822. for(i = 0; i < nlit; i++)
  823. codes[i] = littab[i].bits;
  824. for(i = 0; i < noff; i++)
  825. codes[i + nlit] = offtab[i].bits;
  826. /*
  827. * run-length compress the code-length code
  828. */
  829. excost = 0;
  830. c = 0;
  831. ncode = nlit+noff;
  832. for(i = 0; i < ncode; ){
  833. n = i + 1;
  834. v = codes[i];
  835. while(n < ncode && v == codes[n])
  836. n++;
  837. n -= i;
  838. i += n;
  839. if(v == 0){
  840. while(n >= 11){
  841. m = n;
  842. if(m > 138)
  843. m = 138;
  844. codes[c] = 18;
  845. codeaux[c++] = m - 11;
  846. n -= m;
  847. excost += 7;
  848. }
  849. if(n >= 3){
  850. codes[c] = 17;
  851. codeaux[c++] = n - 3;
  852. n = 0;
  853. excost += 3;
  854. }
  855. }
  856. while(n--){
  857. codes[c++] = v;
  858. while(n >= 3){
  859. m = n;
  860. if(m > 6)
  861. m = 6;
  862. codes[c] = 16;
  863. codeaux[c++] = m - 3;
  864. n -= m;
  865. excost += 3;
  866. }
  867. }
  868. }
  869. memset(codecount, 0, sizeof codecount);
  870. for(i = 0; i < c; i++)
  871. codecount[codes[i]]++;
  872. if(!mkgzprecode(codetab, codecount, Nclen, 8))
  873. return -1;
  874. for(nclen = Nclen; nclen > 4 && codetab[clenorder[nclen-1]].bits == 0; nclen--)
  875. ;
  876. dc->nlit = nlit;
  877. dc->noff = noff;
  878. dc->nclen = nclen;
  879. dc->ncode = c;
  880. return 5 + 5 + 4 + nclen * 3 + bitcost(codetab, codecount, Nclen) + excost;
  881. }
  882. static void
  883. wrdyncode(LZstate *out, Dyncode *dc)
  884. {
  885. Huff *codetab;
  886. uchar *codes, *codeaux;
  887. int i, v, c;
  888. /*
  889. * write out header, then code length code lengths,
  890. * and code lengths
  891. */
  892. lzput(out, dc->nlit-257, 5);
  893. lzput(out, dc->noff-1, 5);
  894. lzput(out, dc->nclen-4, 4);
  895. codetab = dc->codetab;
  896. for(i = 0; i < dc->nclen; i++)
  897. lzput(out, codetab[clenorder[i]].bits, 3);
  898. codes = dc->codes;
  899. codeaux = dc->codeaux;
  900. c = dc->ncode;
  901. for(i = 0; i < c; i++){
  902. v = codes[i];
  903. lzput(out, codetab[v].encode, codetab[v].bits);
  904. if(v >= 16){
  905. if(v == 16)
  906. lzput(out, codeaux[i], 2);
  907. else if(v == 17)
  908. lzput(out, codeaux[i], 3);
  909. else /* v == 18 */
  910. lzput(out, codeaux[i], 7);
  911. }
  912. }
  913. }
  914. static int
  915. bitcost(Huff *tab, ulong *count, int n)
  916. {
  917. ulong tot;
  918. int i;
  919. tot = 0;
  920. for(i = 0; i < n; i++)
  921. tot += count[i] * tab[i].bits;
  922. return tot;
  923. }
  924. static int
  925. mkgzprecode(Huff *tab, ulong *count, int n, int maxbits)
  926. {
  927. ulong bitcount[MaxHuffBits];
  928. int i, nbits;
  929. nbits = mkprecode(tab, count, n, maxbits, bitcount);
  930. for(i = 0; i < n; i++){
  931. if(tab[i].bits == -1)
  932. tab[i].bits = 0;
  933. else if(tab[i].bits == 0){
  934. if(nbits != 0 || bitcount[0] != 1)
  935. return 0;
  936. bitcount[1] = 1;
  937. bitcount[0] = 0;
  938. nbits = 1;
  939. tab[i].bits = 1;
  940. }
  941. }
  942. if(bitcount[0] != 0)
  943. return 0;
  944. return hufftabinit(tab, n, bitcount, nbits);
  945. }
  946. static int
  947. hufftabinit(Huff *tab, int n, ulong *bitcount, int nbits)
  948. {
  949. ulong code, nc[MaxHuffBits];
  950. int i, bits;
  951. code = 0;
  952. for(bits = 1; bits <= nbits; bits++){
  953. code = (code + bitcount[bits-1]) << 1;
  954. nc[bits] = code;
  955. }
  956. for(i = 0; i < n; i++){
  957. bits = tab[i].bits;
  958. if(bits){
  959. code = nc[bits]++ << (16 - bits);
  960. if(code & ~0xffff)
  961. return 0;
  962. tab[i].encode = revtab[code >> 8] | (revtab[code & 0xff] << 8);
  963. }
  964. }
  965. return 1;
  966. }
  967. /*
  968. * this should be in a library
  969. */
  970. struct Chain
  971. {
  972. ulong count; /* occurances of everything in the chain */
  973. ushort leaf; /* leaves to the left of chain, or leaf value */
  974. char col; /* ref count for collecting unused chains */
  975. char gen; /* need to generate chains for next lower level */
  976. Chain *up; /* Chain up in the lists */
  977. };
  978. struct Chains
  979. {
  980. Chain *lists[(MaxHuffBits - 1) * 2];
  981. ulong leafcount[MaxLeaf]; /* sorted list of leaf counts */
  982. ushort leafmap[MaxLeaf]; /* map to actual leaf number */
  983. int nleaf; /* number of leaves */
  984. Chain chains[ChainMem];
  985. Chain *echains;
  986. Chain *free;
  987. char col;
  988. int nlists;
  989. };
  990. /*
  991. * fast, low space overhead algorithm for max depth huffman type codes
  992. *
  993. * J. Katajainen, A. Moffat and A. Turpin, "A fast and space-economical
  994. * algorithm for length-limited coding," Proc. Intl. Symp. on Algorithms
  995. * and Computation, Cairns, Australia, Dec. 1995, Lecture Notes in Computer
  996. * Science, Vol 1004, J. Staples, P. Eades, N. Katoh, and A. Moffat, eds.,
  997. * pp 12-21, Springer Verlag, New York, 1995.
  998. */
  999. static int
  1000. mkprecode(Huff *tab, ulong *count, int n, int maxbits, ulong *bitcount)
  1001. {
  1002. Chains cs;
  1003. Chain *c;
  1004. int i, m, em, bits;
  1005. /*
  1006. * set up the sorted list of leaves
  1007. */
  1008. m = 0;
  1009. for(i = 0; i < n; i++){
  1010. tab[i].bits = -1;
  1011. tab[i].encode = 0;
  1012. if(count[i] != 0){
  1013. cs.leafcount[m] = count[i];
  1014. cs.leafmap[m] = i;
  1015. m++;
  1016. }
  1017. }
  1018. if(m < 2){
  1019. if(m != 0){
  1020. tab[cs.leafmap[0]].bits = 0;
  1021. bitcount[0] = 1;
  1022. }else
  1023. bitcount[0] = 0;
  1024. return 0;
  1025. }
  1026. cs.nleaf = m;
  1027. leafsort(cs.leafcount, cs.leafmap, 0, m);
  1028. for(i = 0; i < m; i++)
  1029. cs.leafcount[i] = count[cs.leafmap[i]];
  1030. /*
  1031. * set up free list
  1032. */
  1033. cs.free = &cs.chains[2];
  1034. cs.echains = &cs.chains[ChainMem];
  1035. cs.col = 1;
  1036. /*
  1037. * initialize chains for each list
  1038. */
  1039. c = &cs.chains[0];
  1040. c->count = cs.leafcount[0];
  1041. c->leaf = 1;
  1042. c->col = cs.col;
  1043. c->up = nil;
  1044. c->gen = 0;
  1045. cs.chains[1] = cs.chains[0];
  1046. cs.chains[1].leaf = 2;
  1047. cs.chains[1].count = cs.leafcount[1];
  1048. for(i = 0; i < maxbits-1; i++){
  1049. cs.lists[i * 2] = &cs.chains[0];
  1050. cs.lists[i * 2 + 1] = &cs.chains[1];
  1051. }
  1052. cs.nlists = 2 * (maxbits - 1);
  1053. m = 2 * m - 2;
  1054. for(i = 2; i < m; i++)
  1055. nextchain(&cs, cs.nlists - 2);
  1056. bits = 0;
  1057. bitcount[0] = cs.nleaf;
  1058. for(c = cs.lists[cs.nlists - 1]; c != nil; c = c->up){
  1059. m = c->leaf;
  1060. bitcount[bits++] -= m;
  1061. bitcount[bits] = m;
  1062. }
  1063. m = 0;
  1064. for(i = bits; i >= 0; i--)
  1065. for(em = m + bitcount[i]; m < em; m++)
  1066. tab[cs.leafmap[m]].bits = i;
  1067. return bits;
  1068. }
  1069. /*
  1070. * calculate the next chain on the list
  1071. * we can always toss out the old chain
  1072. */
  1073. static void
  1074. nextchain(Chains *cs, int list)
  1075. {
  1076. Chain *c, *oc;
  1077. int i, nleaf, sumc;
  1078. oc = cs->lists[list + 1];
  1079. cs->lists[list] = oc;
  1080. if(oc == nil)
  1081. return;
  1082. /*
  1083. * make sure we have all chains needed to make sumc
  1084. * note it is possible to generate only one of these,
  1085. * use twice that value for sumc, and then generate
  1086. * the second if that preliminary sumc would be chosen.
  1087. * however, this appears to be slower on current tests
  1088. */
  1089. if(oc->gen){
  1090. nextchain(cs, list - 2);
  1091. nextchain(cs, list - 2);
  1092. oc->gen = 0;
  1093. }
  1094. /*
  1095. * pick up the chain we're going to add;
  1096. * collect unused chains no free ones are left
  1097. */
  1098. for(c = cs->free; ; c++){
  1099. if(c >= cs->echains){
  1100. cs->col++;
  1101. for(i = 0; i < cs->nlists; i++)
  1102. for(c = cs->lists[i]; c != nil; c = c->up)
  1103. c->col = cs->col;
  1104. c = cs->chains;
  1105. }
  1106. if(c->col != cs->col)
  1107. break;
  1108. }
  1109. /*
  1110. * pick the cheapest of
  1111. * 1) the next package from the previous list
  1112. * 2) the next leaf
  1113. */
  1114. nleaf = oc->leaf;
  1115. sumc = 0;
  1116. if(list > 0 && cs->lists[list-1] != nil)
  1117. sumc = cs->lists[list-2]->count + cs->lists[list-1]->count;
  1118. if(sumc != 0 && (nleaf >= cs->nleaf || cs->leafcount[nleaf] > sumc)){
  1119. c->count = sumc;
  1120. c->leaf = oc->leaf;
  1121. c->up = cs->lists[list-1];
  1122. c->gen = 1;
  1123. }else if(nleaf >= cs->nleaf){
  1124. cs->lists[list + 1] = nil;
  1125. return;
  1126. }else{
  1127. c->leaf = nleaf + 1;
  1128. c->count = cs->leafcount[nleaf];
  1129. c->up = oc->up;
  1130. c->gen = 0;
  1131. }
  1132. cs->free = c + 1;
  1133. cs->lists[list + 1] = c;
  1134. c->col = cs->col;
  1135. }
  1136. static int
  1137. pivot(ulong *c, int a, int n)
  1138. {
  1139. int j, pi, pj, pk;
  1140. j = n/6;
  1141. pi = a + j; /* 1/6 */
  1142. j += j;
  1143. pj = pi + j; /* 1/2 */
  1144. pk = pj + j; /* 5/6 */
  1145. if(c[pi] < c[pj]){
  1146. if(c[pi] < c[pk]){
  1147. if(c[pj] < c[pk])
  1148. return pj;
  1149. return pk;
  1150. }
  1151. return pi;
  1152. }
  1153. if(c[pj] < c[pk]){
  1154. if(c[pi] < c[pk])
  1155. return pi;
  1156. return pk;
  1157. }
  1158. return pj;
  1159. }
  1160. static void
  1161. leafsort(ulong *leafcount, ushort *leafmap, int a, int n)
  1162. {
  1163. ulong t;
  1164. int j, pi, pj, pn;
  1165. while(n > 1){
  1166. if(n > 10){
  1167. pi = pivot(leafcount, a, n);
  1168. }else
  1169. pi = a + (n>>1);
  1170. t = leafcount[pi];
  1171. leafcount[pi] = leafcount[a];
  1172. leafcount[a] = t;
  1173. t = leafmap[pi];
  1174. leafmap[pi] = leafmap[a];
  1175. leafmap[a] = t;
  1176. pi = a;
  1177. pn = a + n;
  1178. pj = pn;
  1179. for(;;){
  1180. do
  1181. pi++;
  1182. while(pi < pn && (leafcount[pi] < leafcount[a] || leafcount[pi] == leafcount[a] && leafmap[pi] > leafmap[a]));
  1183. do
  1184. pj--;
  1185. while(pj > a && (leafcount[pj] > leafcount[a] || leafcount[pj] == leafcount[a] && leafmap[pj] < leafmap[a]));
  1186. if(pj < pi)
  1187. break;
  1188. t = leafcount[pi];
  1189. leafcount[pi] = leafcount[pj];
  1190. leafcount[pj] = t;
  1191. t = leafmap[pi];
  1192. leafmap[pi] = leafmap[pj];
  1193. leafmap[pj] = t;
  1194. }
  1195. t = leafcount[a];
  1196. leafcount[a] = leafcount[pj];
  1197. leafcount[pj] = t;
  1198. t = leafmap[a];
  1199. leafmap[a] = leafmap[pj];
  1200. leafmap[pj] = t;
  1201. j = pj - a;
  1202. n = n-j-1;
  1203. if(j >= n){
  1204. leafsort(leafcount, leafmap, a, j);
  1205. a += j+1;
  1206. }else{
  1207. leafsort(leafcount, leafmap, a + (j+1), n);
  1208. n = j;
  1209. }
  1210. }
  1211. }