1 /*---------------------------------------------------------------------------
3 rpng2 - progressive-model PNG display program readpng2.c
5 ---------------------------------------------------------------------------
8 - 1.01: initial public release
9 - 1.02: added code to skip unused chunks (GR-P)
11 ---------------------------------------------------------------------------
13 Copyright (c) 1998-2002 Greg Roelofs. All rights reserved.
15 This software is provided "as is," without warranty of any kind,
16 express or implied. In no event shall the author or contributors
17 be held liable for any damages arising in any way from the use of
20 Permission is granted to anyone to use this software for any purpose,
21 including commercial applications, and to alter it and redistribute
22 it freely, subject to the following restrictions:
24 1. Redistributions of source code must retain the above copyright
25 notice, disclaimer, and this list of conditions.
26 2. Redistributions in binary form must reproduce the above copyright
27 notice, disclaimer, and this list of conditions in the documenta-
28 tion and/or other materials provided with the distribution.
29 3. All advertising materials mentioning features or use of this
30 software must display the following acknowledgment:
32 This product includes software developed by Greg Roelofs
33 and contributors for the book, "PNG: The Definitive Guide,"
34 published by O'Reilly and Associates.
36 ---------------------------------------------------------------------------*/
39 #include <stdlib.h> /* for exit() prototype */
41 #include "png.h" /* libpng header; includes zlib.h and setjmp.h */
42 #include "readpng2.h" /* typedefs, common macros, public prototypes */
45 /* local prototypes */
47 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr);
48 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
49 png_uint_32 row_num, int pass);
50 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr);
51 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg);
56 void readpng2_version_info(void)
58 #if defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
59 (defined(__i386__) || defined(_M_IX86)) && \
60 defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
62 * WARNING: This preprocessor approach means that the following code
63 * cannot be used with a libpng DLL older than 1.2.0--the
64 * compiled-in symbols for the new functions will not exist.
65 * (Could use dlopen() and dlsym() on Unix and corresponding
66 * calls for Windows, but not portable...)
69 int mmxsupport = png_mmx_support();
71 fprintf(stderr, " Compiled with libpng %s; using libpng %s "
72 "without MMX support.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver);
75 png_uint_32 mmx_mask = png_get_mmx_flagmask(
76 PNG_SELECT_READ | PNG_SELECT_WRITE, &compilerID);
78 fprintf(stderr, " Compiled with libpng %s; using libpng %s "
79 "with MMX support\n (%s version).", PNG_LIBPNG_VER_STRING,
80 png_libpng_ver, compilerID == 1? "MSVC++" :
81 (compilerID == 2? "GNU C" : "unknown"));
82 fprintf(stderr, " Processor %s MMX instructions.\n",
83 mmxsupport? "supports" : "does not support");
88 " Potential MMX optimizations supported by libpng:\n");
89 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_FILTER_SUB)
91 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_FILTER_UP)
93 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_FILTER_AVG)
95 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH)
99 " decoding %s row filters (reading)\n",
100 (num_optims == 4)? "all non-trivial" : "some");
101 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW) {
102 fprintf(stderr, " combining rows (reading)\n");
105 if (mmx_mask & PNG_ASM_FLAG_MMX_READ_INTERLACE) {
107 " expanding interlacing (reading)\n");
110 mmx_mask &= ~( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
111 | PNG_ASM_FLAG_MMX_READ_INTERLACE \
112 | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
113 | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
114 | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
115 | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
117 fprintf(stderr, " other (unknown)\n");
121 fprintf(stderr, " (none)\n");
126 fprintf(stderr, " Compiled with libpng %s; using libpng %s "
127 "without MMX support.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver);
130 fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n",
131 ZLIB_VERSION, zlib_version);
137 int readpng2_check_sig(uch *sig, int num)
139 return png_check_sig(sig, num);
145 /* returns 0 for success, 2 for libpng problem, 4 for out of memory */
147 int readpng2_init(mainprog_info *mainprog_ptr)
149 png_structp png_ptr; /* note: temporary variables! */
153 /* could also replace libpng warning-handler (final NULL), but no need: */
155 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
156 readpng2_error_handler, NULL);
158 return 4; /* out of memory */
160 info_ptr = png_create_info_struct(png_ptr);
162 png_destroy_read_struct(&png_ptr, NULL, NULL);
163 return 4; /* out of memory */
167 /* we could create a second info struct here (end_info), but it's only
168 * useful if we want to keep pre- and post-IDAT chunk info separated
169 * (mainly for PNG-aware image editors and converters) */
172 /* setjmp() must be called in every function that calls a PNG-reading
173 * libpng function, unless an alternate error handler was installed--
174 * but compatible error handlers must either use longjmp() themselves
175 * (as in this program) or exit immediately, so here we are: */
177 if (setjmp(mainprog_ptr->jmpbuf)) {
178 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
182 /* prepare the reader to ignore all recognized chunks whose data isn't
183 * going to be used, i.e., all chunks recognized by libpng except for
184 * IHDR, PLTE, IDAT, IEND, tRNS, bKGD, gAMA, and sRGB : */
186 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
188 #ifndef HANDLE_CHUNK_NEVER
189 /* prior to libpng-1.2.5, this macro was internal, so we define it here. */
190 # define HANDLE_CHUNK_NEVER 1
192 /* these byte strings were copied from png.h.
193 * If a future libpng version recognizes more chunks, add them
194 * to this list. If a future version of readpng2.c recognizes
195 * more chunks, delete them from this list. */
196 png_byte png_chunk_types_to_ignore[]=
197 { 99, 72, 82, 77, '\0', /* cHRM */
198 104, 73, 83, 84, '\0', /* hIST */
199 105, 67, 67, 80, '\0', /* iCCP */
200 105, 84, 88, 116, '\0', /* iTXt */
201 111, 70, 70, 115, '\0', /* oFFs */
202 112, 67, 65, 76, '\0', /* pCAL */
203 115, 67, 65, 76, '\0', /* sCAL */
204 112, 72, 89, 115, '\0', /* pHYs */
205 115, 66, 73, 84, '\0', /* sBIT */
206 115, 80, 76, 84, '\0', /* sPLT */
207 116, 69, 88, 116, '\0', /* tEXt */
208 116, 73, 77, 69, '\0', /* tIME */
209 122, 84, 88, 116, '\0'}; /* zTXt */
210 #define NUM_PNG_CHUNK_TYPES_TO_IGNORE 13
212 png_set_keep_unknown_chunks(png_ptr, HANDLE_CHUNK_NEVER,
213 png_chunk_types_to_ignore, NUM_PNG_CHUNK_TYPES_TO_IGNORE);
217 /* instead of doing png_init_io() here, now we set up our callback
218 * functions for progressive decoding */
220 png_set_progressive_read_fn(png_ptr, mainprog_ptr,
221 readpng2_info_callback, readpng2_row_callback, readpng2_end_callback);
225 * may as well enable or disable MMX routines here, if supported;
227 * to enable all: mask = png_get_mmx_flagmask (
228 * PNG_SELECT_READ | PNG_SELECT_WRITE, &compilerID);
229 * flags = png_get_asm_flags (png_ptr);
231 * png_set_asm_flags (png_ptr, flags);
233 * to disable all: mask = png_get_mmx_flagmask (
234 * PNG_SELECT_READ | PNG_SELECT_WRITE, &compilerID);
235 * flags = png_get_asm_flags (png_ptr);
237 * png_set_asm_flags (png_ptr, flags);
240 #if (defined(__i386__) || defined(_M_IX86)) && \
241 defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200)
243 * WARNING: This preprocessor approach means that the following code
244 * cannot be used with a libpng DLL older than 1.2.0--the
245 * compiled-in symbols for the new functions will not exist.
246 * (Could use dlopen() and dlsym() on Unix and corresponding
247 * calls for Windows, but not portable...)
250 #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
251 png_uint_32 mmx_disable_mask = 0;
252 png_uint_32 asm_flags, mmx_mask;
255 if (mainprog_ptr->nommxfilters)
256 mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
257 | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
258 | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
259 | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
260 if (mainprog_ptr->nommxcombine)
261 mmx_disable_mask |= PNG_ASM_FLAG_MMX_READ_COMBINE_ROW;
262 if (mainprog_ptr->nommxinterlace)
263 mmx_disable_mask |= PNG_ASM_FLAG_MMX_READ_INTERLACE;
264 asm_flags = png_get_asm_flags(png_ptr);
265 png_set_asm_flags(png_ptr, asm_flags & ~mmx_disable_mask);
268 /* Now query libpng's asm settings, just for yuks. Note that this
269 * differs from the querying of its *potential* MMX capabilities
270 * in readpng2_version_info(); this is true runtime verification. */
272 asm_flags = png_get_asm_flags(png_ptr);
273 mmx_mask = png_get_mmx_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE,
275 if (asm_flags & PNG_ASM_FLAG_MMX_SUPPORT_COMPILED)
277 " MMX support (%s version) is compiled into libpng\n",
278 compilerID == 1? "MSVC++" :
279 (compilerID == 2? "GNU C" : "unknown"));
281 fprintf(stderr, " MMX support is not compiled into libpng\n");
282 fprintf(stderr, " MMX instructions are %ssupported by CPU\n",
283 (asm_flags & PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU)? "" : "not ");
284 fprintf(stderr, " MMX read support for combining rows is %sabled\n",
285 (asm_flags & PNG_ASM_FLAG_MMX_READ_COMBINE_ROW)? "en" : "dis");
287 " MMX read support for expanding interlacing is %sabled\n",
288 (asm_flags & PNG_ASM_FLAG_MMX_READ_INTERLACE)? "en" : "dis");
289 fprintf(stderr, " MMX read support for \"sub\" filter is %sabled\n",
290 (asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_SUB)? "en" : "dis");
291 fprintf(stderr, " MMX read support for \"up\" filter is %sabled\n",
292 (asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_UP)? "en" : "dis");
293 fprintf(stderr, " MMX read support for \"avg\" filter is %sabled\n",
294 (asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_AVG)? "en" : "dis");
295 fprintf(stderr, " MMX read support for \"Paeth\" filter is %sabled\n",
296 (asm_flags & PNG_ASM_FLAG_MMX_READ_FILTER_PAETH)? "en" : "dis");
297 asm_flags &= (mmx_mask & ~( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
298 | PNG_ASM_FLAG_MMX_READ_INTERLACE \
299 | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
300 | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
301 | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
302 | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ));
305 " additional MMX support is also enabled (0x%02lx)\n",
307 #else /* !PNG_ASSEMBLER_CODE_SUPPORTED */
308 fprintf(stderr, " MMX querying is disabled in libpng.\n");
309 #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
314 /* make sure we save our pointers for use in readpng2_decode_data() */
316 mainprog_ptr->png_ptr = png_ptr;
317 mainprog_ptr->info_ptr = info_ptr;
320 /* and that's all there is to initialization */
328 /* returns 0 for success, 2 for libpng (longjmp) problem */
330 int readpng2_decode_data(mainprog_info *mainprog_ptr, uch *rawbuf, ulg length)
332 png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
333 png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
336 /* setjmp() must be called in every function that calls a PNG-reading
339 if (setjmp(mainprog_ptr->jmpbuf)) {
340 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
341 mainprog_ptr->png_ptr = NULL;
342 mainprog_ptr->info_ptr = NULL;
347 /* hand off the next chunk of input data to libpng for decoding */
349 png_process_data(png_ptr, info_ptr, rawbuf, length);
357 static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr)
359 mainprog_info *mainprog_ptr;
360 int color_type, bit_depth;
364 /* setjmp() doesn't make sense here, because we'd either have to exit(),
365 * longjmp() ourselves, or return control to libpng, which doesn't want
366 * to see us again. By not doing anything here, libpng will instead jump
367 * to readpng2_decode_data(), which can return an error value to the main
371 /* retrieve the pointer to our special-purpose struct, using the png_ptr
372 * that libpng passed back to us (i.e., not a global this time--there's
373 * no real difference for a single image, but for a multithreaded browser
374 * decoding several PNG images at the same time, one needs to avoid mixing
375 * up different images' structs) */
377 mainprog_ptr = png_get_progressive_ptr(png_ptr);
379 if (mainprog_ptr == NULL) { /* we be hosed */
381 "readpng2 error: main struct not recoverable in info_callback.\n");
385 * Alternatively, we could call our error-handler just like libpng
386 * does, which would effectively terminate the program. Since this
387 * can only happen if png_ptr gets redirected somewhere odd or the
388 * main PNG struct gets wiped, we're probably toast anyway. (If
389 * png_ptr itself is NULL, we would not have been called.)
394 /* this is just like in the non-progressive case */
396 png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width,
397 &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL);
400 /* since we know we've read all of the PNG file's "header" (i.e., up
401 * to IDAT), we can check for a background color here */
403 if (mainprog_ptr->need_bgcolor &&
404 png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD))
406 png_color_16p pBackground;
408 /* it is not obvious from the libpng documentation, but this function
409 * takes a pointer to a pointer, and it always returns valid red,
410 * green and blue values, regardless of color_type: */
411 png_get_bKGD(png_ptr, info_ptr, &pBackground);
413 /* however, it always returns the raw bKGD data, regardless of any
414 * bit-depth transformations, so check depth and adjust if necessary */
415 if (bit_depth == 16) {
416 mainprog_ptr->bg_red = pBackground->red >> 8;
417 mainprog_ptr->bg_green = pBackground->green >> 8;
418 mainprog_ptr->bg_blue = pBackground->blue >> 8;
419 } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
421 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
422 mainprog_ptr->bg_blue = pBackground->gray? 255 : 0;
423 else if (bit_depth == 2)
424 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
425 mainprog_ptr->bg_blue = (255/3) * pBackground->gray;
426 else /* bit_depth == 4 */
427 mainprog_ptr->bg_red = mainprog_ptr->bg_green =
428 mainprog_ptr->bg_blue = (255/15) * pBackground->gray;
430 mainprog_ptr->bg_red = (uch)pBackground->red;
431 mainprog_ptr->bg_green = (uch)pBackground->green;
432 mainprog_ptr->bg_blue = (uch)pBackground->blue;
437 /* as before, let libpng expand palette images to RGB, low-bit-depth
438 * grayscale images to 8 bits, transparency chunks to full alpha channel;
439 * strip 16-bit-per-sample images to 8 bits per sample; and convert
440 * grayscale to RGB[A] */
442 if (color_type == PNG_COLOR_TYPE_PALETTE)
443 png_set_expand(png_ptr);
444 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
445 png_set_expand(png_ptr);
446 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
447 png_set_expand(png_ptr);
449 png_set_strip_16(png_ptr);
450 if (color_type == PNG_COLOR_TYPE_GRAY ||
451 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
452 png_set_gray_to_rgb(png_ptr);
455 /* Unlike the basic viewer, which was designed to operate on local files,
456 * this program is intended to simulate a web browser--even though we
457 * actually read from a local file, too. But because we are pretending
458 * that most of the images originate on the Internet, we follow the recom-
459 * mendation of the sRGB proposal and treat unlabelled images (no gAMA
460 * chunk) as existing in the sRGB color space. That is, we assume that
461 * such images have a file gamma of 0.45455, which corresponds to a PC-like
462 * display system. This change in assumptions will have no effect on a
463 * PC-like system, but on a Mac, SGI, NeXT or other system with a non-
464 * identity lookup table, it will darken unlabelled images, which effec-
465 * tively favors images from PC-like systems over those originating on
466 * the local platform. Note that mainprog_ptr->display_exponent is the
467 * "gamma" value for the entire display system, i.e., the product of
468 * LUT_exponent and CRT_exponent. */
470 if (png_get_gAMA(png_ptr, info_ptr, &gamma))
471 png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma);
473 png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455);
476 /* we'll let libpng expand interlaced images, too */
478 mainprog_ptr->passes = png_set_interlace_handling(png_ptr);
481 /* all transformations have been registered; now update info_ptr data and
482 * then get rowbytes and channels */
484 png_read_update_info(png_ptr, info_ptr);
486 mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr);
487 mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr);
490 /* Call the main program to allocate memory for the image buffer and
491 * initialize windows and whatnot. (The old-style function-pointer
492 * invocation is used for compatibility with a few supposedly ANSI
493 * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */
495 (*mainprog_ptr->mainprog_init)();
498 /* and that takes care of initialization */
507 static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row,
508 png_uint_32 row_num, int pass)
510 mainprog_info *mainprog_ptr;
513 /* first check whether the row differs from the previous pass; if not,
514 * nothing to combine or display */
520 /* retrieve the pointer to our special-purpose struct so we can access
521 * the old rows and image-display callback function */
523 mainprog_ptr = png_get_progressive_ptr(png_ptr);
526 /* save the pass number for optional use by the front end */
528 mainprog_ptr->pass = pass;
531 /* have libpng either combine the new row data with the existing row data
532 * from previous passes (if interlaced) or else just copy the new row
533 * into the main program's image buffer */
535 png_progressive_combine_row(png_ptr, mainprog_ptr->row_pointers[row_num],
539 /* finally, call the display routine in the main program with the number
540 * of the row we just updated */
542 (*mainprog_ptr->mainprog_display_row)(row_num);
545 /* and we're ready for more */
554 static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
556 mainprog_info *mainprog_ptr;
559 /* retrieve the pointer to our special-purpose struct */
561 mainprog_ptr = png_get_progressive_ptr(png_ptr);
564 /* let the main program know that it should flush any buffered image
565 * data to the display now and set a "done" flag or whatever, but note
566 * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
567 * NOT call readpng2_cleanup() either here or in the finish_display()
568 * routine; wait until control returns to the main program via
569 * readpng2_decode_data() */
571 (*mainprog_ptr->mainprog_finish_display)();
583 void readpng2_cleanup(mainprog_info *mainprog_ptr)
585 png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
586 png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
588 if (png_ptr && info_ptr)
589 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
591 mainprog_ptr->png_ptr = NULL;
592 mainprog_ptr->info_ptr = NULL;
599 static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg)
601 mainprog_info *mainprog_ptr;
603 /* This function, aside from the extra step of retrieving the "error
604 * pointer" (below) and the fact that it exists within the application
605 * rather than within libpng, is essentially identical to libpng's
606 * default error handler. The second point is critical: since both
607 * setjmp() and longjmp() are called from the same code, they are
608 * guaranteed to have compatible notions of how big a jmp_buf is,
609 * regardless of whether _BSD_SOURCE or anything else has (or has not)
612 fprintf(stderr, "readpng2 libpng error: %s\n", msg);
615 mainprog_ptr = png_get_error_ptr(png_ptr);
616 if (mainprog_ptr == NULL) { /* we are completely hosed now */
618 "readpng2 severe error: jmpbuf not recoverable; terminating.\n");
623 longjmp(mainprog_ptr->jmpbuf, 1);