readpng2.c 17 KB

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