1 /*---------------------------------------------------------------------------
3 rpng2 - progressive-model PNG display program readpng2.c
5 ---------------------------------------------------------------------------
7 Copyright (c) 1998-2007 Greg Roelofs. All rights reserved.
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
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):
19 LICENSE 1 ("BSD-like with advertising clause"):
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:
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:
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.
38 LICENSE 2 (GNU GPL v2 or later):
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.
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.
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
54 ---------------------------------------------------------------------------*/
57 #include <stdlib.h> /* for exit() prototype */
61 #include "png.h" /* libpng header from the local directory */
62 #include "readpng2.h" /* typedefs, common macros, public prototypes */
65 /* local prototypes */
67 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr);
68 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
69 png_uint_32 row_num, int pass);
70 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr);
71 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg);
72 static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg);
77 void readpng2_version_info(void)
79 fprintf(stderr, " Compiled with libpng %s; using libpng %s\n",
80 PNG_LIBPNG_VER_STRING, png_libpng_ver);
82 fprintf(stderr, " and with zlib %s; using zlib %s.\n",
83 ZLIB_VERSION, zlib_version);
89 int readpng2_check_sig(uch *sig, int num)
91 return !png_sig_cmp(sig, 0, num);
97 /* returns 0 for success, 2 for libpng problem, 4 for out of memory */
99 int readpng2_init(mainprog_info *mainprog_ptr)
101 png_structp png_ptr; /* note: temporary variables! */
105 /* could also replace libpng warning-handler (final NULL), but no need: */
107 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
108 readpng2_error_handler, readpng2_warning_handler);
110 return 4; /* out of memory */
112 info_ptr = png_create_info_struct(png_ptr);
114 png_destroy_read_struct(&png_ptr, NULL, NULL);
115 return 4; /* out of memory */
119 /* we could create a second info struct here (end_info), but it's only
120 * useful if we want to keep pre- and post-IDAT chunk info separated
121 * (mainly for PNG-aware image editors and converters) */
124 /* setjmp() must be called in every function that calls a PNG-reading
125 * libpng function, unless an alternate error handler was installed--
126 * but compatible error handlers must either use longjmp() themselves
127 * (as in this program) or exit immediately, so here we are: */
129 if (setjmp(mainprog_ptr->jmpbuf)) {
130 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
135 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
136 /* prepare the reader to ignore all recognized chunks whose data won't be
137 * used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT,
138 * IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */
140 /* These byte strings were copied from png.h. If a future version
141 * of readpng2.c recognizes more chunks, add them to this list.
143 static PNG_CONST png_byte chunks_to_process[] = {
144 98, 75, 71, 68, '\0', /* bKGD */
145 103, 65, 77, 65, '\0', /* gAMA */
146 115, 82, 71, 66, '\0', /* sRGB */
149 /* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */
150 png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */,
153 /* But do not ignore chunks in the "chunks_to_process" list */
154 png_set_keep_unknown_chunks(png_ptr,
155 0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process,
156 sizeof(chunks_to_process)/5);
158 #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */
161 /* instead of doing png_init_io() here, now we set up our callback
162 * functions for progressive decoding */
164 png_set_progressive_read_fn(png_ptr, mainprog_ptr,
165 readpng2_info_callback, readpng2_row_callback, readpng2_end_callback);
168 /* make sure we save our pointers for use in readpng2_decode_data() */
170 mainprog_ptr->png_ptr = png_ptr;
171 mainprog_ptr->info_ptr = info_ptr;
174 /* and that's all there is to initialization */
182 /* returns 0 for success, 2 for libpng (longjmp) problem */
184 int readpng2_decode_data(mainprog_info *mainprog_ptr, uch *rawbuf, ulg length)
186 png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
187 png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
190 /* setjmp() must be called in every function that calls a PNG-reading
193 if (setjmp(mainprog_ptr->jmpbuf)) {
194 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
195 mainprog_ptr->png_ptr = NULL;
196 mainprog_ptr->info_ptr = NULL;
201 /* hand off the next chunk of input data to libpng for decoding */
203 png_process_data(png_ptr, info_ptr, rawbuf, length);
211 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr)
213 mainprog_info *mainprog_ptr;
214 int color_type, bit_depth;
215 png_uint_32 width, height;
216 #ifdef PNG_FLOATING_POINT_SUPPORTED
219 png_fixed_point gamma;
223 /* setjmp() doesn't make sense here, because we'd either have to exit(),
224 * longjmp() ourselves, or return control to libpng, which doesn't want
225 * to see us again. By not doing anything here, libpng will instead jump
226 * to readpng2_decode_data(), which can return an error value to the main
230 /* retrieve the pointer to our special-purpose struct, using the png_ptr
231 * that libpng passed back to us (i.e., not a global this time--there's
232 * no real difference for a single image, but for a multithreaded browser
233 * decoding several PNG images at the same time, one needs to avoid mixing
234 * up different images' structs) */
236 mainprog_ptr = png_get_progressive_ptr(png_ptr);
238 if (mainprog_ptr == NULL) { /* we be hosed */
240 "readpng2 error: main struct not recoverable in info_callback.\n");
244 * Alternatively, we could call our error-handler just like libpng
245 * does, which would effectively terminate the program. Since this
246 * can only happen if png_ptr gets redirected somewhere odd or the
247 * main PNG struct gets wiped, we're probably toast anyway. (If
248 * png_ptr itself is NULL, we would not have been called.)
253 /* this is just like in the non-progressive case */
255 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
257 mainprog_ptr->width = (ulg)width;
258 mainprog_ptr->height = (ulg)height;
261 /* since we know we've read all of the PNG file's "header" (i.e., up
262 * to IDAT), we can check for a background color here */
264 if (mainprog_ptr->need_bgcolor &&
265 png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD))
267 png_color_16p pBackground;
269 /* it is not obvious from the libpng documentation, but this function
270 * takes a pointer to a pointer, and it always returns valid red,
271 * green and blue values, regardless of color_type: */
272 png_get_bKGD(png_ptr, info_ptr, &pBackground);
274 /* however, it always returns the raw bKGD data, regardless of any
275 * bit-depth transformations, so check depth and adjust if necessary */
276 if (bit_depth == 16) {
277 mainprog_ptr->bg_red = pBackground->red >> 8;
278 mainprog_ptr->bg_green = pBackground->green >> 8;
279 mainprog_ptr->bg_blue = pBackground->blue >> 8;
280 } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
282 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
283 mainprog_ptr->bg_blue = pBackground->gray? 255 : 0;
284 else if (bit_depth == 2)
285 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
286 mainprog_ptr->bg_blue = (255/3) * pBackground->gray;
287 else /* bit_depth == 4 */
288 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
289 mainprog_ptr->bg_blue = (255/15) * pBackground->gray;
291 mainprog_ptr->bg_red = (uch)pBackground->red;
292 mainprog_ptr->bg_green = (uch)pBackground->green;
293 mainprog_ptr->bg_blue = (uch)pBackground->blue;
298 /* as before, let libpng expand palette images to RGB, low-bit-depth
299 * grayscale images to 8 bits, transparency chunks to full alpha channel;
300 * strip 16-bit-per-sample images to 8 bits per sample; and convert
301 * grayscale to RGB[A] */
303 if (color_type == PNG_COLOR_TYPE_PALETTE)
304 png_set_expand(png_ptr);
305 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
306 png_set_expand(png_ptr);
307 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
308 png_set_expand(png_ptr);
309 #ifdef PNG_READ_16_TO_8_SUPPORTED
311 # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
312 png_set_scale_16(png_ptr);
314 png_set_strip_16(png_ptr);
317 if (color_type == PNG_COLOR_TYPE_GRAY ||
318 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
319 png_set_gray_to_rgb(png_ptr);
322 /* Unlike the basic viewer, which was designed to operate on local files,
323 * this program is intended to simulate a web browser--even though we
324 * actually read from a local file, too. But because we are pretending
325 * that most of the images originate on the Internet, we follow the recom-
326 * mendation of the sRGB proposal and treat unlabelled images (no gAMA
327 * chunk) as existing in the sRGB color space. That is, we assume that
328 * such images have a file gamma of 0.45455, which corresponds to a PC-like
329 * display system. This change in assumptions will have no effect on a
330 * PC-like system, but on a Mac, SGI, NeXT or other system with a non-
331 * identity lookup table, it will darken unlabelled images, which effec-
332 * tively favors images from PC-like systems over those originating on
333 * the local platform. Note that mainprog_ptr->display_exponent is the
334 * "gamma" value for the entire display system, i.e., the product of
335 * LUT_exponent and CRT_exponent. */
337 #ifdef PNG_FLOATING_POINT_SUPPORTED
338 if (png_get_gAMA(png_ptr, info_ptr, &gamma))
339 png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma);
341 png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455);
343 if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma))
344 png_set_gamma_fixed(png_ptr,
345 (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma);
347 png_set_gamma_fixed(png_ptr,
348 (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455);
351 /* we'll let libpng expand interlaced images, too */
353 mainprog_ptr->passes = png_set_interlace_handling(png_ptr);
356 /* all transformations have been registered; now update info_ptr data and
357 * then get rowbytes and channels */
359 png_read_update_info(png_ptr, info_ptr);
361 mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr);
362 mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr);
365 /* Call the main program to allocate memory for the image buffer and
366 * initialize windows and whatnot. (The old-style function-pointer
367 * invocation is used for compatibility with a few supposedly ANSI
368 * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */
370 (*mainprog_ptr->mainprog_init)();
373 /* and that takes care of initialization */
382 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
383 png_uint_32 row_num, int pass)
385 mainprog_info *mainprog_ptr;
388 /* first check whether the row differs from the previous pass; if not,
389 * nothing to combine or display */
395 /* retrieve the pointer to our special-purpose struct so we can access
396 * the old rows and image-display callback function */
398 mainprog_ptr = png_get_progressive_ptr(png_ptr);
401 /* save the pass number for optional use by the front end */
403 mainprog_ptr->pass = pass;
406 /* have libpng either combine the new row data with the existing row data
407 * from previous passes (if interlaced) or else just copy the new row
408 * into the main program's image buffer */
410 png_progressive_combine_row(png_ptr, mainprog_ptr->row_pointers[row_num],
414 /* finally, call the display routine in the main program with the number
415 * of the row we just updated */
417 (*mainprog_ptr->mainprog_display_row)(row_num);
420 /* and we're ready for more */
429 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
431 mainprog_info *mainprog_ptr;
434 /* retrieve the pointer to our special-purpose struct */
436 mainprog_ptr = png_get_progressive_ptr(png_ptr);
439 /* let the main program know that it should flush any buffered image
440 * data to the display now and set a "done" flag or whatever, but note
441 * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
442 * NOT call readpng2_cleanup() either here or in the finish_display()
443 * routine; wait until control returns to the main program via
444 * readpng2_decode_data() */
446 (*mainprog_ptr->mainprog_finish_display)();
451 (void)info_ptr; /* Unused */
460 void readpng2_cleanup(mainprog_info *mainprog_ptr)
462 png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
463 png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
465 if (png_ptr && info_ptr)
466 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
468 mainprog_ptr->png_ptr = NULL;
469 mainprog_ptr->info_ptr = NULL;
473 static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
475 fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
477 (void)png_ptr; /* Unused */
481 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg)
483 mainprog_info *mainprog_ptr;
485 /* This function, aside from the extra step of retrieving the "error
486 * pointer" (below) and the fact that it exists within the application
487 * rather than within libpng, is essentially identical to libpng's
488 * default error handler. The second point is critical: since both
489 * setjmp() and longjmp() are called from the same code, they are
490 * guaranteed to have compatible notions of how big a jmp_buf is,
491 * regardless of whether _BSD_SOURCE or anything else has (or has not)
494 fprintf(stderr, "readpng2 libpng error: %s\n", msg);
497 mainprog_ptr = png_get_error_ptr(png_ptr);
498 if (mainprog_ptr == NULL) { /* we are completely hosed now */
500 "readpng2 severe error: jmpbuf not recoverable; terminating.\n");
505 /* Now we have our data structure we can use the information in it
506 * to return control to our own higher level code (all the points
507 * where 'setjmp' is called in this file.) This will work with other
508 * error handling mechanisms as well - libpng always calls png_error
509 * when it can proceed no further, thus, so long as the error handler
510 * is intercepted, application code can do its own error recovery.
512 longjmp(mainprog_ptr->jmpbuf, 1);