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