readpng2.c 18 KB

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