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