binary_to_compressed_c.cpp 13 KB

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