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