1 /* Copyright: stbiw-0.92 - public domain - http://nothings.org/stb/stb_image_write.h
2    writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010
3                             no warranty implied; use at your own risk
4 */
5 
6 #include <stdarg.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <assert.h>
11 
12 #include "graphics/image/stb_image_write.h"
13 
14 namespace stbi {
15 
16 typedef unsigned int stbiw_uint32;
17 typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
18 
writefv(FILE * f,const char * fmt,va_list v)19 static int writefv(FILE *f, const char *fmt, va_list v)
20 {
21    while (*fmt) {
22       switch (*fmt++) {
23          case ' ': break;
24          case '1': { unsigned char x = (unsigned char) va_arg(v, int); fputc(x,f); break; }
25          case '2': { int x = va_arg(v,int); unsigned char b[2];
26                      b[0] = (unsigned char) x; b[1] = (unsigned char) (x>>8);
27                      if(!fwrite(b,2,1,f)) return 0; break; }
28          case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4];
29                      b[0]=(unsigned char)x; b[1]=(unsigned char)(x>>8);
30                      b[2]=(unsigned char)(x>>16); b[3]=(unsigned char)(x>>24);
31                      if(!fwrite(b,4,1,f)) return 0; break; }
32          default:
33             assert(0);
34             return 1;
35       }
36    }
37    return 1;
38 }
39 
write3(FILE * f,unsigned char a,unsigned char b,unsigned char c)40 static int write3(FILE *f, unsigned char a, unsigned char b, unsigned char c)
41 {
42    unsigned char arr[3];
43    arr[0] = a, arr[1] = b, arr[2] = c;
44    return fwrite(arr, 3, 1, f);
45 }
46 
write_pixels(FILE * f,int rgb_dir,int vdir,int x,int y,int comp,const void * data,int write_alpha,int scanline_pad)47 static int write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, const void *data, int write_alpha, int scanline_pad)
48 {
49    unsigned char bg[3] = { 255, 0, 255 }, px[3];
50    stbiw_uint32 zero = 0;
51    int i,j,k, j_end;
52 
53    if (y <= 0)
54       return 1;
55 
56    if (vdir < 0)
57       j_end = -1, j = y-1;
58    else
59       j_end =  y, j = 0;
60 
61    for (; j != j_end; j += vdir) {
62       for (i=0; i < x; ++i) {
63          const unsigned char *d = (const unsigned char *) data + (j*x+i)*comp;
64          if (write_alpha < 0)
65             if(!fwrite(&d[comp-1], 1, 1, f)) return 0;
66          switch (comp) {
67             case 1:
68             case 2: if(!write3(f, d[0],d[0],d[0])) return 0;
69                     break;
70             case 4:
71                if (!write_alpha) {
72                   // composite against pink background
73                   for (k=0; k < 3; ++k)
74                      px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
75                   if(!write3(f, px[1-rgb_dir],px[1],px[1+rgb_dir])) return 0;
76                   break;
77                }
78                /* FALLTHROUGH */
79             case 3:
80                if(!write3(f, d[1-rgb_dir],d[1],d[1+rgb_dir])) return 0;
81                break;
82          }
83          if (write_alpha > 0)
84             if(!fwrite(&d[comp-1], 1, 1, f)) return 0;
85       }
86       if(scanline_pad > 0 && !fwrite(&zero,scanline_pad,1,f)) return 0;
87    }
88    return 1;
89 }
90 
outfile(char const * filename,int rgb_dir,int vdir,int x,int y,int comp,const void * data,int alpha,int pad,const char * fmt,...)91 static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, const void *data, int alpha, int pad, const char *fmt, ...)
92 {
93    FILE *f;
94    if (y < 0 || x < 0) return 0;
95    f = fopen(filename, "wb");
96    if (f) {
97       va_list v;
98       va_start(v, fmt);
99       int ret = writefv(f, fmt, v);
100       va_end(v);
101       if(ret) ret = write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
102       fclose(f);
103       if(!ret) return 0;
104    }
105    return f != NULL;
106 }
107 
stbi_write_bmp(char const * filename,int x,int y,int comp,const void * data)108 extern "C" int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
109 {
110    int pad = (-x*3) & 3;
111    return outfile(filename,-1,-1,x,y,comp,data,0,pad,
112            "11 4 22 4" "4 44 22 444444",
113            'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header
114             40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header
115 }
116 
stbi_write_tga(char const * filename,int x,int y,int comp,const void * data)117 extern "C" int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
118 {
119    int has_alpha = !(comp & 1);
120    return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,
121                   "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
122 }
123 
124 // stretchy buffer; stbi_sbpush() == vector<>::push_back() -- stbi_sbcount() == vector<>::size()
125 #define stbi_sbraw(a) ((int *) (a) - 2)
126 #define stbi_sbm(a)   stbi_sbraw(a)[0]
127 #define stbi_sbn(a)   stbi_sbraw(a)[1]
128 
129 #define stbi_sbneedgrow(a,n)  ((a)==0 || stbi_sbn(a)+n >= stbi_sbm(a))
130 #define stbi_sbmaybegrow(a,n) (stbi_sbneedgrow(a,(n)) ? stbi_sbgrow(a,n) : 0)
131 #define stbi_sbgrow(a,n)  stbi_sbgrowf((void **) &(a), (n), sizeof(*(a)))
132 
133 #define stbi_sbpush(a, v)      (stbi_sbmaybegrow(a,1), (a)[stbi_sbn(a)++] = (v))
134 #define stbi_sbcount(a)        ((a) ? stbi_sbn(a) : 0)
135 #define stbi_sbfree(a)         ((a) ? free(stbi_sbraw(a)),0 : 0)
136 
137 #define stbi_size(x) sizeof(x)
138 
stbi_sbgrowf(void ** arr,int increment,int itemsize)139 static void *stbi_sbgrowf(void **arr, int increment, int itemsize)
140 {
141    int m = *arr ? 2*stbi_sbm(*arr)+increment : increment+1;
142    void *p = realloc(*arr ? stbi_sbraw(*arr) : 0, itemsize * m + stbi_size(int)*2);
143    assert(p);
144    if (p) {
145       if (!*arr) ((int *) p)[1] = 0;
146       *arr = (void *) ((int *) p + 2);
147       stbi_sbm(*arr) = m;
148    }
149    return *arr;
150 }
151 
152 #undef stbi_size
153 
stbi_zlib_flushf(unsigned char * data,unsigned int * bitbuffer,int * bitcount)154 static unsigned char *stbi_zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
155 {
156    while (*bitcount >= 8) {
157       stbi_sbpush(data, (unsigned char) *bitbuffer);
158       *bitbuffer >>= 8;
159       *bitcount -= 8;
160    }
161    return data;
162 }
163 
stbi_zlib_bitrev(int code,int codebits)164 static int stbi_zlib_bitrev(int code, int codebits)
165 {
166    int res=0;
167    while (codebits--) {
168       res = (res << 1) | (code & 1);
169       code >>= 1;
170    }
171    return res;
172 }
173 
stbi_zlib_countm(unsigned char * a,unsigned char * b,int limit)174 static unsigned int stbi_zlib_countm(unsigned char *a, unsigned char *b, int limit)
175 {
176    int i;
177    for (i=0; i < limit && i < 258; ++i)
178       if (a[i] != b[i]) break;
179    return i;
180 }
181 
stbi_zhash(unsigned char * data)182 static unsigned int stbi_zhash(unsigned char *data)
183 {
184    stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
185    hash ^= hash << 3;
186    hash += hash >> 5;
187    hash ^= hash << 4;
188    hash += hash >> 17;
189    hash ^= hash << 25;
190    hash += hash >> 6;
191    return hash;
192 }
193 
194 #define stbi_zlib_flush() (out = stbi_zlib_flushf(out, &bitbuf, &bitcount))
195 #define stbi_zlib_add(code,codebits) \
196       (bitbuf |= (code) << bitcount, bitcount += (codebits), stbi_zlib_flush())
197 #define stbi_zlib_huffa(b,c)  stbi_zlib_add(stbi_zlib_bitrev(b,c),c)
198 // default huffman tables
199 #define stbi_zlib_huff1(n)  stbi_zlib_huffa(0x30 + (n), 8)
200 #define stbi_zlib_huff2(n)  stbi_zlib_huffa(0x190 + (n)-144, 9)
201 #define stbi_zlib_huff3(n)  stbi_zlib_huffa(0 + (n)-256,7)
202 #define stbi_zlib_huff4(n)  stbi_zlib_huffa(0xc0 + (n)-280,8)
203 #define stbi_zlib_huff(n)  ((n) <= 143 ? stbi_zlib_huff1(n) : (n) <= 255 ? stbi_zlib_huff2(n) : (n) <= 279 ? stbi_zlib_huff3(n) : stbi_zlib_huff4(n))
204 #define stbi_zlib_huffb(n) ((n) <= 143 ? stbi_zlib_huff1(n) : stbi_zlib_huff2(n))
205 
206 #define stbi_ZHASH   16384
207 
stbi_zlib_compress(unsigned char * data,int data_len,int * out_len,int quality)208 unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
209 {
210    static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
211    static unsigned char  lengtheb[]= { 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 };
212    static unsigned short distc[]   = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
213    static unsigned char  disteb[]  = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
214    unsigned int bitbuf=0;
215    int i,j, bitcount=0;
216    unsigned char *out = NULL;
217    unsigned char **hash_table[stbi_ZHASH]; // 64KB on the stack!
218    if (quality < 5) quality = 5;
219 
220    stbi_sbpush(out, 0x78);   // DEFLATE 32K window
221    stbi_sbpush(out, 0x5e);   // FLEVEL = 1
222    stbi_zlib_add(1,1);  // BFINAL = 1
223    stbi_zlib_add(1,2);  // BTYPE = 1 -- fixed huffman
224 
225    for (i=0; i < stbi_ZHASH; ++i)
226       hash_table[i] = NULL;
227 
228    i=0;
229    while (i < data_len-3) {
230       // hash next 3 bytes of data to be compressed
231       int h = stbi_zhash(data+i)&(stbi_ZHASH-1), best=3;
232       unsigned char *bestloc = 0;
233       unsigned char **hlist = hash_table[h];
234       int n = stbi_sbcount(hlist);
235       for (j=0; j < n; ++j) {
236          if (hlist[j]-data > i-32768) { // if entry lies within window
237             int d = stbi_zlib_countm(hlist[j], data+i, data_len-i);
238             if (d >= best) best=d,bestloc=hlist[j];
239          }
240       }
241       // when hash table entry is too long, delete half the entries
242       if (hash_table[h] && stbi_sbn(hash_table[h]) == 2*quality) {
243          memcpy(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
244          stbi_sbn(hash_table[h]) = quality;
245       }
246       stbi_sbpush(hash_table[h],data+i);
247 
248       if (bestloc) {
249          // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
250          h = stbi_zhash(data+i+1)&(stbi_ZHASH-1);
251          hlist = hash_table[h];
252          n = stbi_sbcount(hlist);
253          for (j=0; j < n; ++j) {
254             if (hlist[j]-data > i-32767) {
255                int e = stbi_zlib_countm(hlist[j], data+i+1, data_len-i-1);
256                if (e > best) { // if next match is better, bail on current match
257                   bestloc = NULL;
258                   break;
259                }
260             }
261          }
262       }
263 
264       if (bestloc) {
265          int d = data+i - bestloc; // distance back
266          assert(d <= 32767 && best <= 258);
267          for (j=0; best > lengthc[j+1]-1; ++j) ;
268          stbi_zlib_huff(j+257);
269          if (lengtheb[j]) stbi_zlib_add(best - lengthc[j], lengtheb[j]);
270          for (j=0; d > distc[j+1]-1; ++j) ;
271          stbi_zlib_add(stbi_zlib_bitrev(j,5),5);
272          if (disteb[j]) stbi_zlib_add(d - distc[j], disteb[j]);
273          i += best;
274       } else {
275          stbi_zlib_huffb(data[i]);
276          ++i;
277       }
278    }
279    // write out final bytes
280    for (;i < data_len; ++i)
281       stbi_zlib_huffb(data[i]);
282    stbi_zlib_huff(256); // end of block
283    // pad with 0 bits to byte boundary
284    while (bitcount)
285       stbi_zlib_add(0,1);
286 
287    for (i=0; i < stbi_ZHASH; ++i)
288       (void) stbi_sbfree(hash_table[i]);
289 
290    {
291       // compute adler32 on input
292       unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
293       int j=0;
294       while (j < data_len) {
295          for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1;
296          s1 %= 65521, s2 %= 65521;
297          j += blocklen;
298          blocklen = 5552;
299       }
300       stbi_sbpush(out, (unsigned char) (s2 >> 8));
301       stbi_sbpush(out, (unsigned char) s2);
302       stbi_sbpush(out, (unsigned char) (s1 >> 8));
303       stbi_sbpush(out, (unsigned char) s1);
304    }
305    *out_len = stbi_sbn(out);
306    // make returned pointer freeable
307    memmove(stbi_sbraw(out), out, *out_len);
308    return (unsigned char *) stbi_sbraw(out);
309 }
310 
stbi_crc32(unsigned char * buffer,int len)311 unsigned int stbi_crc32(unsigned char *buffer, int len)
312 {
313    static unsigned int crc_table[256];
314    unsigned int crc = ~0u;
315    int i,j;
316    if (crc_table[1] == 0)
317       for(i=0; i < 256; i++)
318          for (crc_table[i]=i, j=0; j < 8; ++j)
319             crc_table[i] = (crc_table[i] >> 1) ^ (crc_table[i] & 1 ? 0xedb88320 : 0);
320    for (i=0; i < len; ++i)
321       crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
322    return ~crc;
323 }
324 
325 #define stbi_wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)
326 #define stbi_wp32(data,v) stbi_wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
327 #define stbi_wptag(data,s) stbi_wpng4(data, s[0],s[1],s[2],s[3])
328 
stbi_wpcrc(unsigned char ** data,int len)329 static void stbi_wpcrc(unsigned char **data, int len)
330 {
331    unsigned int crc = stbi_crc32(*data - len - 4, len+4);
332    stbi_wp32(*data, crc);
333 }
334 
stbi_paeth(int a,int b,int c)335 static unsigned char stbi_paeth(int a, int b, int c)
336 {
337    int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
338    if (pa <= pb && pa <= pc) return (unsigned char) a;
339    if (pb <= pc) return (unsigned char) b;
340    return (unsigned char) c;
341 }
342 
stbi_write_png_to_mem(const unsigned char * pixels,int stride_bytes,int x,int y,int n,int * out_len)343 unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
344 {
345    int ctype[5] = { -1, 0, 4, 2, 6 };
346    unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
347    unsigned char *out,*o, *filt, *zlib;
348    signed char *line_buffer;
349    int i,j,k,p,zlen;
350 
351    if (stride_bytes == 0)
352       stride_bytes = x * n;
353 
354    filt = (unsigned char *) malloc((x*n+1) * y); if (!filt) return 0;
355    line_buffer = (signed char *) malloc(x * n); if (!line_buffer) { free(filt); return 0; }
356    for (j=0; j < y; ++j) {
357       static int mapping[] = { 0,1,2,3,4 };
358       static int firstmap[] = { 0,1,0,5,6 };
359       int *mymap = j ? mapping : firstmap;
360       int best = 0, bestval = 0x7fffffff;
361       for (p=0; p < 2; ++p) {
362          for (k= p?best:0; k < 5; ++k) {
363             int type = mymap[k],est=0;
364             const unsigned char *z = pixels + stride_bytes*j;
365             for (i=0; i < n; ++i)
366                switch (type) {
367                   case 0: line_buffer[i] = z[i]; break;
368                   case 1: line_buffer[i] = z[i]; break;
369                   case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
370                   case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;
371                   case 4: line_buffer[i] = (signed char) (z[i] - stbi_paeth(0,z[i-stride_bytes],0)); break;
372                   case 5: line_buffer[i] = z[i]; break;
373                   case 6: line_buffer[i] = z[i]; break;
374                }
375             for (i=n; i < x*n; ++i) {
376                switch (type) {
377                   case 0: line_buffer[i] = z[i]; break;
378                   case 1: line_buffer[i] = z[i] - z[i-n]; break;
379                   case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
380                   case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;
381                   case 4: line_buffer[i] = z[i] - stbi_paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;
382                   case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;
383                   case 6: line_buffer[i] = z[i] - stbi_paeth(z[i-n], 0,0); break;
384                }
385             }
386             if (p) break;
387             for (i=0; i < x*n; ++i)
388                est += abs((signed char) line_buffer[i]);
389             if (est < bestval) { bestval = est; best = k; }
390          }
391       }
392       // when we get here, best contains the filter type, and line_buffer contains the data
393       filt[j*(x*n+1)] = (unsigned char) best;
394       memcpy(filt+j*(x*n+1)+1, line_buffer, x*n);
395    }
396    free(line_buffer);
397    zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory
398    free(filt);
399    if (!zlib) return 0;
400 
401    // each tag requires 12 bytes of overhead
402    out = (unsigned char *) malloc(8 + 12+13 + 12+zlen + 12);
403    if (!out) return 0;
404    *out_len = 8 + 12+13 + 12+zlen + 12;
405 
406    o=out;
407    memcpy(o,sig,8); o+= 8;
408    stbi_wp32(o, 13); // header length
409    stbi_wptag(o, "IHDR");
410    stbi_wp32(o, x);
411    stbi_wp32(o, y);
412    *o++ = 8;
413    *o++ = (unsigned char) ctype[n];
414    *o++ = 0;
415    *o++ = 0;
416    *o++ = 0;
417    stbi_wpcrc(&o,13);
418 
419    stbi_wp32(o, zlen);
420    stbi_wptag(o, "IDAT");
421    memcpy(o, zlib, zlen); o += zlen; free(zlib);
422    stbi_wpcrc(&o, zlen);
423 
424    stbi_wp32(o,0);
425    stbi_wptag(o, "IEND");
426    stbi_wpcrc(&o,0);
427 
428    assert(o == out + *out_len);
429 
430    return out;
431 }
432 
stbi_write_png(char const * filename,int x,int y,int comp,const void * data,int stride_bytes)433 extern "C" int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
434 {
435    FILE *f;
436    int len;
437    unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);
438    if (!png) return 0;
439    f = fopen(filename, "wb");
440    if (!f) { free(png); return 0; }
441    if (!fwrite(png, len, 1, f)) return 0;
442    fclose(f);
443    free(png);
444    return 1;
445 }
446 
447 } // namespace stbi
448