]> git.jsancho.org Git - lugaru.git/blob - Dependencies/libpng/contrib/gregbook/readpng2.c
CMake: Purge all the bundled dependencies
[lugaru.git] / Dependencies / libpng / contrib / gregbook / readpng2.c
1 /*---------------------------------------------------------------------------
2
3    rpng2 - progressive-model PNG display program                 readpng2.c
4
5   ---------------------------------------------------------------------------
6
7       Copyright (c) 1998-2007 Greg Roelofs.  All rights reserved.
8
9       This software is provided "as is," without warranty of any kind,
10       express or implied.  In no event shall the author or contributors
11       be held liable for any damages arising in any way from the use of
12       this software.
13
14       The contents of this file are DUAL-LICENSED.  You may modify and/or
15       redistribute this software according to the terms of one of the
16       following two licenses (at your option):
17
18
19       LICENSE 1 ("BSD-like with advertising clause"):
20
21       Permission is granted to anyone to use this software for any purpose,
22       including commercial applications, and to alter it and redistribute
23       it freely, subject to the following restrictions:
24
25       1. Redistributions of source code must retain the above copyright
26          notice, disclaimer, and this list of conditions.
27       2. Redistributions in binary form must reproduce the above copyright
28          notice, disclaimer, and this list of conditions in the documenta-
29          tion and/or other materials provided with the distribution.
30       3. All advertising materials mentioning features or use of this
31          software must display the following acknowledgment:
32
33             This product includes software developed by Greg Roelofs
34             and contributors for the book, "PNG: The Definitive Guide,"
35             published by O'Reilly and Associates.
36
37
38       LICENSE 2 (GNU GPL v2 or later):
39
40       This program is free software; you can redistribute it and/or modify
41       it under the terms of the GNU General Public License as published by
42       the Free Software Foundation; either version 2 of the License, or
43       (at your option) any later version.
44
45       This program is distributed in the hope that it will be useful,
46       but WITHOUT ANY WARRANTY; without even the implied warranty of
47       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
48       GNU General Public License for more details.
49
50       You should have received a copy of the GNU General Public License
51       along with this program; if not, write to the Free Software Foundation,
52       Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
53
54   ---------------------------------------------------------------------------*/
55
56
57 #include <stdlib.h>     /* for exit() prototype */
58
59 #include "png.h"        /* libpng header; includes zlib.h and setjmp.h */
60 #include "readpng2.h"   /* typedefs, common macros, public prototypes */
61
62
63 /* local prototypes */
64
65 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr);
66 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
67                                  png_uint_32 row_num, int pass);
68 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr);
69 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg);
70
71
72
73
74 void readpng2_version_info(void)
75 {
76     fprintf(stderr, "   Compiled with libpng %s; using libpng %s\n",
77       PNG_LIBPNG_VER_STRING, png_libpng_ver);
78
79     fprintf(stderr, "   and with zlib %s; using zlib %s.\n",
80       ZLIB_VERSION, zlib_version);
81 }
82
83
84
85
86 int readpng2_check_sig(uch *sig, int num)
87 {
88     return !png_sig_cmp(sig, 0, num);
89 }
90
91
92
93
94 /* returns 0 for success, 2 for libpng problem, 4 for out of memory */
95
96 int readpng2_init(mainprog_info *mainprog_ptr)
97 {
98     png_structp  png_ptr;       /* note:  temporary variables! */
99     png_infop  info_ptr;
100
101
102     /* could also replace libpng warning-handler (final NULL), but no need: */
103
104     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
105       readpng2_error_handler, NULL);
106     if (!png_ptr)
107         return 4;   /* out of memory */
108
109     info_ptr = png_create_info_struct(png_ptr);
110     if (!info_ptr) {
111         png_destroy_read_struct(&png_ptr, NULL, NULL);
112         return 4;   /* out of memory */
113     }
114
115
116     /* we could create a second info struct here (end_info), but it's only
117      * useful if we want to keep pre- and post-IDAT chunk info separated
118      * (mainly for PNG-aware image editors and converters) */
119
120
121     /* setjmp() must be called in every function that calls a PNG-reading
122      * libpng function, unless an alternate error handler was installed--
123      * but compatible error handlers must either use longjmp() themselves
124      * (as in this program) or exit immediately, so here we are: */
125
126     if (setjmp(mainprog_ptr->jmpbuf)) {
127         png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
128         return 2;
129     }
130
131
132 #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
133     /* prepare the reader to ignore all recognized chunks whose data won't be
134      * used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT,
135      * IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */
136     {
137         /* These byte strings were copied from png.h.  If a future libpng
138          * version recognizes more chunks, add them to this list.  If a
139          * future version of readpng2.c recognizes more chunks, delete them
140          * from this list. */
141         static const png_byte chunks_to_ignore[] = {
142              99,  72,  82,  77, '\0',  /* cHRM */
143             104,  73,  83,  84, '\0',  /* hIST */
144             105,  67,  67,  80, '\0',  /* iCCP */
145             105,  84,  88, 116, '\0',  /* iTXt */
146             111,  70,  70, 115, '\0',  /* oFFs */
147             112,  67,  65,  76, '\0',  /* pCAL */
148             112,  72,  89, 115, '\0',  /* pHYs */
149             115,  66,  73,  84, '\0',  /* sBIT */
150             115,  67,  65,  76, '\0',  /* sCAL */
151             115,  80,  76,  84, '\0',  /* sPLT */
152             115,  84,  69,  82, '\0',  /* sTER */
153             116,  69,  88, 116, '\0',  /* tEXt */
154             116,  73,  77,  69, '\0',  /* tIME */
155             122,  84,  88, 116, '\0'   /* zTXt */
156         };
157
158         png_set_keep_unknown_chunks(png_ptr, 1 /* PNG_HANDLE_CHUNK_NEVER */,
159           chunks_to_ignore, sizeof(chunks_to_ignore)/5);
160     }
161 #endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */
162
163
164     /* instead of doing png_init_io() here, now we set up our callback
165      * functions for progressive decoding */
166
167     png_set_progressive_read_fn(png_ptr, mainprog_ptr,
168       readpng2_info_callback, readpng2_row_callback, readpng2_end_callback);
169
170
171     /* make sure we save our pointers for use in readpng2_decode_data() */
172
173     mainprog_ptr->png_ptr = png_ptr;
174     mainprog_ptr->info_ptr = info_ptr;
175
176
177     /* and that's all there is to initialization */
178
179     return 0;
180 }
181
182
183
184
185 /* returns 0 for success, 2 for libpng (longjmp) problem */
186
187 int readpng2_decode_data(mainprog_info *mainprog_ptr, uch *rawbuf, ulg length)
188 {
189     png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
190     png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
191
192
193     /* setjmp() must be called in every function that calls a PNG-reading
194      * libpng function */
195
196     if (setjmp(mainprog_ptr->jmpbuf)) {
197         png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
198         mainprog_ptr->png_ptr = NULL;
199         mainprog_ptr->info_ptr = NULL;
200         return 2;
201     }
202
203
204     /* hand off the next chunk of input data to libpng for decoding */
205
206     png_process_data(png_ptr, info_ptr, rawbuf, length);
207
208     return 0;
209 }
210
211
212
213
214 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr)
215 {
216     mainprog_info  *mainprog_ptr;
217     int  color_type, bit_depth;
218     png_uint_32 width, height;
219     double  gamma;
220
221
222     /* setjmp() doesn't make sense here, because we'd either have to exit(),
223      * longjmp() ourselves, or return control to libpng, which doesn't want
224      * to see us again.  By not doing anything here, libpng will instead jump
225      * to readpng2_decode_data(), which can return an error value to the main
226      * program. */
227
228
229     /* retrieve the pointer to our special-purpose struct, using the png_ptr
230      * that libpng passed back to us (i.e., not a global this time--there's
231      * no real difference for a single image, but for a multithreaded browser
232      * decoding several PNG images at the same time, one needs to avoid mixing
233      * up different images' structs) */
234
235     mainprog_ptr = png_get_progressive_ptr(png_ptr);
236
237     if (mainprog_ptr == NULL) {         /* we be hosed */
238         fprintf(stderr,
239           "readpng2 error:  main struct not recoverable in info_callback.\n");
240         fflush(stderr);
241         return;
242         /*
243          * Alternatively, we could call our error-handler just like libpng
244          * does, which would effectively terminate the program.  Since this
245          * can only happen if png_ptr gets redirected somewhere odd or the
246          * main PNG struct gets wiped, we're probably toast anyway.  (If
247          * png_ptr itself is NULL, we would not have been called.)
248          */
249     }
250
251
252     /* this is just like in the non-progressive case */
253
254     png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
255        NULL, NULL, NULL);
256     mainprog_ptr->width = (ulg)width;
257     mainprog_ptr->height = (ulg)height;
258
259
260     /* since we know we've read all of the PNG file's "header" (i.e., up
261      * to IDAT), we can check for a background color here */
262
263     if (mainprog_ptr->need_bgcolor &&
264         png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD))
265     {
266         png_color_16p pBackground;
267
268         /* it is not obvious from the libpng documentation, but this function
269          * takes a pointer to a pointer, and it always returns valid red,
270          * green and blue values, regardless of color_type: */
271         png_get_bKGD(png_ptr, info_ptr, &pBackground);
272
273         /* however, it always returns the raw bKGD data, regardless of any
274          * bit-depth transformations, so check depth and adjust if necessary */
275         if (bit_depth == 16) {
276             mainprog_ptr->bg_red   = pBackground->red   >> 8;
277             mainprog_ptr->bg_green = pBackground->green >> 8;
278             mainprog_ptr->bg_blue  = pBackground->blue  >> 8;
279         } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
280             if (bit_depth == 1)
281                 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
282                   mainprog_ptr->bg_blue = pBackground->gray? 255 : 0;
283             else if (bit_depth == 2)
284                 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
285                   mainprog_ptr->bg_blue = (255/3) * pBackground->gray;
286             else /* bit_depth == 4 */
287                 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
288                   mainprog_ptr->bg_blue = (255/15) * pBackground->gray;
289         } else {
290             mainprog_ptr->bg_red   = (uch)pBackground->red;
291             mainprog_ptr->bg_green = (uch)pBackground->green;
292             mainprog_ptr->bg_blue  = (uch)pBackground->blue;
293         }
294     }
295
296
297     /* as before, let libpng expand palette images to RGB, low-bit-depth
298      * grayscale images to 8 bits, transparency chunks to full alpha channel;
299      * strip 16-bit-per-sample images to 8 bits per sample; and convert
300      * grayscale to RGB[A] */
301
302     if (color_type == PNG_COLOR_TYPE_PALETTE)
303         png_set_expand(png_ptr);
304     if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
305         png_set_expand(png_ptr);
306     if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
307         png_set_expand(png_ptr);
308     if (bit_depth == 16)
309         png_set_strip_16(png_ptr);
310     if (color_type == PNG_COLOR_TYPE_GRAY ||
311         color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
312         png_set_gray_to_rgb(png_ptr);
313
314
315     /* Unlike the basic viewer, which was designed to operate on local files,
316      * this program is intended to simulate a web browser--even though we
317      * actually read from a local file, too.  But because we are pretending
318      * that most of the images originate on the Internet, we follow the recom-
319      * mendation of the sRGB proposal and treat unlabelled images (no gAMA
320      * chunk) as existing in the sRGB color space.  That is, we assume that
321      * such images have a file gamma of 0.45455, which corresponds to a PC-like
322      * display system.  This change in assumptions will have no effect on a
323      * PC-like system, but on a Mac, SGI, NeXT or other system with a non-
324      * identity lookup table, it will darken unlabelled images, which effec-
325      * tively favors images from PC-like systems over those originating on
326      * the local platform.  Note that mainprog_ptr->display_exponent is the
327      * "gamma" value for the entire display system, i.e., the product of
328      * LUT_exponent and CRT_exponent. */
329
330     if (png_get_gAMA(png_ptr, info_ptr, &gamma))
331         png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma);
332     else
333         png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455);
334
335
336     /* we'll let libpng expand interlaced images, too */
337
338     mainprog_ptr->passes = png_set_interlace_handling(png_ptr);
339
340
341     /* all transformations have been registered; now update info_ptr data and
342      * then get rowbytes and channels */
343
344     png_read_update_info(png_ptr, info_ptr);
345
346     mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr);
347     mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr);
348
349
350     /* Call the main program to allocate memory for the image buffer and
351      * initialize windows and whatnot.  (The old-style function-pointer
352      * invocation is used for compatibility with a few supposedly ANSI
353      * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */
354
355     (*mainprog_ptr->mainprog_init)();
356
357
358     /* and that takes care of initialization */
359
360     return;
361 }
362
363
364
365
366
367 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
368                                   png_uint_32 row_num, int pass)
369 {
370     mainprog_info  *mainprog_ptr;
371
372
373     /* first check whether the row differs from the previous pass; if not,
374      * nothing to combine or display */
375
376     if (!new_row)
377         return;
378
379
380     /* retrieve the pointer to our special-purpose struct so we can access
381      * the old rows and image-display callback function */
382
383     mainprog_ptr = png_get_progressive_ptr(png_ptr);
384
385
386     /* save the pass number for optional use by the front end */
387
388     mainprog_ptr->pass = pass;
389
390
391     /* have libpng either combine the new row data with the existing row data
392      * from previous passes (if interlaced) or else just copy the new row
393      * into the main program's image buffer */
394
395     png_progressive_combine_row(png_ptr, mainprog_ptr->row_pointers[row_num],
396       new_row);
397
398
399     /* finally, call the display routine in the main program with the number
400      * of the row we just updated */
401
402     (*mainprog_ptr->mainprog_display_row)(row_num);
403
404
405     /* and we're ready for more */
406
407     return;
408 }
409
410
411
412
413
414 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
415 {
416     mainprog_info  *mainprog_ptr;
417
418
419     /* retrieve the pointer to our special-purpose struct */
420
421     mainprog_ptr = png_get_progressive_ptr(png_ptr);
422
423
424     /* let the main program know that it should flush any buffered image
425      * data to the display now and set a "done" flag or whatever, but note
426      * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
427      * NOT call readpng2_cleanup() either here or in the finish_display()
428      * routine; wait until control returns to the main program via
429      * readpng2_decode_data() */
430
431     (*mainprog_ptr->mainprog_finish_display)();
432
433
434     /* all done */
435
436     return;
437 }
438
439
440
441
442
443 void readpng2_cleanup(mainprog_info *mainprog_ptr)
444 {
445     png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
446     png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
447
448     if (png_ptr && info_ptr)
449         png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
450
451     mainprog_ptr->png_ptr = NULL;
452     mainprog_ptr->info_ptr = NULL;
453 }
454
455
456
457
458
459 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg)
460 {
461     mainprog_info  *mainprog_ptr;
462
463     /* This function, aside from the extra step of retrieving the "error
464      * pointer" (below) and the fact that it exists within the application
465      * rather than within libpng, is essentially identical to libpng's
466      * default error handler.  The second point is critical:  since both
467      * setjmp() and longjmp() are called from the same code, they are
468      * guaranteed to have compatible notions of how big a jmp_buf is,
469      * regardless of whether _BSD_SOURCE or anything else has (or has not)
470      * been defined. */
471
472     fprintf(stderr, "readpng2 libpng error: %s\n", msg);
473     fflush(stderr);
474
475     mainprog_ptr = png_get_error_ptr(png_ptr);
476     if (mainprog_ptr == NULL) {         /* we are completely hosed now */
477         fprintf(stderr,
478           "readpng2 severe error:  jmpbuf not recoverable; terminating.\n");
479         fflush(stderr);
480         exit(99);
481     }
482
483     longjmp(mainprog_ptr->jmpbuf, 1);
484 }