binary_to_compressed_c.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. // dear imgui
  2. // (binary_to_compressed_c.cpp)
  3. // Helper tool to turn a file into a C array, if you want to embed font data in your source code.
  4. // The data is first compressed with stb_compress() to reduce source code size,
  5. // then encoded in Base85 to fit in a string so we can fit roughly 4 bytes of compressed data into 5 bytes of source code (suggested by @mmalex)
  6. // (If we used 32-bit constants it would require take 11 bytes of source code to encode 4 bytes, and be endianness dependent)
  7. // Note that even with compression, the output array is likely to be bigger than the binary file..
  8. // Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF()
  9. // Build with, e.g:
  10. // # cl.exe binary_to_compressed_c.cpp
  11. // # g++ binary_to_compressed_c.cpp
  12. // # clang++ binary_to_compressed_c.cpp
  13. // You can also find a precompiled Windows binary in the binary/demo package available from https://github.com/ocornut/imgui
  14. // Usage:
  15. // binary_to_compressed_c.exe [-base85] [-nocompress] [-nostatic] <inputfile> <symbolname>
  16. // Usage example:
  17. // # binary_to_compressed_c.exe myfont.ttf MyFont > myfont.cpp
  18. // # binary_to_compressed_c.exe -base85 myfont.ttf MyFont > myfont.cpp
  19. #define _CRT_SECURE_NO_WARNINGS
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <assert.h>
  24. // stb_compress* from stb.h - declaration
  25. typedef unsigned int stb_uint;
  26. typedef unsigned char stb_uchar;
  27. stb_uint stb_compress(stb_uchar* out, stb_uchar* in, stb_uint len);
  28. static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static);
  29. int main(int argc, char** argv)
  30. {
  31. if (argc < 3)
  32. {
  33. printf("Syntax: %s [-base85] [-nocompress] [-nostatic] <inputfile> <symbolname>\n", argv[0]);
  34. return 0;
  35. }
  36. int argn = 1;
  37. bool use_base85_encoding = false;
  38. bool use_compression = true;
  39. bool use_static = true;
  40. while (argn < (argc - 2) && argv[argn][0] == '-')
  41. {
  42. if (strcmp(argv[argn], "-base85") == 0) { use_base85_encoding = true; argn++; }
  43. else if (strcmp(argv[argn], "-nocompress") == 0) { use_compression = false; argn++; }
  44. else if (strcmp(argv[argn], "-nostatic") == 0) { use_static = false; argn++; }
  45. else
  46. {
  47. fprintf(stderr, "Unknown argument: '%s'\n", argv[argn]);
  48. return 1;
  49. }
  50. }
  51. bool ret = binary_to_compressed_c(argv[argn], argv[argn + 1], use_base85_encoding, use_compression, use_static);
  52. if (!ret)
  53. fprintf(stderr, "Error opening or reading file: '%s'\n", argv[argn]);
  54. return ret ? 0 : 1;
  55. }
  56. char Encode85Byte(unsigned int x)
  57. {
  58. x = (x % 85) + 35;
  59. return (char)((x >= '\\') ? x + 1 : x);
  60. }
  61. bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static)
  62. {
  63. // Read file
  64. FILE* f = fopen(filename, "rb");
  65. if (!f) return false;
  66. int data_sz;
  67. if (fseek(f, 0, SEEK_END) || (data_sz = (int)ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; }
  68. char* data = new char[data_sz + 4];
  69. if (fread(data, 1, data_sz, f) != (size_t)data_sz) { fclose(f); delete[] data; return false; }
  70. memset((void*)(((char*)data) + data_sz), 0, 4);
  71. fclose(f);
  72. // Compress
  73. int maxlen = data_sz + 512 + (data_sz >> 2) + sizeof(int); // total guess
  74. char* compressed = use_compression ? new char[maxlen] : data;
  75. int compressed_sz = use_compression ? stb_compress((stb_uchar*)compressed, (stb_uchar*)data, data_sz) : data_sz;
  76. if (use_compression)
  77. memset(compressed + compressed_sz, 0, maxlen - compressed_sz);
  78. // Output as Base85 encoded
  79. FILE* out = stdout;
  80. fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz);
  81. fprintf(out, "// Exported using binary_to_compressed_c.cpp\n");
  82. const char* static_str = use_static ? "static " : "";
  83. const char* compressed_str = use_compression ? "compressed_" : "";
  84. if (use_base85_encoding)
  85. {
  86. fprintf(out, "%sconst char %s_%sdata_base85[%d+1] =\n \"", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*5);
  87. char prev_c = 0;
  88. for (int src_i = 0; src_i < compressed_sz; src_i += 4)
  89. {
  90. // This is made a little more complicated by the fact that ??X sequences are interpreted as trigraphs by old C/C++ compilers. So we need to escape pairs of ??.
  91. unsigned int d = *(unsigned int*)(compressed + src_i);
  92. for (unsigned int n5 = 0; n5 < 5; n5++, d /= 85)
  93. {
  94. char c = Encode85Byte(d);
  95. fprintf(out, (c == '?' && prev_c == '?') ? "\\%c" : "%c", c);
  96. prev_c = c;
  97. }
  98. if ((src_i % 112) == 112 - 4)
  99. fprintf(out, "\"\n \"");
  100. }
  101. fprintf(out, "\";\n\n");
  102. }
  103. #if 0
  104. else
  105. {
  106. // As individual bytes, not subject to endianness issues.
  107. fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
  108. fprintf(out, "%sconst unsigned char %s_%sdata[%d] =\n{", static_str, symbol, compressed_str, (int)compressed_sz);
  109. int column = 0;
  110. for (int i = 0; i < compressed_sz; i++)
  111. {
  112. unsigned char d = *(unsigned char*)(compressed + i);
  113. if (column == 0)
  114. fprintf(out, "\n ");
  115. column += fprintf(out, "%d,", d);
  116. if (column >= 180)
  117. column = 0;
  118. }
  119. fprintf(out, "\n};\n\n");
  120. }
  121. #else
  122. else
  123. {
  124. // As integers
  125. fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
  126. fprintf(out, "%sconst unsigned int %s_%sdata[%d/4] =\n{", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4);
  127. int column = 0;
  128. for (int i = 0; i < compressed_sz; i += 4)
  129. {
  130. unsigned int d = *(unsigned int*)(compressed + i);
  131. if ((column++ % 14) == 0)
  132. fprintf(out, "\n 0x%08x, ", d);
  133. else
  134. fprintf(out, "0x%08x, ", d);
  135. }
  136. fprintf(out, "\n};\n\n");
  137. }
  138. #endif
  139. // Cleanup
  140. delete[] data;
  141. if (use_compression)
  142. delete[] compressed;
  143. return true;
  144. }
  145. // stb_compress* from stb.h - definition
  146. //////////////////// compressor ///////////////////////
  147. static stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)
  148. {
  149. const unsigned long ADLER_MOD = 65521;
  150. unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
  151. unsigned long blocklen, i;
  152. blocklen = buflen % 5552;
  153. while (buflen) {
  154. for (i=0; i + 7 < blocklen; i += 8) {
  155. s1 += buffer[0], s2 += s1;
  156. s1 += buffer[1], s2 += s1;
  157. s1 += buffer[2], s2 += s1;
  158. s1 += buffer[3], s2 += s1;
  159. s1 += buffer[4], s2 += s1;
  160. s1 += buffer[5], s2 += s1;
  161. s1 += buffer[6], s2 += s1;
  162. s1 += buffer[7], s2 += s1;
  163. buffer += 8;
  164. }
  165. for (; i < blocklen; ++i)
  166. s1 += *buffer++, s2 += s1;
  167. s1 %= ADLER_MOD, s2 %= ADLER_MOD;
  168. buflen -= blocklen;
  169. blocklen = 5552;
  170. }
  171. return (s2 << 16) + s1;
  172. }
  173. static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)
  174. {
  175. stb_uint i;
  176. for (i=0; i < maxlen; ++i)
  177. if (m1[i] != m2[i]) return i;
  178. return i;
  179. }
  180. // simple implementation that just takes the source data in a big block
  181. static stb_uchar *stb__out;
  182. static FILE *stb__outfile;
  183. static stb_uint stb__outbytes;
  184. static void stb__write(unsigned char v)
  185. {
  186. fputc(v, stb__outfile);
  187. ++stb__outbytes;
  188. }
  189. //#define stb_out(v) (stb__out ? *stb__out++ = (stb_uchar) (v) : stb__write((stb_uchar) (v)))
  190. #define stb_out(v) do { if (stb__out) *stb__out++ = (stb_uchar) (v); else stb__write((stb_uchar) (v)); } while (0)
  191. static void stb_out2(stb_uint v) { stb_out(v >> 8); stb_out(v); }
  192. static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }
  193. static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16); stb_out(v >> 8 ); stb_out(v); }
  194. static void outliterals(stb_uchar *in, int numlit)
  195. {
  196. while (numlit > 65536) {
  197. outliterals(in,65536);
  198. in += 65536;
  199. numlit -= 65536;
  200. }
  201. if (numlit == 0) ;
  202. else if (numlit <= 32) stb_out (0x000020 + numlit-1);
  203. else if (numlit <= 2048) stb_out2(0x000800 + numlit-1);
  204. else /* numlit <= 65536) */ stb_out3(0x070000 + numlit-1);
  205. if (stb__out) {
  206. memcpy(stb__out,in,numlit);
  207. stb__out += numlit;
  208. } else
  209. fwrite(in, 1, numlit, stb__outfile);
  210. }
  211. static int stb__window = 0x40000; // 256K
  212. static int stb_not_crap(int best, int dist)
  213. {
  214. return ((best > 2 && dist <= 0x00100)
  215. || (best > 5 && dist <= 0x04000)
  216. || (best > 7 && dist <= 0x80000));
  217. }
  218. static stb_uint stb__hashsize = 32768;
  219. // note that you can play with the hashing functions all you
  220. // want without needing to change the decompressor
  221. #define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c])
  222. #define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])
  223. #define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e])
  224. static unsigned int stb__running_adler;
  225. static int stb_compress_chunk(stb_uchar *history,
  226. stb_uchar *start,
  227. stb_uchar *end,
  228. int length,
  229. int *pending_literals,
  230. stb_uchar **chash,
  231. stb_uint mask)
  232. {
  233. (void)history;
  234. int window = stb__window;
  235. stb_uint match_max;
  236. stb_uchar *lit_start = start - *pending_literals;
  237. stb_uchar *q = start;
  238. #define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask)
  239. // stop short of the end so we don't scan off the end doing
  240. // the hashing; this means we won't compress the last few bytes
  241. // unless they were part of something longer
  242. while (q < start+length && q+12 < end) {
  243. int m;
  244. stb_uint h1,h2,h3,h4, h;
  245. stb_uchar *t;
  246. int best = 2, dist=0;
  247. if (q+65536 > end)
  248. match_max = (stb_uint)(end-q);
  249. else
  250. match_max = 65536;
  251. #define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap((int)(b),(int)(d))))
  252. #define STB__TRY(t,p) /* avoid retrying a match we already tried */ \
  253. if (p ? dist != (int)(q-t) : 1) \
  254. if ((m = stb_matchlen(t, q, match_max)) > best) \
  255. if (stb__nc(m,q-(t))) \
  256. best = m, dist = (int)(q - (t))
  257. // rather than search for all matches, only try 4 candidate locations,
  258. // chosen based on 4 different hash functions of different lengths.
  259. // this strategy is inspired by LZO; hashing is unrolled here using the
  260. // 'hc' macro
  261. h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);
  262. t = chash[h1]; if (t) STB__TRY(t,0);
  263. h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);
  264. h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1);
  265. h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);
  266. h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1);
  267. h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);
  268. t = chash[h4]; if (t) STB__TRY(t,1);
  269. // because we use a shared hash table, can only update it
  270. // _after_ we've probed all of them
  271. chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;
  272. if (best > 2)
  273. assert(dist > 0);
  274. // see if our best match qualifies
  275. if (best < 3) { // fast path literals
  276. ++q;
  277. } else if (best > 2 && best <= 0x80 && dist <= 0x100) {
  278. outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best);
  279. stb_out(0x80 + best-1);
  280. stb_out(dist-1);
  281. } else if (best > 5 && best <= 0x100 && dist <= 0x4000) {
  282. outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best);
  283. stb_out2(0x4000 + dist-1);
  284. stb_out(best-1);
  285. } else if (best > 7 && best <= 0x100 && dist <= 0x80000) {
  286. outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best);
  287. stb_out3(0x180000 + dist-1);
  288. stb_out(best-1);
  289. } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) {
  290. outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best);
  291. stb_out3(0x100000 + dist-1);
  292. stb_out2(best-1);
  293. } else if (best > 9 && dist <= 0x1000000) {
  294. if (best > 65536) best = 65536;
  295. outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best);
  296. if (best <= 0x100) {
  297. stb_out(0x06);
  298. stb_out3(dist-1);
  299. stb_out(best-1);
  300. } else {
  301. stb_out(0x04);
  302. stb_out3(dist-1);
  303. stb_out2(best-1);
  304. }
  305. } else { // fallback literals if no match was a balanced tradeoff
  306. ++q;
  307. }
  308. }
  309. // if we didn't get all the way, add the rest to literals
  310. if (q-start < length)
  311. q = start+length;
  312. // the literals are everything from lit_start to q
  313. *pending_literals = (int)(q - lit_start);
  314. stb__running_adler = stb_adler32(stb__running_adler, start, (stb_uint)(q - start));
  315. return (int)(q - start);
  316. }
  317. static int stb_compress_inner(stb_uchar *input, stb_uint length)
  318. {
  319. int literals = 0;
  320. stb_uint len,i;
  321. stb_uchar **chash;
  322. chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));
  323. if (chash == nullptr) return 0; // failure
  324. for (i=0; i < stb__hashsize; ++i)
  325. chash[i] = nullptr;
  326. // stream signature
  327. stb_out(0x57); stb_out(0xbc);
  328. stb_out2(0);
  329. stb_out4(0); // 64-bit length requires 32-bit leading 0
  330. stb_out4(length);
  331. stb_out4(stb__window);
  332. stb__running_adler = 1;
  333. len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);
  334. assert(len == length);
  335. outliterals(input+length - literals, literals);
  336. free(chash);
  337. stb_out2(0x05fa); // end opcode
  338. stb_out4(stb__running_adler);
  339. return 1; // success
  340. }
  341. stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)
  342. {
  343. stb__out = out;
  344. stb__outfile = nullptr;
  345. stb_compress_inner(input, length);
  346. return (stb_uint)(stb__out - out);
  347. }