sdefl.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /*# Small Deflate
  2. `sdefl` is a small bare bone lossless compression library in ANSI C (ISO C90)
  3. which implements the Deflate (RFC 1951) compressed data format specification standard.
  4. It is mainly tuned to get as much speed and compression ratio from as little code
  5. as needed to keep the implementation as concise as possible.
  6. ## Features
  7. - Portable single header and source file duo written in ANSI C (ISO C90)
  8. - Dual license with either MIT or public domain
  9. - Small implementation
  10. - Deflate: 525 LoC
  11. - Inflate: 320 LoC
  12. - Webassembly:
  13. - Deflate ~3.7 KB (~2.2KB compressed)
  14. - Inflate ~3.6 KB (~2.2KB compressed)
  15. ## Usage:
  16. This file behaves differently depending on what symbols you define
  17. before including it.
  18. Header-File mode:
  19. If you do not define `SDEFL_IMPLEMENTATION` before including this file, it
  20. will operate in header only mode. In this mode it declares all used structs
  21. and the API of the library without including the implementation of the library.
  22. Implementation mode:
  23. If you define `SDEFL_IMPLEMENTATION` before including this file, it will
  24. compile the implementation . Make sure that you only include
  25. this file implementation in *one* C or C++ file to prevent collisions.
  26. ### Benchmark
  27. | Compressor name | Compression| Decompress.| Compr. size | Ratio |
  28. | ------------------------| -----------| -----------| ----------- | ----- |
  29. | miniz 1.0 -1 | 122 MB/s | 208 MB/s | 48510028 | 48.51 |
  30. | miniz 1.0 -6 | 27 MB/s | 260 MB/s | 36513697 | 36.51 |
  31. | miniz 1.0 -9 | 23 MB/s | 261 MB/s | 36460101 | 36.46 |
  32. | zlib 1.2.11 -1 | 72 MB/s | 307 MB/s | 42298774 | 42.30 |
  33. | zlib 1.2.11 -6 | 24 MB/s | 313 MB/s | 36548921 | 36.55 |
  34. | zlib 1.2.11 -9 | 20 MB/s | 314 MB/s | 36475792 | 36.48 |
  35. | sdefl 1.0 -0 | 127 MB/s | 355 MB/s | 40004116 | 39.88 |
  36. | sdefl 1.0 -1 | 111 MB/s | 413 MB/s | 38940674 | 38.82 |
  37. | sdefl 1.0 -5 | 45 MB/s | 436 MB/s | 36577183 | 36.46 |
  38. | sdefl 1.0 -7 | 38 MB/s | 432 MB/s | 36523781 | 36.41 |
  39. | libdeflate 1.3 -1 | 147 MB/s | 667 MB/s | 39597378 | 39.60 |
  40. | libdeflate 1.3 -6 | 69 MB/s | 689 MB/s | 36648318 | 36.65 |
  41. | libdeflate 1.3 -9 | 13 MB/s | 672 MB/s | 35197141 | 35.20 |
  42. | libdeflate 1.3 -12 | 8.13 MB/s | 670 MB/s | 35100568 | 35.10 |
  43. ### Compression
  44. Results on the [Silesia compression corpus](http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia):
  45. | File | Original | `sdefl 0` | `sdefl 5` | `sdefl 7` |
  46. | --------| -----------| -------------| ---------- | ------------|
  47. | dickens | 10.192.446 | 4,260,187 | 3,845,261 | 3,833,657 |
  48. | mozilla | 51.220.480 | 20,774,706 | 19,607,009 | 19,565,867 |
  49. | mr | 9.970.564 | 3,860,531 | 3,673,460 | 3,665,627 |
  50. | nci | 33.553.445 | 4,030,283 | 3,094,526 | 3,006,075 |
  51. | ooffice | 6.152.192 | 3,320,063 | 3,186,373 | 3,183,815 |
  52. | osdb | 10.085.684 | 3,919,646 | 3,649,510 | 3,649,477 |
  53. | reymont | 6.627.202 | 2,263,378 | 1,857,588 | 1,827,237 |
  54. | samba | 21.606.400 | 6,121,797 | 5,462,670 | 5,450,762 |
  55. | sao | 7.251.944 | 5,612,421 | 5,485,380 | 5,481,765 |
  56. | webster | 41.458.703 | 13,972,648 | 12,059,432 | 11,991,421 |
  57. | xml | 5.345.280 | 886,620 | 674,009 | 662,141 |
  58. | x-ray | 8.474.240 | 6,304,655 | 6,244,779 | 6,244,779 |
  59. ## License
  60. ```
  61. ------------------------------------------------------------------------------
  62. This software is available under 2 licenses -- choose whichever you prefer.
  63. ------------------------------------------------------------------------------
  64. ALTERNATIVE A - MIT License
  65. Copyright (c) 2020-2023 Micha Mettke
  66. Permission is hereby granted, free of charge, to any person obtaining a copy of
  67. this software and associated documentation files (the "Software"), to deal in
  68. the Software without restriction, including without limitation the rights to
  69. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  70. of the Software, and to permit persons to whom the Software is furnished to do
  71. so, subject to the following conditions:
  72. The above copyright notice and this permission notice shall be included in all
  73. copies or substantial portions of the Software.
  74. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  75. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  76. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  77. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  78. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  79. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  80. SOFTWARE.
  81. ------------------------------------------------------------------------------
  82. ALTERNATIVE B - Public Domain (www.unlicense.org)
  83. This is free and unencumbered software released into the public domain.
  84. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  85. software, either in source code form or as a compiled binary, for any purpose,
  86. commercial or non-commercial, and by any means.
  87. In jurisdictions that recognize copyright laws, the author or authors of this
  88. software dedicate any and all copyright interest in the software to the public
  89. domain. We make this dedication for the benefit of the public at large and to
  90. the detriment of our heirs and successors. We intend this dedication to be an
  91. overt act of relinquishment in perpetuity of all present and future rights to
  92. this software under copyright law.
  93. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  94. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  95. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  96. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  97. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  98. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  99. ------------------------------------------------------------------------------
  100. ```
  101. */
  102. #ifndef SDEFL_H_INCLUDED
  103. #define SDEFL_H_INCLUDED
  104. #ifdef __cplusplus
  105. extern "C" {
  106. #endif
  107. #define SDEFL_MAX_OFF (1 << 15)
  108. #define SDEFL_WIN_SIZ SDEFL_MAX_OFF
  109. #define SDEFL_WIN_MSK (SDEFL_WIN_SIZ-1)
  110. #define SDEFL_HASH_BITS 15
  111. #define SDEFL_HASH_SIZ (1 << SDEFL_HASH_BITS)
  112. #define SDEFL_HASH_MSK (SDEFL_HASH_SIZ-1)
  113. #define SDEFL_MIN_MATCH 4
  114. #define SDEFL_BLK_MAX (256*1024)
  115. #define SDEFL_SEQ_SIZ ((SDEFL_BLK_MAX+2)/3)
  116. #define SDEFL_SYM_MAX (288)
  117. #define SDEFL_OFF_MAX (32)
  118. #define SDEFL_PRE_MAX (19)
  119. #define SDEFL_LVL_MIN 0
  120. #define SDEFL_LVL_DEF 5
  121. #define SDEFL_LVL_MAX 8
  122. struct sdefl_freq {
  123. unsigned lit[SDEFL_SYM_MAX];
  124. unsigned off[SDEFL_OFF_MAX];
  125. };
  126. struct sdefl_code_words {
  127. unsigned lit[SDEFL_SYM_MAX];
  128. unsigned off[SDEFL_OFF_MAX];
  129. };
  130. struct sdefl_lens {
  131. unsigned char lit[SDEFL_SYM_MAX];
  132. unsigned char off[SDEFL_OFF_MAX];
  133. };
  134. struct sdefl_codes {
  135. struct sdefl_code_words word;
  136. struct sdefl_lens len;
  137. };
  138. struct sdefl_seqt {
  139. int off, len;
  140. };
  141. struct sdefl {
  142. int bits, bitcnt;
  143. int tbl[SDEFL_HASH_SIZ];
  144. int prv[SDEFL_WIN_SIZ];
  145. int seq_cnt;
  146. struct sdefl_seqt seq[SDEFL_SEQ_SIZ];
  147. struct sdefl_freq freq;
  148. struct sdefl_codes cod;
  149. };
  150. extern int sdefl_bound(int in_len);
  151. extern int sdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);
  152. extern int zsdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);
  153. #ifdef __cplusplus
  154. }
  155. #endif
  156. #endif /* SDEFL_H_INCLUDED */
  157. #ifdef SDEFL_IMPLEMENTATION
  158. #include <assert.h> /* assert */
  159. #include <string.h> /* memcpy */
  160. #include <limits.h> /* CHAR_BIT */
  161. #define SDEFL_NIL (-1)
  162. #define SDEFL_MAX_MATCH 258
  163. #define SDEFL_MAX_CODE_LEN (15)
  164. #define SDEFL_SYM_BITS (10u)
  165. #define SDEFL_SYM_MSK ((1u << SDEFL_SYM_BITS)-1u)
  166. #define SDEFL_RAW_BLK_SIZE (65535)
  167. #define SDEFL_LIT_LEN_CODES (14)
  168. #define SDEFL_OFF_CODES (15)
  169. #define SDEFL_PRE_CODES (7)
  170. #define SDEFL_CNT_NUM(n) ((((n)+3u/4u)+3u)&~3u)
  171. #define SDEFL_EOB (256)
  172. #define sdefl_npow2(n) (1 << (sdefl_ilog2((n)-1) + 1))
  173. #define sdefl_div_round_up(n,d) (((n)+((d)-1))/(d))
  174. static int
  175. sdefl_ilog2(int n) {
  176. if (!n) return 0;
  177. #ifdef _MSC_VER
  178. unsigned long msbp = 0;
  179. _BitScanReverse(&msbp, (unsigned long)n);
  180. return (int)msbp;
  181. #elif defined(__GNUC__) || defined(__clang__)
  182. return (int)sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl((unsigned long)n);
  183. #else
  184. #define lt(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
  185. static const char tbl[256] = {
  186. 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,lt(4), lt(5), lt(5), lt(6), lt(6), lt(6), lt(6),
  187. lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7)};
  188. int tt, t;
  189. if ((tt = (n >> 16))) {
  190. return (t = (tt >> 8)) ? 24 + tbl[t] : 16 + tbl[tt];
  191. } else {
  192. return (t = (n >> 8)) ? 8 + tbl[t] : tbl[n];
  193. }
  194. #undef lt
  195. #endif
  196. }
  197. static unsigned
  198. sdefl_uload32(const void *p) {
  199. /* hopefully will be optimized to an unaligned read */
  200. unsigned n = 0;
  201. memcpy(&n, p, sizeof(n));
  202. return n;
  203. }
  204. static unsigned
  205. sdefl_hash32(const void *p) {
  206. unsigned n = sdefl_uload32(p);
  207. return (n * 0x9E377989) >> (32 - SDEFL_HASH_BITS);
  208. }
  209. static void
  210. sdefl_put(unsigned char **dst, struct sdefl *s, int code, int bitcnt) {
  211. s->bits |= (code << s->bitcnt);
  212. s->bitcnt += bitcnt;
  213. while (s->bitcnt >= 8) {
  214. unsigned char *tar = *dst;
  215. *tar = (unsigned char)(s->bits & 0xFF);
  216. s->bits >>= 8;
  217. s->bitcnt -= 8;
  218. *dst = *dst + 1;
  219. }
  220. }
  221. static void
  222. sdefl_heap_sub(unsigned A[], unsigned len, unsigned sub) {
  223. unsigned c, p = sub;
  224. unsigned v = A[sub];
  225. while ((c = p << 1) <= len) {
  226. if (c < len && A[c + 1] > A[c]) c++;
  227. if (v >= A[c]) break;
  228. A[p] = A[c], p = c;
  229. }
  230. A[p] = v;
  231. }
  232. static void
  233. sdefl_heap_array(unsigned *A, unsigned len) {
  234. unsigned sub;
  235. for (sub = len >> 1; sub >= 1; sub--)
  236. sdefl_heap_sub(A, len, sub);
  237. }
  238. static void
  239. sdefl_heap_sort(unsigned *A, unsigned n) {
  240. A--;
  241. sdefl_heap_array(A, n);
  242. while (n >= 2) {
  243. unsigned tmp = A[n];
  244. A[n--] = A[1];
  245. A[1] = tmp;
  246. sdefl_heap_sub(A, n, 1);
  247. }
  248. }
  249. static unsigned
  250. sdefl_sort_sym(unsigned sym_cnt, unsigned *freqs,
  251. unsigned char *lens, unsigned *sym_out) {
  252. unsigned cnts[SDEFL_CNT_NUM(SDEFL_SYM_MAX)] = {0};
  253. unsigned cnt_num = SDEFL_CNT_NUM(sym_cnt);
  254. unsigned used_sym = 0;
  255. unsigned sym, i;
  256. for (sym = 0; sym < sym_cnt; sym++)
  257. cnts[freqs[sym] < cnt_num-1 ? freqs[sym]: cnt_num-1]++;
  258. for (i = 1; i < cnt_num; i++) {
  259. unsigned cnt = cnts[i];
  260. cnts[i] = used_sym;
  261. used_sym += cnt;
  262. }
  263. for (sym = 0; sym < sym_cnt; sym++) {
  264. unsigned freq = freqs[sym];
  265. if (freq) {
  266. unsigned idx = freq < cnt_num-1 ? freq : cnt_num-1;
  267. sym_out[cnts[idx]++] = sym | (freq << SDEFL_SYM_BITS);
  268. } else lens[sym] = 0;
  269. }
  270. sdefl_heap_sort(sym_out + cnts[cnt_num-2], cnts[cnt_num-1] - cnts[cnt_num-2]);
  271. return used_sym;
  272. }
  273. static void
  274. sdefl_build_tree(unsigned *A, unsigned sym_cnt) {
  275. unsigned i = 0, b = 0, e = 0;
  276. do {
  277. unsigned m, n, freq_shift;
  278. if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
  279. m = i++;
  280. else m = b++;
  281. if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
  282. n = i++;
  283. else n = b++;
  284. freq_shift = (A[m] & ~SDEFL_SYM_MSK) + (A[n] & ~SDEFL_SYM_MSK);
  285. A[m] = (A[m] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
  286. A[n] = (A[n] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
  287. A[e] = (A[e] & SDEFL_SYM_MSK) | freq_shift;
  288. } while (sym_cnt - ++e > 1);
  289. }
  290. static void
  291. sdefl_gen_len_cnt(unsigned *A, unsigned root, unsigned *len_cnt,
  292. unsigned max_code_len) {
  293. int n;
  294. unsigned i;
  295. for (i = 0; i <= max_code_len; i++)
  296. len_cnt[i] = 0;
  297. len_cnt[1] = 2;
  298. A[root] &= SDEFL_SYM_MSK;
  299. for (n = (int)root - 1; n >= 0; n--) {
  300. unsigned p = A[n] >> SDEFL_SYM_BITS;
  301. unsigned pdepth = A[p] >> SDEFL_SYM_BITS;
  302. unsigned depth = pdepth + 1;
  303. unsigned len = depth;
  304. A[n] = (A[n] & SDEFL_SYM_MSK) | (depth << SDEFL_SYM_BITS);
  305. if (len >= max_code_len) {
  306. len = max_code_len;
  307. do len--; while (!len_cnt[len]);
  308. }
  309. len_cnt[len]--;
  310. len_cnt[len+1] += 2;
  311. }
  312. }
  313. static void
  314. sdefl_gen_codes(unsigned *A, unsigned char *lens, const unsigned *len_cnt,
  315. unsigned max_code_word_len, unsigned sym_cnt) {
  316. unsigned i, sym, len, nxt[SDEFL_MAX_CODE_LEN + 1];
  317. for (i = 0, len = max_code_word_len; len >= 1; len--) {
  318. unsigned cnt = len_cnt[len];
  319. while (cnt--) lens[A[i++] & SDEFL_SYM_MSK] = (unsigned char)len;
  320. }
  321. nxt[0] = nxt[1] = 0;
  322. for (len = 2; len <= max_code_word_len; len++)
  323. nxt[len] = (nxt[len-1] + len_cnt[len-1]) << 1;
  324. for (sym = 0; sym < sym_cnt; sym++)
  325. A[sym] = nxt[lens[sym]]++;
  326. }
  327. static unsigned
  328. sdefl_rev(unsigned c, unsigned char n) {
  329. c = ((c & 0x5555) << 1) | ((c & 0xAAAA) >> 1);
  330. c = ((c & 0x3333) << 2) | ((c & 0xCCCC) >> 2);
  331. c = ((c & 0x0F0F) << 4) | ((c & 0xF0F0) >> 4);
  332. c = ((c & 0x00FF) << 8) | ((c & 0xFF00) >> 8);
  333. return c >> (16-n);
  334. }
  335. static void
  336. sdefl_huff(unsigned char *lens, unsigned *codes, unsigned *freqs,
  337. unsigned num_syms, unsigned max_code_len) {
  338. unsigned c, *A = codes;
  339. unsigned len_cnt[SDEFL_MAX_CODE_LEN + 1];
  340. unsigned used_syms = sdefl_sort_sym(num_syms, freqs, lens, A);
  341. if (!used_syms) return;
  342. if (used_syms == 1) {
  343. unsigned s = A[0] & SDEFL_SYM_MSK;
  344. unsigned i = s ? s : 1;
  345. codes[0] = 0, lens[0] = 1;
  346. codes[i] = 1, lens[i] = 1;
  347. return;
  348. }
  349. sdefl_build_tree(A, used_syms);
  350. sdefl_gen_len_cnt(A, used_syms-2, len_cnt, max_code_len);
  351. sdefl_gen_codes(A, lens, len_cnt, max_code_len, num_syms);
  352. for (c = 0; c < num_syms; c++) {
  353. codes[c] = sdefl_rev(codes[c], lens[c]);
  354. }
  355. }
  356. struct sdefl_symcnt {
  357. int items;
  358. int lit;
  359. int off;
  360. };
  361. static void
  362. sdefl_precode(struct sdefl_symcnt *cnt, unsigned *freqs, unsigned *items,
  363. const unsigned char *litlen, const unsigned char *offlen) {
  364. unsigned *at = items;
  365. unsigned run_start = 0;
  366. unsigned total = 0;
  367. unsigned char lens[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
  368. for (cnt->lit = SDEFL_SYM_MAX; cnt->lit > 257; cnt->lit--)
  369. if (litlen[cnt->lit - 1]) break;
  370. for (cnt->off = SDEFL_OFF_MAX; cnt->off > 1; cnt->off--)
  371. if (offlen[cnt->off - 1]) break;
  372. total = (unsigned)(cnt->lit + cnt->off);
  373. memcpy(lens, litlen, sizeof(unsigned char) * (size_t)cnt->lit);
  374. memcpy(lens + cnt->lit, offlen, sizeof(unsigned char) * (size_t)cnt->off);
  375. do {
  376. unsigned len = lens[run_start];
  377. unsigned run_end = run_start;
  378. do run_end++; while (run_end != total && len == lens[run_end]);
  379. if (!len) {
  380. while ((run_end - run_start) >= 11) {
  381. unsigned n = (run_end - run_start) - 11;
  382. unsigned xbits = n < 0x7f ? n : 0x7f;
  383. freqs[18]++;
  384. *at++ = 18u | (xbits << 5u);
  385. run_start += 11 + xbits;
  386. }
  387. if ((run_end - run_start) >= 3) {
  388. unsigned n = (run_end - run_start) - 3;
  389. unsigned xbits = n < 0x7 ? n : 0x7;
  390. freqs[17]++;
  391. *at++ = 17u | (xbits << 5u);
  392. run_start += 3 + xbits;
  393. }
  394. } else if ((run_end - run_start) >= 4) {
  395. freqs[len]++;
  396. *at++ = len;
  397. run_start++;
  398. do {
  399. unsigned xbits = (run_end - run_start) - 3;
  400. xbits = xbits < 0x03 ? xbits : 0x03;
  401. *at++ = 16 | (xbits << 5);
  402. run_start += 3 + xbits;
  403. freqs[16]++;
  404. } while ((run_end - run_start) >= 3);
  405. }
  406. while (run_start != run_end) {
  407. freqs[len]++;
  408. *at++ = len;
  409. run_start++;
  410. }
  411. } while (run_start != total);
  412. cnt->items = (int)(at - items);
  413. }
  414. struct sdefl_match_codest {
  415. int ls, lc;
  416. int dc, dx;
  417. };
  418. static void
  419. sdefl_match_codes(struct sdefl_match_codest *cod, int dist, int len) {
  420. static const short dxmax[] = {0,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576};
  421. static const unsigned char lslot[258+1] = {
  422. 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12,
  423. 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16,
  424. 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18,
  425. 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  426. 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
  427. 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
  428. 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
  429. 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  430. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
  431. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  432. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26,
  433. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  434. 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  435. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  436. 27, 27, 28
  437. };
  438. assert(len <= 258);
  439. assert(dist <= 32768);
  440. cod->ls = lslot[len];
  441. cod->lc = 257 + cod->ls;
  442. assert(cod->lc <= 285);
  443. cod->dx = sdefl_ilog2(sdefl_npow2(dist) >> 2);
  444. cod->dc = cod->dx ? ((cod->dx + 1) << 1) + (dist > dxmax[cod->dx]) : dist-1;
  445. }
  446. enum sdefl_blk_type {
  447. SDEFL_BLK_UCOMPR,
  448. SDEFL_BLK_DYN
  449. };
  450. static enum sdefl_blk_type
  451. sdefl_blk_type(const struct sdefl *s, int blk_len, int pre_item_len,
  452. const unsigned *pre_freq, const unsigned char *pre_len) {
  453. static const unsigned char x_pre_bits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  454. static const unsigned char x_len_bits[] = {0,0,0,0,0,0,0,0, 1,1,1,1,2,2,2,2,
  455. 3,3,3,3,4,4,4,4, 5,5,5,5,0};
  456. static const unsigned char x_off_bits[] = {0,0,0,0,1,1,2,2, 3,3,4,4,5,5,6,6,
  457. 7,7,8,8,9,9,10,10, 11,11,12,12,13,13};
  458. int dyn_cost = 0;
  459. int fix_cost = 0;
  460. int sym = 0;
  461. dyn_cost += 5 + 5 + 4 + (3 * pre_item_len);
  462. for (sym = 0; sym < SDEFL_PRE_MAX; sym++)
  463. dyn_cost += pre_freq[sym] * (x_pre_bits[sym] + pre_len[sym]);
  464. for (sym = 0; sym < 256; sym++)
  465. dyn_cost += s->freq.lit[sym] * s->cod.len.lit[sym];
  466. dyn_cost += s->cod.len.lit[SDEFL_EOB];
  467. for (sym = 257; sym < 286; sym++)
  468. dyn_cost += s->freq.lit[sym] * (x_len_bits[sym - 257] + s->cod.len.lit[sym]);
  469. for (sym = 0; sym < 30; sym++)
  470. dyn_cost += s->freq.off[sym] * (x_off_bits[sym] + s->cod.len.off[sym]);
  471. fix_cost += 8*(5 * sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE) + blk_len + 1 + 2);
  472. return (dyn_cost < fix_cost) ? SDEFL_BLK_DYN : SDEFL_BLK_UCOMPR;
  473. }
  474. static void
  475. sdefl_put16(unsigned char **dst, unsigned short x) {
  476. unsigned char *val = *dst;
  477. val[0] = (unsigned char)(x & 0xff);
  478. val[1] = (unsigned char)(x >> 8);
  479. *dst = val + 2;
  480. }
  481. static void
  482. sdefl_match(unsigned char **dst, struct sdefl *s, int dist, int len) {
  483. static const char lxn[] = {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};
  484. static const short lmin[] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,
  485. 51,59,67,83,99,115,131,163,195,227,258};
  486. static const short dmin[] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,
  487. 385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577};
  488. struct sdefl_match_codest cod;
  489. sdefl_match_codes(&cod, dist, len);
  490. sdefl_put(dst, s, (int)s->cod.word.lit[cod.lc], s->cod.len.lit[cod.lc]);
  491. sdefl_put(dst, s, len - lmin[cod.ls], lxn[cod.ls]);
  492. sdefl_put(dst, s, (int)s->cod.word.off[cod.dc], s->cod.len.off[cod.dc]);
  493. sdefl_put(dst, s, dist - dmin[cod.dc], cod.dx);
  494. }
  495. static void
  496. sdefl_flush(unsigned char **dst, struct sdefl *s, int is_last,
  497. const unsigned char *in, int blk_begin, int blk_end) {
  498. int blk_len = blk_end - blk_begin;
  499. int j, i = 0, item_cnt = 0;
  500. struct sdefl_symcnt symcnt = {0};
  501. unsigned codes[SDEFL_PRE_MAX];
  502. unsigned char lens[SDEFL_PRE_MAX];
  503. unsigned freqs[SDEFL_PRE_MAX] = {0};
  504. unsigned items[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
  505. static const unsigned char perm[SDEFL_PRE_MAX] = {16,17,18,0,8,7,9,6,10,5,11,
  506. 4,12,3,13,2,14,1,15};
  507. /* calculate huffman codes */
  508. s->freq.lit[SDEFL_EOB]++;
  509. sdefl_huff(s->cod.len.lit, s->cod.word.lit, s->freq.lit, SDEFL_SYM_MAX, SDEFL_LIT_LEN_CODES);
  510. sdefl_huff(s->cod.len.off, s->cod.word.off, s->freq.off, SDEFL_OFF_MAX, SDEFL_OFF_CODES);
  511. sdefl_precode(&symcnt, freqs, items, s->cod.len.lit, s->cod.len.off);
  512. sdefl_huff(lens, codes, freqs, SDEFL_PRE_MAX, SDEFL_PRE_CODES);
  513. for (item_cnt = SDEFL_PRE_MAX; item_cnt > 4; item_cnt--) {
  514. if (lens[perm[item_cnt - 1]]){
  515. break;
  516. }
  517. }
  518. /* write block */
  519. switch (sdefl_blk_type(s, blk_len, item_cnt, freqs, lens)) {
  520. case SDEFL_BLK_UCOMPR: {
  521. /* uncompressed blocks */
  522. int n = sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE);
  523. for (i = 0; i < n; ++i) {
  524. int fin = is_last && (i + 1 == n);
  525. int amount = blk_len < SDEFL_RAW_BLK_SIZE ? blk_len : SDEFL_RAW_BLK_SIZE;
  526. sdefl_put(dst, s, !!fin, 1); /* block */
  527. sdefl_put(dst, s, 0x00, 2); /* stored block */
  528. if (s->bitcnt) {
  529. sdefl_put(dst, s, 0x00, 8 - s->bitcnt);
  530. }
  531. assert(s->bitcnt == 0);
  532. sdefl_put16(dst, (unsigned short)amount);
  533. sdefl_put16(dst, ~(unsigned short)amount);
  534. memcpy(*dst, in + blk_begin + i * SDEFL_RAW_BLK_SIZE, amount);
  535. *dst = *dst + amount;
  536. blk_len -= amount;
  537. }
  538. } break;
  539. case SDEFL_BLK_DYN: {
  540. /* dynamic huffman block */
  541. sdefl_put(dst, s, !!is_last, 1); /* block */
  542. sdefl_put(dst, s, 0x02, 2); /* dynamic huffman */
  543. sdefl_put(dst, s, symcnt.lit - 257, 5);
  544. sdefl_put(dst, s, symcnt.off - 1, 5);
  545. sdefl_put(dst, s, item_cnt - 4, 4);
  546. for (i = 0; i < item_cnt; ++i) {
  547. sdefl_put(dst, s, lens[perm[i]], 3);
  548. }
  549. for (i = 0; i < symcnt.items; ++i) {
  550. unsigned sym = items[i] & 0x1F;
  551. sdefl_put(dst, s, (int)codes[sym], lens[sym]);
  552. if (sym < 16) continue;
  553. if (sym == 16) sdefl_put(dst, s, items[i] >> 5, 2);
  554. else if(sym == 17) sdefl_put(dst, s, items[i] >> 5, 3);
  555. else sdefl_put(dst, s, items[i] >> 5, 7);
  556. }
  557. /* block sequences */
  558. for (i = 0; i < s->seq_cnt; ++i) {
  559. if (s->seq[i].off >= 0) {
  560. for (j = 0; j < s->seq[i].len; ++j) {
  561. int c = in[s->seq[i].off + j];
  562. sdefl_put(dst, s, (int)s->cod.word.lit[c], s->cod.len.lit[c]);
  563. }
  564. } else {
  565. sdefl_match(dst, s, -s->seq[i].off, s->seq[i].len);
  566. }
  567. }
  568. sdefl_put(dst, s, (int)(s)->cod.word.lit[SDEFL_EOB], (s)->cod.len.lit[SDEFL_EOB]);
  569. } break;}
  570. memset(&s->freq, 0, sizeof(s->freq));
  571. s->seq_cnt = 0;
  572. }
  573. static void
  574. sdefl_seq(struct sdefl *s, int off, int len) {
  575. assert(s->seq_cnt + 2 < SDEFL_SEQ_SIZ);
  576. s->seq[s->seq_cnt].off = off;
  577. s->seq[s->seq_cnt].len = len;
  578. s->seq_cnt++;
  579. }
  580. static void
  581. sdefl_reg_match(struct sdefl *s, int off, int len) {
  582. struct sdefl_match_codest cod;
  583. sdefl_match_codes(&cod, off, len);
  584. assert(cod.lc < SDEFL_SYM_MAX);
  585. assert(cod.dc < SDEFL_OFF_MAX);
  586. s->freq.lit[cod.lc]++;
  587. s->freq.off[cod.dc]++;
  588. }
  589. struct sdefl_match {
  590. int off;
  591. int len;
  592. };
  593. static void
  594. sdefl_fnd(struct sdefl_match *m, const struct sdefl *s, int chain_len,
  595. int max_match, const unsigned char *in, int p, int e) {
  596. int i = s->tbl[sdefl_hash32(in + p)];
  597. int limit = ((p - SDEFL_WIN_SIZ) < SDEFL_NIL) ? SDEFL_NIL : (p-SDEFL_WIN_SIZ);
  598. assert(p < e);
  599. assert(p + max_match <= e);
  600. while (i > limit) {
  601. assert(i + m->len < e);
  602. assert(p + m->len < e);
  603. assert(i + SDEFL_MIN_MATCH < e);
  604. assert(p + SDEFL_MIN_MATCH < e);
  605. if (in[i + m->len] == in[p + m->len] &&
  606. (sdefl_uload32(&in[i]) == sdefl_uload32(&in[p]))) {
  607. int n = SDEFL_MIN_MATCH;
  608. while (n < max_match && in[i + n] == in[p + n]) {
  609. assert(i + n < e);
  610. assert(p + n < e);
  611. n++;
  612. }
  613. if (n > m->len) {
  614. m->len = n, m->off = p - i;
  615. if (n == max_match)
  616. break;
  617. }
  618. }
  619. if (!(--chain_len)) break;
  620. i = s->prv[i & SDEFL_WIN_MSK];
  621. }
  622. }
  623. static int
  624. sdefl_compr(struct sdefl *s, unsigned char *out, const unsigned char *in,
  625. int in_len, int lvl) {
  626. unsigned char *q = out;
  627. static const unsigned char pref[] = {8,10,14,24,30,48,65,96,130};
  628. int max_chain = (lvl < 8) ? (1 << (lvl + 1)): (1 << 13);
  629. int n, i = 0, litlen = 0;
  630. for (n = 0; n < SDEFL_HASH_SIZ; ++n) {
  631. s->tbl[n] = SDEFL_NIL;
  632. }
  633. do {int blk_begin = i;
  634. int blk_end = ((i + SDEFL_BLK_MAX) < in_len) ? (i + SDEFL_BLK_MAX) : in_len;
  635. while (i < blk_end) {
  636. struct sdefl_match m = {0};
  637. int left = blk_end - i;
  638. int max_match = (left > SDEFL_MAX_MATCH) ? SDEFL_MAX_MATCH : left;
  639. int nice_match = pref[lvl] < max_match ? pref[lvl] : max_match;
  640. int run = 1, inc = 1, run_inc = 0;
  641. if (max_match > SDEFL_MIN_MATCH) {
  642. sdefl_fnd(&m, s, max_chain, max_match, in, i, in_len);
  643. }
  644. if (lvl >= 5 && m.len >= SDEFL_MIN_MATCH && m.len + 1 < nice_match){
  645. struct sdefl_match m2 = {0};
  646. sdefl_fnd(&m2, s, max_chain, m.len + 1, in, i + 1, in_len);
  647. m.len = (m2.len > m.len) ? 0 : m.len;
  648. }
  649. if (m.len >= SDEFL_MIN_MATCH) {
  650. if (litlen) {
  651. sdefl_seq(s, i - litlen, litlen);
  652. litlen = 0;
  653. }
  654. sdefl_seq(s, -m.off, m.len);
  655. sdefl_reg_match(s, m.off, m.len);
  656. if (lvl < 2 && m.len >= nice_match) {
  657. inc = m.len;
  658. } else {
  659. run = m.len;
  660. }
  661. } else {
  662. s->freq.lit[in[i]]++;
  663. litlen++;
  664. }
  665. run_inc = run * inc;
  666. if (in_len - (i + run_inc) > SDEFL_MIN_MATCH) {
  667. while (run-- > 0) {
  668. unsigned h = sdefl_hash32(&in[i]);
  669. s->prv[i&SDEFL_WIN_MSK] = s->tbl[h];
  670. s->tbl[h] = i, i += inc;
  671. assert(i <= blk_end);
  672. }
  673. } else {
  674. i += run_inc;
  675. assert(i <= blk_end);
  676. }
  677. }
  678. if (litlen) {
  679. sdefl_seq(s, i - litlen, litlen);
  680. litlen = 0;
  681. }
  682. sdefl_flush(&q, s, blk_end == in_len, in, blk_begin, blk_end);
  683. } while (i < in_len);
  684. if (s->bitcnt) {
  685. sdefl_put(&q, s, 0x00, 8 - s->bitcnt);
  686. }
  687. assert(s->bitcnt == 0);
  688. return (int)(q - out);
  689. }
  690. extern int
  691. sdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
  692. s->bits = s->bitcnt = 0;
  693. return sdefl_compr(s, (unsigned char*)out, (const unsigned char*)in, n, lvl);
  694. }
  695. static unsigned
  696. sdefl_adler32(unsigned adler32, const unsigned char *in, int in_len) {
  697. #define SDEFL_ADLER_INIT (1)
  698. const unsigned ADLER_MOD = 65521;
  699. unsigned s1 = adler32 & 0xffff;
  700. unsigned s2 = adler32 >> 16;
  701. unsigned blk_len, i;
  702. blk_len = in_len % 5552;
  703. while (in_len) {
  704. for (i = 0; i + 7 < blk_len; i += 8) {
  705. s1 += in[0]; s2 += s1;
  706. s1 += in[1]; s2 += s1;
  707. s1 += in[2]; s2 += s1;
  708. s1 += in[3]; s2 += s1;
  709. s1 += in[4]; s2 += s1;
  710. s1 += in[5]; s2 += s1;
  711. s1 += in[6]; s2 += s1;
  712. s1 += in[7]; s2 += s1;
  713. in += 8;
  714. }
  715. for (; i < blk_len; ++i) {
  716. s1 += *in++, s2 += s1;
  717. }
  718. s1 %= ADLER_MOD;
  719. s2 %= ADLER_MOD;
  720. in_len -= blk_len;
  721. blk_len = 5552;
  722. }
  723. return (unsigned)(s2 << 16) + (unsigned)s1;
  724. }
  725. extern int
  726. zsdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
  727. int p = 0;
  728. unsigned a = 0;
  729. unsigned char *q = (unsigned char*)out;
  730. s->bits = s->bitcnt = 0;
  731. sdefl_put(&q, s, 0x78, 8); /* deflate, 32k window */
  732. sdefl_put(&q, s, 0x01, 8); /* fast compression */
  733. q += sdefl_compr(s, q, (const unsigned char*)in, n, lvl);
  734. /* append adler checksum */
  735. a = sdefl_adler32(SDEFL_ADLER_INIT, (const unsigned char*)in, n);
  736. for (p = 0; p < 4; ++p) {
  737. sdefl_put(&q, s, (a >> 24) & 0xFF, 8);
  738. a <<= 8;
  739. }
  740. return (int)(q - (unsigned char*)out);
  741. }
  742. extern int
  743. sdefl_bound(int len) {
  744. int max_blocks = 1 + sdefl_div_round_up(len, SDEFL_RAW_BLK_SIZE);
  745. int bound = 5 * max_blocks + len + 1 + 4 + 8;
  746. return bound;
  747. }
  748. #endif /* SDEFL_IMPLEMENTATION */