]> git.xonotic.org Git - xonotic/darkplaces.git/blob - image_png.c
fix jump buffer type
[xonotic/darkplaces.git] / image_png.c
1 /*
2         Copyright (C) 2006  Serge "(515)" Ziryukin, Forest "LordHavoc" Hale
3
4         This program is free software; you can redistribute it and/or
5         modify it under the terms of the GNU General Public License
6         as published by the Free Software Foundation; either version 2
7         of the License, or (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24 //[515]: png implemented into DP ONLY FOR TESTING 2d stuff with csqc
25 // so delete this bullshit :D
26 //
27 //LordHavoc: rewrote most of this.
28
29 #include "quakedef.h"
30 #include "image.h"
31 #include "image_png.h"
32
33 /*
34 #ifdef __cplusplus
35 #ifdef WIN64
36 typedef _JBTYPE *qpng_jmpbuf_t;
37 #elif defined(MACOSX) || defined(WIN32)
38 typedef int *qpng_jmpbuf_t;
39 #else
40 typedef __jmp_buf_tag *qpng_jmpbuf_t;
41 #endif
42 #else
43 typedef void *qpng_jmpbuf_t;
44 #endif
45 */
46 typedef jmp_buf qpng_jmpbuf_t;
47
48 static void                             (*qpng_set_sig_bytes)           (void*, int);
49 static int                              (*qpng_sig_cmp)                         (const unsigned char*, size_t, size_t);
50 static void*                    (*qpng_create_read_struct)      (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
51 static void*                    (*qpng_create_write_struct)     (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
52 static void*                    (*qpng_create_info_struct)      (void*);
53 static void                             (*qpng_read_info)                       (void*, void*);
54 static void                             (*qpng_set_compression_level)   (void*, int);
55 static void                             (*qpng_set_filter)                      (void*, int, int);
56 static void                             (*qpng_set_expand)                      (void*);
57 static void                             (*qpng_set_palette_to_rgb)      (void*);
58 static void                             (*qpng_set_tRNS_to_alpha)       (void*);
59 static void                             (*qpng_set_gray_to_rgb)         (void*);
60 static void                             (*qpng_set_filler)                      (void*, unsigned int, int);
61 static void                             (*qpng_set_IHDR)                        (void*, void*, unsigned long, unsigned long, int, int, int, int, int);
62 static void                             (*qpng_set_packing)                     (void*);
63 static void                             (*qpng_set_bgr)                         (void*);
64 static int                              (*qpng_set_interlace_handling)  (void*);
65 static void                             (*qpng_read_update_info)        (void*, void*);
66 static void                             (*qpng_read_image)                      (void*, unsigned char**);
67 static void                             (*qpng_read_end)                        (void*, void*);
68 static void                             (*qpng_destroy_read_struct)     (void**, void**, void**);
69 static void                             (*qpng_destroy_write_struct)    (void**, void**);
70 static void                             (*qpng_set_read_fn)                     (void*, void*, void(*)(void *png, unsigned char *data, size_t length));
71 static void                             (*qpng_set_write_fn)            (void*, void*, void(*)(void *png, unsigned char *data, size_t length), void(*)(void *png));
72 static unsigned int             (*qpng_get_valid)                       (void*, void*, unsigned int);
73 static unsigned int             (*qpng_get_rowbytes)            (void*, void*);
74 static unsigned char    (*qpng_get_channels)            (void*, void*);
75 static unsigned char    (*qpng_get_bit_depth)           (void*, void*);
76 static unsigned int             (*qpng_get_IHDR)                        (void*, void*, unsigned long*, unsigned long*, int *, int *, int *, int *, int *);
77 static unsigned int                     (*qpng_access_version_number)           (void); // FIXME is this return type right? It is a png_uint_32 in libpng
78 static void                             (*qpng_write_info)                      (void*, void*);
79 static void                             (*qpng_write_row)                       (void*, unsigned char*);
80 static void                             (*qpng_write_end)                       (void*, void*);
81 static qpng_jmpbuf_t                    (*qpng_jmpbuf)          (void*);
82
83 static dllfunction_t pngfuncs[] =
84 {
85         {"png_set_sig_bytes",           (void **) &qpng_set_sig_bytes},
86         {"png_sig_cmp",                         (void **) &qpng_sig_cmp},
87         {"png_create_read_struct",      (void **) &qpng_create_read_struct},
88         {"png_create_write_struct",     (void **) &qpng_create_write_struct},
89         {"png_create_info_struct",      (void **) &qpng_create_info_struct},
90         {"png_read_info",                       (void **) &qpng_read_info},
91         {"png_set_compression_level",   (void **) &qpng_set_compression_level},
92         {"png_set_filter",                      (void **) &qpng_set_filter},
93         {"png_set_expand",                      (void **) &qpng_set_expand},
94         {"png_set_palette_to_rgb",      (void **) &qpng_set_palette_to_rgb},
95         {"png_set_tRNS_to_alpha",       (void **) &qpng_set_tRNS_to_alpha},
96         {"png_set_gray_to_rgb",         (void **) &qpng_set_gray_to_rgb},
97         {"png_set_filler",                      (void **) &qpng_set_filler},
98         {"png_set_IHDR",                        (void **) &qpng_set_IHDR},
99         {"png_set_packing",                     (void **) &qpng_set_packing},
100         {"png_set_bgr",                         (void **) &qpng_set_bgr},
101         {"png_set_interlace_handling",  (void **) &qpng_set_interlace_handling},
102         {"png_read_update_info",        (void **) &qpng_read_update_info},
103         {"png_read_image",                      (void **) &qpng_read_image},
104         {"png_read_end",                        (void **) &qpng_read_end},
105         {"png_destroy_read_struct",     (void **) &qpng_destroy_read_struct},
106         {"png_destroy_write_struct",    (void **) &qpng_destroy_write_struct},
107         {"png_set_read_fn",                     (void **) &qpng_set_read_fn},
108         {"png_set_write_fn",            (void **) &qpng_set_write_fn},
109         {"png_get_valid",                       (void **) &qpng_get_valid},
110         {"png_get_rowbytes",            (void **) &qpng_get_rowbytes},
111         {"png_get_channels",            (void **) &qpng_get_channels},
112         {"png_get_bit_depth",           (void **) &qpng_get_bit_depth},
113         {"png_get_IHDR",                        (void **) &qpng_get_IHDR},
114         {"png_access_version_number",           (void **) &qpng_access_version_number},
115         {"png_write_info",                      (void **) &qpng_write_info},
116         {"png_write_row",                       (void **) &qpng_write_row},
117         {"png_write_end",                       (void **) &qpng_write_end},
118         {"png_jmpbuf",          (void **) &qpng_jmpbuf},
119         {NULL, NULL}
120 };
121
122 // Handle for PNG DLL
123 dllhandle_t png_dll = NULL;
124
125
126 /*
127 =================================================================
128
129   DLL load & unload
130
131 =================================================================
132 */
133
134 /*
135 ====================
136 PNG_OpenLibrary
137
138 Try to load the PNG DLL
139 ====================
140 */
141 qboolean PNG_OpenLibrary (void)
142 {
143         const char* dllnames [] =
144         {
145 #if WIN32
146                 "libpng15-15.dll",
147                 "libpng15.dll",
148                 "libpng14-14.dll",
149                 "libpng14.dll",
150                 "libpng12.dll",
151 #elif defined(MACOSX)
152                 "libpng15.15.dylib",
153                 "libpng14.14.dylib",
154                 "libpng12.0.dylib",
155 #else
156                 "libpng15.so.15", // WTF libtool guidelines anyone?
157                 "libpng14.so.14", // WTF libtool guidelines anyone?
158                 "libpng12.so.0",
159                 "libpng.so", // FreeBSD
160 #endif
161                 NULL
162         };
163
164         // Already loaded?
165         if (png_dll)
166                 return true;
167
168         // Load the DLL
169         return Sys_LoadLibrary (dllnames, &png_dll, pngfuncs);
170 }
171
172
173 /*
174 ====================
175 PNG_CloseLibrary
176
177 Unload the PNG DLL
178 ====================
179 */
180 void PNG_CloseLibrary (void)
181 {
182         Sys_UnloadLibrary (&png_dll);
183 }
184
185 /*
186 =================================================================
187
188         PNG decompression
189
190 =================================================================
191 */
192
193 #define PNG_LIBPNG_VER_STRING_12 "1.2.4"
194 #define PNG_LIBPNG_VER_STRING_14 "1.4.0"
195 #define PNG_LIBPNG_VER_STRING_15 "1.5.0"
196
197 #define PNG_COLOR_MASK_PALETTE    1
198 #define PNG_COLOR_MASK_COLOR      2
199 #define PNG_COLOR_MASK_ALPHA      4
200
201 #define PNG_COLOR_TYPE_GRAY 0
202 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
203 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
204 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
205 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
206
207 #define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
208 #define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
209
210 #define PNG_INFO_tRNS 0x0010
211
212 // this struct is only used for status information during loading
213 static struct
214 {
215         const unsigned char     *tmpBuf;
216         int             tmpBuflength;
217         int             tmpi;
218         //int           FBgColor;
219         //int           FTransparent;
220         unsigned int    FRowBytes;
221         //double        FGamma;
222         //double        FScreenGamma;
223         unsigned char   **FRowPtrs;
224         unsigned char   *Data;
225         //char  *Title;
226         //char  *Author;
227         //char  *Description;
228         int             BitDepth;
229         int             BytesPerPixel;
230         int             ColorType;
231         unsigned long   Height; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
232         unsigned long   Width; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
233         int             Interlace;
234         int             Compression;
235         int             Filter;
236         //double        LastModified;
237         //int           Transparent;
238         qfile_t *outfile;
239 } my_png;
240
241 //LordHavoc: removed __cdecl prefix, added overrun protection, and rewrote this to be more efficient
242 static void PNG_fReadData(void *png, unsigned char *data, size_t length)
243 {
244         size_t l;
245         l = my_png.tmpBuflength - my_png.tmpi;
246         if (l < length)
247         {
248                 Con_Printf("PNG_fReadData: overrun by %i bytes\n", (int)(length - l));
249                 // a read going past the end of the file, fill in the remaining bytes
250                 // with 0 just to be consistent
251                 memset(data + l, 0, length - l);
252                 length = l;
253         }
254         memcpy(data, my_png.tmpBuf + my_png.tmpi, length);
255         my_png.tmpi += (int)length;
256         //Com_HexDumpToConsole(data, (int)length);
257 }
258
259 static void PNG_fWriteData(void *png, unsigned char *data, size_t length)
260 {
261         FS_Write(my_png.outfile, data, length);
262 }
263
264 static void PNG_fFlushData(void *png)
265 {
266 }
267
268 static void PNG_error_fn(void *png, const char *message)
269 {
270         Con_Printf("PNG_LoadImage: error: %s\n", message);
271 }
272
273 static void PNG_warning_fn(void *png, const char *message)
274 {
275         Con_Printf("PNG_LoadImage: warning: %s\n", message);
276 }
277
278 extern int      image_width;
279 extern int      image_height;
280
281 unsigned char *PNG_LoadImage_BGRA (const unsigned char *raw, int filesize, int *miplevel)
282 {
283         unsigned int c;
284         unsigned int    y;
285         void *png, *pnginfo;
286         unsigned char *imagedata = NULL;
287         unsigned char ioBuffer[8192];
288
289         // FIXME: register an error handler so that abort() won't be called on error
290
291         // No DLL = no PNGs
292         if (!png_dll)
293                 return NULL;
294
295         if(qpng_sig_cmp(raw, 0, filesize))
296                 return NULL;
297         png = (void *)qpng_create_read_struct(
298                 (qpng_access_version_number() / 100 == 102) ? PNG_LIBPNG_VER_STRING_12 :
299                 (qpng_access_version_number() / 100 == 104) ? PNG_LIBPNG_VER_STRING_14 :
300                 PNG_LIBPNG_VER_STRING_15, // nasty hack... whatever
301                 0, PNG_error_fn, PNG_warning_fn
302         );
303         if(!png)
304                 return NULL;
305
306         // this must be memset before the setjmp error handler, because it relies
307         // on the fields in this struct for cleanup
308         memset(&my_png, 0, sizeof(my_png));
309
310         // NOTE: this relies on jmp_buf being the first thing in the png structure
311         // created by libpng! (this is correct for libpng 1.2.x)
312         if (setjmp(qpng_jmpbuf(png)))
313         {
314                 if (my_png.Data)
315                         Mem_Free(my_png.Data);
316                 my_png.Data = NULL;
317                 if (my_png.FRowPtrs)
318                         Mem_Free(my_png.FRowPtrs);
319                 my_png.FRowPtrs = NULL;
320                 qpng_destroy_read_struct(&png, &pnginfo, 0);
321                 return NULL;
322         }
323         //
324
325         pnginfo = qpng_create_info_struct(png);
326         if(!pnginfo)
327         {
328                 qpng_destroy_read_struct(&png, &pnginfo, 0);
329                 return NULL;
330         }
331         qpng_set_sig_bytes(png, 0);
332
333         my_png.tmpBuf = raw;
334         my_png.tmpBuflength = filesize;
335         my_png.tmpi = 0;
336         //my_png.Data           = NULL;
337         //my_png.FRowPtrs       = NULL;
338         //my_png.Height         = 0;
339         //my_png.Width          = 0;
340         my_png.ColorType        = PNG_COLOR_TYPE_RGB;
341         //my_png.Interlace      = 0;
342         //my_png.Compression    = 0;
343         //my_png.Filter         = 0;
344         qpng_set_read_fn(png, ioBuffer, PNG_fReadData);
345         qpng_read_info(png, pnginfo);
346         qpng_get_IHDR(png, pnginfo, &my_png.Width, &my_png.Height,&my_png.BitDepth, &my_png.ColorType, &my_png.Interlace, &my_png.Compression, &my_png.Filter);
347
348         // this check guards against pngconf.h with unsigned int *width/height parameters on big endian systems by detecting the strange values and shifting them down 32bits
349         // (if it's little endian the unwritten bytes are the most significant
350         //  ones and we don't worry about that)
351         //
352         // this is only necessary because of retarded 64bit png_uint_32 types in libpng 1.2, which can (conceivably) vary by platform
353 #if LONG_MAX > 4000000000
354         if (my_png.Width > LONG_MAX || my_png.Height > LONG_MAX)
355         {
356                 my_png.Width >>= 32;
357                 my_png.Height >>= 32;
358         }
359 #endif
360
361         if (my_png.ColorType == PNG_COLOR_TYPE_PALETTE)
362                 qpng_set_palette_to_rgb(png);
363         if (my_png.ColorType == PNG_COLOR_TYPE_GRAY || my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
364                 qpng_set_gray_to_rgb(png);
365         if (qpng_get_valid(png, pnginfo, PNG_INFO_tRNS))
366                 qpng_set_tRNS_to_alpha(png);
367         if (my_png.BitDepth == 8 && !(my_png.ColorType  & PNG_COLOR_MASK_ALPHA))
368                 qpng_set_filler(png, 255, 1);
369         if (( my_png.ColorType == PNG_COLOR_TYPE_GRAY) || (my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA ))
370                 qpng_set_gray_to_rgb(png);
371         if (my_png.BitDepth < 8)
372                 qpng_set_expand(png);
373
374         qpng_read_update_info(png, pnginfo);
375
376         my_png.FRowBytes = qpng_get_rowbytes(png, pnginfo);
377         my_png.BytesPerPixel = qpng_get_channels(png, pnginfo);
378
379         my_png.FRowPtrs = (unsigned char **)Mem_Alloc(tempmempool, my_png.Height * sizeof(*my_png.FRowPtrs));
380         if (my_png.FRowPtrs)
381         {
382                 imagedata = (unsigned char *)Mem_Alloc(tempmempool, my_png.Height * my_png.FRowBytes);
383                 if(imagedata)
384                 {
385                         my_png.Data = imagedata;
386                         for(y = 0;y < my_png.Height;y++)
387                                 my_png.FRowPtrs[y] = my_png.Data + y * my_png.FRowBytes;
388                         qpng_read_image(png, my_png.FRowPtrs);
389                 }
390                 else
391                 {
392                         Con_Printf("PNG_LoadImage : not enough memory\n");
393                         qpng_destroy_read_struct(&png, &pnginfo, 0);
394                         Mem_Free(my_png.FRowPtrs);
395                         return NULL;
396                 }
397                 Mem_Free(my_png.FRowPtrs);
398                 my_png.FRowPtrs = NULL;
399         }
400         else
401         {
402                 Con_Printf("PNG_LoadImage : not enough memory\n");
403                 qpng_destroy_read_struct(&png, &pnginfo, 0);
404                 return NULL;
405         }
406
407         qpng_read_end(png, pnginfo);
408         qpng_destroy_read_struct(&png, &pnginfo, 0);
409
410         image_width = (int)my_png.Width;
411         image_height = (int)my_png.Height;
412
413         if (my_png.BitDepth != 8)
414         {
415                 Con_Printf ("PNG_LoadImage : bad color depth\n");
416                 Mem_Free(imagedata);
417                 return NULL;
418         }
419
420         // swizzle RGBA to BGRA
421         for (y = 0;y < (unsigned int)(image_width*image_height*4);y += 4)
422         {
423                 c = imagedata[y+0];
424                 imagedata[y+0] = imagedata[y+2];
425                 imagedata[y+2] = c;
426         }
427
428         return imagedata;
429 }
430
431 /*
432 =================================================================
433
434         PNG compression
435
436 =================================================================
437 */
438
439 #define Z_BEST_SPEED 1
440 #define Z_BEST_COMPRESSION 9
441 #define PNG_INTERLACE_NONE 0
442 #define PNG_INTERLACE_ADAM7 1
443 #define PNG_FILTER_TYPE_BASE 0
444 #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
445 #define PNG_COMPRESSION_TYPE_BASE 0
446 #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
447 #define PNG_NO_FILTERS     0x00
448 #define PNG_FILTER_NONE    0x08
449 #define PNG_FILTER_SUB     0x10
450 #define PNG_FILTER_UP      0x20
451 #define PNG_FILTER_AVG     0x40
452 #define PNG_FILTER_PAETH   0x80
453 #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
454                          PNG_FILTER_AVG | PNG_FILTER_PAETH)
455
456 /*
457 ====================
458 PNG_SaveImage_preflipped
459
460 Save a preflipped PNG image to a file
461 ====================
462 */
463 qboolean PNG_SaveImage_preflipped (const char *filename, int width, int height, qboolean has_alpha, unsigned char *data)
464 {
465         unsigned int offset, linesize;
466         qfile_t* file = NULL;
467         void *png, *pnginfo;
468         unsigned char ioBuffer[8192];
469         int passes, i, j;
470
471         // No DLL = no JPEGs
472         if (!png_dll)
473         {
474                 Con_Print("You need the libpng library to save PNG images\n");
475                 return false;
476         }
477
478         png = (void *)qpng_create_write_struct( 
479                 (qpng_access_version_number() / 100 == 102) ? PNG_LIBPNG_VER_STRING_12 : PNG_LIBPNG_VER_STRING_14, // nasty hack to support both libpng12 and libpng14
480                 0, PNG_error_fn, PNG_warning_fn
481         );
482         if(!png)
483                 return false;
484         pnginfo = (void *)qpng_create_info_struct(png);
485         if(!pnginfo)
486         {
487                  qpng_destroy_write_struct(&png, NULL);
488                  return false;
489         }
490
491         // this must be memset before the setjmp error handler, because it relies
492         // on the fields in this struct for cleanup
493         memset(&my_png, 0, sizeof(my_png));
494
495         // NOTE: this relies on jmp_buf being the first thing in the png structure
496         // created by libpng! (this is correct for libpng 1.2.x)
497 #ifdef __cplusplus
498 #ifdef WIN64
499         if (setjmp((_JBTYPE *)png))
500 #elif defined(MACOSX) || defined(WIN32)
501         if (setjmp((int *)png))
502 #else
503         if (setjmp((__jmp_buf_tag *)png))
504 #endif
505 #else
506         if (setjmp(png))
507 #endif
508         {
509                 qpng_destroy_write_struct(&png, &pnginfo);
510                 return false;
511         }
512
513         // Open the file
514         file = FS_OpenRealFile(filename, "wb", true);
515         if (!file)
516                 return false;
517         my_png.outfile = file;
518         qpng_set_write_fn(png, ioBuffer, PNG_fWriteData, PNG_fFlushData);
519
520         //qpng_set_compression_level(png, Z_BEST_COMPRESSION);
521         qpng_set_compression_level(png, Z_BEST_SPEED);
522         qpng_set_IHDR(png, pnginfo, width, height, 8, has_alpha ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB, PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
523         qpng_set_filter(png, 0, PNG_NO_FILTERS);
524         qpng_write_info(png, pnginfo);
525         qpng_set_packing(png);
526         qpng_set_bgr(png);
527
528         passes = qpng_set_interlace_handling(png);
529
530         linesize = width * (has_alpha ? 4 : 3);
531         offset = linesize * (height - 1);
532         for(i = 0; i < passes; ++i)
533                 for(j = 0; j < height; ++j)
534                         qpng_write_row(png, &data[offset - j * linesize]);
535
536         qpng_write_end(png, NULL);
537         qpng_destroy_write_struct(&png, &pnginfo);
538
539         FS_Close (file);
540
541         return true;
542 }