binary_to_compressed_c.cpp 13 KB

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