Debian Codegraph @

pngcrush.c

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1
2 /* pngcrush.c - recompresses png files
3 * Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson
4 * (glennrp at users.sf.net)
5 * Portions Copyright (C) 2005 Greg Roelofs
6 */
7
8 #define PNGCRUSH_VERSION "1.8.13"
9
10 #undef BLOCKY_DEINTERLACE
11
12 /* This software is released under a license derived from the libpng
13 * license (see LICENSE, below).
14 *
15 * The most recent version of pngcrush can be found at SourceForge in
16 * http://pmt.sf.net/pngcrush/
17 *
18 * This program reads in a PNG image, and writes it out again, with the
19 * optimum filter_method and zlib_level. It uses brute force (trying
20 * filter_method none, and libpng adaptive filtering, with compression
21 * levels 3 and 9).
22 *
23 * Optionally, it can remove unwanted chunks or add gAMA, sRGB, bKGD,
24 * tEXt/zTXt, and tRNS chunks. It will remove some chunks such as gAMA,
25 * cHRM, pHYs, and oFFs when their data fields contain all zero, which is a
26 * mistake.
27 *
28 * Uses libpng and zlib. This program was based upon libpng's pngtest.c.
29 *
30 * NOTICES:
31 *
32 * If you have modified this source, you may insert additional notices
33 * immediately after this sentence.
34 *
35 * COPYRIGHT:
36 *
37 * Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson
38 * (glennrp at users.sf.net)
39 * Portions Copyright (C) 2005 Greg Roelofs
40 *
41 * LICENSE:
42 *
43 * Permission is hereby irrevocably granted to everyone to use, copy, modify,
44 * and distribute this source code, or portions hereof, or executable programs
45 * compiled from it, for any purpose, without payment of any fee, subject to
46 * the following restrictions:
47 *
48 * 1. The origin of this source code must not be misrepresented.
49 *
50 * 2. Altered versions must be plainly marked as such and must not be
51 * misrepresented as being the original source.
52 *
53 * 3. This Copyright notice, disclaimers, and license may not be removed
54 * or altered from any source or altered source distribution.
55 *
56 * DISCLAIMERS:
57 *
58 * The pngcrush computer program is supplied "AS IS". The Author disclaims all
59 * warranties, expressed or implied, including, without limitation, the
60 * warranties of merchantability and of fitness for any purpose. The
61 * Author assumes no liability for direct, indirect, incidental, special,
62 * exemplary, or consequential damages, which may result from the use of
63 * the computer program, even if advised of the possibility of such damage.
64 * There is no warranty against interference with your enjoyment of the
65 * computer program or against infringement. There is no warranty that my
66 * efforts or the computer program will fulfill any of your particular purposes
67 * or needs. This computer program is provided with all faults, and the entire
68 * risk of satisfactory quality, performance, accuracy, and effort is with
69 * the user.
70 *
71 * EXPORT CONTROL
72 *
73 * I am not a lawyer, but I believe that the Export Control Classification
74 * Number (ECCN) for pngcrush is EAR99, which means not subject to export
75 * controls or International Traffic in Arms Regulations (ITAR) because it
76 * and cexcept.c, libpng, and zlib, which may be bundled with pngcrush, are
77 * all open source, publicly available software, that do not contain any
78 * encryption software. See the EAR, paragraphs 734.3(b)(3) and 734.7(b).
79 *
80 * TRADEMARK:
81 *
82 * The name "pngcrush" has not been registered by the Copyright owner
83 * as a trademark in any jurisdiction. However, because pngcrush has
84 * been distributed and maintained world-wide, continually since 1998,
85 * the Copyright owner claims "common-law trademark protection" in any
86 * jurisdiction where common-law trademark is recognized.
87 *
88 * CEXCEPT COPYRIGHT, DISCLAIMER, and LICENSE:
89 *
90 * The cexcept.h header file which is bundled with this software
91 * is conveyed under the license and disclaimer described in lines 10
92 * through 18 of cexcept.h.
93 *
94 * LIBPNG COPYRIGHT, DISCLAIMER, and LICENSE:
95 *
96 * If libpng is bundled with this software, it is conveyed under the
97 * libpng license (see COPYRIGHT NOTICE, DISCLAIMER, and LICENSE, in png.h).
98 *
99 * If intel_init.c and filter_sse2_intrinsics.c are bundled with this
100 * software, they are conveyed under the libpng license (see the
101 * copyright notices within those files and the COPYRIGHT NOTICE, DISCLAIMER,
102 * and LICENSE in png.h).
103 *
104 * ZLIB COPYRIGHT, DISCLAIMER, and LICENSE:
105 *
106 * If zlib is bundled with this software, it is conveyed under the
107 * zlib license (see the copyright notice, disclaimer, and license
108 * appearing in zlib.h).
109 *
110 * ACKNOWLEDGMENTS:
111 *
112 * Thanks to Greg Roelofs for various bug fixes, suggestions, and
113 * occasionally creating Linux executables.
114 *
115 * Thanks to Stephan Levavej for some helpful suggestions about gcc compiler
116 * options and for a suggestion to increase the Z_MEM_LEVEL from default.
117 *
118 * Thanks to others who have made bug reports and suggestions mentioned
119 * in the change log.
120 *
121 * CAUTION:
122 *
123 * There is another version of pngcrush that has been distributed by
124 * Apple since mid-2008 as a part of the Xcode SDK. Although it claims
125 * to be pngcrush by Glenn Randers-Pehrson, it has additional options
126 * "-iPhone", "-speed", "-revert-iphone-optimizations", and perhaps others.
127 * It is an "altered version". I've seen output from a 2006 version that
128 * says on its help screen, "and modified by Apple as indicated in the
129 * sources".
130 *
131 * It writes files that have the PNG 8-byte signature but are not valid PNG
132 * files (instead they are "IOS-optimized PNG files"), due to at least
133 *
134 * 1. the presence of the CgBI chunk ahead of the IHDR chunk;
135 * 2. nonstandard deflate compression in IDAT, iCCP, and perhaps zTXt chunks
136 * (I believe this only amounts to the omission of the zlib header from
137 * the IDAT and perhaps other compressed chunks);
138 * 3. Omission of the CRC bytes from the IDAT chunk and perhaps other chunks;
139 * 4. the use of premultiplied alpha in color_type 6 files; and
140 * 5. the sample order, which is ARGB instead of RGBA in color_type 6 files.
141 *
142 * See http://iphonedevwiki.net/index.php/CgBI_file_format for more info.
143 *
144 * Although there is no loss in converting a CgBI PNG back to a regular
145 * PNG file, the original PNG file cannot be losslessly recovered from such
146 * files because of the losses that occurred during the conversion to
147 * premultiplied alpha.
148 *
149 * Most PNG decoders will recognize the fact that an unknown critical
150 * chunk "CgBI" is present and will immediately reject the file.
151 *
152 * It is said that the Xcode version of pngcrush is automatically applied
153 * when PNG files are prepared for downloading to the iPhone unless the
154 * user takes special measures to prevent it.
155 *
156 * It is said that the Xcode pngcrush does have a command to undo the
157 * premultiplied alpha. It's not theoretically possible, however, to recover
158 * the original file without loss. The underlying color data will either be
159 * reduced in precision, or, in the case of fully-transparent pixels,
160 * completely lost.
161 *
162 * I have not seen the source for the Xcode version of pngcrush. All I
163 * know, for now, is from running "strings -a" on an old copy of the
164 * executable, looking at two Xcode-PNG files, and reading Apple's patent
165 * application <http://www.freepatentsonline.com/y2008/0177769.html>. Anyone
166 * who does have access to the revised pngcrush code cannot show it to me
167 * anyhow because of their Non-Disclosure Agreement with Apple.
168 */
169
170 /* To do (TODO, TO DO):
171 *
172 * (As noted below, some of the features that aren't yet implemented
173 * in pngcrush are already available in ImageMagick; you can try a
174 * workflow that makes a first pass over the image with ImageMagick
175 * to select the bit depth, color type, interlacing, etc., and then makes
176 * another pass with pngcrush to optimize the compression, and finally
177 * makes a pass with libpng's "pngfix" app to optimize the zlib CMF
178 * bytes.)
179 *
180 * 0. Make pngcrush optionally operate as a filter, writing the crushed PNG
181 * to standard output, if an output file is not given, and reading
182 * the source file from standard input if no input file is given.
183 *
184 * 1. Reset CINFO to reflect decoder's required window size (instead of
185 * libz-1.1.3 encoder's required window size, which is 262 bytes larger).
186 * See discussion about zlib in png-list archives for April 2001.
187 * libpng-1.2.9 does some of this and libpng-1.5.4 does better.
188 * But neither has access to the entire datastream, so pngcrush could
189 * do even better.
190 *
191 * This has no effect on the "crushed" filesize. The reason for setting
192 * CINFO properly is to provide the *decoder* with information that will
193 * allow it to request only the minimum amount of memory required to decode
194 * the image (note that libpng-based decoders don't make use of this
195 * hint, because of the large number of files found in the wild that have
196 * incorrect CMF bytes).
197 *
198 * In the meantime, one can just run
199 *
200 * pc input.png crushed.png
201 *
202 * where the "pc" script is the following:
203 *
204 * #!/bin/sh
205 * cp $1 temp-$$.png
206 * for w in 512 1 2 4 8 16 32
207 * do
208 * pngcrush -ow -w $w -brute temp-$$.png
209 * done
210 * mv temp-$$.png $2
211 *
212 * It turns out that sometimes this finds a smaller compressed PNG
213 * than plain "pngcrush -brute input.png crushed.png" finds.
214 *
215 * There are several ways that pngcrush could implement this.
216 *
217 * a. Revise the bundled zlib to report the maximum window size that
218 * it actually used, then rewrite CINFO to contain the next power-of-two
219 * size equal or larger than the size. This method would of course
220 * only work when pngcrush is built with the bundled zlib, and won't
221 * work with zopfli compression.
222 *
223 * b. Do additional trials after the best filter method, strategy,
224 * and compression level have been determined, using those settings
225 * and reducing the window size until the measured filesize increases,
226 * then choosing the smallest size which did not cause the filesize
227 * to increase. This is expensive.
228 *
229 * c. After the trials are complete, replace CINFO with smaller
230 * settings, then attempt to decode the zlib datastream, and choose
231 * the smallest setting whose datastream can still be decoded
232 * successfully. This is likely to be the simplest and fastest
233 * solution; however, it will only work with a version of libpng
234 * in which the decoder actually uses the CINFO hint.
235 * This seems to be the only method that would work with zopfli
236 * compression which always writes "7" (i.e., a 32k window) in CINFO.
237 *
238 * d. The simplest is to use pngfix, which comes with libpng16 and
239 * later, as a final step:
240 *
241 * pngcrush input.png temp.png
242 * pngfix --optimize --out=output.png temp.png
243 * # To do: find out if this works with zopfli output
244 *
245 * 2. Check for the possiblity of using the tRNS chunk instead of
246 * the full alpha channel. If all of the transparent pixels are
247 * fully transparent, and they all have the same underlying color,
248 * and no opaque pixel has that same color, then write a tRNS
249 * chunk and reduce the color-type to 0 or 2. This is a lossless
250 * operation. ImageMagick already does this, as of version 6.7.0.
251 * If the lossy "-blacken" option is present, do that operation first.
252 *
253 * 3. Add choice of interlaced or non-interlaced output. Currently you
254 * can change interlaced to non-interlaced and vice versa by using
255 * ImageMagick before running pngcrush. Note, when implementing this,
256 * disallow changing interlacing if APNG chunks are being copied.
257 *
258 * 4. Use a better compression algorithm for "deflating" (result must
259 * still be readable with zlib!) e.g., http://en.wikipedia.org/wiki/7-Zip
260 * says that the 7-zip deflate compressor achieves better compression
261 * (smaller files) than zlib. If tests show that this would be worth
262 * while, incorporate the 7-zip compressor as an optional alternative
263 * or additional method of pngcrush compression. See the GPL-licensed code
264 * at http://en.wikipedia.org/wiki/AdvanceCOMP and note that if this
265 * is incorporated in pngcrush, then pngcrush would have to be re-licensed,
266 * or released in two versions, one libpng-licensed and one GPL-licensed!
267 *
268 * Also consider Google's "zopfli" compressor, which is said to slow but
269 * achieves better compression. It is Apache-2.0 licensed and available from
270 * a GIT repository at SourceForge (see https://code.google.com/p/zopfli/).
271 * See also the "pngzop" directory under the pmt.sourceforge.net project.
272 * Note paragraph 1.c above; zopfli always writes "7" in CINFO. See
273 * my "pmt/pngzop" project at SourceForge and GitHub.
274 *
275 * 5. Optionally recognize any sRGB iCCP profile and replace it with the
276 * sRGB chunk. Turn this option on if the "-reduce" option is on. Also,
277 * if "-reduce" is on, delete any gAMA and cHRM chunks if the sRGB chunk
278 * is being written.
279 *
280 * 6. Accept "--long-option". For starters, just accept -long_option
281 * and --long_option equally.
282 *
283 * 7. Implement a "copy_idat" option that simply copies the IDAT data,
284 * implemented as "-m 176". This will still repackage the IDAT chunks
285 * in a possibly different IDAT chunk size.
286 *
287 * 8. Implement palette-building (from ImageMagick-6.7.0 or later, minus
288 * the "PNG8" part) -- actually ImageMagick puts the transparent colors
289 * first, then the semitransparent colors, and finally the opaque colors,
290 * and does not sort colors by frequency of use but just adds them
291 * to the palette/colormap as it encounters them, so it might be improved.
292 * Also it might be made faster by using a hash table as was partially
293 * implemented in pngcrush-1.6.x. If the latter is done, also port that
294 * back to ImageMagick/GraphicsMagick. See also ppmhist from the NetPBM
295 * package which counts RGB pixels in an image; this and its supporting
296 * lib/libppmcmap.c would need to be revised to count RGBA pixels instead.
297 *
298 * 9. Improve the -help output and/or write a good man page.
299 *
300 * 10. Finish pplt (MNG partial palette) feature.
301 *
302 * 11. Remove text-handling and color-handling features and put
303 * those in a separate program or programs, to avoid unnecessary
304 * recompressing. Note that in pngcrush-1.7.34, pngcrush began doing
305 * this extra work only once instead of for every trial, so the potential
306 * benefit in CPU savings is much smaller now.
307 *
308 * 12. Add a "pcRu" ancillary chunk that keeps track of the best method,
309 * methods already tried, and whether "loco crushing" was effective.
310 *
311 * 13. Try both transformed and untransformed colors when "-loco" is used.
312 *
313 * 14. Move the Photoshop-fixing stuff into a separate program.
314 *
315 * 15. GRR: More generally (superset of previous 3 items): split into
316 * separate "edit" and "crush" programs (or functions). Former is fully
317 * libpng-aware, much like current pngcrush; latter makes little or no use of
318 * libpng (maybe IDAT-compression parts only?), instead handling virtually
319 * all chunks as opaque binary blocks that are copied to output file _once_,
320 * with IDATs alone replaced (either by best in-memory result or by original
321 * _data_ resplit into bigger IDATs, if pngcrush cannot match/beat). "edit"
322 * version should be similar to current code but more efficient: make
323 * _one_ pass through args list, creating table of PNG_UINTs for removal;
324 * then make initial pass through PNG image, creating (in-order) table of
325 * all chunks (and byte offsets?) and marking each as "keep" or "remove"
326 * according to args table. Could start with static table of 16 or 32 slots,
327 * then double size & copy if run out of room: still O(n) algorithm.
328 *
329 * 16. With libpng17, png_write throws an "affirm()" with tc.format=256
330 * when attempting to write a sub-8-bit grayscale image.
331 *
332 * 17. Figure out why we aren't calling png_read_update_info() and fix.
333 *
334 * 18. Fix ADLER32 checksum handling in conjunction with iCCP chunk
335 * reading.
336 *
337 * 19. Fix Coverity "TOCTOU" warning about our "stat()" usage.
338 *
339 * 20. Warn about removing copyright and license info appearing in
340 * PNG text chunks.
341 *
342 * 21. Implement the "eXIf" chunk if it is approved by the PNG
343 * Development Group. Optionally, remove preview and thumbnail
344 * images from the Exif profile contained in the eXIf chunk.
345 *
346 */
347
348 #if 0 /* changelog */
349
350 Change log:
351
352 Version 1.8.13 (built with libpng-1.6.32 and zlib-1.2.11)
353 Add "exit(0)" after processing "-version" argument, to avoid
354 displaying the Usage information (bug report by Peter Hagan,
355 Issue #76).
356 Fix problem with MacOS prior to Sierra; it uses CLOCK_MONOTONIC
357 for some other purpose (bug report and help developing patch by
358 Github user "ilovezfs", Homebrew/homebrew-core PR#16391).
359
360 Version 1.8.12 (built with libpng-1.6.31 and zlib-1.2.11)
361 Added POWERPC-VSX support.
362 Report whether using optimizations.
363 Added filter_method 6 (same as filter 5 with -speed).
364 Added "methods" 149-176 (that use filter_method 6).
365 Changed default verbosity from 1 (normal) to 0 (quiet). Use "-v" to get
366 the previous default behavior and "-v -v" to get the previous "verbose"
367 behavior. The "-s" (silent) and "-q" (quiet) options behave as before.
368
369 Version 1.8.11 (built with libpng-1.6.28 and zlib-1.2.11)
370 Use png_set_option(PNG_IGNORE_ADLER32) to control ADLER32 handling.
371 Changed LD=gcc to LD=$(CC) in Makefile and Makefile-nolib (suggested
372 by Helmut G in Bug#850927 of some GIT project)
373
374 Version 1.8.10 (built with libpng-1.6.26 and zlib-1.2.8.1)
375 Changed ADLER32 checksum handling to only use inflateValidate()
376 during IDAT chunk handling; it broke iCCP chunk handling.
377
378 Version 1.8.9 (built with libpng-1.6.26 and zlib-1.2.8.1)
379 Added "-warn" option, to show only warnings.
380 Enabled method 149. For now it writes uncompressed IDAT but in
381 a future version of pngcrush it will just copy the IDAT data.
382
383 Version 1.8.8 (built with libpng-1.6.26beta06 and zlib-1.2.8.1)
384 Fixed "nolib" build (bug report by Hanspeter Niederstrasser).
385 Make sure we use system-png.h, and not the local file. It is now
386 possible to build either the regular pngcrush or the "nolib"
387 pngcrush in the complete pngcrush source directory (use
388 "make clean" before rebuilding!)
389 Fixed timing when using "clock()". Sometimes an additional second
390 was added when the timer crossed a one-second boundary, since
391 version 1.8.5.
392 Upgrade libpng to version 1.6.26beta06 and zlib to 1.2.8.1.
393 Use zlib-1.2.8.1 new "inflateValidate()" function to avoid checking
394 ADLER32 checksums. Version 1.8.7 did not work when the "-fix"
395 option was used.
396
397 Version 1.8.7 (built with libpng-1.6.25 and zlib-1.2.8)
398 Do not check the ADLER32 CRC while reading except during the final write
399 pass (requires libpng-1.6.26 or later and zlib-1.2.4 or later).
400 This saves some CPU time, around five to ten percent, in decoding.
401 Do not calculate the ADLER32 CRC while writing except during the final
402 write pass (writing raw deflate streams instead of zlib streams to
403 the IDAT chunks; these are invalid PNGs but since all we do is count
404 the bytes that does not matter). This saves some CPU time in encoding
405 but it is barely perceptible. Requires zlib 1.2.4 or later and modified
406 pngwutil.c.
407
408 Version 1.8.6 (built with libpng-1.6.25 and zlib-1.2.8)
409 Enabled ARM_NEON support.
410 Fixed error in handling of timer wraparound when interval exceeds one
411 second.
412 Disable high resolution timers by default in Makefile. To enable them,
413 you must enable/disable relevant CPPFLAGS and LIBS in Makefile.
414
415 Version 1.8.5 (built with libpng-1.6.24 and zlib-1.2.8)
416 Added "-benchmark n" option. It runs the main loop "n" times, and
417 records the minimum value for each timer.
418 After checking for CLOCK_ID, use clock() if none is found.
419 Avoid some timing when verbose<0 ("-s" or "--silent")
420 Added PNGCRUSH_CHECK_CRC (off by default) to use libpng default
421 CRC checking. Otherwise, CRC are only computed and checked during
422 the first read pass and while writing.
423 Accept "--option" (for now, by simply skipping the first "-").
424
425 Version 1.8.4 (built with libpng-1.6.24 and zlib-1.2.8)
426 Fixed handling of CLOCK_ID, removed some "//"-delimited comments.
427 Revised intel_init.c to always optimize 4bpp images, because the
428 poor optimization noted previously has been fixed.
429
430 Version 1.8.3 (built with libpng-1.6.24 and zlib-1.2.8)
431 Fixed bug introduced in 1.8.2 that causes trial 10 to be skipped when
432 using the default heuristic method.
433 Fixed incorrect typecast in call to png_create_write_struct_2() (Bug
434 report by Richard K. Lloyd).
435 Added intel_init.c, filter_sse2_intrinsics.c, and Makefile-sse,
436 to enable INTEL SSE optimization. Revised intel_init.c to optionally
437 only optimize 4bpp images, because the optimization appears to slow
438 down reading of 3bpp images.
439 Added PNGCRUSH_TIMERS (nanosecond resolution using clock_gettime), to
440 measure defiltering time in png_read_filter_row(). For now, this only
441 works with a modified libpng, on platforms that provide "clock_gettime()".
442 To enable all timers, define PNGCRUSH_TIMERS=11.
443 Revised "-q" to show a short summary of results (final size and timing)
444 To do: Add ZLIB_AMALGAMATED configuration; currently produces different output
445 https://blog.forrestthewoods.com/
446 improving-open-source-with-amalgamation-cf293592c5f4#.g9fb2tyhs
447 (added #ifndef NO_GZ / #endif to skip the gz* code in zlib_amalg.[ch]).
448 Added LIBPNG_UNIFIED configuration.
449
450 Version 1.8.2 (built with libpng-1.6.23 and zlib-1.2.8)
451 Fixed filesize reduction report when "-ow" option is used (Bug report #68).
452 When a single method is specified, turn -reduce off by default and skip
453 trial 0.
454
455 Version 1.8.1 (built with libpng-1.6.21 and zlib-1.2.8)
456 Added the LICENSE file to the tar and zip distributions.
457 Made "-force" force output even when the IDAT is larger, and added
458 "-noforce" option; "-noforce" is now the default behavior (Bug
459 report #68 at SourceForge by "wintakeall")
460 Use right filename in filesize reduction report (overwrite?inname:outname)
461 (bug report #69 by "wintakeall").
462 Removed some superfluous spaces from the Copyright statement.
463 Added "-speed" option; it avoids using the AVG or PAETH filters which
464 are slower to decode.
465
466 Version 1.8.0 (built with libpng-1.6.21 and zlib-1.2.8)
467 Made "-reduce" and "-force" the default behavior. Removed obsolete
468 options "-plte_len", "-cc", "-nocc", "-double_gamma", "-already_crushed",
469 and "-bit_depth". Removed "things_have_changed" code.
470
471 Version 1.7.92 (built with libpng-1.6.20 and zlib-1.2.8)
472 Deleted png_read_update_info() statement that was mistakenly added to
473 version 1.7.89. It caused "bad adaptive filter value" errors.
474
475 Version 1.7.91 (built with libpng-1.6.20 and zlib-1.2.8)
476 Suppress warning about "damaged LZ stream" when bailing out and building
477 with libpng-1.7.0beta.
478 Added a LICENSE file to the distribution. It points to the actual
479 license appearing in the NOTICES section near the top of pngcrush.c
480 Show if pngcrush is built with bundled or system libpng and zlib.
481 Fixed segfault while writing a -loco MNG (bug found with AFL, reported
482 by Brian Carpenter). Bug was introduced in pngcrush-1.7.35.
483
484 Version 1.7.88 (built with libpng-1.6.19 and zlib-1.2.8)
485 Eliminated a potential overflow while adding iTXt chunk (over-length
486 text_lang or text_lang_key), reported by Coverity.
487
488 Version 1.7.87 (built with libpng-1.6.18 and zlib-1.2.8)
489 Fixed a double-free bug (CVE-2015-7700). There was a "free" of the
490 sPLT chunk structure in pngcrush and then again in png.c (Bug report
491 by Brian Carpenter).
492 Added common-law trademark notice and export control information.
493 Rearranged some paragraphs in the comments at the beginning of pngcrush.c
494 Increased some buffer sizes in an attempt to prevent possible overflows.
495
496 Version 1.7.86 (built with libpng-1.6.18 and zlib-1.2.8)
497 Increased maximum size of a text chunk input from 260 to 2048
498 (STR_BUF_SIZE) bytes, to agree with the help screen (bug report by
499 Tamas Jursonovics).
500 Fixed bug that caused text chunks after IDAT to be written only when
501 the "-save" option is used.
502
503 Version 1.7.85 (built with libpng-1.6.16 and zlib-1.2.8)
504 Improved reporting of invalid chunk names. Does not try to put
505 non-printable characters in STDERR; displays hex numbers instead.
506 Fixed include path for utime.h on MSVC (Louis McLaughlin).
507 Eliminated "FAR" memory support (it was removed from libpng at version
508 1.6.0).
509 Disabled the "-already_crushed" option which does not really work well.
510
511 Version 1.7.84 (built with libpng-1.6.16 and zlib-1.2.8)
512 Cleaned up more Coverity-scan warnings. Fixing those also fixed
513 CVE-2015-2158.
514
515 Version 1.7.83 (built with libpng-1.6.16 and zlib-1.2.8)
516 Cleaned up some Coverity-scan warnings. Unfortunately one of these
517 changes introduced the vulnerability reported in CVE-2015-2158.
518
519 Version 1.7.82 (built with libpng-1.6.16 and zlib-1.2.8)
520
521 Version 1.7.81 (built with libpng-1.6.15 and zlib-1.2.8)
522 Fixed off-by-one error in calculation of plte_len. Bug reports by
523 Ivan Kuchin and Frederic Kayser.
524
525 Version 1.7.80 (built with libpng-1.6.14 and zlib-1.2.8)
526 Added "-reduce_palette" and "-noreduce_palette" options. Enable
527 reduce_palette when the "-new" or "-reduce" option is used.
528
529 Version 1.7.79 (built with libpng-1.6.14 and zlib-1.2.8)
530 Fixed bug in -plte_len N option.
531
532 Version 1.7.78 (built with libpng-1.6.14 and zlib-1.2.8)
533 Made "-s" and "-silent" options suppress libpng warnings.
534
535 Version 1.7.77 (built with libpng-1.6.13 and zlib-1.2.8)
536 Updated libpng to version 1.6.13.
537
538 Version 1.7.76 (built with libpng-1.6.12 and zlib-1.2.8)
539 Updated libpng to version 1.6.12.
540
541 Version 1.7.75 (built with libpng-1.6.10 and zlib-1.2.8)
542 Reverted libpng to version 1.6.10 due to a misplaced statement in png.c
543
544 Version 1.7.74 (built with libpng-1.6.11 and zlib-1.2.8)
545 Fixed "-zmem" option (only "-zm" would work since version 1.7.62).
546
547 Version 1.7.73 (built with libpng-1.6.10 and zlib-1.2.8)
548 Restored calls to png_set_crc_action() which had been removed from
549 version 1.7.72 for some testing and inadvertently not restored.
550 Changed "fix" internal variable name to "salvage" (still set with "-fix")
551 Added code to fix/salvage PNG with "bad adaptive filter value" error.
552 Avoid calculating CRC during compression trials except for the last trial,
553 when the output is actually written.
554 Fixed a bug with reducing 16-bit images to 8-bit using "-reduce" option.
555
556 Version 1.7.72 (built with libpng-1.6.10 and zlib-1.2.8)
557
558 Version 1.7.71 (built with libpng-1.6.9 and zlib-1.2.8)
559 Built the Windows binaries using -DTOO_FAR=32767; neglected to do this
560 in versions 1.7.42 through 1.7.70, which caused the Windows binaries
561 to produce different (usually a few bytes larger) results than Linux.
562 Thanks to F. Kayser for reporting the discrepancy.
563
564 Version 1.7.70 (built with libpng-1.6.8 and zlib-1.2.8)
565
566 Version 1.7.69 (built with libpng-1.6.6 and zlib-1.2.8)
567 Updated libpng to version 1.6.6.
568
569 Version 1.7.68 (built with libpng-1.6.4 and zlib-1.2.8)
570 Check for NULL return from malloc().
571 Undefine CLOCKS_PER_SECOND "1000" found in some version of MinGW.
572 Replaced most "atoi(argv[++i])" with "pngcrush_get_long" which does
573 "BUMP_I; strtol(argv[i],ptr,10)" and added pngcrush_check_long macro
574 to detect malformed or missing parameters (debian bug 716149).
575 Added global_things_have_changed=1 when reading -bkgd.
576 The "-bit_depth N" option did not work reliably and has been removed.
577
578 Version 1.7.67 (built with libpng-1.5.17 and zlib-1.2.8)
579 Fixed handling of "-text" and "-ztext" options for text input. They had been
580 reduced to "-t" and "-z" with an incorrect argument (3 instead of 2) in
581 version 1.7.62. Bug report and patch from Tsukasa Oi.
582
583 Version 1.7.66 (built with libpng-1.5.17 and zlib-1.2.8)
584 Revised pngcrush_examine_pixels_fn() to fix some incorrect reductions.
585
586 Version 1.7.65 (built with libpng-1.5.17 and zlib-1.2.8)
587 Do not allow any colortype or depth reductions if acTL is present.
588 Added warnings to explain why any requested reductions were not allowed.
589
590 Version 1.7.64 (built with libpng-1.5.17 and zlib-1.2.8)
591
592 Version 1.7.63 (built with libpng-1.5.16 and zlib-1.2.8)
593 Add "int dowildcard=-1;" in an attempt to get wildcard arguments working
594 in the cross-compiled MinGW executables.
595
596 Version 1.7.62 (built with libpng-1.5.16 and zlib-1.2.8)
597 Remove old filename before renaming, when using the "-ow" option on
598 any Windows platform, not just CYGWIN (see log entry for pngcrush-1.7.43).
599 Reverted error with handling single-character options like "-v", introduced
600 in 1.7.61.
601
602 Version 1.7.61 (built with libpng-1.5.16 and zlib-1.2.8)
603 Check sBIT chunk data to see if reduction to gray or to 8-bit is permitted,
604 i.e., the RGB sBIT values are equal to each other or the sBIT values are
605 not greater than 8, respectively.
606 Do not try to make_opaque if the tRNS chunk is found.
607 Added warning when ignoring an invalid commandline option.
608 Improved brute_force handling with specified level, filter, or strategy.
609
610 Version 1.7.60 (built with libpng-1.5.16 and zlib-1.2.8)
611 Revise -reduce so reducing from color-type 6 to grayscale works.
612 Issue a warning if reducing bit depth or color type would violate various
613 chunk dependencies, and do not perform the action:
614 Do not reduce to grayscale if a color bKGD chunk, sBIT or iCCP chunk
615 is present.
616 Do not reduce bit depth if bKGD or sBIT chunk is present.
617 Do not reduce palette length if the hIST chunk is present.
618 Set "found_iCCP" flag to zero to avoid re-reading a bad iCCP chunk.
619
620 Version 1.7.59 (built with libpng-1.5.16 and zlib-1.2.8)
621 Show the acTL chunk in the chunk list in verbose output.
622 Fixed several bugs reported by pornel at users.sf.net:
623 Do not call png_set_benign_errors when PNG_BENIGN_ERRORS_SUPPORTED
624 is not defined
625 Renamed PNG_UNUSED() macro PNGCRUSH_UNUSED().
626 Moved a closing bracket inside the PNGCRUSH_LOCO block.
627 Moved the declaration of "new_mng" outside a PNGCRUSH_LOCO block.
628 Put reference to "input_format" inside a PNGCRUSH_LOCO block.
629 Moved declarations of mng_out and mngname inside a PNGCRUSH_LOCO block.
630
631 Version 1.7.58 (built with libpng-1.5.15 and zlib-1.2.7-1)
632 Do not enable reduce_palette by default for "-reduce", "-new", or "-old".
633 It still is failing for some files.
634
635 Version 1.7.57 (built with libpng-1.5.15 and zlib-1.2.7-1)
636 Added "-new" option that turns on "-reduce" which will be
637 the default setting for version 1.8.0 and beyond.
638 Added "-old" option that turns off "-reduce" which is the
639 current default setting.
640 Updated copyright year for zlib-1.2.7-1.
641 Reverted to libpng-1.5.15 to be able to read old PNG files with TOO FAR
642 errors. This will of course only work with the embedded libpng.
643
644 Version 1.7.56 (built with libpng-1.6.1 and zlib-1.2.7-1)
645 Only use pngcrush_debug_malloc() and pngcrush_debug_free() if the result
646 is going to be shown.
647 Added PNG_PASS_ROWS, PNG_UNUSED, and other macro definitions, when building
648 with libpng-1.4.x and older libpng versions.
649 Multiplied rowbytes by 8/bit_depth when using the system library because
650 we do not call png_read_transform_info(). This prevents a crash when
651 reading sub-8-bit input files.
652
653 Version 1.7.55 (built with libpng-1.6.1 and zlib-1.2.7-1)
654
655 Version 1.7.54 (built with libpng-1.6.1rc01 and zlib-1.2.7-1)
656
657 Version 1.7.53 (built with libpng-1.6.1rc01 and zlib-1.2.7)
658 Removed plte_len stuff from the "To do" list because it is done.
659 Shorten the indexed-PNG tRNS chunk length if it has more entries than the PLTE chunk.
660
661 Version 1.7.52 (built with libpng-1.6.1beta06 and zlib-1.2.7)
662 Added license info for cexcept.h, libpng, and zlib.
663 Added consideration of "zopfli" compression to the "To do" list.
664 Fixed a typo that caused a cHRM chunk to be "found" if an iCCP chunk
665 were present.
666 Reset best_byte_count before trial loop.
667 Revise global png_set_keep_unknown_chunks() calls to avoid a libpng16
668 warning.
669 Reset "intent" to "specified_intent" before trial loop.
670 Reset "plte_len" to "specified_plte_len" before trial loop.
671 Initialize length of each trial to 0x7fffffff so any untried method
672 is not the "best method".
673
674 Version 1.7.51 (built with libpng-1.6.0 and zlib-1.2.7)
675 Added "-noreduce" option, in preparation for "-reduce" becoming the
676 default behaviour in version 1.8.0. This turns off lossless bit depth,
677 color type, palette reduction, and opaque alpha channel removal.
678 Zero out the high byte of transparent color for color-type 0 and 2,
679 when reducing from 16 bits to 8.
680 Undefined a bunch of stuff in pngcrush.h that we do not use, saves about
681 100 kbytes of executable file size in addition to about 50k saved by
682 undefining the simplified API.
683 Fixed double-underscore typo in an #ifdef in png.c
684 If "-reduce" is on and the background index is larger than the reduced
685 palette_length+1, reduce it to the palette_length+1.
686 Increased required_window_size if necessary to account for slightly larger
687 size of interlaced files due to additional filter bytes and padding.
688
689 Version 1.7.50 (built with libpng-1.6.0 and zlib-1.2.7)
690 Removed completed items from the "To do" list.
691 Ignore the argument of the "plte_len" argument and just set the
692 "reduce_palette" flag.
693
694 Version 1.7.49 (built with libpng-1.5.14 and zlib-1.2.7)
695 Use png_set_benign_errors() to allow certain errors in the input file
696 to be handled as warnings.
697 Skip PNG_ABORT redefinition when using libpng-1.4.0 and later.
698 Implemented "-reduce" option to identify and reduce all-gray images,
699 all-opaque images, unused PLTE entries, and 16-bit images that can be
700 reduced losslessly to 8-bit.
701
702 Version 1.7.48 (built with libpng-1.5.14 and zlib-1.2.7)
703 Reserved method==0 for examining the pixels during trial 0, if necessary.
704 Changed blacken_fn() to separate pngcrush_examine_pixels_fn() and
705 pngcrush_transform_pixels_fn() callback functions. The "examine"
706 function is only done during trial 0; it sets a flag whether
707 any fully transparent pixels were found, and pngcrush only runs
708 pngcrush_transform_pixels_fn() if necessary.
709 This is in preparation for future versions, which will examine other
710 conditions such as if the image is opaque or gray or can be losslessly
711 reduced in bit depth, set flags in trial 0 and accomplish the
712 transformations in the remaining trials (see the To do list starting
713 about line 200 in the pngcrush.c source).
714 Removed "PNGCRUSH_COUNT_COLORS" blocks again.
715
716 Version 1.7.47 (built with libpng-1.5.13 and zlib-1.2.7)
717 Do not do the heuristic trials of the first 10 methods when -brute is
718 specified, because it did not save time as I hoped.
719 Fixed a mistake in 1.7.45 and 1.7.46 that caused the output file to
720 not be written.
721
722 Version 1.7.46 (built with libpng-1.5.13 and zlib-1.2.7)
723 Moved the new level 0 methods to the end of the trial list (methods 137-148)
724
725 Version 1.7.45 (built with libpng-1.5.13 and zlib-1.2.7)
726 Added method 0 (uncompressed). "-m 0" now simply turns on method 0.
727 Added "-try10" option that has the same effect that "-m 0" previously did,
728 namely to try only the first ten methods.
729 Inserted new methods 17 through 21 with zlib level 0.
730 Do the heuristic trials of the first 10 methods when -brute is specified,
731 to get quickly to a small solution, so we can bail out of most of the
732 remaining trials early. Previously these 10 methods were skipped during
733 a -brute run.
734 Removed the "-reduce" line from the help screen when PNGCRUSH_COUNT_COLORS
735 is disabled.
736
737 Version 1.7.44 (built with libpng-1.5.14 and zlib-1.2.7)
738
739 Version 1.7.43 (built with libpng-1.5.13 and zlib-1.2.7)
740 Added "remove(inname)" before "rename(outname, inname)" when using the "-ow"
741 option on CYGWIN/MinGW because "rename()" does not work if the target file
742 exists.
743 Use the bundled "zlib.h" when PNGCRUSH_H is defined, otherwise use the
744 system <zlib.h>.
745
746 Version 1.7.42 (built with libpng-1.5.13 and zlib-1.2.7)
747 Use malloc() and free() instead of png_malloc_default() and
748 png_free_default(). This will be required to run with libpng-1.7.x.
749 Revised the PNG_ABORT definition in pngcrush.h to work with libpng-1.7.x.
750 Revised zutil.h to avoid redefining ptrdiff_t on MinGW/CYGWIN platforms.
751
752 Version 1.7.41 (built with libpng-1.5.13 and zlib-1.2.7)
753 Reverted to version 1.7.38. Versions 1.7.39 and 1.7.40 failed to
754 open an output file.
755
756 Version 1.7.40 (built with libpng-1.5.13 and zlib-1.2.7)
757 Revised the "To do" list.
758
759 Version 1.7.39 (built with libpng-1.5.13 and zlib-1.2.7)
760 Removed "PNGCRUSH_COUNT_COLORS" blocks which I no longer intend to
761 implement because that feature is already available in ImageMagick. Kept
762 "reduce_to_gray" and "it_is_opaque" flags which I do hope to implement
763 soon.
764 Changed NULL to pngcrush_default_read_data in png_set_read_fn() calls, to fix
765 an insignificant error introduced in pngcrush-1.7.14, that caused most
766 reads to not go through the alternate read function. Also always set this
767 function, instead of depending on STDIO_SUPPORTED.
768
769 Version 1.7.38 (built with libpng-1.5.13 and zlib-1.2.7)
770 Bail out of a trial if byte count exceeds best byte count so far. This
771 avoids wasting CPU time on trial compressions of trials that exceed the
772 best compression found so far.
773 Added -bail and -nobail options. Use -nobail to get a complete report
774 of filesizes; otherwise the report just says ">N" for any trial
775 that exceeds size N where N is the best size achieved so far.
776 Added -blacken option, to enable changing the color samples of any
777 fully-transparent pixels to zero in PNG files with color-type 4 or 6,
778 potentially improving their compressibility. Note that this is an
779 irreversible lossy change: the underlying colors of all fully transparent
780 pixels are lost, if they were not already black.
781
782 Version 1.7.37 (built with libpng-1.5.12 and zlib-1.2.7)
783 Reverted pngcrush.c back to 1.7.35 and fixed the bug with PLTE handling.
784
785 Version 1.7.36 (built with libpng-1.5.12 and zlib-1.2.7)
786 Reverted pngcrush.c to version 1.7.34 because pngcrush is failing with
787 some paletted PNGs.
788 Separated CFLAGS and CPPFLAGS in the makefile (with "-I" and "-DZ_SOLO"
789 in CPPFLAGS)
790
791 Version 1.7.35 (built with libpng-1.5.12 and zlib-1.2.7)
792 Removed FOPEN of fpout except for the last trial. The open files caused
793 "pngcrush -brute -e _ext.png *.png" to fail on the 10th file (about the
794 1024th compression trial) due to being unable to open the output file.
795
796 Version 1.7.34 (built with libpng-1.5.12 and zlib-1.2.7)
797 Compute and report sum of critical chunk lengths IHDR, PLTE, IDAT, and IEND,
798 plus the 8-byte PNG signature instead of just the total IDAT data length.
799 Simplify finding the lengths from the trial compressions, by replacing
800 the write function with one that simply counts the bytes that would have
801 been written to a trial PNG, instead of actually writing a PNG, reading it
802 back, and counting the IDAT bytes.
803 Removed comments about the system library having to be libpng14 or earlier.
804 This restriction was fixed in version 1.7.20.
805
806 Version 1.7.33 (built with libpng-1.5.12 and zlib-1.2.7)
807 Ignore all ancillary chunks except during the final trial. This can be
808 significantly faster when large ancillary chunks such as iCCP and zTXt
809 are present.
810
811 Version 1.7.32 (built with libpng-1.5.12 and zlib-1.2.7)
812 Fixed bug introduced in 1.7.30: Do not call png_set_check_for_invalid_index()
813 when nosave != 0 (otherwise pngcrush crashes with the "-n" option).
814
815 Version 1.7.31 (built with libpng-1.5.11 and zlib-1.2.7)
816 Dropped *.tar.bz2 from distribution.
817 Added a comma that was missing from one of the "usage" strings (error
818 introduced in version 1.7.29).
819
820 Version 1.7.30 (built with libpng-1.5.11 and zlib-1.2.7)
821 Only run the new (in libpng-1.5.10) test of palette indexes during the
822 first trial.
823
824 Version 1.7.29 (built with libpng-1.5.10 and zlib-1.2.7)
825 Set "things_have_changed" flag when adding text chunks, so the "-force"
826 option is no longer necessary when adding text to an already-compressed
827 file.
828 Direct usage message and error messages to stderr instead of stdout. If
829 anyone is still using DOS they may have to change the "if 0" at line
830 990 to "if 1". If you need to have the messages on standard output
831 as in the past, use 2>&1 to redirect them.
832 Added "pngcrush -n -v files.png" to the usage message.
833
834 Version 1.7.28 (built with libpng-1.5.10 and zlib-1.2.7)
835 Write proper copyright year for zlib, depending upon ZLIB_VERNUM
836
837 Version 1.7.27 (built with libpng-1.5.10 and zlib-1.2.6)
838 Increased row_buf malloc to row_bytes+64 instead of row_bytes+16, to
839 match the size of big_row_buf in pngrutil.c (it is 48 in libpng14, 15, 16,
840 and 64 in libpng10, 12. Otherwise there is a double-free crash when the
841 row_buf is destroyed.
842
843 Version 1.7.26 (built with libpng-1.5.10 and zlib-1.2.6)
844 Increased the text_text buffer from 2048 to 10*2048 (Ralph Giles), and
845 changed an incorrect test for keyword length "< 180" to "< 80". The
846 text_text buffer was inadvertently reduced from 20480 to 2048 in
847 pngcrush-1.7.9.
848 Added -DZ_SOLO to CFLAGS, needed to compile zlib-1.2.6.
849 Changed user limits to width and height max 500000, malloc max 2MB,
850 cache max 500.
851 Added -nolimits option which sets the user limits to the default
852 unlimited values.
853
854 Version 1.7.25 (built with libpng-1.5.9 and zlib-1.2.5)
855
856 Version 1.7.24 (built with libpng-1.5.7 and zlib-1.2.5)
857 Do not append a slash to the directory name if it already has one.
858
859 Version 1.7.23 (built with libpng-1.5.7 and zlib-1.2.5)
860 Ignore any attempt to use "-ow" with the "-d" or "-e" options, with warning.
861 Include zlib.h if ZLIB_H is not defined (instead of checking the libpng
862 version; see entry below for pngcrush-1.7.14), and include string.h
863 if _STRING_H_ is not defined (because libpng-1.6 does not include string.h)
864 Define SLASH = backslash on Windows platforms so the "-d" option will work..
865
866 Version 1.7.22 (built with libpng-1.5.6 and zlib-1.2.5)
867 Added "-ow" (overwrite) option. The input file is overwritten and the
868 output file is just used temporarily and removed after it is copied
869 over the input file.. If you do not specify an output file, "pngout.png"
870 is used as the temporary file. Caution: the temporary file must be on
871 the same filesystem as the input file. Contributed by a group of students
872 of the University of Paris who were taking the "Understanding of Programs"
873 course and wished to gain familiarity with an open-source program.
874
875 Version 1.7.21 (built with libpng-1.5.6 and zlib-1.2.5)
876 Defined TOO_FAR=32767 in Makefile (instead of in pngcrush.h)
877
878 Version 1.7.20 (built with libpng-1.5.5 and zlib-1.2.5)
879 Removed the call to png_read_transform_info() when the system libpng
880 is being used, so it can be built with a system libpng.
881
882 Version 1.7.19 (built with libpng-1.5.5 and zlib-1.2.5)
883 pngcrush-1.7.18 failed to read interlaced PNGs. Reverted the change
884 from calling png_read_transform_info() to png_read_update_info().
885 Since png_read_transform_info() is not exported we again cannot build
886 with the system libpng15.
887
888 Version 1.7.18 (built with libpng-1.5.5 and zlib-1.2.5)
889 This version will work with either a "system" libpng14 or libpng15, or with
890 the embedded libpng15. The deprecated usage of libpng png_struct members
891 and unexported functions has been removed.
892 Fixing "too far back" errors does not work with libpng15.
893 Revised the format of the time report (all on one line so you can get
894 a nice compact report by piping the output to "grep coding").
895
896 Version 1.7.17 (built with libpng-1.5.5beta08 and zlib-1.2.5)
897 Changed "#if !defined(PNG_NO_STDIO)" to "#ifdef PNG_STDIO_SUPPORTED"
898 as recommended in the libpng documentation.
899 Added PNG_UINT_32_NAME macro and used it to simplify chunk_type integer
900 definitions.
901
902 Version 1.7.16 (built with libpng-1.5.4 and zlib-1.2.5)
903 Only report best method==0 if pngcrush cannot match the input filesize.
904 Otherwise, if there is no improvement, report the first matching method.
905
906 Version 1.7.15 (built with libpng-1.5.2rc02 and zlib-1.2.5)
907 Force bit_depth to 1, 2, or 4 when -plte_len is <=2, <=4, or <=16 and
908 the -bit_depth option is not present, to avoid writing invalid palette
909 indexes.
910
911 Version 1.7.14 (built with libpng-1.5.1beta08 and zlib-1.2.5)
912 Removed WIN32_WCE support (libpng has dropped it already)
913 Include zlib.h and define png_memcpy, etc., and revise the
914 png_get_iCCP() and png_set_iCCP() calls to be able to build
915 with bundled libpng-1.5.x. Pngcrush cannot be built yet with
916 a system libpng-1.5.x.
917 Dropped most of pngcrush.h, that eliminates various parts of libpng.
918
919 Version 1.7.13 (built with libpng-1.4.5 and zlib-1.2.5)
920
921 Version 1.7.12 (built with libpng-1.4.4beta05 and zlib-1.2.5)
922
923 Version 1.7.11 (built with libpng-1.4.2 and zlib-1.2.5)
924
925 Version 1.7.10 (built with libpng-1.4.1 and zlib-1.2.3.9)
926 Added missing "(...)" in png_get_uint_32().
927 Only compile png_get_uint_32(), etc., when PNG_LIBPNG_VER < 1.2.9
928 Revised help info for "-zitxt".
929
930 Version 1.7.9 (built with libpng-1.4.1 and zlib-1.2.3.9)
931 Defined TOO_FAR == 32767 in pngcrush.h (instead of in deflate.c)
932 Revised the "nolib" Makefiles to remove reference to gzio.c and
933 pnggccrd.c
934 Imposed user limits of chunk_malloc_max=4000000 and chunk_cache_max=500.
935
936 Version 1.7.8 (built with libpng-1.4.0 and zlib-1.2.3.5)
937 Removed gzio.c
938
939 Version 1.7.7 (built with libpng-1.4.0 and zlib-1.2.3.4)
940 Updated bundled libpng to version 1.4.0.
941 Check the "-plte_len n" option for out-of-range value of n.
942 Changed local variable "write" to "z_write" in inffast.c (zlib-1.2.3.4)
943 to avoid shadowed declaration warning.
944
945 Version 1.7.6 (built with libpng-1.4.0rc02 and zlib-1.2.3.2)
946 Change some "#if defined(X)" to "#ifdef X" according to libpng coding style.
947 Added some defines to suppress pedantic warnings from libpng-1.2.41beta15
948 and later. A warning about deprecated access to png_ptr->zstream is
949 otherwise unavoidable. When building the embedded libpng, a warning
950 about png_default_error() returning is also otherwise unavoidable.
951 Write premultiplied alpha if output extension is .ppng and
952 PNG_READ_PREMULTIPLIED_ALPHA_SUPPORTED is set (needs libpng-1.5.0).
953 Check the "-m method" option for out-of-range method value.
954
955 Version 1.7.5 (built with libpng-1.2.41beta14 and zlib-1.2.3.2)
956
957 Version 1.7.4 (built with libpng-1.2.40rc01 and zlib-1.2.3.2)
958 Use unmodified pngconf.h from libpng-1.2.41beta05 or later.
959
960 Version 1.7.3 (built with libpng-1.2.40 and zlib-1.2.3.2)
961 Print contents of text chunks after IDAT, even when the -n option
962 is used. This requires a slight modification of pngconf.h,
963 when libpng-1.2.x is used.
964
965 Version 1.7.2 (built with libpng-1.2.40 and zlib-1.2.3.2)
966 Added check for "verbose" on some printf statements.
967
968 Version 1.7.1 (built with libpng-1.2.39 and zlib-1.2.3.2)
969 Revised some prototypes to eliminate "Shadowed Declaration" warnings.
970 Moved warning about discarding APNG chunks to the end.
971 Replaced *.tar.lzma with *.tar.xz in the distribution.
972
973 Version 1.7.0 (built with libpng-1.2.38 and zlib-1.2.3.2)
974 Save (but do not recompress) APNG chunks if the output file has the
975 ".apng" extension and the color_type and bit_depth are not changed.
976
977 Version 1.6.20 (built with libpng-1.2.38 and zlib-1.2.3.2)
978 Changed local variable "write" to "wwrite" in inffast.c (zlib) to avoid
979 shadowed declaration warning.
980
981 Version 1.6.19 (built with libpng-1.2.37 and zlib-1.2.3.2)
982 Added missing braces that cause an incorrect png_error() to be issued.
983
984 Version 1.6.18 (built with libpng-1.2.37 and zlib-1.2.3.2)
985 Removed extra FCLOSE(fpin) and FCLOSE(fpout) in the first Catch{} block,
986 since they get removed anyway right after that (Hanno Boeck).
987 Define PNG_NO_READ|WRITE_cHRM and PNG_NO_READ_|WRITEiCCP in pngcrush.h
988 and reordered pngcrush.h
989
990 Version 1.6.17 (built with libpng-1.2.36 and zlib-1.2.3.2)
991 Defined TOO_FAR == 32767 in deflate.c (again). The definition
992 has continually been inadvertently omitted during zlib updates
993 since pngcrush version 1.6.4.
994 Revised handling of xcode files so at least we can get printout
995 of IHDR values with "pngcrush -fix -n -v xcode.png".
996 Moved ChangeLog.txt back into pngcrush.c so it does not get lost.
997 Removed single quotes from the ChangeLog.
998
999 Version 1.6.16 (built with libpng-1.2.35 and zlib-1.2.3.2)
1000 Added -newtimestamp and -oldtimestamp options and changed
1001 default condition to timestamping the output file with
1002 the current time (i.e., -newtimestamp is default)
1003 If the -oldtimestamp option is used then the output file
1004 has the same timestamp as the input file.
1005 Added CgBI chunk detection.
1006
1007 Version 1.6.15 (built with libpng-1.2.35 and zlib-1.2.3.2)
1008 Fixes some missing typecasts on png_malloc() calls, patch from
1009 an anonymous reporter to the SourceForge bug tracker.
1010 Added -time_stamp option to change time stamping from default
1011 condition.
1012
1013 Version 1.6.14 (built with libpng-1.2.35 and zlib-1.2.3.2)
1014 Avoids CVE-2009-0040.
1015
1016 Version 1.6.12 (built with libpng-1.2.34 and zlib-1.2.3.2)
1017
1018 Version 1.6.11 (built with libpng-1.2.33 and zlib-1.2.3.2)
1019 Eliminated a memory leak in libpng with writing bad tEXt chunks.
1020
1021 Version 1.6.10 (built with libpng-1.2.31 and zlib-1.2.3.2)
1022 Add sTER chunk support.
1023
1024 Version 1.6.9 (built with libpng-1.2.31 and zlib-1.2.3.2)
1025 Updated cexcept.h to version 2.0.1
1026 Add missing curly brackets.
1027
1028 Version 1.6.8 (built with libpng-1.2.29 and zlib-1.2.3.2)
1029 Fixed bug with handling of -z and -zi options.
1030
1031 Version 1.6.7 (built with libpng-1.2.29 and zlib-1.2.3.2)
1032 Moved PNG_UINT_CHNK and some other defines from pngcrush.h to pngcrush.c
1033 Reject invalid color_type or bit_depth.
1034
1035 Version 1.6.6 (built with libpng-1.2.29 and zlib-1.2.3.2)
1036 Added dSIG support. Pngcrush will not rewrite an image containing
1037 a dSIG chunk immediately following the IHDR chunk, unless the
1038 dSIG is explicitly removed with "-rem dSIG" or explicitly kept
1039 with "-keep dSIG". In the latter case the saved dSIG chunks will
1040 become invalid if any changes are made to the datastream.
1041
1042 Fixed bug in writing unknown chunks from the end_info_ptr.
1043
1044 Version 1.6.5 (built with libpng-1.2.29 and zlib-1.2.3.2)
1045 Discontinued adding a new gAMA chunk when writing sRGB chunk.
1046
1047 Version 1.6.4 (built with libpng-1.2.9rc1 and zlib-1.2.3)
1048 Fixed bug in handling of undocumented -trns_a option (Michal Politowski).
1049 Fixed bug with "nosave" handling of unknown chunks.
1050
1051 Version 1.6.3 (built with libpng-1.2.9beta11 and zlib-1.2.3)
1052
1053 Fixed documentation of iTXt input (Shlomi Tal).
1054 Removed #define PNG_INTERNAL and provided prototypes for some
1055 internal libpng functions that are duplicated in pngcrush.c
1056
1057 Version 1.6.2 (built with libpng-1.2.8 and zlib-1.2.3)
1058
1059 Fixed bug with "PNG_ROWBYTES" usage, introduced in version 1.6.0.
1060 The bug could cause a crash and only affects the "nolib" builds.
1061
1062 Converted C++ style (// ...) comments to C style (/* ... */).
1063
1064 Defined TOO_FAR == 32767 in deflate.c (again). The definition was
1065 omitted from version 1.6.0 when zlib was upgraded to version 1.2.3.
1066
1067 Version 1.6.1 (distributed as 1.6.0, built with libpng-1.2.8 and zlib-1.2.3)
1068
1069 Copied non-exported libpng functions from libpng into pngcrush, to make
1070 pngcrush play more nicely with shared libpng. These are not compiled
1071 when a static library is being built with the bundled libpng and
1072 pngcrush.h is included.
1073
1074 Version 1.6.0-grr (built with libpng-1.2.4 and zlib-1.1.4pc or zlib-1.2.2)
1075
1076 Moved ChangeLog out of pngcrush.c comments and into a separate file.
1077
1078 Filtered pngcrush.c through "indent -kr" and "expand" for readability.
1079
1080 Moved 550 lines of usage/help/copyright/license/version info to separate
1081 function(s) and cleaned up significantly.
1082
1083 Added some comments for ease of navigation and readability.
1084
1085 Stripped out a bunch of ancient-libpng compatibility stuff.
1086
1087 Defined PNG_UINT_* macros (pngcrush.h for now).
1088
1089 Fixed unknown-chunk handling ("-rem alla" and "-rem gifx" now work).
1090
1091 Created modified version of makefile that supports external zlib.
1092
1093 Added support for methods using Z_RLE zlib strategy (zlib 1.2.x only).
1094
1095 Documented -huffman option in usage screen.
1096
1097 Added IDAT statistics to final per-file summary.
1098
1099 Added utime() support to give output files same timestamps as input files.
1100
1101 Version 1.5.10 (built with libpng-1.2.4 and zlib-1.1.4pc)
1102
1103 Fixed bug, introduced in 1.5.9, that caused defaults for method 0 to
1104 be used instead of copying the original image, when the original was
1105 already smallest.
1106
1107 Version 1.5.9 (built with libpng-1.2.4beta3 and zlib-1.1.4pc)
1108
1109 Work around CPU timer wraparound at 2G microseconds.
1110
1111 Upgraded zlib from 1.1.3 to 1.1.4. Pngcrush is believed not to
1112 be vulnerable to the zlib-1.1.3 buffer-overflow bug.
1113
1114 Choose the first instance of smallest IDAT instead of the last,
1115 for faster final recompression, suggested by TSamuel.
1116
1117 Version 1.5.8 (built with libpng-1.2.1)
1118
1119 Added -trns_a option for entering a tRNS array.
1120
1121 Version 1.5.7 (built with libpng-1.2.0)
1122
1123 Added setargv.obj to Makefile.msc to expand wildcards, e.g., *.png
1124
1125 Use constant string "pngcrush" instead of argv[0] when appropriate.
1126
1127 Only check stats for infile==outfile once per input file, or not at all
1128 if "-nofilecheck" option is present or if a directory was created.
1129
1130 Fixed bugs with changing bit_depth of grayscale images.
1131
1132 Version 1.5.6 (built with libpng-1.0.12)
1133
1134 Eliminated extra "Removed the cHNK chunk" messages generated by version
1135 1.5.5 when "-rem alla" or "-rem allb" is used.
1136
1137 All unknown chunks including safe-to-copy chunks are now removed in
1138 response to the "-rem alla" or "-rem allb" options.
1139
1140 Issue a warning if the user tries "-cc" option when it is not supported.
1141
1142 Version 1.5.5 (built with libpng-1.0.12)
1143
1144 Reset reduce_to_gray and it_is_opaque flags prior to processing each
1145 image.
1146
1147 Enable removal of safe-to-copy chunks that are being handled as unknown
1148 e.g., "-rem time".
1149
1150 Version 1.5.4 (built with libpng-1.0.11)
1151
1152 Added 262 to the length of uncompressed data when calculating
1153 required_window_size, to account for zlib/deflate implementation.
1154
1155 Added "-bit_depth n" to the help screen.
1156
1157 Call png_set_packing() when increasing bit_depth to 2 or 4.
1158
1159 Added warning about not overwriting an existing tRNS chunk.
1160
1161 Reduced the memory usage
1162
1163 Write 500K IDAT chunks even when system libpng is being used.
1164
1165 Ignore all-zero cHRM chunks, with a warning.
1166
1167 Version 1.5.3 (built with libpng-1.0.9beta5)
1168
1169 Added "-loco" option (writes MNG files with filter_method 64)
1170
1171 "-dir" and "-ext" options are no longer mutually exclusive, e.g.:
1172 pngcrush -loco -dir Crushed -ext .mng *.png
1173
1174 Version 1.5.2 (built with libpng-1.0.9beta1)
1175
1176 Added "-iccp" option.
1177
1178 Increased the zlib memory level, which improves compression (typically
1179 about 1.3 percent for photos) at the expense of increased memory usage.
1180
1181 Enabled the "-max max_idat_size" option, even when max_idat_size
1182 exceeds the default 1/2 megabyte size.
1183
1184 Added missing "png_ptr" argument to png_error() call
1185
1186 Added "-loco" option, to enable the LOCO color transformation
1187 (R->R-G, G, B->B-G) while writing a MNG with filter_method 64. Undo
1188 the transformation and write the regular PNG filter_method (0) if the
1189 MNG filter_method 64 is detected.
1190
1191 Revised the "-help" output slightly and improved the "-version" output.
1192
1193 The "-already[_crushed]" option is now ignored if the "-force" option
1194 is present or if chunks are being added, deleted, or modified.
1195
1196 Improved "things_have_changed" behavior (now, when set in a particular
1197 file, it is not set for all remaining files)
1198
1199 Version 1.5.1 (built with libpng-1.0.8)
1200
1201 Disabled color counting by default and made it controllable with new
1202 -cc and -no_cc commandline arguments.
1203
1204 Added some #ifdef PNGCRUSH_COUNT_COLORS around code that needs it.
1205
1206 Revised count_colors() attempting to avoid stack corruption that has
1207 been observed on RedHat 6.2
1208
1209 Added the word "irrevocably" to the license and changed "without fee"
1210 to "without payment of any fee".
1211
1212 Version 1.5.0 (built with libpng-1.0.8)
1213
1214 After encountering an image with a bad Photoshop iCCP chunk, pngcrush
1215 1.4.5 through 1.4.8 write sRGB and gAMA=45455 chunks in all
1216 remaining PNG files on the command line. This has been fixed so the
1217 correction is only applied to the particular bad input file.
1218
1219 Version 1.4.8 (built with libpng-1.0.8rc1)
1220
1221 Detect and remove all-opaque alpha channel.
1222 Detect and reduce all-gray truecolor images to grayscale.
1223
1224 Version 1.4.7 (built with libpng-1.0.8rc1)
1225
1226 Restored the "-ext" option that was inadvertently overridden with
1227 a new "-exit" option in version 1.4.6 ("-exit" is used to force an
1228 "exit" instead of a "return" from the main program).
1229
1230 Version 1.4.6 (built with libpng-1.0.8rc1)
1231
1232 Fixed bug in color-counting of noninterlaced images.
1233
1234 Added capability of processing multiple rows at a time (disabled by
1235 default because it turns out to be no faster).
1236
1237 Replaced "return" statements in main() with "exit" statements.
1238 Force exit instead of return with "-exit" argument.
1239
1240 Added the UCITA disclaimers to the help output.
1241
1242 Version 1.4.5 (built with libpng-1.0.7rc2 and cexcept-1.0.0)
1243
1244 Added color-counting and palette-building capability (enable by
1245 defining PNGCRUSH_COUNT_COLORS). In a future version, this will
1246 give pngcrush the ability to reduce RGBA images to indexed-color
1247 or grayscale when fewer than 257 RGBA combinations are present,
1248 and no color is present that requires 16-bit precision. For now,
1249 it only reports the frequencies.
1250
1251 Added "-fix" option, for fixing bad CRCs and other correctable
1252 conditions.
1253
1254 Write sBIT.alpha=1 when adding an opaque alpha channel and sBIT
1255 is present.
1256
1257 Identify the erroneous 2615-byte sRGB monitor profile being written
1258 by Photoshop 5.5, which causes many apps to crash, and replace it with
1259 an sRGB chunk.
1260
1261 Added a check for input and output on different devices before rejecting
1262 the output file as being the same as the input file based on inode.
1263
1264 Added some UCITA language to the disclaimer.
1265
1266 Version 1.4.4 (built with libpng-1.0.6i and cexcept-0.6.3)
1267
1268 Can be built on RISC OS platforms, thanks to Darren Salt.
1269
1270 Version 1.4.3 (built with libpng-1.0.6h and cexcept-0.6.3)
1271
1272 Reduced scope of Try/Catch blocks to avoid nesting them, and
1273 removed returns from within the Try blocks, where they are not
1274 allowed.
1275
1276 Removed direct access to the png structure when possible, and isolated
1277 the remaining direct accesses to the png structure into new
1278 png_get_compression_buffer_size(), png_set_compression_buffer_size(),
1279 and png_set_unknown_chunk_location() functions that were installed
1280 in libpng version 1.0.6g.
1281
1282 Version 1.4.2 (built with libpng-1.0.6f and cexcept-0.6.0)
1283
1284 Removes extra IDAT chunks (such as found in some POV-ray PNGs) with
1285 a warning instead of bailing out (this feature requires libpng-1.0.6f
1286 or later, compiled with "#define PNG_ABORT()").
1287
1288 Removed old setjmp interface entirely.
1289
1290 Version 1.4.1 (built with libpng-1.0.6e and cexcept-0.6.0)
1291
1292 Uses cexcept.h for error handling instead of the libpng built-in
1293 setjmp/longjmp mechanism. See http://cexcept.sf.net/
1294
1295 Pngcrush.c will now run when compiled with old versions of libpng back
1296 to version 0.96, although some features will not be available.
1297
1298 Version 1.4.0 (built with libpng-1.0.6 + libpng-1.0.6-patch-a)
1299
1300 Version 1.3.6 (built with libpng-1.0.5v)
1301
1302 RGB to Grayscale conversion is more accurate (15-bit instead of 8-bit)
1303 and now uses only integer arithmetic.
1304
1305 "#ifdefed" out PNG_READ_DITHER
1306
1307 Changed "Compressed" to "Uncompressed" in help for -itxt.
1308
1309 Stifled some compiler warnings
1310
1311 Version 1.3.5 (built with libpng-1.0.5s)
1312
1313 Add test on stat_buf.st_size to verify fpin==fpout, because stat in
1314 MSVC++6.0 standard version returns stat_buf.st_ino=0 for all files.
1315
1316 Revised pngcrush.h to make it easier to control PNG_ZBUF_SIZE and
1317 PNG_NO_FLOATING_POINT_SUPPORTED from a makefile.
1318
1319 Restored ability to enter "replace_gamma" value as a float even when
1320 floating point arithmetic is not enabled.
1321
1322 Enabled removing tEXt, zTXt, or iTXt chunks by chunk type, i.e.,
1323 "-rem tEXt" only removes tEXt chunks, while "-rem text" removes all
1324 three types of text chunk.
1325
1326 Removed definition of TOO_FAR from pngcrush.h
1327
1328 Uses new libpng error handler; if a file has errors, pngcrush now will
1329 continue on and compress the remaining files instead of bailing out.
1330
1331 Version 1.3.4 (built with libpng-1.0.5m)
1332
1333 Do not allow pngcrush to overwrite the input file.
1334
1335 Version 1.3.3 (built with libpng-1.0.5m)
1336
1337 Restored ability to enter gamma as a float even when floating point
1338 arithmetic is not enabled.
1339
1340 Version 1.3.2 (built with libpng-1.0.5k)
1341
1342 Renamed "dirname" to "directory_name" to avoid conflict with "dirname"
1343 that appears in string.h on some platforms.
1344
1345 Fixed "PNG_NO_FLOAING_POINT" typo in pngcrush.h
1346
1347 "#ifdefed" out parts of the help screen for options that are unsupported.
1348
1349 Version 1.3.1 (built with libpng-1.0.5k): Eliminated some spurious warnings
1350 that were being issued by libpng-1.0.5j. Added -itxt, -ztxt, and
1351 -zitxt descriptions to the help screen.
1352
1353 Dropped explicit support for pCAL, hIST, sCAL, sPLT, iCCP, tIME, and
1354 cHRM chunks and handle them as unknown but safe-to-copy instead, using
1355 new png_handle_as_unknown function available in libpng-1.0.5k.
1356
1357 Version 1.3.0 (built with libpng-1.0.5j): Added support for handling
1358 unknown chunks.
1359
1360 pngcrush is now fixed-point only, unless PNG_NO_FLOATING_POINT_SUPPORTED
1361 is undefined in pngcrush.h.
1362
1363 Added support for the iCCP, iTXt, sCAL, and sPLT chunks, which
1364 are now supported by libpng (since libpng-1.0.5j). None of these have
1365 been adequately tested.
1366
1367 "#ifdefed" out more unused code (weighted filters and progressive read;
1368 this saves about 15k in the size of the executable).
1369
1370 Moved the special definitions from pngconf.h into a new pngcrush.h
1371
1372 Disallow 256-byte compression window size when writing, to work around
1373 an apparent zlib bug. Either deflate was producing incorrect results in a
1374 21x21 4-bit image or inflate was decoding it incorrectly; the uncompressed
1375 stream is 252 bytes, which is uncomfortably close to the resulting
1376 256-byte compression window. This workaround can be removed when zlib
1377 is fixed.
1378
1379 The "-m method" can be used any of the 124 methods, without having to
1380 specify the filter, level, and strategy, instead of just the first 10.
1381
1382 Version 1.2.1 (built with libpng-1.0.5f): Fixed -srgb parameter so it
1383 really does take an argument, and so it continues to use "0" if an
1384 integer does not follow the -srgb.
1385
1386 Added "-plte_len n" argument for truncating the PLTE. Be sure not to
1387 truncate it to less than the greatest index actually appearing in IDAT.
1388
1389 Version 1.2.0: Removed registration requirement. Added open source
1390 license. Redefined TOO_FAR=32k in deflate.c.
1391
1392 Changes prior to going "open source":
1393
1394 Version 1.1.8: built with libpng-1.0.5a. Runs OK with pngvcrd.c.
1395
1396 Version 1.1.7: added ability to add tEXt/zTXt chunks. Fixed bug with
1397 closing a file that was not opened when using "pngcrush -n". Fixed
1398 bug with tEXt/zTXt chunks after IDAT not being copied.
1399 Added alpha to the displayed palette table. Rebuilt with libpng-1.0.5.
1400
1401 Version 1.1.6: fixed bug with one file left open after each image is
1402 processed
1403
1404 Version 1.1.5: Shorten or remove tRNS chunks that are all opaque or have
1405 opaque entries at the end. Added timing report.
1406
1407 Version 1.1.4: added ability to restrict brute_force to one or more filter
1408 types, compression levels, or compression strategies.
1409
1410 #endif /* end of changelog */
1411
1412 static int verbose = 0;
1413 static int show_warnings = 0; /* =1 to show warnings even with verbose < 0 */
1414 static int copy_idat = 0; /* = 1 to simply copy the IDAT chunk data */
1415
1416 /* Experimental: define these if you wish, but, good luck.
1417 #define PNGCRUSH_COUNT_COLORS
1418 #define PNGCRUSH_MULTIPLE_ROWS
1419 */
1420
1421 #define PNGCRUSH_LARGE
1422
1423 #define PNGCRUSH_ROWBYTES(pixel_bits, width) \
1424 ((pixel_bits) >= 8 ? \
1425 ((png_size_t)(width) * (((png_size_t)(pixel_bits)) >> 3)) : \
1426 (( ((png_size_t)(width) * ((png_size_t)(pixel_bits))) + 7) >> 3) )
1427
1428 /* Suppress libpng pedantic warnings */
1429 #if 0
1430 #define PNG_DEPSTRUCT /* Access to this struct member is deprecated */
1431 #endif
1432
1433 #ifndef PNGCRUSH_TIMERS
1434 # define PNGCRUSH_TIMERS 4
1435 #endif
1436
1437 #if PNGCRUSH_TIMERS > 0
1438
1439 /* TIMER function
1440 ===== ======================
1441 set in pngcrush.c:
1442 0 total time
1443 1 total decode
1444 2 total encode
1445 3 total other
1446 set in pngread.c:
1447 4 decode deinterlace
1448 5 decode filter 0 (none)
1449 6 decode filter 1 (sub)
1450 7 decode filter 2 (up)
1451 8 decode filter 3 (avg)
1452 9 decode filter 4 (paeth)
1453 set in pngwutil.c:
1454 10 encode filter setup
1455 */
1456 #undef _POSIX_C_SOURCE
1457 #define _POSIX_C_SOURCE 199309L /* for clock_gettime */
1458
1459 #include <time.h>
1460
1461 #ifdef CLOCKS_PER_SECOND
1462 # if CLOCKS_PER_SECOND == '"1000"'
1463 # undef CLOCKS_PER_SEC
1464 # endif
1465 #endif
1466
1467 #ifndef CLOCKS_PER_SEC
1468 # define CLOCKS_PER_SEC 1000
1469 #endif
1470
1471 #ifdef __STDC__
1472 # define TIME_T clock_t
1473 #else
1474 # if CLOCKS_PER_SEC <= 100
1475 # define TIME_T long
1476 # else
1477 # define TIME_T float
1478 # endif
1479 #endif
1480
1481 #ifdef __APPLE__
1482 # include <AvailabilityMacros.h>
1483 #endif
1484
1485 /* As in GraphicsMagick */
1486 # if PNGCRUSH_USE_CLOCK_GETTIME == 0
1487 # define PNGCRUSH_USING_CLOCK "clock()"
1488 # elif defined(CLOCK_HIGHRES) /* Solaris */
1489 # define PNGCRUSH_CLOCK_ID CLOCK_HIGHRES
1490 # define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_HIGHRES,&t)"
1491 # define PNGCRUSH_USE_CLOCK_GETTIME 1
1492 # elif defined(CLOCK_MONOTONIC_RAW) /* Linux */
1493 # define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC_RAW
1494 # define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC_RAW,&t)"
1495 # define PNGCRUSH_USE_CLOCK_GETTIME 1
1496 # elif defined(CLOCK_MONOTONIC_PRECISE) /* FreeBSD */
1497 # define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC_PRECISE
1498 # define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC_PRECISE,&t)"
1499 # define PNGCRUSH_USE_CLOCK_GETTIME 1
1500 # elif defined(CLOCK_MONOTONIC) /* Linux, FreeBSD & macOS Sierra & up */ && \
1501 !(defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
1502 # define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC
1503 # define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC,&t)"
1504 # define PNGCRUSH_USE_CLOCK_GETTIME 1
1505 # else
1506 # define PNGCRUSH_USING_CLOCK "clock()"
1507 # undef PNGCRUSH_USE_CLOCK_GETTIME
1508 # define PNGCRUSH_USE_CLOCK_GETTIME 0
1509 # endif
1510 #else /* PNGCRUSH_TIMERS */
1511 # define PNGCRUSH_USING_CLOCK "clock()"
1512 # define PNGCRUSH_USE_CLOCK_GETTIME 0
1513 #endif
1514
1515 #ifndef LIBPNG_UNIFIED
1516 #include <png.h>
1517 #define PNGCRUSH_TIMER_UINT_API extern unsigned int PNGAPI
1518 #define PNGCRUSH_TIMER_VOID_API extern void PNGAPI
1519 #else
1520 #define PNGCRUSH_TIMER_UINT_API unsigned int
1521 #define PNGCRUSH_TIMER_VOID_API void
1522 #endif
1523
1524 #define PNGCRUSH_TIMER_DECODE 1
1525 #define PNGCRUSH_TIMER_ENCODE 2
1526 #define PNGCRUSH_TIMER_MISC 3
1527 #define PNGCRUSH_TIMER_TOTAL 0
1528
1529 static unsigned int pngcrush_timer_hits[PNGCRUSH_TIMERS];
1530 static unsigned int pngcrush_timer_secs[PNGCRUSH_TIMERS];
1531 static unsigned int pngcrush_timer_nsec[PNGCRUSH_TIMERS];
1532 static unsigned int pngcrush_clock_secs[PNGCRUSH_TIMERS];
1533 static unsigned int pngcrush_clock_nsec[PNGCRUSH_TIMERS];
1534
1535 PNGCRUSH_TIMER_UINT_API
1536 pngcrush_timer_get_seconds(unsigned int n);
1537 PNGCRUSH_TIMER_UINT_API
1538 pngcrush_timer_get_hits(unsigned int n);
1539 PNGCRUSH_TIMER_UINT_API
1540 pngcrush_timer_get_nanoseconds(unsigned int n);
1541 PNGCRUSH_TIMER_VOID_API
1542 pngcrush_timer_reset(unsigned int n);
1543 PNGCRUSH_TIMER_VOID_API
1544 pngcrush_timer_start(unsigned int n);
1545 PNGCRUSH_TIMER_VOID_API
1546 pngcrush_timer_stop(unsigned int n);
1547
1548 #if PNGCRUSH_TIMERS > 0
1549 PNGCRUSH_TIMER_UINT_API
1550 pngcrush_timer_get_hits(unsigned int n)
1551 {
1552 if (n < PNGCRUSH_TIMERS)
1553 {
1554 return pngcrush_timer_hits[n];
1555 }
1556 return 0;
1557 }
1558 PNGCRUSH_TIMER_UINT_API
1559 pngcrush_timer_get_seconds(unsigned int n)
1560 {
1561 if (n < PNGCRUSH_TIMERS)
1562 {
1563 return pngcrush_timer_secs[n];
1564 }
1565 return 0;
1566 }
1567 PNGCRUSH_TIMER_UINT_API
1568 pngcrush_timer_get_nanoseconds(unsigned int n)
1569 {
1570 if (n < PNGCRUSH_TIMERS)
1571 {
1572 return pngcrush_timer_nsec[n];
1573 }
1574 return 0;
1575 }
1576 PNGCRUSH_TIMER_VOID_API
1577 pngcrush_timer_reset(unsigned int n)
1578 {
1579 if (n < PNGCRUSH_TIMERS)
1580 {
1581 pngcrush_timer_secs[n] = 0;
1582 pngcrush_timer_nsec[n] = 0;
1583 pngcrush_timer_hits[n] = 0;
1584 }
1585 }
1586 PNGCRUSH_TIMER_VOID_API
1587 pngcrush_timer_start(unsigned int n)
1588 {
1589 if (verbose >= 0 && n < PNGCRUSH_TIMERS)
1590 {
1591 #if PNGCRUSH_USE_CLOCK_GETTIME
1592 struct timespec t;
1593 clock_gettime(PNGCRUSH_CLOCK_ID, &t);
1594 pngcrush_clock_secs[n] = t.tv_sec;
1595 pngcrush_clock_nsec[n] = t.tv_nsec;
1596 #else
1597 TIME_T t = clock();
1598 pngcrush_clock_secs[n] = t/CLOCKS_PER_SEC;
1599 pngcrush_clock_nsec[n] = (t*1000000000/CLOCKS_PER_SEC) -
1600 pngcrush_clock_secs[n]*1000000000;
1601 #endif
1602 }
1603 }
1604 PNGCRUSH_TIMER_VOID_API
1605 pngcrush_timer_stop(unsigned int n)
1606 {
1607 if (verbose >= 0 && n < PNGCRUSH_TIMERS)
1608 {
1609 unsigned long seconds;
1610 unsigned long nseconds;
1611 unsigned long delta_secs;
1612 unsigned long delta_nsec;
1613 #if PNGCRUSH_USE_CLOCK_GETTIME
1614 struct timespec t;
1615 clock_gettime(PNGCRUSH_CLOCK_ID, &t);
1616 seconds = t.tv_sec;
1617 nseconds = t.tv_nsec;
1618 #else
1619 TIME_T t = clock();
1620 seconds = t/CLOCKS_PER_SEC;
1621 nseconds = (t*1000000000/CLOCKS_PER_SEC) - seconds*1000000000;
1622 #endif
1623 delta_secs = (unsigned int)seconds - pngcrush_clock_secs[n];
1624 if ((unsigned long)nseconds < pngcrush_clock_nsec[n])
1625 {
1626 delta_nsec = 1000000000;
1627 delta_secs--;
1628 }
1629 else
1630 {
1631 delta_nsec = 0;
1632 }
1633
1634 delta_nsec += (unsigned long)nseconds - pngcrush_clock_nsec[n];
1635 pngcrush_timer_secs[n] += delta_secs;
1636 pngcrush_timer_nsec[n] += delta_nsec;
1637
1638 if (pngcrush_timer_nsec[n] >= 1000000000)
1639 {
1640 pngcrush_timer_nsec[n] -= 1000000000;
1641 pngcrush_timer_secs[n]++;
1642 }
1643
1644 pngcrush_clock_secs[n] = (unsigned long)seconds;
1645 pngcrush_clock_nsec[n] = (unsigned long)nseconds;
1646 pngcrush_timer_hits[n]++;
1647 }
1648 }
1649
1650 static unsigned long pngcrush_timer_min_secs[PNGCRUSH_TIMERS];
1651 static unsigned long pngcrush_timer_min_nsec[PNGCRUSH_TIMERS];
1652 #endif /* PNGCRUSH_TIMERS */
1653
1654
1655 #ifdef ZLIB_AMALGAMATED
1656 /* See
1657 https://blog.forrestthewoods.com/
1658 improving-open-source-with-amalgamation-cf293592c5f4#.g9fb2tyhs
1659 */
1660 #include "zlib_amalg.c"
1661 #define ZLIB_H
1662 #endif /* ZLIB_AMALGAMATED */
1663
1664 #ifdef ZLIB_UNIFIED /* Not working */
1665 #include "zutil.h"
1666
1667 #include "adler32.c"
1668 #undef DO1
1669 #undef DO8
1670
1671 #include "compress.c"
1672 #include "crc32.c"
1673 #include "deflate.c"
1674 #include "infback.c"
1675 #undef PULLBYTE
1676
1677 #include "inffast.c"
1678 #undef CHECK
1679 #undef CODES
1680 #undef DISTS
1681 #undef DONE
1682 #undef LENGTH
1683 #undef LENS
1684
1685 #include "inflate.c"
1686 #undef CHECK
1687 #undef CODES
1688 #undef DISTS
1689 #undef DONE
1690 #undef LENGTH
1691 #undef LENS
1692 #undef PULLBYTE
1693
1694 #include "inftrees.c"
1695 #undef CHECK
1696 #undef CODES
1697 #undef DISTS
1698 #undef DONE
1699 #undef LENGTH
1700 #undef LENS
1701
1702 #include "trees.c"
1703 #include "uncompr.c"
1704 #include "zutil.c"
1705 #endif /* ZLIB_UNIFIED */
1706
1707 #ifdef LIBPNG_UNIFIED
1708 #include "pngcrush.h"
1709 #include "png.c"
1710 #include "pngerror.c"
1711 #include "pngget.c"
1712 #include "pngmem.c"
1713 #include "pngpread.c"
1714 #include "pngread.c"
1715 #include "pngrio.c"
1716 #include "pngrtran.c"
1717 #include "pngrutil.c"
1718 #include "pngset.c"
1719 #include "pngtrans.c"
1720 #include "pngwio.c"
1721 #include "pngwrite.c"
1722 #include "pngwtran.c"
1723 #include "pngwutil.c"
1724 #ifdef PNGCRUSH_USE_ARM_NEON
1725 # include "arm_init.c"
1726 # include "filter_neon_intrinsics.c"
1727 #endif
1728 #ifdef PNGCRUSH_USE_MIPS_NSA
1729 # include "mips_init.c"
1730 # include "filter_msa_intrinsics.c"
1731 #endif
1732 #ifdef PNGCRUSH_USE_INTEL_SSE
1733 # include "intel_init.c"
1734 # include "filter_sse2_intrinsics.c"
1735 #endif
1736 #ifdef PNGCRUSH_USE_POWERPC_VSX
1737 # include "powerpc_init.c"
1738 # include "filter_vsx_intrinsics.c"
1739 #endif
1740 #endif /* LIBPNG_UNIFIED */
1741
1742 #include "png.h"
1743
1744 #ifndef PNGCBAPI /* Needed when building with libpng-1.4.x and earlier */
1745 # define PNGCBAPI PNGAPI
1746 #endif
1747
1748 /* internal libpng macros */
1749
1750 #ifdef PNG_LIBPNG_VER
1751 #define PNGCRUSH_LIBPNG_VER PNG_LIBPNG_VER
1752 #else
1753 /*
1754 * This must agree with PNG_LIBPNG_VER; you have to define it manually
1755 * here if you are using libpng-1.0.6h or earlier
1756 */
1757 #define PNGCRUSH_LIBPNG_VER 10007
1758 #endif
1759
1760 #define PNGCRUSH_UNUSED(param) (void)param;
1761 #define pngcrush_get_uint_31 png_get_uint_31
1762 #define pngcrush_get_uint_32 png_get_uint_32
1763 #define pngcrush_save_uint_32 png_save_uint_32
1764
1765 #undef PNG_ABORT
1766 #if (PNGCRUSH_LIBPNG_VER < 10400)
1767 /* This allows png_default_error() to return, when it is called after our
1768 * own exception handling, which only returns after "Too many IDAT's",
1769 * or anything else that we might want to handle as a warning instead of
1770 * an error. Doesn't work in libpng-1.4.0 and later; there we use
1771 * png_benign_error() instead.
1772 */
1773 # define PNG_ABORT() (void)0
1774 #elif (PNGCRUSH_LIBPNG_VER < 10700)
1775 # define PNG_ABORT() abort()
1776 #else
1777 # define PNG_ABORT abort();
1778 #endif
1779
1780 #if (PNGCRUSH_LIBPNG_VER < 10500)
1781 /* Two macros to return the first row and first column of the original,
1782 * full, image which appears in a given pass. 'pass' is in the range 0
1783 * to 6 and the result is in the range 0 to 7.
1784 */
1785 #define PNG_PASS_START_ROW(pass) (((1&~(pass))<<(3-((pass)>>1)))&7)
1786 #define PNG_PASS_START_COL(pass) (((1& (pass))<<(3-(((pass)+1)>>1)))&7)
1787
1788 /* A macro to return the offset between pixels in the output row for a pair of
1789 * pixels in the input - effectively the inverse of the 'COL_SHIFT' macro that
1790 * follows. Note that ROW_OFFSET is the offset from one row to the next whereas
1791 * COL_OFFSET is from one column to the next, within a row.
1792 */
1793 #define PNG_PASS_ROW_OFFSET(pass) ((pass)>2?(8>>(((pass)-1)>>1)):8)
1794 #define PNG_PASS_COL_OFFSET(pass) (1<<((7-(pass))>>1))
1795
1796 /* Two macros to help evaluate the number of rows or columns in each
1797 * pass. This is expressed as a shift - effectively log2 of the number or
1798 * rows or columns in each 8x8 tile of the original image.
1799 */
1800 #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
1801 #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
1802
1803 /* Hence two macros to determine the number of rows or columns in a given
1804 * pass of an image given its height or width. In fact these macros may
1805 * return non-zero even though the sub-image is empty, because the other
1806 * dimension may be empty for a small image.
1807 */
1808 #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
1809 -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
1810 #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
1811 -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
1812 #endif /* PNGCRUSH_LIBPNG_VER < 10500 */
1813
1814 #if PNGCRUSH_LIBPNG_VER >= 10500
1815 #if !defined(ZLIB_AMALGAMATED) && !defined(ZLIB_UNIFIED)
1816 /* "#include <zlib.h>" is not provided by libpng15 */
1817 #ifdef PNGCRUSH_H
1818 /* Use the bundled zlib */
1819 # include "zlib.h"
1820 #else
1821 /* Use the system zlib */
1822 # include <zlib.h>
1823 #endif
1824 #endif /* ZLIB_AMALGAMATED || ZLIB_UNIFIED */
1825
1826 /* Not provided by libpng16 */
1827 # include <string.h>
1828
1829 /* The following became unavailable in libpng16 (and were
1830 * deprecated in libpng14 and 15)
1831 */
1832 # ifdef _WINDOWS_ /* Favor Windows over C runtime fns */
1833 # define png_memcmp memcmp
1834 # define png_memcpy CopyMemory
1835 # define png_memset memset
1836 # else
1837 # define png_memcmp memcmp /* SJT: added */
1838 # define png_memcpy memcpy
1839 # define png_memset memset
1840 # endif
1841 #endif /* PNGCRUSH_LIBPNG_VER >= 10500 */
1842
1843 #if PNGCRUSH_LIBPNG_VER < 10800 || defined(PNGCRUSH_H)
1844
1845 /* Changed in version 0.99 */
1846 #if PNGCRUSH_LIBPNG_VER < 99
1847 # undef PNG_CONST
1848 # ifndef PNG_NO_CONST
1849 # define PNG_CONST const
1850 # else
1851 # define PNG_CONST
1852 # endif
1853 #endif
1854
1855 #ifndef LIBPNG_UNIFIED
1856 #define PNG_IDAT const png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
1857 #define PNG_IHDR const png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
1858 #define PNG_acTL const png_byte png_acTL[5] = { 97, 99, 84, 76, '\0'}
1859 #define PNG_dSIG const png_byte png_dSIG[5] = {100, 83, 73, 71, '\0'}
1860 #define PNG_fcTL const png_byte png_fcTL[5] = {102, 99, 84, 76, '\0'}
1861 #define PNG_fdAT const png_byte png_fdAT[5] = {102, 100, 65, 84, '\0'}
1862 #define PNG_iCCP const png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
1863 #define PNG_IEND const png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
1864 #endif
1865
1866 /* GRR 20050220: added these, which apparently aren't defined anywhere else */
1867 /* GRP 20110714: define PNG_UINT_32_NAME macro and used that instead */
1868 #define PNG_UINT_32_NAME(a,b,c,d) \
1869 ((png_uint_32) ((a) & 0xff) << 24 | \
1870 ((png_uint_32) (b) << 16) | \
1871 ((png_uint_32) (c) << 8) | \
1872 ((png_uint_32) (d) ))
1873 #ifndef PNG_UINT_IHDR
1874 # define PNG_UINT_IHDR PNG_UINT_32_NAME(73, 72, 68, 82)
1875 #endif
1876
1877 #ifndef PNG_UINT_IDAT
1878 # define PNG_UINT_IDAT PNG_UINT_32_NAME(73, 68, 65, 84)
1879 #endif
1880
1881 #ifndef PNG_UINT_IEND
1882 # define PNG_UINT_IEND PNG_UINT_32_NAME(73, 69, 78, 68)
1883 #endif
1884
1885 #ifndef PNG_UINT_PLTE
1886 # define PNG_UINT_PLTE PNG_UINT_32_NAME(80, 76, 84, 69)
1887 #endif
1888
1889 #ifndef PNG_UINT_bKGD
1890 # define PNG_UINT_bKGD PNG_UINT_32_NAME(98, 75, 71, 68)
1891 #endif
1892
1893 /* glennrp added CgBI at pngcrush-1.6.16 */
1894 #ifndef PNG_UINT_CgBI
1895 # define PNG_UINT_CgBI PNG_UINT_32_NAME(67,103, 66, 73)
1896 #endif
1897
1898 /* glennrp added acTL, fcTL, and fdAT at pngcrush-1.7.0 */
1899 # define PNG_UINT_acTL PNG_UINT_32_NAME(97, 99, 84, 76)
1900 # define PNG_UINT_fcTL PNG_UINT_32_NAME(102, 99, 84, 76)
1901 # define PNG_UINT_fdAT PNG_UINT_32_NAME(102,100, 65, 84)
1902
1903 #ifndef PNG_UINT_cHRM
1904 # define PNG_UINT_cHRM PNG_UINT_32_NAME(99, 72, 82, 77)
1905 #endif
1906
1907 #ifndef PNG_UINT_dSIG
1908 # define PNG_UINT_dSIG PNG_UINT_32_NAME(100, 83, 73, 71)
1909 #endif
1910
1911 #ifndef PNG_UINT_gAMA
1912 # define PNG_UINT_gAMA PNG_UINT_32_NAME(103, 65, 77, 65)
1913 #endif
1914
1915 #ifndef PNG_UINT_hIST
1916 # define PNG_UINT_hIST PNG_UINT_32_NAME(104, 73, 83, 84)
1917 #endif
1918
1919 #ifndef PNG_UINT_iCCP
1920 # define PNG_UINT_iCCP PNG_UINT_32_NAME(105, 67, 67, 80)
1921 #endif
1922
1923 #ifndef PNG_UINT_iTXt
1924 # define PNG_UINT_iTXt PNG_UINT_32_NAME(105, 84, 88, 116)
1925 #endif
1926
1927 #ifndef PNG_UINT_oFFs
1928 # define PNG_UINT_oFFs PNG_UINT_32_NAME(111, 70, 70, 115)
1929 #endif
1930
1931 #ifndef PNG_UINT_pCAL
1932 # define PNG_UINT_pCAL PNG_UINT_32_NAME(112, 67, 65, 76)
1933 #endif
1934
1935 #ifndef PNG_UINT_pHYs
1936 # define PNG_UINT_pHYs PNG_UINT_32_NAME(112, 72, 89, 115)
1937 #endif
1938
1939 #ifndef PNG_UINT_sBIT
1940 # define PNG_UINT_sBIT PNG_UINT_32_NAME(115, 66, 73, 84)
1941 #endif
1942
1943 #ifndef PNG_UINT_sCAL
1944 # define PNG_UINT_sCAL PNG_UINT_32_NAME(115, 67, 65, 76)
1945 #endif
1946
1947 #ifndef PNG_UINT_sPLT
1948 # define PNG_UINT_sPLT PNG_UINT_32_NAME(115, 80, 76, 84)
1949 #endif
1950
1951 #ifndef PNG_UINT_sRGB
1952 # define PNG_UINT_sRGB PNG_UINT_32_NAME(115, 82, 71, 66)
1953 #endif
1954
1955 /* glennrp added sTER at pngcrush-1.6.10 */
1956 #ifndef PNG_UINT_sTER
1957 # define PNG_UINT_sTER PNG_UINT_32_NAME(115, 84, 69, 82)
1958 #endif
1959
1960 #ifndef PNG_UINT_tEXt
1961 # define PNG_UINT_tEXt PNG_UINT_32_NAME(116, 69, 88, 116)
1962 #endif
1963
1964 #ifndef PNG_UINT_tIME
1965 # define PNG_UINT_tIME PNG_UINT_32_NAME(116, 73, 77, 69)
1966 #endif
1967
1968 #ifndef PNG_UINT_tRNS
1969 # define PNG_UINT_tRNS PNG_UINT_32_NAME(116, 82, 78, 83)
1970 #endif
1971
1972 #ifndef PNG_UINT_zTXt
1973 # define PNG_UINT_zTXt PNG_UINT_32_NAME(122, 84, 88, 116)
1974 #endif
1975
1976 #ifndef LIBPNG_UNIFIED
1977 #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
1978 #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
1979 #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
1980 #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
1981 #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
1982 PNG_FLAG_CRC_ANCILLARY_NOWARN)
1983 #define PNG_PACK 0x0004
1984 #define PNG_DITHER 0x0040
1985 #define PNG_BACKGROUND 0x0080
1986 #define PNG_16_TO_8 0x0400
1987 #define PNG_RGBA 0x0800
1988 #define PNG_EXPAND 0x1000
1989 #define PNG_GAMMA 0x2000
1990 #define PNG_GRAY_TO_RGB 0x4000
1991 #define PNG_FILLER 0x8000L
1992 #define PNG_USER_TRANSFORM 0x100000L
1993 #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
1994 #endif /* LIBPNG_UNIFIED */
1995
1996 /*
1997 * We don't need some of the extra libpng transformations
1998 * so they are ifdef'ed out in pngcrush.h, which is included by
1999 * pngcrush's local copy of libpng's pngconf.h which is included
2000 * by png.h
2001 *
2002 */
2003
2004 /* Defined so I can write to a file on gui/windowing platforms */
2005 #if 0 /* Change this to "#if 1" if you need to. */
2006 # define STDERR stdout /* for DOS */
2007 #else
2008 # define STDERR stderr
2009 #endif
2010
2011 #ifdef PNG_MNG_FEATURES_SUPPORTED
2012 # define PNGCRUSH_LOCO
2013 #endif
2014
2015 #ifdef PNGCRUSH_H
2016 int png_ignore_crc = 0;
2017 #else
2018 png_uint_32 pngcrush_crc;
2019 #endif
2020
2021 #ifndef PNG_UINT_31_MAX
2022 #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
2023 #endif
2024
2025 /* These macros were renamed in libpng-1.2.6 */
2026 #ifndef PNG_HANDLE_CHUNK_ALWAYS
2027 #define PNG_HANDLE_CHUNK_ALWAYS HANDLE_CHUNK_ALWAYS
2028 #define PNG_HANDLE_CHUNK_NEVER HANDLE_CHUNK_NEVER
2029 #define PNG_HANDLE_CHUNK_IF_SAFE HANDLE_CHUNK_IF_SAFE
2030 #endif
2031
2032 #if defined(__DJGPP__) && ((__DJGPP__ == 2) && (__DJGPP_MINOR__ == 0))
2033 # include <libc/dosio.h> /* for _USE_LFN, djgpp 2.0 only */
2034 #endif
2035
2036 #if ( defined(_Windows) || defined(_WINDOWS) || defined(WIN32) || \
2037 defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || \
2038 defined(__DJGPP__) )
2039 # define SLASH "\\"
2040 # define DOT "."
2041 #else
2042 # ifdef __riscos
2043 # define SLASH "."
2044 # define DOT "/"
2045 # else
2046 # define SLASH "/"
2047 # define DOT "."
2048 # endif
2049 #endif
2050
2051 #define BACK_SLASH "\\"
2052 #define FWD_SLASH "/"
2053
2054 #ifndef GAS_VERSION
2055 # define GAS_VERSION "2.9.5(?)" /* used only in help/usage screen */
2056 #endif
2057
2058 #if !defined(__TURBOC__) && !defined(_MSC_VER) && !defined(_MBCS) && \
2059 !defined(__riscos)
2060 # include <unistd.h>
2061 #endif
2062
2063 #ifndef __riscos
2064 # include <sys/types.h>
2065 # include <sys/stat.h>
2066 # ifndef _MSC_VER
2067 # include <utime.h>
2068 # else
2069 # include <sys/utime.h>
2070 # endif
2071 #endif
2072
2073 #include <stdio.h>
2074 #include <stdlib.h>
2075 #include <time.h>
2076 #include <assert.h>
2077 #include <errno.h>
2078
2079 #if defined(_MBCS) || defined(WIN32) || defined(__WIN32__)
2080 # include <direct.h>
2081 #endif
2082
2083 #define DEFAULT_MODE 0
2084 #define DIRECTORY_MODE 1
2085 #define EXTENSION_MODE 2
2086 #define DIREX_MODE 3
2087 #define OVERWRITE_MODE 4
2088 #define FOPEN(file, how) fopen(file, how)
2089 #define FCLOSE(file) {fclose(file); file=NULL;--number_of_open_files;};
2090
2091 #define P0 if(last_trial && verbose > 0)printf
2092 #define P1 if(verbose > 1)printf
2093 #define P2 if(verbose > 2)printf
2094
2095 #define STRNGIFY_STAGE1(x) #x
2096 #define STRNGIFY(x) STRNGIFY_STAGE1(x)
2097
2098 #define STR_BUF_SIZE 2048
2099 #define MAX_IDAT_SIZE 524288L
2100 #define MAX_METHODS 177
2101 #define MAX_METHODSP1 (MAX_METHODS+1)
2102 #define DEFAULT_METHODS 10
2103 #define FAKE_PAUSE_STRING "P"
2104
2105 #ifdef Z_RLE
2106 # define NUM_STRATEGIES 4
2107 #else
2108 # define NUM_STRATEGIES 3
2109 #endif
2110
2111 #ifdef __TURBOC__
2112 # include <mem.h>
2113 #endif
2114
2115 struct options_help
2116 {
2117 int verbosity; /* if verbose >= this value, then print line */
2118 const char *textline; /* static string with newline chopped off */
2119 };
2120
2121 #ifdef MINGW32
2122 /* enable commandline wildcard interpretation (doesn't necessarily work!) */
2123 int _dowildcard = 1;
2124 #endif
2125
2126 /* Input and output filenames */
2127 static PNG_CONST char *progname;
2128 static PNG_CONST char *inname = "pngtest" DOT "png";
2129 static PNG_CONST char *outname = "pngout" DOT "png";
2130 #ifdef PNGCRUSH_LOCO
2131 static PNG_CONST char *mngname = "mngout" DOT "mng";
2132 #endif
2133 static PNG_CONST char *directory_name = "pngcrush" DOT "bak";
2134 static PNG_CONST char *extension = "_C" DOT "png";
2135
2136 static png_uint_32 width, height;
2137 static png_uint_32 measured_idat_length;
2138 static int found_bKGD = 0;
2139 static int found_color_bKGD = 0;
2140 #ifdef PNG_cHRM_SUPPORTED
2141 static int found_cHRM = 0;
2142 #endif
2143 static int found_gAMA = 0;
2144 static int found_hIST = 0;
2145 static int found_iCCP = 0;
2146 static int found_IDAT = 0;
2147 static int found_sBIT = 0;
2148 static int found_sBIT_max = 0;
2149 static int found_sBIT_different_RGB_bits = 0;
2150 static int found_sRGB = 0;
2151 static int found_tRNS = 0;
2152
2153 static int premultiply = 0;
2154 static int printed_version_info = 0;
2155 static int interlace_method = 0;
2156 #if (PNGCRUSH_LIBPNG_VER < 10400)
2157 png_size_t max_bytes;
2158 #else
2159 png_alloc_size_t max_bytes;
2160 #endif
2161
2162 /* 0: not premultipled
2163 * 1: premultiplied input (input has .ppng suffix)
2164 * 2: premultiplied output (output has .ppng suffix)
2165 * 3: premultiplied input and output (both have .ppng suffix)
2166 *
2167 * .png -> .ppng is OK, do premultiplication.
2168 * .ppng -> .ppng is OK, simply copy data.
2169 * .ppng -> .ppng is not OK because colors are irretrievably lost.
2170 * .ppng -> no output (pngcrush -n) is OK.
2171 *
2172 * To do: Implement this stuff!
2173 */
2174
2175 static int found_CgBI = 0;
2176 static int found_any_chunk = 0;
2177 static int save_apng_chunks = 0; /* 0: output not .apng 1: .apng 2: rejected */
2178 static int found_acTL_chunk = 0; /* 0: not found, 1: found, 2: rejected */
2179 static int image_is_immutable = 0;
2180 static int pngcrush_must_exit = 0;
2181 static int all_chunks_are_safe = 0;
2182 static int number_of_open_files;
2183 static int do_pplt = 0;
2184 #ifdef PNGCRUSH_MULTIPLE_ROWS
2185 static png_uint_32 max_rows_at_a_time = 1;
2186 static png_uint_32 rows_at_a_time;
2187 #endif
2188 char pplt_string[STR_BUF_SIZE];
2189 char *ip, *op, *dot;
2190 char in_string[STR_BUF_SIZE];
2191 char prog_string[STR_BUF_SIZE];
2192 char out_string[STR_BUF_SIZE];
2193 char in_extension[STR_BUF_SIZE];
2194 static int text_inputs = 0;
2195 int text_where[10]; /* 0: no text; 1: before PLTE; 2: after PLTE */
2196 int text_compression[10]; /* -1: uncompressed tEXt; 0: compressed zTXt
2197 1: uncompressed iTXt; 2: compressed iTXt */
2198 char text_text[11*STR_BUF_SIZE+1]; /* It would be nice to png_malloc this but we
2199 don't have a png_ptr yet when we need it. */
2200 char text_keyword[11*80+1];
2201
2202 /* PNG_iTXt_SUPPORTED */
2203 char text_lang[881];
2204 char text_lang_key[881];
2205
2206 /* PNG_iCCP_SUPPORTED */
2207 int iccp_length = 0;
2208 char *iccp_text;
2209 char *iccp_file;
2210 char iccp_name[80];
2211
2212 int best;
2213
2214 char buffer[256];
2215
2216 /* Set up the "cexcept" Try/Throw/Catch exception handler. */
2217 #include "cexcept.h"
2218 define_exception_type(const char *);
2219 extern struct exception_context the_exception_context[1];
2220 struct exception_context the_exception_context[1];
2221 png_const_charp msg;
2222
2223 static png_uint_32 input_length;
2224 static png_uint_32 total_input_length = 0;
2225 static png_uint_32 total_output_length = 0;
2226 static int pngcrush_mode = DEFAULT_MODE;
2227 static int resolution = 0;
2228 static int remove_chunks = 0;
2229 static int output_color_type;
2230 static int output_bit_depth;
2231 static int force_output_color_type = 8;
2232 static int force_output_bit_depth = 0;
2233 static int input_color_type;
2234 static int input_bit_depth;
2235 static int trial;
2236 static int last_trial = 0;
2237 static png_uint_32 pngcrush_write_byte_count;
2238 static png_uint_32 pngcrush_best_byte_count=0xffffffff;
2239
2240 static int salvage = 0;
2241 static int bail = 0; /* if 0, bail out of trials early */
2242 static int check_crc = 0; /* if 0, skip CRC and ADLER32 checks */
2243 /* otherwise check both */
2244 static int force = 1; /* if 1, force output even if IDAT is larger */
2245 static unsigned int benchmark_iterations = 0;
2246
2247
2248 static int blacken = 0; /* if 0, or 2 after the first trial,
2249 do not blacken color samples */
2250
2251 /* Delete these in pngcrush-1.8.0 */
2252 #if 0
2253 static int make_gray = 0; /* if 0, 2, or 3 after the first trial,
2254 do not change color_type to gray */
2255 static int make_opaque = 0; /* if 0, 2, or 3 after the first trial,
2256 do not change color_type to opaque */
2257 static int make_8_bit = 0; /* if 0, 2, or 3 after the first trial,
2258 do not reduce bit_depth from 16 */
2259 static int reduce_palette = 0;
2260 #endif
2261
2262 /* Activate these in pngcrush-1.8.0 */
2263 #if 1
2264 static int noreduce = 1; /* if 0, "-reduce" was specified */
2265 static int make_gray = 1; /* if 0, 2, or 3 after the first trial,
2266 do not change color_type to gray */
2267 static int make_opaque = 1; /* if 0, 2, or 3 after the first trial,
2268 do not change color_type to opaque */
2269 static int make_8_bit = 1; /* if 0, 2, or 3 after the first trial,
2270 do not reduce bit_depth from 16 */
2271 static int reduce_palette = 1;
2272 #endif
2273
2274 static int compression_window;
2275 static int default_compression_window = 15;
2276 static int force_compression_window = 0;
2277 static int compression_mem_level = 9;
2278 static int final_method = 0;
2279 static int brute_force = 0;
2280 static int brute_force_level = 0;
2281 static int brute_force_filter = 0;
2282 static int brute_force_strategy = 0;
2283 static int brute_force_levels[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
2284 static int brute_force_filters[6] = { 1, 1, 1, 1, 1, 1 };
2285 #ifdef Z_RLE
2286 static int brute_force_strategies[NUM_STRATEGIES] = { 1, 1, 1, 1 };
2287 #else
2288 static int brute_force_strategies[NUM_STRATEGIES] = { 1, 1, 1 };
2289 #endif
2290 static int speed = 0;
2291 static int method = 10;
2292 static int pauses = 0;
2293 static int nosave = 0; /* 0: save; 1: do not save */
2294 static int overwrite = 0; /* 1: overwrite the input file instead of
2295 creating a new output file */
2296 static int nofilecheck = 0;
2297 static int no_limits = 0;
2298 static int new_mng = 0;
2299 static png_bytep row_buf;
2300 #ifdef PNGCRUSH_MULTIPLE_ROWS
2301 static png_bytepp row_pointers;
2302 #endif
2303 static int z_strategy;
2304 static int best_of_three;
2305 static int methods_specified = 0;
2306 static int specified_intent = -1;
2307 static int intent = -1;
2308 static int ster_mode = -1;
2309 static int new_time_stamp = 1;
2310 static int plte_len = -1;
2311 #ifdef PNG_FIXED_POINT_SUPPORTED
2312 static int specified_gamma = 0;
2313 static int image_specified_gamma = 0;
2314 static int force_specified_gamma = 0;
2315 #else
2316 static double specified_gamma = 0.0;
2317 static double image_specified_gamma = 0;
2318 static double force_specified_gamma = 0.0;
2319 #endif
2320 static int double_gamma = 0;
2321
2322 static int names;
2323 static int first_name;
2324
2325 static int have_trns = 0;
2326 static png_uint_16 trns_index = 0;
2327 static png_uint_16 trns_red = 0;
2328 static png_uint_16 trns_green = 0;
2329 static png_uint_16 trns_blue = 0;
2330 static png_uint_16 trns_gray = 0;
2331
2332 static png_byte trns_array[256];
2333 static png_byte trans_in[256];
2334 static png_uint_16 num_trans_in;
2335
2336 #if defined(PNG_READ_tRNS_SUPPORTED) && defined(PNG_WRITE_tRNS_SUPPORTED)
2337 png_bytep trans;
2338 int num_trans;
2339 png_color_16p trans_values;
2340 #endif
2341
2342 static int have_bkgd = 0;
2343 static png_uint_16 bkgd_red = 0;
2344 static png_uint_16 bkgd_green = 0;
2345 static png_uint_16 bkgd_blue = 0;
2346 static png_byte bkgd_index = 0;
2347
2348 static png_colorp palette;
2349 static int num_palette;
2350
2351 #ifdef REORDER_PALETTE
2352 static png_byte palette_reorder[256];
2353 #endif
2354
2355 static png_structp read_ptr, write_ptr, mng_ptr;
2356 static png_infop read_info_ptr, write_info_ptr;
2357 static png_infop end_info_ptr;
2358 static png_infop write_end_info_ptr;
2359 static FILE *fpin, *fpout;
2360 png_uint_32 measure_idats(FILE * fp);
2361 #ifdef PNGCRUSH_LOCO
2362 static FILE *mng_out;
2363 static int do_loco = 0;
2364 static int input_format = 0; /* 0: PNG 1: MNG */
2365 static int output_format = 0;
2366 #endif
2367 static int do_color_count;
2368 png_uint_32 pngcrush_measure_idat(png_structp png_ptr);
2369
2370 static png_uint_32 idat_length[MAX_METHODSP1];
2371 static int filter_type, zlib_level;
2372 static png_bytep png_row_filters = NULL;
2373
2374 #if PNGCRUSH_TIMERS > 0
2375 unsigned int pc_timer;
2376 static float t_filter[PNGCRUSH_TIMERS] = {0};
2377 static png_uint_32 filter_count[PNGCRUSH_TIMERS] = {0};
2378 png_uint_32 t_sec;
2379 png_uint_32 t_nsec;
2380 #endif
2381
2382 static png_uint_32 max_idat_size = MAX_IDAT_SIZE; /* increases the IDAT size */
2383
2384 #if 0 /* disabled */
2385 static png_uint_32 crushed_idat_size = 0x3ffffffL;
2386 static int already_crushed = 0;
2387 #endif
2388
2389 int ia;
2390
2391 #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
2392 static /* const */ png_byte chunks_to_ignore[] = {
2393
2394 98, 75, 71 , 68, '\0', /* bKGD */
2395 99, 72, 82, 77, '\0', /* cHRM */
2396 103, 65, 77, 65, '\0', /* gAMA */
2397 104, 73, 83, 84, '\0', /* hIST */
2398 105, 67, 67, 80, '\0', /* iCCP */
2399 105, 84, 88, 116, '\0', /* iTXt */
2400 111, 70, 70, 115, '\0', /* oFFs */
2401 112, 67, 65, 76, '\0', /* pCAL */
2402 112, 72, 89, 115, '\0', /* pHYs */
2403 115, 66, 73, 84, '\0', /* sBIT */
2404 115, 67, 65, 76, '\0', /* sCAL */
2405 115, 80, 76, 84, '\0', /* sPLT */
2406 115, 82, 71, 66, '\0', /* sRGB */
2407 115, 84, 69, 82, '\0', /* sTER */
2408 116, 69, 88, 116, '\0', /* tEXt */
2409 116, 73, 77, 69, '\0', /* tIME */
2410 116, 82, 78, 83, '\0', /* tRNS */
2411 122, 84, 88, 116, '\0' /* zTXt */
2412 };
2413 #endif
2414
2415 /* Prototypes */
2416 static void pngcrush_cexcept_error(png_structp png_ptr,
2417 png_const_charp message);
2418
2419 static void pngcrush_warning(png_structp png_ptr,
2420 png_const_charp message);
2421
2422 void PNGCBAPI pngcrush_default_read_data(png_structp png_ptr, png_bytep data,
2423 png_size_t length);
2424
2425 #ifdef PNGCRUSH_H
2426 void png_read_transform_info(png_structp png_ptr, png_infop info_ptr);
2427 #endif
2428
2429 void PNGCBAPI pngcrush_default_write_data(png_structp png_ptr, png_bytep data,
2430 png_size_t length);
2431
2432 void pngcrush_write_png(png_structp write_pointer, png_bytep data,
2433 png_size_t length);
2434
2435 #ifdef PNG_USER_MEM_SUPPORTED
2436 png_voidp pngcrush_debug_malloc(png_structp png_ptr, png_uint_32 size);
2437 void pngcrush_debug_free(png_structp png_ptr, png_voidp ptr);
2438 #endif
2439
2440 void pngcrush_pause(void);
2441
2442 #ifdef __riscos
2443 static int fileexists(const char *name)
2444 static int filesize(const char *name)
2445 static int mkdir(const char *name, int ignored)
2446 static void setfiletype(const char *name)
2447 #endif
2448
2449 int keep_unknown_chunk(png_const_charp name, char *argv[]);
2450 int keep_chunk(png_const_charp name, char *argv[]);
2451 void show_result(void);
2452 png_uint_32 measure_idats(FILE * fp);
2453 png_uint_32 pngcrush_measure_idat(png_structp png_ptr);
2454
2455 void print_version_info(void);
2456 void print_usage(int retval);
2457
2458 #ifdef PNGCRUSH_H
2459 /* Use unexported functions in the embedded libpng */
2460 # define pngcrush_reset_crc(png_ptr) png_reset_crc(png_ptr)
2461 # define pngcrush_calculate_crc(png_ptr, ptr, length) \
2462 png_calculate_crc(png_ptr, ptr, length)
2463 # define pngcrush_crc_read(png_ptr, buf, length) \
2464 png_crc_read(png_ptr, buf, length)
2465 # define pngcrush_crc_error(png_ptr) png_crc_error(png_ptr)
2466 # define pngcrush_crc_finish(png_ptr, skip) png_crc_finish(png_ptr, skip)
2467
2468 #else
2469 /*
2470 * ============================================================
2471 * We aren't using the bundled libpng functions, so we must
2472 * reproduce the libpng routines that aren't exported by libpng
2473 * ============================================================
2474 */
2475
2476 # if (PNGCRUSH_LIBPNG_VER >= 10209)
2477 # ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
2478 # undef pngcrush_get_uint_32
2479 png_uint_32 pngcrush_get_uint_32(png_bytep buf);
2480 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
2481 png_uint_32 /* PRIVATE */
2482 pngcrush_get_uint_32(png_bytep buf)
2483 {
2484 png_uint_32 i = ((png_uint_32) (*buf & 0xff) << 24) +
2485 (*(buf + 1) << 16) + (*(buf + 2) << 8) + (*(buf + 3)) ;
2486
2487 return (i);
2488 }
2489 # else /*! BIG_ENDIAN */
2490 # define pngcrush_get_uint_32(buf) ( *((png_uint_32p) (buf)))
2491 # endif /* BIG_ENDIAN */
2492
2493 # undef pngcrush_get_uint_31
2494 png_uint_32 pngcrush_get_uint_31(png_structp png_ptr, png_bytep buf);
2495 png_uint_32 /* PRIVATE */
2496 pngcrush_get_uint_31(png_structp png_ptr, png_bytep buf)
2497 {
2498 png_uint_32 i = pngcrush_get_uint_32(buf);
2499 if (i > PNG_UINT_31_MAX)
2500 {
2501 i=0;
2502 png_error(png_ptr, "PNG unsigned integer out of range.\n");
2503 }
2504 return (i);
2505 }
2506
2507 # undef pngcrush_save_uint_32
2508 void pngcrush_save_uint_32(png_bytep buf, png_uint_32 i);
2509 void /* PRIVATE */
2510 pngcrush_save_uint_32(png_bytep buf, png_uint_32 i)
2511 {
2512 buf[0] = (png_byte)((i >> 24) & 0xff);
2513 buf[1] = (png_byte)((i >> 16) & 0xff);
2514 buf[2] = (png_byte)((i >> 8) & 0xff);
2515 buf[3] = (png_byte)(i & 0xff);
2516 }
2517 # endif /* PNGCRUSH_LIBPNG_VER < 10209 */
2518
2519 /*
2520 * Reset the CRC variable to 32 bits of 1's. Care must be taken
2521 * in case CRC is > 32 bits to leave the top bits 0.
2522 */
2523 void PNGAPI
2524 pngcrush_reset_crc(png_structp png_ptr)
2525 {
2526 pngcrush_crc = crc32(0, Z_NULL, 0);
2527 }
2528 /*
2529 * Calculate the CRC over a section of data. We can only pass as
2530 * much data to this routine as the largest single buffer size. We
2531 * also check that this data will actually be used before going to the
2532 * trouble of calculating it.
2533 */
2534 void PNGAPI
2535 pngcrush_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
2536 {
2537 pngcrush_crc = crc32(pngcrush_crc, ptr, (uInt)length);
2538 }
2539
2540 /* Read data, and (optionally) run it through the CRC. */
2541 void PNGAPI
2542 pngcrush_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
2543 {
2544 pngcrush_default_read_data(png_ptr, buf, length);
2545 pngcrush_calculate_crc(png_ptr, buf, length);
2546 }
2547
2548 /* Compare the CRC stored in the PNG file with that calculated by libpng from
2549 * the data it has read thus far.
2550 */
2551 int PNGAPI
2552 pngcrush_crc_error(png_structp png_ptr)
2553 {
2554 png_byte crc_bytes[4];
2555 png_uint_32 crc;
2556
2557 pngcrush_default_read_data(png_ptr, crc_bytes, 4);
2558
2559 crc = pngcrush_get_uint_32(crc_bytes);
2560 return ((int)(crc != pngcrush_crc));
2561 }
2562
2563 /*
2564 * Optionally skip data and then check the CRC. Depending on whether we
2565 * are reading a ancillary or critical chunk, and how the program has set
2566 * things up, we may calculate the CRC on the data and print a message.
2567 * Returns '1' if there was a CRC error, '0' otherwise.
2568 */
2569 int PNGAPI
2570 pngcrush_crc_finish(png_structp png_ptr, png_uint_32 skip)
2571 {
2572 png_size_t i;
2573 png_byte bytes[1024];
2574 png_size_t istop = 1024;
2575
2576 for (i = (png_size_t)skip; i > istop; i -= istop)
2577 {
2578 pngcrush_crc_read(png_ptr, bytes, (png_size_t)1024);
2579 }
2580 if (i)
2581 {
2582 pngcrush_crc_read(png_ptr, bytes, i);
2583 }
2584
2585 if (pngcrush_crc_error(png_ptr))
2586 {
2587 {
2588 png_chunk_error(png_ptr, "CRC error");
2589 }
2590 return (1);
2591 }
2592
2593 return (0);
2594 }
2595 #endif /* PNGCRUSH_H */
2596
2597 #ifdef PNG_STDIO_SUPPORTED
2598 /*
2599 * This is the function that does the actual reading of data. If you are
2600 * not reading from a standard C stream, you should create a replacement
2601 * read_data function and use it at run time with png_set_read_fn(), rather
2602 * than changing the library.
2603 */
2604 void PNGCBAPI pngcrush_default_read_data(png_structp png_ptr, png_bytep data,
2605 png_size_t length)
2606 {
2607 png_FILE_p io_ptr;
2608
2609 if (length == 0)
2610 png_error(png_ptr, "Read Error: invalid length requested");
2611
2612 io_ptr = png_get_io_ptr(png_ptr);
2613
2614 if (fileno(io_ptr) == -1)
2615 png_error(png_ptr, "Read Error: invalid io_ptr");
2616
2617 /*
2618 * fread() returns 0 on error, so it is OK to store this in a png_size_t
2619 * instead of an int, which is what fread() actually returns.
2620 */
2621 if ((png_size_t)fread((void *)data, sizeof (png_byte), length,
2622 io_ptr) != length)
2623 {
2624 png_error(png_ptr, "Read Error: invalid length returned");
2625 #if PNGCRUSH_LIBPNG_VER >= 10700
2626 PNG_ABORT
2627 #else
2628 PNG_ABORT();
2629 #endif
2630 }
2631
2632 clearerr(io_ptr);
2633
2634 if (ferror(io_ptr))
2635 {
2636 clearerr(io_ptr);
2637 png_error(png_ptr, "Read Error: error returned by fread()");
2638 }
2639
2640 if (feof(io_ptr))
2641 {
2642 clearerr(io_ptr);
2643 png_error(png_ptr, "Read Error: unexpected end of file");
2644 }
2645
2646 clearerr(io_ptr);
2647 }
2648 #endif /* PNG_STDIO_SUPPORTED */
2649
2650 #ifdef PNG_STDIO_SUPPORTED
2651 /*
2652 * This is the function that does the actual writing of data. If you are
2653 * not writing to a standard C stream, you should create a replacement
2654 * write_data function and use it at run time with png_set_write_fn(), rather
2655 * than changing the library.
2656 */
2657 void PNGCBAPI pngcrush_default_write_data(png_structp png_ptr, png_bytep data,
2658 png_size_t length)
2659 {
2660 png_uint_32 check;
2661 png_FILE_p io_ptr;
2662
2663 io_ptr = png_get_io_ptr(png_ptr);
2664
2665 check = fwrite(data, 1, length, io_ptr);
2666 if (check != length)
2667 png_error(png_ptr, "Write Error");
2668 }
2669 #endif /* PNG_STDIO_SUPPORTED */
2670
2671 static void pngcrush_warning(png_structp png_ptr,
2672 png_const_charp warning_msg)
2673 {
2674 #if (PNGCRUSH_LIBPNG_VER >= 10700)
2675 /* don't warn about damaged LZ stream due to bailing */
2676 if (bail == 0 && !strcmp(warning_msg, "damaged LZ stream"))
2677 return;
2678 #endif
2679
2680 if (verbose >= 0)
2681 fprintf(stderr, "pngcrush: %s\n", warning_msg);
2682 else
2683 {
2684 if (show_warnings)
2685 fprintf(stderr, "%s: %s\n", inname, warning_msg);
2686 }
2687 return;
2688 }
2689
2690 /* cexcept interface */
2691
2692 static void pngcrush_cexcept_error(png_structp png_ptr,
2693 png_const_charp err_msg)
2694 {
2695
2696 #if 0
2697 /* Handle "bad adaptive filter value" error. */
2698 if (!strcmp(err_msg, "bad adaptive filter value")) {
2699 #ifdef PNG_CONSOLE_IO_SUPPORTED
2700 fprintf(stderr, "\nIn %s, correcting %s\n", inname,err_msg);
2701 #else
2702 pngcrush_warning(png_ptr, err_msg);
2703 #endif
2704 return;
2705 }
2706
2707 #if PNGCRUSH_LIBPNG_VER < 10400
2708 /* Handle "Too many IDAT's found" error. In libpng-1.4.x this became
2709 * a benign error, "Too many IDATs found". This scheme will not work
2710 * in libpng-1.5.0 and later.
2711 */
2712 # ifdef PNGCRUSH_H /* Why would this not work with the system library? */
2713 if (!strcmp(err_msg, "Too many IDAT's found")) {
2714 # ifdef PNG_CONSOLE_IO_SUPPORTED
2715 fprintf(stderr, "\nIn %s, correcting %s\n", inname,err_msg);
2716 # else
2717 pngcrush_warning(png_ptr, err_msg);
2718 # endif
2719 return;
2720 }
2721 # endif /* PNGCRUSH_H */
2722 #endif /* PNGCRUSH_LIBPNG_VER */
2723 #endif /* 0 */
2724
2725 {
2726 Throw err_msg;
2727 }
2728 }
2729
2730
2731 /* START of code to validate memory allocation and deallocation */
2732 #ifdef PNG_USER_MEM_SUPPORTED
2733
2734 /*
2735 * Allocate memory. For reasonable files, size should never exceed
2736 * 64K. However, zlib may allocate more then 64K if you don't tell
2737 * it not to. See zconf.h and png.h for more information. zlib does
2738 * need to allocate exactly 64K, so whatever you call here must
2739 * have the ability to do that.
2740 *
2741 * This piece of code can be compiled to validate max 64K allocations
2742 * by setting MAXSEG_64K in zlib zconf.h *or* PNG_MAX_MALLOC_64K.
2743 */
2744 typedef struct memory_information {
2745 png_uint_32 size;
2746 png_voidp pointer;
2747 struct memory_information *next;
2748 } memory_information;
2749 typedef memory_information *memory_infop;
2750
2751 static memory_infop pinformation = NULL;
2752 static int current_allocation = 0;
2753 static int maximum_allocation = 0;
2754
2755
2756 png_voidp pngcrush_debug_malloc(png_structp png_ptr, png_uint_32 size)
2757 {
2758
2759 /*
2760 * png_malloc has already tested for NULL; png_create_struct calls
2761 * pngcrush_debug_malloc directly (with png_ptr == NULL prior to
2762 * libpng-1.2.0 which is OK since we are not using a user mem_ptr)
2763 */
2764
2765 if (size == 0)
2766 return (png_voidp) (NULL);
2767
2768 /*
2769 * This calls the library allocator twice, once to get the requested
2770 * buffer and once to get a new free list entry.
2771 */
2772 {
2773 memory_infop pinfo = (memory_infop)malloc(sizeof *pinfo);
2774 if (pinfo == NULL)
2775 return (png_voidp) (NULL);
2776 pinfo->size = size;
2777 current_allocation += size;
2778 if (current_allocation > maximum_allocation)
2779 maximum_allocation = current_allocation;
2780 pinfo->pointer = malloc(size);
2781 pinfo->next = pinformation;
2782 pinformation = pinfo;
2783 /* Make sure the caller isn't assuming zeroed memory. */
2784 png_memset(pinfo->pointer, 0xdd, pinfo->size);
2785 if (verbose > 2)
2786 fprintf(STDERR, "Pointer %p allocated %lu bytes\n",
2787 (png_voidp) pinfo->pointer, (unsigned long)size);
2788 return (png_voidp) (pinfo->pointer);
2789 }
2790 }
2791
2792 /* Free a pointer. It is removed from the list at the same time. */
2793 void pngcrush_debug_free(png_structp png_ptr, png_voidp ptr)
2794 {
2795 if (png_ptr == NULL)
2796 fprintf(STDERR, "NULL pointer to pngcrush_debug_free.\n");
2797 if (ptr == 0) {
2798 #if 0 /* This happens all the time. */
2799 fprintf(STDERR, "WARNING: freeing NULL pointer\n");
2800 #endif /* 0 */
2801 return;
2802 }
2803
2804 /* Unlink the element from the list. */
2805 {
2806 memory_infop *ppinfo = &pinformation;
2807 for (;;) {
2808 memory_infop pinfo = *ppinfo;
2809 if (pinfo->pointer == ptr) {
2810 *ppinfo = pinfo->next;
2811 current_allocation -= pinfo->size;
2812 if (current_allocation < 0)
2813 fprintf(STDERR, "Duplicate free of memory\n");
2814 /* We must free the list element too, but first kill
2815 the memory that is to be freed. */
2816 memset(ptr, 0x55, pinfo->size);
2817 if (verbose > 2)
2818 fprintf(STDERR, "Pointer %p freed %lu bytes\n",
2819 (png_voidp) ptr, (unsigned long)pinfo->size);
2820 free(pinfo);
2821 break;
2822 }
2823 if (pinfo->next == NULL) {
2824 fprintf(STDERR, "Pointer %p not found\n",
2825 (png_voidp) ptr);
2826 break;
2827 }
2828 ppinfo = &pinfo->next;
2829 }
2830 }
2831
2832 /* Finally free the data. */
2833 free(ptr);
2834 }
2835
2836 #endif /* PNG_USER_MEM_SUPPORTED */
2837 /* END of code to test memory allocation/deallocation */
2838
2839
2840
2841
2842 void pngcrush_pause(void)
2843 {
2844 if (pauses > 0) {
2845 char keystroke;
2846 fprintf(STDERR, "Press [ENTER] key to continue.\n");
2847 keystroke = (char) getc(stdin);
2848 keystroke = keystroke; /* stifle compiler warning */
2849 }
2850 }
2851
2852
2853 void png_skip_chunk(png_structp png_ptr)
2854 {
2855 png_byte buff[4] = { 0, 0, 0, 0 };
2856 int ib;
2857 unsigned long length;
2858
2859 /* read the length field */
2860 pngcrush_default_read_data(png_ptr, buff, 4);
2861 length = pngcrush_get_uint_31(png_ptr,buff);
2862 /* read the chunk name */
2863 pngcrush_default_read_data(png_ptr, buff, 4);
2864 if (verbose > 0)
2865 printf("Skipping %c%c%c%c chunk.\n",buff[0],buff[1],
2866 buff[2],buff[3]);
2867 /* skip the data and CRC */
2868 for (ib=0; ib<length+4; ib++)
2869 {
2870 png_byte junk[1] = { 0 };
2871 pngcrush_default_read_data(png_ptr, junk, 1);
2872 }
2873 }
2874
2875 #ifndef __riscos
2876 # define setfiletype(x)
2877
2878 #else /* defined(__riscos) */
2879 # include <kernel.h>
2880
2881 /* The riscos/acorn support was contributed by Darren Salt. */
2882 static int fileexists(const char *name)
2883 {
2884 # ifdef __acorn
2885 int ret;
2886 return _swix(8, 3 | 1 << 31, 17, name, &ret) ? 0 : ret;
2887 # else
2888 _kernel_swi_regs r;
2889 r.r[0] = 17;
2890 r.r[1] = (int) name;
2891 return _kernel_swi(8, &r, &r) ? 0 : r.r[0];
2892 # endif
2893 }
2894
2895
2896 static int filesize(const char *name)
2897 {
2898 # ifdef __acorn
2899 int ret;
2900 return _swix(8, 3 | 1 << 27, 17, name, &ret) ? 0 : ret;
2901 # else
2902 _kernel_swi_regs r;
2903 r.r[0] = 17;
2904 r.r[1] = (int) name;
2905 return _kernel_swi(8, &r, &r) ? 0 : r.r[4];
2906 # endif
2907 }
2908
2909
2910 static int mkdir(const char *name, int ignored)
2911 {
2912 # ifdef __acorn
2913 _swi(8, 0x13, 8, name, 0);
2914 return 0;
2915 # else
2916 _kernel_swi_regs r;
2917 r.r[0] = 8;
2918 r.r[1] = (int) name;
2919 r.r[4] = r.r[3] = r.r[2] = 0;
2920 return (int) _kernel_swi(8 | 1 << 31, &r, &r);
2921 # endif
2922 }
2923
2924
2925 static void setfiletype(const char *name)
2926 {
2927 # ifdef __acorn
2928 _swi(8, 7, 18, name, 0xB60);
2929 # else
2930 _kernel_swi_regs r;
2931 r.r[0] = 18;
2932 r.r[1] = (int) name;
2933 r.r[2] = 0xB60;
2934 _kernel_swi(8 | 1 << 31, &r, &r);
2935 # endif
2936 }
2937
2938 #endif /* defined(__riscos) */
2939
2940
2941
2942
2943 /*
2944 * GRR: basically boolean; first arg is chunk name-string (e.g., "tIME" or
2945 * "alla"); second is always full argv[] command line
2946 * - remove_chunks is argv index of *last* -rem arg on command line
2947 * (would be more efficient to build table at time of cmdline processing!)
2948 * (i.e., build removal_list with names or unique IDs or whatever--skip
2949 * excessive string-processing on every single one)
2950 * - reprocesses command line _every_ time called, looking for -rem opts...
2951 * - just like keep_chunk() except that latter sets things_have_changed
2952 * variable and debug stmts say "Removed chunk" (but caller actually does
2953 * so, by choosing not to copy chunk to new file)
2954 * - for any given chunk name, "name" must either match exact command-line
2955 * arg (e.g., -rem fOOb), OR it must match one of the official PNG chunk
2956 * names explicitly listed below AND command-line arg either used all-
2957 * lowercase form or one of "all[ab]" options
2958 */
2959 int keep_unknown_chunk(png_const_charp name, char *argv[])
2960 {
2961 int i;
2962 if (remove_chunks == 0)
2963 return 1; /* no -rem options, so always keeping */
2964 for (i = 1; i <= remove_chunks; i++) {
2965 if (!strncmp(argv[i], "-rem", 4)) {
2966 int allb = 0;
2967 i++;
2968 if (!strncmp(argv[i], "all", 3)) {
2969 allb++; /* all but gamma, but not doing gamma here */
2970 }
2971 if (!strncmp(argv[i], name, 4) /* exact chunk-name match in args */
2972 /* ...or exact match for one of known set, plus args included
2973 * either "alla", "allb", or all-lowercase form of "name" */
2974 || (!strncmp(name, "cHRM", 4)
2975 && (!strncmp(argv[i], "chrm", 4) || allb))
2976 || (!strncmp(name, "dSIG", 4)
2977 && (!strncmp(argv[i], "dsig", 4) || allb))
2978 || (!strncmp(name, "gIFg", 4)
2979 && (!strncmp(argv[i], "gifg", 4) || allb))
2980 || (!strncmp(name, "gIFt", 4)
2981 && (!strncmp(argv[i], "gift", 4) || allb))
2982 || (!strncmp(name, "gIFx", 4)
2983 && (!strncmp(argv[i], "gifx", 4) || allb))
2984 || (!strncmp(name, "hIST", 4)
2985 && (!strncmp(argv[i], "hist", 4) || allb))
2986 || (!strncmp(name, "iCCP", 4)
2987 && (!strncmp(argv[i], "iccp", 4) || allb))
2988 || (!strncmp(name, "pCAL", 4)
2989 && (!strncmp(argv[i], "pcal", 4) || allb))
2990 || (!strncmp(name, "sCAL", 4)
2991 && (!strncmp(argv[i], "scal", 4) || allb))
2992 || (!strncmp(name, "sPLT", 4)
2993 && (!strncmp(argv[i], "splt", 4) || allb))
2994 || (!strncmp(name, "tIME", 4)
2995 && (!strncmp(argv[i], "time", 4) || allb)))
2996 {
2997 return 0;
2998 }
2999 }
3000 }
3001 return 1;
3002 }
3003
3004
3005
3006
3007 int keep_chunk(png_const_charp name, char *argv[])
3008 {
3009 int i;
3010 if (verbose > 2 && last_trial)
3011 fprintf(STDERR, " Read the %s chunk.\n", name);
3012 if (remove_chunks == 0)
3013 return 1;
3014 if (verbose > 1 && last_trial)
3015 fprintf(STDERR, " Check for removal of the %s chunk.\n", name);
3016 for (i = 1; i <= remove_chunks; i++) {
3017 if (!strncmp(argv[i], "-rem", 4)) {
3018 int alla = 0;
3019 int allb = 0;
3020 int allt = 0;
3021 i++;
3022 if (!strncmp(argv[i], "all", 3)) {
3023 allt++; /* all forms of text chunk are ancillary */
3024 allb++; /* all ancillaries but gamma... */
3025 if (!strncmp(argv[i], "alla", 4))
3026 alla++; /* ...no, all ancillaries, period */
3027 } else if (!strncmp(argv[i], "text", 4)) {
3028 allt++; /* all forms of text chunk */
3029 }
3030 if (!strncmp(argv[i], name, 4) /* exact chunk-name match in args
3031 * ...or exact match for one of known set, plus args included
3032 * either "alla", "allb", or all-lowercase form of "name": */
3033 || (!strncmp(name, "PLTE", 4)
3034 && (!strncmp(argv[i], "plte", 4) ))
3035 || (!strncmp(name, "bKGD", 4)
3036 && (!strncmp(argv[i], "bkgd", 4) || allb))
3037 || (!strncmp(name, "cHRM", 4)
3038 && (!strncmp(argv[i], "chrm", 4) || allb))
3039 || (!strncmp(name, "dSIG", 4)
3040 && (!strncmp(argv[i], "dsig", 4) || allb))
3041 || (!strncmp(name, "gAMA", 4)
3042 && (!strncmp(argv[i], "gama", 4) || alla))
3043 || (!strncmp(name, "gIFg", 4)
3044 && (!strncmp(argv[i], "gifg", 4) || allb))
3045 || (!strncmp(name, "gIFt", 4)
3046 && (!strncmp(argv[i], "gift", 4) || allb))
3047 || (!strncmp(name, "gIFx", 4)
3048 && (!strncmp(argv[i], "gifx", 4) || allb))
3049 || (!strncmp(name, "hIST", 4)
3050 && (!strncmp(argv[i], "hist", 4) || allb))
3051 || (!strncmp(name, "iCCP", 4)
3052 && (!strncmp(argv[i], "iccp", 4) || allb))
3053 || (!strncmp(name, "iTXt", 4)
3054 && (!strncmp(argv[i], "itxt", 4) || allt))
3055 || (!strncmp(name, "oFFs", 4)
3056 && (!strncmp(argv[i], "offs", 4) || allb))
3057 || (!strncmp(name, "pHYs", 4)
3058 && (!strncmp(argv[i], "phys", 4) || allb))
3059 || (!strncmp(name, "pCAL", 4)
3060 && (!strncmp(argv[i], "pcal", 4) || allb))
3061 || (!strncmp(name, "sBIT", 4)
3062 && (!strncmp(argv[i], "sbit", 4) || allb))
3063 || (!strncmp(name, "sCAL", 4)
3064 && (!strncmp(argv[i], "scal", 4) || allb))
3065 || (!strncmp(name, "sRGB", 4)
3066 && (!strncmp(argv[i], "srgb", 4) || allb))
3067 || (!strncmp(name, "sTER", 4)
3068 && (!strncmp(argv[i], "ster", 4) || allb))
3069 || (!strncmp(name, "sPLT", 4)
3070 && (!strncmp(argv[i], "splt", 4) || allb))
3071 || (!strncmp(name, "tEXt", 4)
3072 && ( allt))
3073 || (!strncmp(name, "tIME", 4)
3074 && (!strncmp(argv[i], "time", 4) || allb))
3075 || (!strncmp(name, "tRNS", 4)
3076 && (!strncmp(argv[i], "trns", 4) ))
3077 || (!strncmp(name, "zTXt", 4)
3078 && (!strncmp(argv[i], "ztxt", 4) || allt)) )
3079 {
3080 /* (caller actually does the removal--by failing to create
3081 * copy) */
3082 if (verbose > 0 && last_trial)
3083 fprintf(STDERR, " Removed the %s chunk.\n", name);
3084 return 0;
3085 }
3086 }
3087 }
3088 if (verbose > 1 && last_trial)
3089 fprintf(STDERR, " Preserving the %s chunk.\n", name);
3090 return 1;
3091 }
3092
3093
3094
3095
3096 void show_result(void)
3097 {
3098 if (total_output_length) {
3099 if (total_input_length == total_output_length)
3100 fprintf(STDERR, " Overall result: no change\n");
3101 else if (total_input_length > total_output_length)
3102 fprintf(STDERR,
3103 " Overall result: %4.2f%% reduction, %lu bytes\n",
3104 (100.0 -
3105 (100.0 * total_output_length) / total_input_length),
3106 (unsigned long)(total_input_length-total_output_length));
3107 else
3108 fprintf(STDERR,
3109 " Overall result: %4.2f%% increase, %lu bytes\n",
3110 -(100.0 -
3111 (100.0 * total_output_length) / total_input_length),
3112 (unsigned long)(total_output_length - total_input_length));
3113 }
3114
3115 #if PNGCRUSH_TIMERS > 0
3116 for (pc_timer=0;pc_timer < PNGCRUSH_TIMERS; pc_timer++)
3117 {
3118 filter_count[pc_timer]+=pngcrush_timer_get_hits(pc_timer);
3119 t_sec=pngcrush_timer_get_seconds(pc_timer);
3120 t_nsec=pngcrush_timer_get_nanoseconds(pc_timer);
3121 t_filter[pc_timer] = (float)t_nsec/1000000000.;
3122 if (t_sec)
3123 t_filter[pc_timer] += (float)t_sec;
3124 }
3125
3126 # if PNGCRUSH_TIMERS >= 3
3127 if (benchmark_iterations > 0 && verbose >= 0)
3128 {
3129 fprintf(STDERR, " CPU time decode %.4f,", t_filter[1]);
3130 fprintf(STDERR, " encode %.4f,", t_filter[2]);
3131 fprintf(STDERR, " other %.4f,", t_filter[3]);
3132 fprintf(STDERR, " total %.4f sec\n", t_filter[0]);
3133 }
3134 #endif
3135
3136 if (verbose <= 0)
3137 return;
3138
3139 # if PNGCRUSH_TIMERS > 9
3140 {
3141 float total_t_filter=0;
3142 float total_filter_count=0;
3143 for (pc_timer = 5; pc_timer < 10; pc_timer++)
3144 {
3145 total_t_filter+=t_filter[pc_timer];
3146 total_filter_count+=filter_count[pc_timer];
3147 }
3148 if (total_filter_count > 0)
3149 {
3150 for (pc_timer = 5; pc_timer < 10; pc_timer++)
3151 {
3152 fprintf(STDERR, " filter[%u] defilter time = %15.9f, count = %lu\n",
3153 pc_timer-5, t_filter[pc_timer],
3154 (unsigned long)filter_count[pc_timer]);
3155 }
3156 fprintf(STDERR, " total defilter time = %15.9f, count = %lu\n",
3157 total_t_filter, (unsigned long) total_filter_count);
3158 }
3159 }
3160 # endif
3161 # if PNGCRUSH_TIMERS > 4
3162 {
3163 if (filter_count[4] > 0)
3164 fprintf(STDERR, " deinterlace time = %15.9f, count = %lu\n",
3165 t_filter[4], (unsigned long)filter_count[4]);
3166 }
3167 # endif
3168 # if PNGCRUSH_USE_CLOCK_GETTIME != 0
3169 # if PNGCRUSH_TIMERS > 1
3170 {
3171 fprintf(STDERR, " total decode time = %15.9f, count = %lu\n",
3172 t_filter[1], (unsigned long)filter_count[1]);
3173 }
3174 # endif
3175 # if PNGCRUSH_TIMERS > 10
3176 {
3177 if (filter_count[10] > 0)
3178 fprintf(STDERR, " filter setup time = %15.9f, count = %lu\n",
3179 t_filter[10], (unsigned long)filter_count[10]);
3180 }
3181 # endif
3182 # if PNGCRUSH_TIMERS > 2
3183 {
3184 fprintf(STDERR, " total encode time = %15.9f, count = %lu\n",
3185 t_filter[2], (unsigned long)filter_count[2]);
3186 }
3187 # endif
3188 # if PNGCRUSH_TIMERS > 3
3189 {
3190 fprintf(STDERR, " total misc time = %15.9f, count = %lu\n",
3191 t_filter[3], (unsigned long)filter_count[3]);
3192 }
3193 # endif
3194 # if PNGCRUSH_TIMERS > 0
3195 {
3196 fprintf(STDERR, " total time = %15.9f, count = %lu\n",
3197 t_filter[0], (unsigned long)filter_count[0]);
3198 }
3199 # endif
3200 # endif
3201 #else
3202 # ifdef PNGCRUSH_TIMERS
3203 fprintf(STDERR, " CPU time defilter = 0.000000\n");
3204 fprintf(STDERR, " (PNGCRUSH_TIMERS=%d)\n\n", (int)PNGCRUSH_TIMERS);
3205 # endif
3206 #endif
3207
3208 #ifdef PNG_USER_MEM_SUPPORTED
3209 if (current_allocation) {
3210 memory_infop pinfo = pinformation;
3211 fprintf(STDERR, "MEMORY ERROR: %d bytes still allocated\n",
3212 current_allocation);
3213 while (pinfo != NULL) {
3214 fprintf(STDERR, "%10lu bytes at %p\n", (unsigned long)pinfo->size,
3215 (png_voidp) pinfo->pointer);
3216 free(pinfo->pointer);
3217 pinfo = pinfo->next;
3218 }
3219 }
3220 #endif /* PNG_USER_MEM_SUPPORTED */
3221 if (found_acTL_chunk == 2)
3222 fprintf(STDERR,
3223 " **** Discarded APNG chunks. ****\n");
3224 }
3225
3226 void pngcrush_write_png(png_structp write_pointer, png_bytep data,
3227 png_size_t length)
3228 {
3229 pngcrush_write_byte_count += (int) length;
3230 if (nosave == 0 && last_trial == 1)
3231 pngcrush_default_write_data(write_pointer, data, length);
3232 }
3233
3234 static void pngcrush_flush(png_structp png_ptr)
3235 {
3236 /* Do nothing. */
3237 PNGCRUSH_UNUSED(png_ptr)
3238 }
3239
3240
3241 void pngcrush_examine_pixels_fn(png_structp png_ptr, png_row_infop
3242 row_info, png_bytep data)
3243 {
3244 if (blacken == 1 || make_gray == 1 || make_opaque == 1)
3245 {
3246 /* Check if there are any fully transparent pixels. If one is found,
3247 * without the underlying color already black, set blacken==2. If the
3248 * PNG colortype does not support an alpha channel, set blacken==3.
3249 *
3250 * Check if there are any transparent pixels. If one is found,
3251 * set make_opaque==2. If the PNG colortype does not support an alpha
3252 * channel, set make_opaque==3.
3253 *
3254 * Check if there are any non-gray pixels. If one is found,
3255 * set make_gray == 2. If the PNG colortype is already gray, set
3256 * make_gray = 3.
3257 *
3258 * Check if any 16-bit pixels do not have identical high and low
3259 * bytes. If one is found, set make_8_bit == 2. If the PNG bit_depth
3260 * is not 16-bits, set make_8_bit = 3.
3261 *
3262 * Find the maximum palette entry present in the IDAT chunks of
3263 * an indexed PNG.
3264 *
3265 */
3266
3267 int i;
3268
3269 if (row_info->color_type < 4)
3270 {
3271 blacken = 3; /* It doesn't have an alpha channel */
3272 /* To do: check if tRNS chunk can be removed from color type 0 or 2 */
3273 make_opaque = 3;
3274 }
3275
3276 if (row_info->color_type == 0 || row_info->color_type == 4)
3277 make_gray = 3; /* It's already gray! */
3278
3279 if (row_info->color_type == 3)
3280 make_gray = 3; /* Don't change indexed PNG */
3281
3282 if (row_info->bit_depth < 16)
3283 make_8_bit = 3;
3284
3285 i = (int) row_info->rowbytes-1;
3286
3287 if ((row_info->color_type == 2 || row_info->color_type == 6) &&
3288 make_gray == 1) /* RGB */
3289 {
3290 if (row_info->bit_depth == 8)
3291 {
3292 int incr=3;
3293 if (row_info->color_type == 6)
3294 {
3295 incr=4;
3296 i--;
3297 }
3298 for ( ; i > 0 ; )
3299 {
3300 if (data[i] != data[i-1] || data[i] != data[i-2])
3301 {
3302 make_gray = 2;
3303 }
3304
3305 i-=incr;
3306 }
3307 }
3308
3309 else /* bit depth == 16 */
3310 {
3311 int incr = 6;
3312 if (row_info->color_type == 6)
3313 {
3314 incr = 8;
3315 i-=2;
3316 }
3317 for ( ; i > 0 ; )
3318 {
3319 if (data[i] != data[i-2] || data[i] != data[i-4] ||
3320 data[i-1] != data[i-3] || data[i-1] != data[i-5])
3321 {
3322 make_gray = 2;
3323 }
3324 i-=incr;
3325 }
3326 }
3327 }
3328
3329 else if (row_info->color_type == 4 && (blacken == 1 ||
3330 make_opaque == 1)) /* GA */
3331 {
3332 i = (int) row_info->rowbytes-1;
3333
3334 if (row_info->bit_depth == 8)
3335 {
3336 for ( ; i > 0 ; )
3337 {
3338 if (blacken == 1 && data[i] == 0 && data[i-1] != 0)
3339 {
3340 blacken = 2;
3341 }
3342
3343 if (make_opaque == 1 && data[i] != 255)
3344 {
3345 make_opaque = 2;
3346 }
3347 i-=2;
3348 }
3349 }
3350
3351 else /* bit depth == 16 */
3352 {
3353 for ( ; i > 0 ; )
3354 {
3355 if (blacken == 1 && (data[i] == 0 && data[i-1] == 0) &&
3356 (data[i-2] != 0 || data[i-3] != 0))
3357 {
3358 blacken = 2;
3359 }
3360
3361 if (make_opaque == 1 && (data[i] != 255 || data[i-1] != 255))
3362 {
3363 make_opaque = 2;
3364 }
3365 i-=4;
3366 }
3367 }
3368 }
3369
3370 /* color_type == 6, RGBA */
3371 if (row_info->color_type == 6 && (blacken == 1 || make_gray == 1 ||
3372 make_opaque == 1))
3373 {
3374 i = (int) row_info->rowbytes-1;
3375
3376 if (row_info->bit_depth == 8)
3377 {
3378 for ( ; i > 0 ; )
3379 {
3380 if (blacken == 1 && data[i] == 0 &&
3381 (data[i-1] != 0 || data[i-2] != 0 || data[i-3] != 0))
3382 {
3383 blacken = 2;
3384 }
3385
3386 if (make_gray == 1 &&
3387 (data[i-1] != data[i-2] || data[i-1] != data[i-3]))
3388 {
3389 make_gray = 2;
3390 }
3391
3392 if (make_opaque == 1 && data[i] != 255)
3393 {
3394 make_opaque = 2;
3395 }
3396
3397 i-=4;
3398 }
3399 }
3400
3401 else /* bit depth == 16 */
3402 {
3403 for ( ; i > 0 ; )
3404 {
3405 if (blacken == 1 && (data[i] == 0 && data[i-1]== 0) &&
3406 (data[i-2] != 0 || data[i-3] != 0 || data[i-4] != 0 ||
3407 data[i-5] != 0 || data[i-6] != 0 || data[i-7] != 0))
3408 {
3409 blacken = 2;
3410 }
3411
3412 if (make_gray == 1 &&
3413 (data[i-2] != data[i-4] || data[i-2] != data[i-6] ||
3414 data[i-3] != data[i-5] || data[i-3] != data[i-7]))
3415 {
3416 make_gray = 2;
3417 }
3418
3419 if (make_opaque == 1 && (data[i] != 255 || data[i-1] != 255))
3420 {
3421 make_opaque = 2;
3422 }
3423
3424 i-=8;
3425 }
3426 }
3427 }
3428 }
3429
3430 if (make_8_bit == 1)
3431 {
3432 int i;
3433 i = (int) row_info->rowbytes-1;
3434
3435 if (row_info->color_type == 0)
3436 {
3437 for ( ; i > 0 ; )
3438 {
3439 if (data[i] != data[i-1])
3440 make_8_bit = 2;
3441 i-=2;
3442 }
3443 }
3444
3445 if (row_info->color_type == 2)
3446 {
3447 for ( ; i > 0 ; )
3448 {
3449 if (data[i] != data[i-1] || data[i-2] != data[i-3] ||
3450 data[i-4] != data [i-5])
3451 make_8_bit = 2;
3452 i-=6;
3453 }
3454 }
3455
3456 if (row_info->color_type == 4)
3457 {
3458 for ( ; i > 0 ; )
3459 {
3460 if (data[i] != data[i-1] || data[i-2] != data[i-3])
3461 make_8_bit = 2;
3462 i-=4;
3463 }
3464 }
3465
3466 if (row_info->color_type == 6)
3467 {
3468 for ( ; i > 0 ; )
3469 {
3470 if (data[i] != data[i-1] || data[i-2] != data[i-3] ||
3471 data[i-4] != data [i-5] || data[i-6] != data[i-7])
3472 make_8_bit = 2;
3473 i-=8;
3474 }
3475 }
3476 }
3477
3478 if (reduce_palette == 1 && row_info->color_type == 3)
3479 {
3480 int i;
3481 i = (int) row_info->rowbytes-1;
3482
3483 for ( ; i > 0 ; i--)
3484 {
3485 if (data[i] >= plte_len)
3486 plte_len = data[i] + 1;
3487 }
3488 }
3489 }
3490
3491 void pngcrush_transform_pixels_fn(png_structp png_ptr, png_row_infop row_info,
3492 png_bytep data)
3493 {
3494
3495 int i;
3496
3497 if (blacken == 2)
3498 {
3499 /* change the underlying color of any fully transparent pixels to black */
3500 i=(int) row_info->rowbytes-1;
3501
3502 if (row_info->color_type == 4) /* GA */
3503 {
3504 if (row_info->bit_depth == 8)
3505 {
3506 for ( ; i > 0 ; )
3507 {
3508 if (data[i] == 0 && data[i-1] != 0)
3509 {
3510 data[i-1]=0;
3511 }
3512 i-=2;
3513 }
3514 }
3515
3516 else /* bit depth == 16 */
3517 {
3518 for ( ; i > 0 ; )
3519 {
3520 if (data[i] == 0 && data[i-1] == 0)
3521 {
3522 data[i-2]=0;
3523 data[i-3]=0;
3524 }
3525 i-=4;
3526 }
3527 }
3528 }
3529
3530 else /* color_type == 6, RGBA */
3531 {
3532 if (row_info->bit_depth == 8)
3533 {
3534 for ( ; i > 0 ; )
3535 {
3536 if (data[i] == 0)
3537 {
3538 data[i-1]=0;
3539 data[i-2]=0;
3540 data[i-3]=0;
3541 }
3542 i-=4;
3543 }
3544 }
3545
3546 else /* bit depth == 16 */
3547 {
3548 for ( ; i > 0 ; )
3549 {
3550 if (data[i] == 0 && data[i-1] == 0)
3551 {
3552 data[i-2]=0;
3553 data[i-3]=0;
3554 data[i-4]=0;
3555 data[i-5]=0;
3556 data[i-6]=0;
3557 data[i-7]=0;
3558 }
3559 i-=8;
3560 }
3561 }
3562 }
3563 }
3564 }
3565
3566
3567 int main(int argc, char *argv[])
3568 {
3569 unsigned int bench = 0;
3570 png_uint_32 y;
3571 int bit_depth = 0;
3572 int color_type = 0;
3573 int num_pass, pass;
3574 int num_methods;
3575
3576 int try10 = 0;
3577
3578 char *endptr = NULL;
3579
3580 /* try_method[n]: 0 means try this method;
3581 *
3582 * : 1 means do not try this method.
3583 */
3584 int try_method[MAX_METHODSP1];
3585 int methods_enabled = 0;
3586 int last_method = MAX_METHODS;
3587
3588 int fm[MAX_METHODSP1];
3589 int lv[MAX_METHODSP1];
3590 int zs[MAX_METHODSP1];
3591 int lev, strat, filt;
3592
3593 #ifdef PNG_gAMA_SUPPORTED
3594 # ifdef PNG_FIXED_POINT_SUPPORTED
3595 png_fixed_point file_gamma = 0;
3596 # else
3597 double file_gamma = 0.;
3598 # endif
3599 #endif
3600 char *cp;
3601 int i;
3602
3603 #if PNGCRUSH_TIMERS >= 0
3604 for (pc_timer=0;pc_timer< PNGCRUSH_TIMERS; pc_timer++)
3605 {
3606 pngcrush_timer_reset(pc_timer);
3607 pngcrush_timer_min_secs[pc_timer]=0xffffffff;
3608 pngcrush_timer_min_nsec[pc_timer]=0xffffffff;
3609 }
3610 pngcrush_timer_start(PNGCRUSH_TIMER_TOTAL);
3611 pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
3612 #endif
3613
3614 row_buf = (png_bytep) NULL;
3615 P2(" row_buf = %p\n",row_buf);
3616 number_of_open_files = 0;
3617 do_color_count = 0;
3618 PNGCRUSH_UNUSED(do_color_count) /* silence compiler warning */
3619
3620 strncpy(prog_string, argv[0], STR_BUF_SIZE);
3621 prog_string[STR_BUF_SIZE-1] = '\0';
3622 progname = prog_string;
3623 for (i = 0, cp = prog_string; *cp != '\0'; i++, cp++)
3624 {
3625 #ifdef __riscos
3626 if (*cp == '.' || *cp == ':')
3627 progname = ++cp;
3628 #else
3629 if (*cp == '\\' || *cp == '/')
3630 progname = ++cp;
3631 #endif
3632 }
3633
3634 /*
3635 * Definition of methods ("canonical list" is methods 11 and up)
3636 */
3637 for (i = 0; i <= MAX_METHODS; i++)
3638 {
3639 try_method[i] = 1; /* 1 means do not try this method */
3640 fm[i] = 6; lv[i] = 9; zs[i] = 1; /* default: method 136 */
3641 }
3642
3643
3644 fm[0] = 0; lv[0] = 0; zs[0] = 0; /* method 0 == uncompressed */
3645 fm[1] = 0; lv[1] = 4; zs[1] = 0; /* method 1 == method 53 */
3646 fm[2] = 1; lv[2] = 4; zs[2] = 0; /* method 2 == method 54 */
3647 /* fm[3] = 6;*/ lv[3] = 4;/* zs[3] = 1;*/ /* method 3 == method 161 */
3648 fm[4] = 0;/* lv[4] = 9; zs[4] = 1;*/ /* method 4 == method 119 */
3649 fm[5] = 1;/* lv[5] = 9; zs[5] = 0;*/ /* method 5 == method 114 */
3650 /* fm[6] = 6; lv[6] = 9;*/ zs[6] = 0; /* method 6 == method 157 */
3651 fm[7] = 0;/* lv[7] = 9;*/ zs[7] = 0; /* method 7 == method 113 */
3652 fm[8] = 1;/* lv[8] = 9; zs[8] = 1;*/ /* method 8 == method 120 */
3653 /* fm[9] = 6;*/ lv[9] = 2; zs[9] = 2; /* method 9 == method xxx */
3654 /* fm[10]= 6; lv[10]= 9; zs[10]= 1;*/ /* method 10 == method 166 */
3655
3656 /* methods 11 through 16
3657 *
3658 * [strategy 2 (Z_HUFFMAN_ONLY) is independent of zlib compression level]
3659 */
3660 method = 11;
3661 for (filt = 0; filt <= 5; filt++)
3662 {
3663 fm[method] = filt;
3664 lv[method] = 2;
3665 zs[method] = 2;
3666 method++;
3667 }
3668
3669 /*
3670 * methods 17 through 136 (10*2*6 = 120)
3671 */
3672 for (lev = 1; lev <= 9; lev++)
3673 {
3674 for (strat = 0; strat <= 1; strat++)
3675 {
3676 for (filt = 0; filt <= 5; filt++)
3677 {
3678 fm[method] = filt;
3679 lv[method] = lev;
3680 zs[method] = strat;
3681 method++;
3682 }
3683 }
3684 }
3685
3686 #ifdef Z_RLE
3687 /* methods 125 through 136
3688 *
3689 * [strategy 3 (Z_RLE) is mostly independent of level; 1-3 and 4-9 are
3690 * same]
3691 */
3692 for (filt = 0; filt <= 5; filt++)
3693 {
3694 fm[method] = filt;
3695 lv[method] = 1;
3696 zs[method] = 3;
3697 method++;
3698 }
3699 for (filt = 0; filt <= 5; filt++)
3700 {
3701 fm[method] = filt;
3702 lv[method] = 4;
3703 zs[method] = 3;
3704 method++;
3705 }
3706 #endif /* Z_RLE */
3707
3708 /* methods 137 through 148 (12*1*1 = 12), level 0 */
3709
3710 for (strat = 0; strat <= 1; strat++)
3711 {
3712 for (filt = 0; filt <= 5; filt++)
3713 {
3714 fm[method] = filt;
3715 lv[method] = 0;
3716 zs[method] = strat;
3717 method++;
3718 }
3719 }
3720
3721 /*
3722 * methods 149 through 176 (9*3*1 + 1 = 28), speedy
3723 */
3724 for (strat = 0; strat <= 3; strat++)
3725 {
3726 for (lev = 1; lev <= 9; lev++)
3727 {
3728 lv[method] = lev;
3729 zs[method] = strat;
3730 fm[method] = 6;
3731 method++;
3732 if (strat == 2)
3733 break; /* HUFFMAN ONLY is independent of level */
3734 }
3735 }
3736
3737
3738 num_methods = method; /* GRR */
3739
3740 /* method 177 */
3741 fm[method] = 0; lv[method] = 0; zs[method] = 0; /* copy_idat */
3742 method++;
3743
3744 #define pngcrush_get_long strtol(argv[i],&endptr,10)
3745
3746 #define pngcrush_check_long \
3747 {if (errno || endptr == argv[i] || *endptr != '\0') \
3748 { fprintf(STDERR, "pngcrush: malformed or missing argument\n"); \
3749 exit(1); \
3750 } \
3751 }
3752
3753 #define BUMP_I \
3754 { i++; \
3755 if(i >= argc) {fprintf(STDERR,"pngcrush: insufficient parameters\n");\
3756 exit(1);} }
3757
3758 names = 1;
3759
3760 /* ===================================================================== */
3761 /* FIXME: move args-processing block into separate function (470 lines) */
3762 for (i = 1; i < argc; i++)
3763 {
3764 errno=0;
3765
3766 if (!strncmp(argv[i], "--", 2))
3767 argv[i]++;
3768
3769 if (!strncmp(argv[i], "-", 1))
3770 names++;
3771
3772 /* GRR: start of giant else-if block */
3773
3774 if (!strncmp(argv[i], "-bail", 5))
3775 bail=0;
3776
3777 if (!strncmp(argv[i], "-bench", 6))
3778 {
3779 names++;
3780 BUMP_I;
3781 benchmark_iterations = (unsigned int) pngcrush_get_long;
3782 pngcrush_check_long;
3783 }
3784
3785 else if (!strncmp(argv[i], "-bkgd", 5) ||
3786 !strncmp(argv[i], "-bKGD", 5))
3787 {
3788 names += 3;
3789 have_bkgd = 1;
3790 BUMP_I;
3791 bkgd_red = (png_uint_16) pngcrush_get_long;
3792 pngcrush_check_long;
3793 BUMP_I;
3794 bkgd_green = (png_uint_16) pngcrush_get_long;
3795 pngcrush_check_long;
3796 BUMP_I;
3797 bkgd_blue = (png_uint_16) pngcrush_get_long;
3798 pngcrush_check_long;
3799 bkgd_index = 0;
3800 }
3801
3802 else if (!strncmp(argv[i], "-blacken", 8))
3803 blacken=1;
3804
3805 else if (!strncmp(argv[i], "-brute", 6))
3806 /* brute force: try everything */
3807 {
3808 methods_specified = 1;
3809 brute_force++;
3810 for (method = 1; method < num_methods; method++)
3811 try_method[method] = 0;
3812 if (brute_force_filter == 0)
3813 for (filt = 0; filt < 6; filt++)
3814 brute_force_filters[filt] = 0;
3815 if (brute_force_level == 0)
3816 for (lev = 0; lev < 10; lev++)
3817 brute_force_levels[lev] = 0;
3818 if (brute_force_strategy == 0)
3819 for (strat = 0; strat < NUM_STRATEGIES; strat++)
3820 brute_force_strategies[strat] = 0;
3821 }
3822
3823 else if (!strncmp(argv[i], "-check", 6))
3824 {
3825 check_crc = 1;
3826 }
3827
3828 else if (!strncmp(argv[i], "-c", 3) || !strncmp(argv[i], "-col", 4))
3829 {
3830 names++;
3831 BUMP_I;
3832 force_output_color_type = pngcrush_get_long;
3833 pngcrush_check_long;
3834 }
3835
3836 else if (!strncmp(argv[i], "-d", 3) || !strncmp(argv[i], "-dir", 4))
3837 {
3838 BUMP_I;
3839 if (pngcrush_mode == EXTENSION_MODE)
3840 pngcrush_mode = DIREX_MODE;
3841 else
3842 pngcrush_mode = DIRECTORY_MODE;
3843 directory_name = argv[names++];
3844 }
3845
3846 else if (!strncmp(argv[i], "-exit", 5))
3847 {
3848 pngcrush_must_exit = 1;
3849 }
3850
3851 else if (!strncmp(argv[i], "-e", 3) || !strncmp(argv[i], "-ext", 4))
3852 {
3853 BUMP_I;
3854 if (pngcrush_mode == DIRECTORY_MODE)
3855 pngcrush_mode = DIREX_MODE;
3856 else
3857 pngcrush_mode = EXTENSION_MODE;
3858 extension = argv[names++];
3859 }
3860
3861 else if (!strncmp(argv[i], "-fast", 5))
3862 {
3863 /* try two fast filters */
3864 methods_specified = 1;
3865 try_method[16] = 0;
3866 try_method[53] = 0;
3867 }
3868
3869 else if (!strncmp(argv[i], "-force", 6))
3870 {
3871 force = 1;
3872 }
3873
3874 else if (!strncmp(argv[i], "-fix", 4))
3875 {
3876 salvage++;
3877 }
3878
3879 else if (!strncmp(argv[i], "-f", 3) || !strncmp(argv[i], "-fil", 4))
3880 {
3881 int specified_filter;
3882 BUMP_I;
3883 specified_filter = pngcrush_get_long;
3884 pngcrush_check_long;
3885 if (specified_filter > 5 || specified_filter < 0)
3886 specified_filter = 5;
3887 names++;
3888 if (brute_force == 0)
3889 fm[method] = specified_filter;
3890 else
3891 {
3892 if (brute_force_filter == 0)
3893 for (filt = 0; filt < 6; filt++)
3894 brute_force_filters[filt] = 1;
3895 brute_force_filters[specified_filter] = 0;
3896 brute_force_filter++;
3897 }
3898 }
3899
3900 #ifdef PNG_gAMA_SUPPORTED
3901 else if (!strncmp(argv[i], "-g", 3) || !strncmp(argv[i], "-gam", 4))
3902 {
3903 names++;
3904 BUMP_I;
3905 found_gAMA=1;
3906 if (specified_intent < 0)
3907 {
3908 #ifdef PNG_FIXED_POINT_SUPPORTED
3909 int c;
3910 char number[16];
3911 char *n = number;
3912 int nzeroes = -1;
3913 int length = strlen(argv[i]);
3914 for (c = 0; c < length; c++)
3915 {
3916 if (*(argv[i] + c) == '.')
3917 {
3918 nzeroes = 5;
3919 }
3920 else if (nzeroes)
3921 {
3922 *n++ = *(argv[i] + c);
3923 nzeroes--;
3924 }
3925 }
3926 for (c = 0; c < nzeroes; c++)
3927 *n++ = '0';
3928 *n = '\0';
3929 specified_gamma = strtol(number,&endptr,10);
3930 #else
3931 specified_gamma = strtof(argv[i],&endptr);
3932 #endif
3933 pngcrush_check_long;
3934 }
3935 }
3936 #endif /* PNG_gAMA_SUPPORTED */
3937
3938 else if (!strncmp(argv[i], "-h", 3) || !strncmp(argv[i], "-hel", 4))
3939 {
3940 ++verbose;
3941 print_version_info();
3942 printed_version_info++;
3943 print_usage(0); /* this exits */
3944 }
3945
3946 else if (!strncmp(argv[i], "-huffman", 8))
3947 {
3948 /* try all filters with huffman */
3949 methods_specified = 1;
3950 for (method = 11; method <= 16; method++)
3951 {
3952 try_method[method] = 0;
3953 }
3954 }
3955
3956 #ifdef PNG_iCCP_SUPPORTED
3957 else if (!strncmp(argv[i], "-iccp", 5))
3958 {
3959 FILE *iccp_fn;
3960 if (iccp_length)
3961 free(iccp_text);
3962 BUMP_I;
3963 iccp_length = pngcrush_get_long;
3964 pngcrush_check_long;
3965 names += 3;
3966 BUMP_I;
3967 strncpy(iccp_name, argv[i], 80);
3968 iccp_name[79] = '\0';
3969 BUMP_I;
3970 iccp_file = argv[i];
3971 if ((iccp_fn = FOPEN(iccp_file, "rb")) == NULL) {
3972 fprintf(STDERR, "Could not find file: %s\n", iccp_file);
3973 iccp_length = 0;
3974 }
3975 else
3976 {
3977 int ic;
3978 number_of_open_files++;
3979 iccp_text = (char*)malloc(iccp_length);
3980 if (iccp_text == NULL)
3981 {
3982 fprintf(STDERR, "malloc of iccp_text failed\n");
3983 iccp_length = 0;
3984 }
3985
3986 for (ic = 0; ic < iccp_length; ic++)
3987 {
3988 png_size_t num_in;
3989 num_in = fread((void *)buffer, 1, 1, iccp_fn);
3990
3991 if (!num_in)
3992 break;
3993
3994 iccp_text[ic] = buffer[0];
3995 }
3996
3997 FCLOSE(iccp_fn);
3998 }
3999 }
4000 #endif /* PNG_iCCP_SUPPORTED */
4001
4002 else if (!strncmp(argv[i], "-keep", 5))
4003 {
4004 names++;
4005 BUMP_I;
4006 if (!strncmp(argv[i], "-dSIG", 5)
4007 && (!strncmp(argv[i], "-dsig", 5) ))
4008 found_any_chunk=1;
4009 }
4010
4011 else if (!strncmp(argv[i], "-l", 3) || !strncmp(argv[i], "-lev", 4))
4012 {
4013 int specified_level;
4014 BUMP_I;
4015 specified_level = pngcrush_get_long;
4016 pngcrush_check_long;
4017 if (specified_level > 9 || specified_level < 0)
4018 specified_level = 9;
4019 names++;
4020 if (brute_force == 0)
4021 lv[method] = specified_level;
4022 else
4023 {
4024 if (brute_force_level == 0)
4025 for (lev = 0; lev < 10; lev++)
4026 brute_force_levels[lev] = 1;
4027 brute_force_levels[specified_level] = 0;
4028 brute_force_level++;
4029 }
4030 }
4031
4032 else if (!strncmp(argv[i], "-loco", 5))
4033 {
4034 #ifdef PNGCRUSH_LOCO
4035 do_loco = 1;
4036 #else
4037 fprintf
4038 (STDERR,"Cannot do -loco because libpng was compiled"
4039 " without MNG features");
4040 #endif
4041 }
4042
4043 else if (!strncmp(argv[i], "-max", 4))
4044 {
4045 names++;
4046 BUMP_I;
4047 max_idat_size = (png_uint_32) pngcrush_get_long;
4048 pngcrush_check_long;
4049 if (max_idat_size == 0 || max_idat_size > PNG_UINT_31_MAX)
4050 max_idat_size = PNG_ZBUF_SIZE;
4051 }
4052
4053 else if (!strncmp(argv[i], "-m", 3) || !strncmp(argv[i], "-met", 4))
4054 {
4055 names++;
4056 BUMP_I;
4057 method = pngcrush_get_long;
4058 pngcrush_check_long;
4059 if (method >= 1 && method <= MAX_METHODS)
4060 {
4061 methods_specified = 1;
4062 brute_force = 0;
4063 try_method[method] = 0;
4064 }
4065 else
4066 {
4067 fprintf(STDERR, "\n Ignoring invalid method: %d\n",
4068 method);
4069 method = MAX_METHODS;
4070 }
4071 }
4072
4073 #ifdef PNGCRUSH_LOCO
4074 else if (!strncmp(argv[i], "-mng", 4))
4075 {
4076 names++;
4077 BUMP_I;
4078 mngname = argv[i];
4079 new_mng++;
4080 }
4081 #endif
4082
4083 else if (!strncmp(argv[i], "-new", 4))
4084 {
4085 make_opaque = 1; /* -reduce */
4086 make_gray = 1; /* -reduce */
4087 make_8_bit = 1; /* -reduce */
4088 reduce_palette = 1; /* -reduce */
4089 }
4090
4091 else if (!strncmp(argv[i], "-nobail", 7))
4092 bail=1;
4093
4094 else if (!strncmp(argv[i], "-nocheck", 8))
4095 {
4096 check_crc = 0;
4097 }
4098
4099 else if (!strncmp(argv[i], "-nofilecheck", 5))
4100 {
4101 nofilecheck++;
4102 }
4103 else if (!strncmp(argv[i], "-noforce", 6))
4104 {
4105 force = 0;
4106 }
4107
4108
4109 else if (!strncmp(argv[i], "-nolimits", 5))
4110 {
4111 no_limits++;
4112 }
4113
4114 else if (!strncmp(argv[i], "-noreduce_pal", 13))
4115 {
4116 reduce_palette = 0;
4117 }
4118
4119 else if (!strncmp(argv[i], "-noreduce", 9))
4120 {
4121 make_opaque = 0;
4122 make_gray = 0;
4123 make_8_bit = 0;
4124 reduce_palette = 0;
4125 }
4126
4127 else if (!strncmp(argv[i], "-n", 3) || !strncmp(argv[i], "-nos", 4))
4128 {
4129 /* no save; I just use this for testing decode speed */
4130 /* also to avoid saving if a CgBI chunk was found */
4131 nosave++;
4132 pngcrush_mode = EXTENSION_MODE;
4133 }
4134
4135 else if (!strncmp(argv[i], "-oldtimestamp", 5))
4136 {
4137 new_time_stamp=0;
4138 }
4139
4140 else if (!strncmp(argv[i], "-old", 4))
4141 {
4142 make_opaque = 0; /* no -reduce */
4143 make_gray = 0; /* no -reduce */
4144 make_8_bit = 0; /* no -reduce */
4145 reduce_palette = 0; /* no -reduce */
4146 }
4147
4148 else if(!strncmp(argv[i], "-ow",3))
4149 {
4150 overwrite = 1;
4151 }
4152
4153 else if (!strncmp(argv[i], "-pplt", 3))
4154 {
4155 names++;
4156 do_pplt++;
4157 BUMP_I;
4158 strncpy(pplt_string, argv[i], STR_BUF_SIZE);
4159 pplt_string[STR_BUF_SIZE-1] = '\0';
4160 }
4161
4162 else if (!strncmp(argv[i], "-premultiply", 5))
4163 {
4164 premultiply=2;
4165 }
4166
4167 else if (!strncmp(argv[i], "-p", 3) || !strncmp(argv[i], "-pau", 4))
4168 {
4169 pauses++;
4170 }
4171
4172 else if (!strncmp(argv[i], "-q", 3) || !strncmp(argv[i], "-qui", 4))
4173 {
4174 /* quiet, does not suppress warnings or timing */
4175 verbose = 0;
4176 }
4177
4178 else if (!strncmp(argv[i], "-reduce_pal", 11))
4179 {
4180 reduce_palette = 1;
4181 }
4182
4183 else if (!strncmp(argv[i], "-reduce", 7))
4184 {
4185 noreduce = 0;
4186 make_opaque = 1;
4187 make_gray = 1;
4188 make_8_bit = 1;
4189 reduce_palette = 1;
4190 }
4191
4192 #ifdef PNG_gAMA_SUPPORTED
4193 else if (!strncmp(argv[i], "-replace_gamma", 4))
4194 {
4195 names++;
4196 BUMP_I;
4197 found_gAMA=1;
4198 {
4199 #ifdef PNG_FIXED_POINT_SUPPORTED
4200 int c;
4201 char number[16];
4202 char *n = number;
4203 int nzeroes = -1;
4204 int length = strlen(argv[i]);
4205 for (c = 0; c < length; c++)
4206 {
4207 if (*(argv[i] + c) == '.')
4208 {
4209 nzeroes = 5;
4210 }
4211 else if (nzeroes)
4212 {
4213 *n++ = *(argv[i] + c);
4214 nzeroes--;
4215 }
4216 }
4217 for (c = 0; c < nzeroes; c++)
4218 *n++ = '0';
4219 *n = '\0';
4220 force_specified_gamma = strtol(number,&endptr,10);
4221 #else
4222 force_specified_gamma = strtof(argv[i],&endptr);
4223 #endif
4224 pngcrush_check_long;
4225 }
4226 }
4227 #endif /* PNG_gAMA_SUPPORTED */
4228
4229 #ifdef PNG_pHYs_SUPPORTED
4230 else if (!strncmp(argv[i], "-res", 4))
4231 {
4232 names++;
4233 BUMP_I;
4234 resolution = pngcrush_get_long;
4235 pngcrush_check_long;
4236 }
4237 #endif
4238
4239 #ifdef Z_RLE
4240 else if (!strncmp(argv[i], "-rle", 4))
4241 {
4242 /* try all filters with RLE */
4243 methods_specified = 1;
4244 for (method = 125; method <= 136; method++)
4245 {
4246 try_method[method] = 0;
4247 }
4248 }
4249 #endif
4250
4251 #ifdef PNGCRUSH_MULTIPLE_ROWS
4252 else if (!strncmp(argv[i], "-rows", 5))
4253 {
4254 names++;
4255 BUMP_I;
4256 max_rows_at_a_time = pngcrush_get_long;
4257 pngcrush_check_long;
4258 }
4259 #endif
4260
4261 else if (!strncmp(argv[i], "-r", 3) || !strncmp(argv[i], "-rem", 4))
4262 {
4263 remove_chunks = i;
4264 names++;
4265 BUMP_I;
4266 if (!strncmp(argv[i], "-dSIG", 5)
4267 && (!strncmp(argv[i], "-dsig", 5)))
4268 image_is_immutable=0;
4269 }
4270
4271 else if (!strncmp(argv[i], "-save", 5))
4272 {
4273 all_chunks_are_safe++;
4274 }
4275
4276 else if (!strncmp(argv[i], "-speed", 6))
4277 {
4278 speed = 1;
4279 }
4280
4281 else if (!strncmp(argv[i], "-srgb", 5) ||
4282 !strncmp(argv[i], "-sRGB", 5))
4283 {
4284 #ifdef PNG_gAMA_SUPPORTED
4285 # ifdef PNG_FIXED_POINT_SUPPORTED
4286 specified_gamma = 45455L;
4287 # else
4288 specified_gamma = 0.45455;
4289 # endif
4290 #endif
4291 specified_intent = 0;
4292 BUMP_I;
4293 if (!strncmp(argv[i], "0", 1) ||
4294 !strncmp(argv[i], "1", 1) ||
4295 !strncmp(argv[i], "2", 1) ||
4296 !strncmp(argv[i], "3", 1))
4297 {
4298 names++;
4299 specified_intent = (int) pngcrush_get_long;
4300 pngcrush_check_long;
4301 } else
4302 i--;
4303 }
4304
4305 else if (!strncmp(argv[i], "-ster", 5) ||
4306 !strncmp(argv[i], "-sTER", 5))
4307 {
4308 BUMP_I;
4309 ster_mode = -1;
4310 if (!strncmp(argv[i], "0", 1) ||
4311 !strncmp(argv[i], "1", 1))
4312 {
4313 names++;
4314 ster_mode = (int) pngcrush_get_long;
4315 pngcrush_check_long;
4316 }
4317 else
4318 i--;
4319 }
4320
4321 else if (!strncmp(argv[i], "-s", 3) || !strncmp(argv[i], "-sil", 4))
4322 {
4323 /* silent, suppresses warnings, timing, and results */
4324 verbose = -1;
4325 }
4326
4327 else if (!strncmp(argv[i], "-text", 5)
4328 || !strncmp(argv[i], "-tEXt", 5) ||
4329 #ifdef PNG_iTXt_SUPPORTED
4330 !strncmp(argv[i], "-itxt", 5)
4331 || !strncmp(argv[i], "-iTXt", 5)
4332 || !strncmp(argv[i], "-zitxt", 6)
4333 || !strncmp(argv[i], "-ziTXt", 6) ||
4334 #endif
4335 !strncmp(argv[i], "-ztxt", 5)
4336 || !strncmp(argv[i], "-zTXt", 5))
4337 {
4338 i += 2;
4339 BUMP_I;
4340 i -= 3;
4341 if (strlen(argv[i + 2]) < 80 &&
4342 strlen(argv[i + 3]) < STR_BUF_SIZE &&
4343 text_inputs < 10)
4344 {
4345 #ifdef PNG_iTXt_SUPPORTED
4346 if (!strncmp(argv[i], "-zi", 3))
4347 {
4348 text_compression[text_inputs] =
4349 PNG_ITXT_COMPRESSION_zTXt;
4350 /* names += 2; */
4351 }
4352 else
4353 #endif
4354 if (!strncmp(argv[i], "-z", 2))
4355 text_compression[text_inputs] =
4356 PNG_TEXT_COMPRESSION_zTXt;
4357 else if (!strncmp(argv[i], "-t", 2))
4358 text_compression[text_inputs] =
4359 PNG_TEXT_COMPRESSION_NONE;
4360 #ifdef PNG_iTXt_SUPPORTED
4361 else
4362 {
4363 text_compression[text_inputs] =
4364 PNG_ITXT_COMPRESSION_NONE;
4365 /* names += 2; */
4366 }
4367 #endif
4368 names += 3;
4369 if (!strncmp(argv[++i], "b", 1))
4370 text_where[text_inputs] = 1;
4371 if (!strncmp(argv[i], "a", 1))
4372 text_where[text_inputs] = 2;
4373 strncpy(&text_keyword[text_inputs * 80], argv[++i],
4374 80);
4375 text_keyword[text_inputs * 80 + 79] = '\0';
4376 #ifdef PNG_iTXt_SUPPORTED
4377 if (text_compression[text_inputs] <= 0)
4378 {
4379 text_lang[text_inputs * 80] = '\0';
4380 text_lang_key[text_inputs * 80] = '\0';
4381 }
4382 else
4383 {
4384 i += 2;
4385 BUMP_I;
4386 i -= 3;
4387 names += 2;
4388 strncpy(&text_lang[text_inputs * 80], argv[++i], 80);
4389 text_lang[text_inputs * 80 + 79] = '\0';
4390 /* libpng-1.0.5j and later */
4391 strncpy(&text_lang_key[text_inputs * 80], argv[++i], 80);
4392 text_lang_key[text_inputs * 80 + 79] = '\0';
4393 }
4394 #endif
4395 strncpy(&text_text[text_inputs * STR_BUF_SIZE], argv[++i],
4396 STR_BUF_SIZE);
4397 text_text[(text_inputs + 1) * STR_BUF_SIZE - 1] = '\0';
4398 text_inputs++;
4399 } else {
4400 if (text_inputs > 9)
4401 fprintf(STDERR,
4402 "too many text/zTXt inputs; only 10 allowed\n");
4403 else
4404 fprintf(STDERR,
4405 "keyword exceeds 79 characters or text"
4406 " exceeds 2047 characters\n");
4407 i += 3;
4408 names += 3;
4409 #ifdef PNG_iTXt_SUPPORTED
4410 if (!strncmp(argv[i], "-i", 3) || !strncmp(argv[i], "-itx", 4))
4411 {
4412 i++;
4413 BUMP_I;
4414 names += 2;
4415 }
4416 #endif
4417 }
4418 }
4419
4420 else if (!strncmp(argv[i], "-time_stamp", 5) || /* legacy */
4421 !strncmp(argv[i], "-newtimestamp", 5))
4422 new_time_stamp=1;
4423
4424 #ifdef PNG_tRNS_SUPPORTED
4425 else if (!strncmp(argv[i], "-trns_a", 7) ||
4426 !strncmp(argv[i], "-tRNS_a", 7))
4427 {
4428 num_trans_in = (png_uint_16) pngcrush_get_long;
4429 pngcrush_check_long;
4430 if (num_trans_in > 256)
4431 num_trans_in = 256;
4432 trns_index=num_trans_in-1;
4433 have_trns = 1;
4434 for (ia = 0; ia < num_trans_in; ia++)
4435 {
4436 BUMP_I;
4437 trans_in[ia] = (png_byte) pngcrush_get_long;
4438 pngcrush_check_long;
4439 }
4440 names += 1 + num_trans_in;
4441 }
4442
4443 else if (!strncmp(argv[i], "-trns", 5) ||
4444 !strncmp(argv[i], "-tRNS", 5))
4445 {
4446 names += 5;
4447 have_trns = 1;
4448 BUMP_I;
4449 trns_index = (png_uint_16) pngcrush_get_long;
4450 pngcrush_check_long;
4451 BUMP_I;
4452 trns_red = (png_uint_16) pngcrush_get_long;
4453 pngcrush_check_long;
4454 BUMP_I;
4455 trns_green = (png_uint_16) pngcrush_get_long;
4456 pngcrush_check_long;
4457 BUMP_I;
4458 trns_blue = (png_uint_16) pngcrush_get_long;
4459 pngcrush_check_long;
4460 BUMP_I;
4461 trns_gray = (png_uint_16) pngcrush_get_long;
4462 pngcrush_check_long;
4463 }
4464 #endif /* tRNS */
4465
4466 else if(!strncmp(argv[i], "-try10",6))
4467 {
4468 try10 = 1;
4469 }
4470
4471 else if (!strncmp(argv[i], "-version", 8))
4472 {
4473 fprintf(STDERR, " pngcrush ");
4474 fprintf(STDERR, PNGCRUSH_VERSION);
4475 fprintf(STDERR, ", uses libpng ");
4476 fprintf(STDERR, PNG_LIBPNG_VER_STRING);
4477 fprintf(STDERR, " and zlib ");
4478 fprintf(STDERR, ZLIB_VERSION);
4479 fprintf(STDERR, "\n Check http://pmt.sf.net/\n");
4480 fprintf(STDERR, " for the most recent version.\n");
4481 verbose = 0;
4482 exit(0);
4483 }
4484
4485 else if (!strncmp(argv[i], "-v", 3) || !strncmp(argv[i], "-ver", 4))
4486 {
4487 verbose++;
4488 }
4489
4490 else if (!strncmp(argv[i], "-warn", 5))
4491 {
4492 show_warnings++;
4493 verbose = -1;
4494 }
4495
4496 else if (!strncmp(argv[i], "-w", 3) || !strncmp(argv[i], "-win", 4))
4497 {
4498 BUMP_I;
4499 default_compression_window = pngcrush_get_long;
4500 pngcrush_check_long;
4501 force_compression_window++;
4502 names++;
4503 }
4504
4505 else if (!strncmp(argv[i], "-zm", 4) || !strncmp(argv[i], "-zmem", 5))
4506 {
4507 BUMP_I;
4508 compression_mem_level = pngcrush_get_long;
4509 pngcrush_check_long;
4510 names++;
4511 }
4512
4513 else if (!strncmp(argv[i], "-z", 3))
4514 {
4515 int specified_strategy;
4516 BUMP_I;
4517 specified_strategy = pngcrush_get_long;
4518 pngcrush_check_long;
4519 if (specified_strategy > 2 || specified_strategy < 0)
4520 specified_strategy = 0;
4521 names++;
4522 if (brute_force == 0)
4523 zs[method] = specified_strategy;
4524 else
4525 {
4526 if (brute_force_strategy == 0)
4527 for (strat = 0; strat < 2; strat++)
4528 brute_force_strategies[strat] = 1;
4529 brute_force_strategies[specified_strategy] = 0;
4530 brute_force_strategy++;
4531 }
4532 }
4533
4534 else if (!strncmp(argv[i], "-", 1))
4535 {
4536 if (verbose > 0 && printed_version_info == 0)
4537 {
4538 print_version_info();
4539 printed_version_info++;
4540 }
4541 fprintf(STDERR, "\n Ignoring invalid option: %s\n",
4542 argv[i]);
4543 } /* GRR: end of giant if-else block */
4544 } /* end of loop over args ============================================ */
4545
4546 if (verbose > 0 && printed_version_info == 0)
4547 print_version_info();
4548
4549 if (default_compression_window == 32)
4550 default_compression_window = 15;
4551 else if (default_compression_window == 16)
4552 default_compression_window = 14;
4553 else if (default_compression_window == 8)
4554 default_compression_window = 13;
4555 else if (default_compression_window == 4)
4556 default_compression_window = 12;
4557 else if (default_compression_window == 2)
4558 default_compression_window = 11;
4559 else if (default_compression_window == 1)
4560 default_compression_window = 10;
4561 else if (default_compression_window == 512)
4562 default_compression_window = 9;
4563 /* Use of compression window size 256 is not recommended. */
4564 else if (default_compression_window == 256)
4565 default_compression_window = 8;
4566 else if (default_compression_window == 0)
4567 /* do nothing */;
4568 else if (default_compression_window != 15) {
4569 fprintf(STDERR, "Invalid window size (%d); using window size=4\n",
4570 default_compression_window);
4571 default_compression_window = 12;
4572 }
4573
4574 if (pngcrush_mode == DEFAULT_MODE)
4575 {
4576 if (argc - names == 2)
4577 {
4578 inname = argv[names];
4579 outname = argv[names + 1];
4580 }
4581
4582 else if (overwrite)
4583 {
4584 inname = argv[names];
4585 }
4586
4587 else
4588 {
4589 if ((argc - names == 1 || nosave))
4590 {
4591 inname = argv[names];
4592 }
4593 if (verbose > 0 && !nosave)
4594 {
4595 print_usage(1); /* this exits */
4596 }
4597 }
4598 }
4599
4600 first_name = names;
4601
4602 if (benchmark_iterations)
4603 bench=1;
4604 else
4605 bench=0;
4606
4607 for (; bench <= benchmark_iterations; bench++)
4608 {
4609 if (benchmark_iterations > 0)
4610 {
4611 P1(" Pngcrush benchmark iteration %d\n",bench);
4612 names = first_name;
4613 }
4614
4615 #if PNGCRUSH_TIMERS > 0
4616 for (pc_timer = 0; pc_timer < PNGCRUSH_TIMERS; pc_timer++)
4617 {
4618 pngcrush_timer_reset(pc_timer);
4619 filter_count[pc_timer]=0;
4620 }
4621 pngcrush_timer_start(PNGCRUSH_TIMER_TOTAL);
4622 pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
4623 #endif
4624
4625 for (ia = 0; ia < 256; ia++)
4626 trns_array[ia]=255;
4627
4628 for (;;) /* loop on input files */
4629 {
4630 methods_enabled = 0;
4631 last_trial = 0;
4632
4633 if (png_row_filters != NULL)
4634 {
4635 free(png_row_filters);
4636 png_row_filters = NULL;
4637 }
4638
4639 image_specified_gamma = 0;
4640 intent=specified_intent;
4641
4642 inname = argv[names++];
4643
4644 if (inname == NULL)
4645 {
4646 #if PNGCRUSH_TIMERS > 0
4647 pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
4648 pngcrush_timer_stop(PNGCRUSH_TIMER_TOTAL);
4649 #endif
4650 if (verbose >= 0)
4651 {
4652 show_result();
4653 }
4654 break;
4655 }
4656
4657 if (pngcrush_mode == DIRECTORY_MODE || pngcrush_mode == DIREX_MODE) {
4658 int inlen, outlen;
4659 #ifndef __riscos
4660 struct stat stat_buf;
4661 if (stat(directory_name, &stat_buf))
4662 #else
4663 if (fileexists(directory_name) & 2)
4664 #endif
4665 {
4666 #if defined(_MBCS) || defined(WIN32) || defined(__WIN32__)
4667 if (_mkdir(directory_name))
4668 #else
4669 if (mkdir(directory_name, 0755))
4670 #endif
4671 {
4672 fprintf(STDERR,
4673 "pngcrush: could not create directory %s\n",
4674 directory_name);
4675 exit(1);
4676 }
4677 nofilecheck = 1;
4678 }
4679 outlen = strlen(directory_name);
4680 if (outlen >= STR_BUF_SIZE-1)
4681 {
4682 fprintf(STDERR,
4683 "pngcrush: directory %s is too long for buffer\n",
4684 directory_name);
4685 exit(1);
4686 }
4687
4688 strcpy(out_string, directory_name);
4689 /* Append a slash if it hasn't already got one at the end. */
4690 if (out_string[outlen-1] != SLASH[0] &&
4691 out_string[outlen-1] != FWD_SLASH[0] &&
4692 out_string[outlen-1] != BACK_SLASH[0])
4693 out_string[outlen++] = SLASH[0]; /* (assume SLASH is 1 byte) */
4694 out_string[outlen] = '\0';
4695
4696 inlen = strlen(inname);
4697 if (inlen >= STR_BUF_SIZE)
4698 {
4699 fprintf(STDERR,
4700 "pngcrush: filename %s is too long for buffer\n", inname);
4701 exit(1);
4702 }
4703 strcpy(in_string, inname);
4704 in_string[inlen] = '\0';
4705 #ifdef __riscos
4706 op = strrchr(in_string, '.');
4707 if (!op)
4708 op = in_string;
4709 else
4710 op++;
4711 #else
4712 op = in_string;
4713 ip = in_string + inlen - 1; /* start at last char in string */
4714 while (ip > in_string)
4715 {
4716 if (*ip == '\\' || *ip == '/')
4717 {
4718 op = ip + 1;
4719 break;
4720 }
4721 --ip;
4722 }
4723 #endif
4724
4725 if (outlen + (inlen - (op - in_string)) >= STR_BUF_SIZE)
4726 {
4727 fprintf(STDERR,
4728 "pngcrush: full path is too long for buffer\n");
4729 exit(1);
4730 }
4731 strcpy(out_string+outlen, op);
4732 /*outlen += inlen - (op - in_string); */
4733 outname = out_string;
4734 }
4735
4736 if (overwrite && (pngcrush_mode == EXTENSION_MODE ||
4737 pngcrush_mode == DIRECTORY_MODE ||
4738 pngcrush_mode == DIREX_MODE))
4739 {
4740 if (overwrite > 0)
4741 {
4742 P1( "Ignoring \"-ow\"; cannot use it with \"-d\" or \"-e\"");
4743 overwrite=0;
4744 }
4745 }
4746
4747 /*
4748 * FIXME: need same input-validation fixes (as above) here, too
4749 *
4750 * FIXME: what was the point of setting in_string and out_string in
4751 * DIREX_MODE above if going to do all over again here?
4752 */
4753 if (pngcrush_mode == EXTENSION_MODE || pngcrush_mode == DIREX_MODE)
4754 {
4755 ip = in_string;
4756 in_string[0] = '\0';
4757 if (pngcrush_mode == EXTENSION_MODE)
4758 strncat(in_string, inname, STR_BUF_SIZE-1);
4759 else
4760 strncat(in_string, outname, STR_BUF_SIZE-1);
4761 ip = in_string;
4762 op = dot = out_string;
4763 while (*ip != '\0')
4764 {
4765 *op++ = *ip++;
4766 #ifdef __riscos
4767 if (*ip == '/')
4768 dot = op;
4769 #else
4770 if (*ip == '.')
4771 dot = op;
4772 #endif
4773 }
4774 *op = '\0';
4775
4776 if (dot != out_string)
4777 *dot = '\0';
4778
4779 in_extension[0] = '\0';
4780 if (dot != out_string)
4781 {
4782 strncat(in_extension, ++dot, STR_BUF_SIZE - 1);
4783 }
4784
4785 strncat(out_string, extension, STR_BUF_SIZE - 1);
4786 outname = out_string;
4787 }
4788
4789 if ((outname[strlen(outname) - 4] == 'p') &&
4790 (outname[strlen(outname) - 3] == 'p') &&
4791 (outname[strlen(outname) - 2] == 'n') &&
4792 (outname[strlen(outname) - 1] == 'g'))
4793 {
4794 /* Writing a *.ppng (png with premultiplied alpha) */
4795 premultiply=2;
4796 #ifndef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
4797 png_error(read_ptr, "Premultiplied alpha is not supported");
4798 #endif
4799 }
4800
4801 if ((outname[strlen(outname) - 4] == 'a') &&
4802 (outname[strlen(outname) - 3] == 'p') &&
4803 (outname[strlen(outname) - 2] == 'n') &&
4804 (outname[strlen(outname) - 1] == 'g'))
4805 {
4806 /* Writing an APNG */
4807 save_apng_chunks=1;
4808 }
4809
4810 if (nosave < 2)
4811 {
4812 P1( "Opening file %s for length measurement\n",
4813 inname);
4814
4815 if ((fpin = FOPEN(inname, "rb")) == NULL)
4816 {
4817 fprintf(STDERR, "Could not find file: %s\n", inname);
4818 continue;
4819 }
4820 number_of_open_files++;
4821
4822 #ifdef PNGCRUSH_LOCO
4823 if (new_mng)
4824 {
4825
4826 # ifdef PNG_USER_MEM_SUPPORTED
4827 if (verbose > 0)
4828 mng_ptr = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
4829 (png_voidp) NULL, (png_error_ptr) pngcrush_cexcept_error,
4830 (png_error_ptr) pngcrush_warning, (png_voidp) NULL,
4831 (png_malloc_ptr) pngcrush_debug_malloc,
4832 (png_free_ptr) pngcrush_debug_free);
4833 else
4834 # endif
4835 mng_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
4836 (png_voidp) NULL,
4837 (png_error_ptr) pngcrush_cexcept_error,
4838 (png_error_ptr) pngcrush_warning);
4839 if (mng_ptr == NULL)
4840 fprintf(STDERR, "pngcrush could not create mng_ptr");
4841
4842 if ((mng_out = FOPEN(mngname, "wb")) == NULL)
4843 {
4844 fprintf(STDERR,
4845 "pngcrush: could not open output file %s\n",
4846 mngname);
4847 FCLOSE(fpin);
4848 exit(1);
4849 }
4850 number_of_open_files++;
4851 png_init_io(mng_ptr, mng_out);
4852 png_set_write_fn(mng_ptr, (png_voidp) mng_out,
4853 (png_rw_ptr) pngcrush_write_png,
4854 pngcrush_flush);
4855 }
4856 #endif /* PNGCRUSH_LOCO */
4857
4858 idat_length[0] = measure_idats(fpin);
4859
4860 #ifdef PNGCRUSH_LOCO
4861 if (new_mng)
4862 {
4863 png_destroy_write_struct(&mng_ptr, NULL);
4864 FCLOSE(mng_out);
4865 }
4866 #endif
4867
4868 FCLOSE(fpin);
4869
4870
4871 if (verbose >= 0 && bench < 2)
4872 {
4873 if (nosave)
4874 {
4875 fprintf(STDERR, " %s:\n", inname);
4876 }
4877 else if (overwrite)
4878 {
4879 fprintf(STDERR,
4880 " Recompressing IDAT chunks in %s\n", inname);
4881 }
4882 else
4883 {
4884 fprintf(STDERR,
4885 " Recompressing IDAT chunks in %s to %s\n",
4886 inname, outname);
4887 }
4888 fprintf(STDERR,
4889 " Total length of data found in critical chunks "
4890 " =%10lu\n", (unsigned long)idat_length[0]);
4891 fflush(STDERR);
4892 }
4893
4894 if (idat_length[0] == 0)
4895 continue;
4896
4897 }
4898
4899 else
4900 idat_length[0] = 1;
4901
4902 if (image_is_immutable)
4903 {
4904 fprintf(STDERR,
4905 " Image %s has a dSIG chunk and is immutable.\n", inname);
4906 }
4907
4908 if (!image_is_immutable)
4909 {
4910
4911 if (force_output_color_type != 8 &&
4912 force_output_color_type != 0 &&
4913 force_output_color_type != 2 &&
4914 force_output_color_type != 3 &&
4915 force_output_color_type != 4 &&
4916 force_output_color_type != 6)
4917 {
4918 fprintf(STDERR, "\n Ignoring invalid color_type: %d\n",
4919 force_output_color_type);
4920 force_output_color_type=8;
4921 }
4922 output_color_type = force_output_color_type;
4923
4924 output_bit_depth = force_output_bit_depth;
4925
4926 best_of_three = 1;
4927 pngcrush_best_byte_count=0xffffffff;
4928
4929 if (blacken == 1 || make_gray == 1 || make_opaque == 1 ||
4930 reduce_palette == 1)
4931 {
4932 try_method[0] = 0;
4933 }
4934
4935 /*
4936 * From the PNG spec, various dependencies among chunk types
4937 * must be accounted for during any reduction of color type
4938 * or bit depth:
4939 *
4940 * IHDR valid bit depth depends on color type
4941 * valid filter type depends on color type (for MNG extensions)
4942 * tRNS depends on color type
4943 * depends on num_palette for color type 3 (palette)
4944 * iCCP valid profile depends on color type
4945 * sBIT depends on color type and bit depth
4946 * bKGD depends on color type and bit depth
4947 * hIST depends on num_palette
4948 *
4949 * Chunk types present have been detected in the first pass over
4950 * the file, in the measure_idat() function.
4951 */
4952
4953 if (make_gray)
4954 {
4955 if ((found_iCCP && keep_unknown_chunk("iCCP", argv)) ||
4956 (found_color_bKGD && keep_unknown_chunk("bKGD", argv)) ||
4957 found_acTL_chunk == 1 ||
4958 (found_sBIT_different_RGB_bits &&
4959 keep_unknown_chunk("sBIT", argv)))
4960 {
4961 P1 ("Cannot change colortype to gray when iCCP,"
4962 " acTL, bKGD with color, or sBIT chunk is present\n");
4963 make_gray = 0;
4964 }
4965 else
4966 {
4967 make_gray = 1;
4968 try_method[0] = 0;
4969 }
4970 }
4971
4972 if (make_opaque)
4973 {
4974 if (found_tRNS || found_acTL_chunk == 1)
4975 {
4976 P1("Cannot remove the alpha channel when tRNS"
4977 " or acTL chunk is present\n");
4978 make_opaque = 0;
4979 }
4980 else
4981 {
4982 make_opaque = 1;
4983 try_method[0] = 0;
4984 }
4985 }
4986
4987 if (make_8_bit)
4988 {
4989 if ((found_bKGD && keep_unknown_chunk("bKGD", argv)) ||
4990 found_acTL_chunk == 1 ||
4991 (found_sBIT_max > 8 && keep_unknown_chunk("sBIT", argv)))
4992 {
4993 P1 ("Cannot reduce bit depth to 8 when bKGD,"
4994 " sBIT or acTL chunk is present\n");
4995 make_8_bit = 0;
4996 }
4997 else
4998 {
4999 make_8_bit = 1;
5000 try_method[0] = 0;
5001 }
5002 }
5003
5004 if (input_color_type == 3 && reduce_palette)
5005 {
5006 if ((found_hIST && keep_unknown_chunk("hIST", argv)) ||
5007 found_acTL_chunk == 1)
5008 {
5009 P1("Cannot reduce palette length when hIST"
5010 " or acTL chunk is present\n");
5011 reduce_palette = 0;
5012 plte_len = -1;
5013 }
5014 else
5015 {
5016 try_method[0] = 0;
5017 plte_len = 0;
5018 }
5019 }
5020
5021 /* Handle specified brute_force options */
5022 if (brute_force_level || brute_force_filter || brute_force_strategy)
5023 {
5024 for (method = 1; method < num_methods; method++)
5025 {
5026 int option;
5027
5028 try_method[method]=1;
5029 if (brute_force_level)
5030 {
5031 for (option = 0; option < 10; option++)
5032 if (option == lv[method])
5033 try_method[method]=brute_force_levels[option];
5034 }
5035
5036 if ((try_method[method] == 0) && brute_force_filter)
5037 {
5038 for (option = 0; option < 6; option++)
5039 if (option == fm[method])
5040 try_method[method]=brute_force_filters[option];
5041 }
5042
5043 if ((try_method[method] == 0) && brute_force_strategy)
5044 {
5045 for (option = 0; option < NUM_STRATEGIES; option++)
5046 if (option == zs[method])
5047 try_method[method]=brute_force_strategies[option];
5048 }
5049
5050 if (method && method < 11)
5051 try_method[method] = 1;
5052 }
5053
5054 if (speed)
5055 {
5056 /* Do not try AVG or PAETH */
5057 for (method = 1; method < num_methods; method++)
5058 {
5059 if (try_method[method] == 0 && (fm[method] == 3 ||
5060 fm[method] == 4 || fm[method] == 5))
5061 try_method[method] = 1;
5062 }
5063 }
5064 }
5065
5066 if (methods_specified == 0 || try10 != 0)
5067 {
5068 for (i = 0; i <= DEFAULT_METHODS; i++)
5069 try_method[i] = 0;
5070
5071 try_method[6] = try10;
5072 }
5073
5074 for (i = 1; i <= MAX_METHODS; i++)
5075 {
5076 methods_enabled += (1 - try_method[i]);
5077 }
5078 P1("%d methods enabled\n",methods_enabled);
5079 /* Skip trial 0 when a single method was specified and -reduce was not */
5080 if (methods_specified != 0 && noreduce != 0)
5081 {
5082 if (methods_enabled == 1)
5083 {
5084 try_method[0] = 1;
5085 make_opaque = 0;
5086 make_gray = 0;
5087 make_8_bit = 0;
5088 reduce_palette = 0;
5089 }
5090 }
5091
5092 last_method = 0;
5093 for (i = 1; i <= MAX_METHODS; i++)
5094 {
5095 if (try_method[i] == 0)
5096 last_method = i;
5097 }
5098
5099 if (methods_enabled > 1)
5100 last_method++;
5101
5102 P1(" pngcrush: methods = %d\n",methods_enabled);
5103 P1(" pngcrush: last_method = %d\n",last_method);
5104
5105 if (methods_enabled == 1 && last_method == 176)
5106 copy_idat = 1;
5107
5108 best_of_three = 1;
5109
5110 #ifndef __riscos
5111 {
5112 /* COVERITY complains about TOCTOU when inname is used later */
5113 struct stat stat_buf;
5114 stat(inname, &stat_buf);
5115 input_length = (unsigned long) stat_buf.st_size;
5116 }
5117 #else
5118 input_length = (unsigned long) filesize(inname);
5119 #endif
5120
5121 /* ////////////////////////////////////////////////////////////////////
5122 //////////////// ////////////////////
5123 //////////////// START OF MAIN LOOP OVER METHODS ////////////////////
5124 //////////////// ////////////////////
5125 //////////////////////////////////////////////////////////////////// */
5126
5127 /* MAX_METHODS is 177 */
5128 P1("\n\nENTERING MAIN LOOP OVER %d METHODS\n", MAX_METHODS);
5129 for (trial = 0; trial <= last_method; trial++)
5130 {
5131 if (nosave || trial == last_method)
5132 last_trial = 1;
5133
5134 if (verbose > 1)
5135 fprintf(STDERR, "pngcrush: trial = %d\n",trial);
5136
5137 pngcrush_write_byte_count=0;
5138 #ifdef PNGCRUSH_H
5139 # if ZLIB_VERNUM > 0x1240
5140 if (last_trial == 0)
5141 pngcrush_write_byte_count=6; /* zlib header that isn't written */
5142 # endif
5143 #endif
5144
5145 found_IDAT = 0;
5146
5147 if (trial != 0)
5148 idat_length[trial] = (png_uint_32) 0xffffffff;
5149
5150 /* this part of if-block is for final write-the-best-file
5151 iteration */
5152 if (trial == last_method)
5153 {
5154 png_uint_32 best_length;
5155
5156 if (methods_enabled == 1)
5157 {
5158 best = trial;
5159 best_length = idat_length[trial];
5160 }
5161 else
5162 {
5163 int j;
5164
5165 /* check lengths */
5166 best = 0; /* i.e., input file */
5167 best_length = (png_uint_32) 0xffffffff;
5168 for (j = 0; j <= last_method; j++)
5169 {
5170 if (best == 0 && best_length == idat_length[j])
5171 {
5172 /* If no change, report the first match */
5173 best = j;
5174 }
5175 if ((force == 0 || j != 0) &&
5176 best_length > idat_length[j])
5177 {
5178 best_length = idat_length[j];
5179 best = j;
5180 }
5181 if (j > 148 && j < 176 && best_length == idat_length[j])
5182 {
5183 /* break ties in favor of method 6 */
5184 best = j;
5185 }
5186 }
5187 }
5188
5189 if (image_is_immutable ||
5190 (idat_length[best] == idat_length[0] &&
5191 force == 0 && nosave == 0))
5192 {
5193 /* just copy input to output */
5194
5195 P2("prepare to copy input to output\n");
5196 pngcrush_pause();
5197
5198 if ((fpin = FOPEN(inname, "rb")) == NULL)
5199 {
5200 fprintf(STDERR, "Could not find input file %s\n",
5201 inname);
5202 continue;
5203 }
5204
5205 number_of_open_files++;
5206 if ((fpout = FOPEN(outname, "wb")) == NULL)
5207 {
5208 fprintf(STDERR,
5209 "pngcrush: could not open output file %s\n",
5210 outname);
5211 FCLOSE(fpin);
5212 exit(1);
5213 }
5214
5215 number_of_open_files++;
5216 P2("copying input to output...");
5217
5218 for (;;)
5219 {
5220 png_size_t num_in, num_out;
5221
5222 num_in = fread((void *)buffer, 1, 1, fpin);
5223 if (!num_in)
5224 break;
5225 num_out = fwrite(buffer, 1, 1, fpout);
5226 if (num_out != num_in)
5227 P2("copy error.\n");
5228 }
5229 P2("copy complete.\n");
5230 pngcrush_pause();
5231 FCLOSE(fpin);
5232 FCLOSE(fpout);
5233 setfiletype(outname);
5234 break;
5235 }
5236
5237 filter_type = fm[best];
5238 zlib_level = lv[best];
5239 if (zs[best] == 1)
5240 z_strategy = Z_FILTERED;
5241 else if (zs[best] == 2)
5242 z_strategy = Z_HUFFMAN_ONLY;
5243 #ifdef Z_RLE
5244 else if (zs[best] == 3)
5245 z_strategy = Z_RLE;
5246 #endif
5247 else /* if (zs[best] == 0) */
5248 z_strategy = Z_DEFAULT_STRATEGY;
5249 }
5250
5251 else /* Trial < last_method */
5252 {
5253 if (trial > 2 && trial < 5 && idat_length[trial - 1]
5254 < idat_length[best_of_three])
5255 best_of_three = trial - 1;
5256
5257 if (try_method[trial])
5258 {
5259 P2("skipping \"late\" trial %d\n", trial);
5260 continue;
5261 }
5262
5263 /* default behavior is to do the heuristics (6 of the first
5264 * 10 methods). try10 means try all of 1-10.
5265 */
5266 if (!methods_specified && try10 == 0)
5267 {
5268 if ((trial == 4 || trial == 7) && best_of_three != 1)
5269 {
5270 P2("skipping \"early\" trial %d\n", trial);
5271 continue;
5272 }
5273 if ((trial == 5 || trial == 8) && best_of_three != 2)
5274 {
5275 P2("skipping \"early\" trial %d\n", trial);
5276 continue;
5277 }
5278 if ((trial == 6 || trial == 9 || trial == 10)
5279 && best_of_three != 3)
5280 {
5281 P2("skipping \"early\" trial %d\n", trial);
5282 continue;
5283 }
5284 }
5285 filter_type = fm[trial];
5286 zlib_level = lv[trial];
5287 if (zs[trial] == 1)
5288 z_strategy = Z_FILTERED;
5289 else if (zs[trial] == 2)
5290 z_strategy = Z_HUFFMAN_ONLY;
5291 #ifdef Z_RLE
5292 else if (zs[trial] == 3)
5293 z_strategy = Z_RLE;
5294 #endif
5295 else /* if (zs[trial] == 0) */
5296 z_strategy = Z_DEFAULT_STRATEGY;
5297 final_method = trial;
5298 if (!nosave)
5299 {
5300 P2("\n\n------------------------------------------------\n"
5301 "Begin trial %d, filter %d, strategy %d, level %d\n",
5302 trial, filter_type, z_strategy, zlib_level);
5303 }
5304 }
5305
5306 P2("prepare to open files.\n");
5307 pngcrush_pause();
5308
5309 if ((fpin = FOPEN(inname, "rb")) == NULL)
5310 {
5311 fprintf(STDERR, "Could not find input file %s\n", inname);
5312 continue;
5313 }
5314 number_of_open_files++;
5315
5316 if (last_trial && nosave == 0)
5317 {
5318 #ifndef __riscos
5319 /* Can't sensibly check this on RISC OS without opening a file
5320 for update or output
5321 */
5322 struct stat stat_in, stat_out;
5323 if (last_trial && !nofilecheck
5324 && (stat(inname, &stat_in) == 0)
5325 && (stat(outname, &stat_out) == 0) &&
5326 #if defined(_MSC_VER) || defined(__MINGW32__) /* maybe others? */
5327 /* MSVC++6.0 will erroneously return 0 for both files, so
5328 we simply check the size instead. It is possible that
5329 we will erroneously reject the attempt when inputsize
5330 and outputsize are equal, for different files
5331 */
5332 (stat_in.st_size == stat_out.st_size) &&
5333 #else
5334 (stat_in.st_ino == stat_out.st_ino) &&
5335 #endif
5336 (stat_in.st_dev == stat_out.st_dev))
5337 {
5338 fprintf(STDERR,
5339 "\n pngcrush: cannot overwrite input file %s\n",
5340 outname);
5341 P1(" st_ino=%d, st_size=%d\n\n",
5342 (int) stat_in.st_ino, (int) stat_in.st_size);
5343 FCLOSE(fpin);
5344 exit(1);
5345 }
5346 #endif
5347 if ((fpout = FOPEN(outname, "wb")) == NULL)
5348 {
5349 fprintf(STDERR,
5350 "pngcrush: could not open output file %s\n",
5351 outname);
5352 FCLOSE(fpin);
5353 exit(1);
5354 }
5355
5356 number_of_open_files++;
5357 }
5358
5359 P2("files are opened.\n");
5360 pngcrush_pause();
5361
5362 /* OK to ignore any warning about the address of exception__prev in "Try" */
5363 Try {
5364 png_uint_32 row_length;
5365 P1( "Allocating read and write structures\n");
5366 #ifdef PNG_USER_MEM_SUPPORTED
5367 if (verbose > 0)
5368 read_ptr = png_create_read_struct_2(PNG_LIBPNG_VER_STRING,
5369 (png_voidp) NULL,
5370 (png_error_ptr) pngcrush_cexcept_error,
5371 (png_error_ptr) pngcrush_warning,
5372 (png_voidp) NULL,
5373 (png_malloc_ptr) pngcrush_debug_malloc,
5374 (png_free_ptr) pngcrush_debug_free);
5375 else
5376 #endif /* PNG_USER_MEM_SUPPORTED */
5377 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
5378 (png_voidp) NULL,
5379 (png_error_ptr) pngcrush_cexcept_error,
5380 (png_error_ptr) pngcrush_warning);
5381 if (read_ptr == NULL)
5382 Throw "pngcrush could not create read_ptr";
5383
5384 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
5385 # if PNGCRUSH_LIBPNG_VER >= 10400
5386 /* Allow certain errors in the input file to be handled
5387 * as warnings.
5388 */
5389 png_set_benign_errors(read_ptr, 1);
5390 # endif
5391 #endif
5392
5393 #ifdef PNG_SET_USER_LIMITS_SUPPORTED
5394 if (no_limits == 0)
5395 {
5396 # if PNGCRUSH_LIBPNG_VER >= 10400
5397 png_set_user_limits(read_ptr, 500000L, 500000L);
5398 png_set_chunk_cache_max(read_ptr, 500);
5399 # endif
5400 # if PNGCRUSH_LIBPNG_VER >= 10401
5401 png_set_chunk_malloc_max(read_ptr, 2000000L);
5402 # endif
5403 }
5404 #endif /* PNG_SET_USER_LIMITS_SUPPORTED */
5405
5406 #if defined(PNG_MAXIMUM_INFLATE_WINDOW) && defined(PNG_OPTION_ON)
5407 if (salvage)
5408 {
5409 P1(" Setting MAXIMUM_INFLATE_WINDOW\n");
5410 png_set_option(read_ptr, PNG_MAXIMUM_INFLATE_WINDOW,
5411 PNG_OPTION_ON);
5412 }
5413 #endif
5414
5415 #if 0
5416 /* Use a smaller decompression buffer for speed */
5417 png_set_compression_buffer_size(read_ptr,
5418 (png_size_t)256);
5419 #endif /* 0 */
5420
5421 /* Change the underlying color of any fully transparent pixel to black.
5422 * Remove the alpha channel from any fully-opaque image.
5423 * Change any all-gray image to a gray colortype.
5424 * Reduce 16-bit image to 8-bit if possible without loss.
5425 */
5426 if (trial == 0 &&
5427 (blacken == 1 || make_gray == 1 || make_opaque == 1 ||
5428 make_8_bit == 1 || reduce_palette == 1))
5429 {
5430 P1(" Examine image for possible lossless reductions\n");
5431 png_set_read_user_transform_fn(read_ptr, pngcrush_examine_pixels_fn);
5432 }
5433 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
5434 if (last_trial == 0)
5435 {
5436 png_set_keep_unknown_chunks(read_ptr,
5437 PNG_HANDLE_CHUNK_NEVER, (png_bytep) NULL, 0);
5438
5439 png_set_keep_unknown_chunks(read_ptr,
5440 PNG_HANDLE_CHUNK_NEVER, chunks_to_ignore,
5441 sizeof (chunks_to_ignore)/5);
5442 }
5443 #endif
5444
5445 if (nosave == 0)
5446 {
5447 #ifdef PNG_USER_MEM_SUPPORTED
5448 if (verbose > 0)
5449 write_ptr = png_create_write_struct_2(
5450 PNG_LIBPNG_VER_STRING,
5451 (png_voidp) NULL,
5452 (png_error_ptr) pngcrush_cexcept_error,
5453 (png_error_ptr) pngcrush_warning,
5454 (png_voidp) NULL,
5455 (png_malloc_ptr) pngcrush_debug_malloc,
5456 (png_free_ptr) pngcrush_debug_free);
5457 else
5458 #endif
5459 write_ptr = png_create_write_struct(
5460 PNG_LIBPNG_VER_STRING,
5461 (png_voidp) NULL,
5462 (png_error_ptr) pngcrush_cexcept_error,
5463 (png_error_ptr) NULL);
5464 if (write_ptr == NULL)
5465 Throw "pngcrush could not create write_ptr";
5466
5467 }
5468 P1("Allocating read_info, write_info, end_info structures\n");
5469 read_info_ptr = png_create_info_struct(read_ptr);
5470
5471 if (read_info_ptr == NULL)
5472 Throw "pngcrush could not create read_info_ptr";
5473
5474 end_info_ptr = png_create_info_struct(read_ptr);
5475 if (end_info_ptr == NULL)
5476 Throw "pngcrush could not create end_info_ptr";
5477
5478 if (nosave == 0)
5479 {
5480 write_info_ptr = png_create_info_struct(write_ptr);
5481 if (write_info_ptr == NULL)
5482 Throw "pngcrush could not create write_info_ptr";
5483
5484 write_end_info_ptr = png_create_info_struct(write_ptr);
5485 if (write_end_info_ptr == NULL)
5486 Throw
5487 "pngcrush could not create write_end_info_ptr";
5488 }
5489
5490 P2("structures created.\n");
5491 pngcrush_pause();
5492
5493 P1( "Initializing input and output streams\n");
5494 #ifdef PNG_STDIO_SUPPORTED
5495 png_init_io(read_ptr, fpin);
5496 #else
5497 png_set_read_fn(read_ptr, (png_voidp) fpin,
5498 (png_rw_ptr) NULL);
5499 #endif /* PNG_STDIO_SUPPORTED */
5500
5501 if (nosave == 0)
5502 png_set_write_fn(write_ptr, (png_voidp) fpout,
5503 (png_rw_ptr) pngcrush_write_png, pngcrush_flush);
5504
5505 P2("io has been initialized.\n");
5506 pngcrush_pause();
5507
5508 #ifdef PNG_CRC_QUIET_USE
5509 if (check_crc == 0)
5510 {
5511 /* We don't need to check IDAT CRC's and ADLER32 because
5512 * they were already checked in the pngcrush_measure_idat
5513 * function
5514 */
5515 png_set_option(read_ptr, PNG_IGNORE_ADLER32,
5516 PNG_OPTION_ON);
5517 png_set_crc_action(read_ptr, PNG_CRC_QUIET_USE,
5518 PNG_CRC_QUIET_USE);
5519 }
5520 #endif
5521
5522 #ifndef PNGCRUSH_CHECK_ADLER32
5523 # ifdef PNG_IGNORE_ADLER32
5524 if (last_trial == 0)
5525 {
5526 /* During trials other than the final output, avoid
5527 * calculating CRC and ADLER32 checksums (just write
5528 * a DEFLATE datastream)
5529 */
5530 png_set_option(write_ptr, PNG_IGNORE_ADLER32,
5531 PNG_OPTION_ON);
5532 }
5533 # endif
5534 #endif
5535
5536 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
5537 /* Only run this test (new in libpng-1.5.10) during the
5538 * 0th and last trial
5539 */
5540 if ((input_color_type == 3) &&
5541 ((last_trial && reduce_palette == 0) ||
5542 (trial == 0 && reduce_palette == 1)))
5543 {
5544 P1(" Check the read palette\n");
5545 png_set_check_for_invalid_index (read_ptr, 1);
5546 }
5547 #endif
5548 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
5549 if (last_trial && nosave == 0 && output_color_type == 3)
5550 {
5551 P1(" Check the written palette\n");
5552 png_set_check_for_invalid_index (write_ptr, 1);
5553 }
5554 #endif
5555
5556 if (last_trial == 1)
5557 {
5558
5559 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
5560 png_set_keep_unknown_chunks(read_ptr, PNG_HANDLE_CHUNK_ALWAYS,
5561 (png_bytep) NULL, 0);
5562 #endif
5563
5564 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
5565 if (nosave == 0)
5566 {
5567 if (save_apng_chunks == 1)
5568 {
5569 /* To do: Why use write_ptr not read_ptr here? */
5570 png_set_keep_unknown_chunks(write_ptr,
5571 PNG_HANDLE_CHUNK_ALWAYS,
5572 (png_bytep) "acTL", 1);
5573 png_set_keep_unknown_chunks(write_ptr,
5574 PNG_HANDLE_CHUNK_ALWAYS,
5575 (png_bytep) "fcTL", 1);
5576 png_set_keep_unknown_chunks(write_ptr,
5577 PNG_HANDLE_CHUNK_ALWAYS,
5578 (png_bytep) "fdAT", 1);
5579 }
5580
5581 if (found_any_chunk == 1)
5582 png_set_keep_unknown_chunks(write_ptr,
5583 PNG_HANDLE_CHUNK_ALWAYS,
5584 (png_bytep) "dSIG", 1);
5585 if (all_chunks_are_safe)
5586 {
5587 png_set_keep_unknown_chunks(write_ptr,
5588 PNG_HANDLE_CHUNK_ALWAYS,
5589 (png_bytep) NULL, 0);
5590 printf("while saving, all_chunks_are_safe=\n");
5591 if (save_apng_chunks == 0)
5592 {
5593 png_set_keep_unknown_chunks(write_ptr,
5594 PNG_HANDLE_CHUNK_ALWAYS,
5595 (png_bytep) "acTL", 1);
5596 png_set_keep_unknown_chunks(write_ptr,
5597 PNG_HANDLE_CHUNK_ALWAYS,
5598 (png_bytep) "fcTL", 1);
5599 png_set_keep_unknown_chunks(write_ptr,
5600 PNG_HANDLE_CHUNK_ALWAYS,
5601 (png_bytep) "fdAT", 1);
5602 }
5603 }
5604
5605 else
5606 {
5607 #if !defined(PNG_cHRM_SUPPORTED) || !defined(PNG_hIST_SUPPORTED) || \
5608 !defined(PNG_iCCP_SUPPORTED) || !defined(PNG_sCAL_SUPPORTED) || \
5609 !defined(PNG_pCAL_SUPPORTED) || !defined(PNG_sPLT_SUPPORTED) || \
5610 !defined(PNG_sTER_SUPPORTED) || !defined(PNG_tIME_SUPPORTED)
5611 png_byte chunk_name[5];
5612 chunk_name[4] = '\0';
5613 #endif
5614
5615 /* To do: Why use write_ptr not read_ptr here? */
5616
5617 if (keep_unknown_chunk("alla", argv) &&
5618 keep_unknown_chunk("allb", argv))
5619 png_set_keep_unknown_chunks(write_ptr,
5620 PNG_HANDLE_CHUNK_IF_SAFE,
5621 (png_bytep) NULL,
5622 0);
5623 else
5624 png_set_keep_unknown_chunks(write_ptr,
5625 PNG_HANDLE_CHUNK_NEVER,
5626 (png_bytep) NULL,
5627 0);
5628
5629 #ifndef PNG_cHRM_SUPPORTED
5630 if (keep_unknown_chunk("cHRM", argv))
5631 {
5632 pngcrush_save_uint_32(chunk_name, PNG_UINT_cHRM);
5633 png_set_keep_unknown_chunks(write_ptr,
5634 PNG_HANDLE_CHUNK_ALWAYS,
5635 chunk_name, 1);
5636 }
5637 #endif
5638 #ifndef PNG_hIST_SUPPORTED
5639 if (keep_unknown_chunk("hIST", argv))
5640 {
5641 pngcrush_save_uint_32(chunk_name, PNG_UINT_hIST);
5642 png_set_keep_unknown_chunks(write_ptr,
5643 PNG_HANDLE_CHUNK_ALWAYS,
5644 chunk_name, 1);
5645 }
5646 #endif
5647 #ifndef PNG_iCCP_SUPPORTED
5648 if (keep_unknown_chunk("iCCP", argv))
5649 {
5650 pngcrush_save_uint_32(chunk_name, PNG_UINT_iCCP);
5651 png_set_keep_unknown_chunks(write_ptr,
5652 PNG_HANDLE_CHUNK_ALWAYS,
5653 chunk_name, 1);
5654 }
5655 #endif
5656 #ifndef PNG_iTXt_SUPPORTED
5657 if (keep_unknown_chunk("iTXt", argv))
5658 {
5659 pngcrush_save_uint_32(chunk_name, PNG_UINT_iTXt);
5660 png_set_keep_unknown_chunks(write_ptr,
5661 PNG_HANDLE_CHUNK_ALWAYS,
5662 chunk_name, 1);
5663 }
5664 #endif
5665 #ifndef PNG_sCAL_SUPPORTED
5666 if (keep_unknown_chunk("sCAL", argv))
5667 {
5668 pngcrush_save_uint_32(chunk_name, PNG_UINT_sCAL);
5669 png_set_keep_unknown_chunks(write_ptr,
5670 PNG_HANDLE_CHUNK_ALWAYS,
5671 chunk_name, 1);
5672 }
5673 #endif
5674 #ifndef PNG_pCAL_SUPPORTED
5675 if (keep_unknown_chunk("pCAL", argv))
5676 {
5677 pngcrush_save_uint_32(chunk_name, PNG_UINT_pCAL);
5678 png_set_keep_unknown_chunks(write_ptr,
5679 PNG_HANDLE_CHUNK_ALWAYS,
5680 chunk_name, 1);
5681 }
5682 #endif
5683 #ifndef PNG_sPLT_SUPPORTED
5684 if (keep_unknown_chunk("sPLT", argv))
5685 {
5686 pngcrush_save_uint_32(chunk_name, PNG_UINT_sPLT);
5687 png_set_keep_unknown_chunks(write_ptr,
5688 PNG_HANDLE_CHUNK_ALWAYS,
5689 chunk_name, 1);
5690 }
5691 #endif
5692 #ifndef PNG_sTER_SUPPORTED
5693 if (keep_unknown_chunk("sTER", argv))
5694 {
5695 pngcrush_save_uint_32(chunk_name, PNG_UINT_sTER);
5696 png_set_keep_unknown_chunks(write_ptr,
5697 PNG_HANDLE_CHUNK_ALWAYS,
5698 chunk_name, 1);
5699 }
5700 #endif
5701 #ifndef PNG_tIME_SUPPORTED
5702 if (keep_unknown_chunk("tIME", argv))
5703 {
5704 pngcrush_save_uint_32(chunk_name, PNG_UINT_tIME);
5705 png_set_keep_unknown_chunks(write_ptr,
5706 PNG_HANDLE_CHUNK_ALWAYS,
5707 chunk_name, 1);
5708 }
5709 #endif
5710 }
5711 } /* nosave == 0 */
5712 #endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
5713 } /* last trial */
5714
5715 /* To do: Remove this? We already did this in measure_idats */
5716 P1(" Reading signature bytes\n");
5717 {
5718 #ifdef PNGCRUSH_LOCO
5719 png_byte mng_signature[8] =
5720 { 138, 77, 78, 71, 13, 10, 26, 10 };
5721 #endif
5722 png_byte png_signature[8] =
5723 { 137, 80, 78, 71, 13, 10, 26, 10 };
5724
5725 pngcrush_default_read_data(read_ptr, png_signature, 8);
5726 png_set_sig_bytes(read_ptr, 8);
5727
5728 #ifdef PNGCRUSH_LOCO
5729 if (!(int)(png_memcmp(mng_signature, png_signature, 8)))
5730 {
5731 /* Skip the MHDR */
5732 png_permit_mng_features(read_ptr,
5733 PNG_FLAG_MNG_FILTER_64);
5734 png_skip_chunk(read_ptr);
5735 input_format = 1;
5736 }
5737
5738 else
5739 #endif
5740 if (png_sig_cmp(png_signature, 0, 8))
5741 {
5742 if (png_sig_cmp(png_signature, 0, 4))
5743 png_error(read_ptr, "Not a PNG file!");
5744 else
5745 png_error(read_ptr,
5746 "PNG file corrupted by ASCII conversion");
5747 }
5748 if (salvage && found_CgBI)
5749 {
5750 /* Skip the CgBI chunk */
5751
5752 png_skip_chunk(read_ptr);
5753
5754 /* iCCP and zTXt are probably unreadable
5755 * because of the nonstandard deflate */
5756
5757 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
5758 png_set_keep_unknown_chunks(read_ptr,
5759 PNG_HANDLE_CHUNK_NEVER,
5760 (png_bytep)"iCCP", 1);
5761 png_set_keep_unknown_chunks(read_ptr,
5762 PNG_HANDLE_CHUNK_NEVER,
5763 (png_bytep)"zTXt", 1);
5764 #endif
5765 }
5766 }
5767
5768 #ifndef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
5769 if (premultiply)
5770 png_error(read_ptr, "Premultiplied alpha is not supported");
5771 #endif
5772
5773 P1( " Reading info struct\n");
5774 png_read_info(read_ptr, read_info_ptr);
5775
5776 if (trial != 0)
5777 {
5778 if (make_opaque == 1)
5779 {
5780 P1(" Remove all-opaque alpha channel\n");
5781 if (output_color_type == 4)
5782 output_color_type = 0;
5783 if (output_color_type == 6)
5784 output_color_type = 2;
5785 }
5786 P1(" make_opaque= %d\n",make_opaque);
5787
5788 if (make_gray == 1)
5789 {
5790 /* Note: Take care that iCCP, sBIT, and bKGD data are not
5791 * lost or become invalid when reducing images from
5792 * truecolor to grayscale or when reducing the bit depth.
5793 * (To do: test this; it's probably OK)
5794 */
5795 /* To do: check bKGD color */
5796
5797 P1(" Encode all-gray image with a gray colortype\n");
5798 if (output_color_type == 6)
5799 output_color_type = 4;
5800 if (output_color_type == 2)
5801 output_color_type = 0;
5802 }
5803 P1(" make_gray= %d\n",make_gray);
5804
5805 if (make_8_bit == 1)
5806 {
5807 /* Note: Take care that sBIT and bKGD data are not
5808 * lost or become invalid when reducing the bit depth.
5809 * (To do: test this; it's probably OK)
5810 */
5811 P1(" Reduce 16-bit image losslessly to 8-bit\n");
5812 }
5813 P1(" make_8_bit= %d\n",make_8_bit);
5814
5815 if (make_opaque != 1 && blacken == 2)
5816 {
5817 P1(" Blacken the fully transparent pixels\n");
5818 png_set_read_user_transform_fn(read_ptr,
5819 pngcrush_transform_pixels_fn);
5820 }
5821 P1(" make_opaque= %d\n",make_opaque);
5822 P1(" blacken= %d\n",blacken);
5823
5824 if (reduce_palette == 1)
5825 {
5826 /* Note: Take care that sBIT and bKGD data are not
5827 * lost or become invalid when reducing the bit depth.
5828 * (To do: test this; it's probably OK)
5829 */
5830 P1(" Reduce palette by truncating unused entries\n");
5831 }
5832 P1(" reduce_palette= %d\n",reduce_palette);
5833 P1(" new plte_len = %d\n",plte_len);
5834 }
5835
5836 /* { GRR added for quick %-navigation (1) */
5837
5838 /* Start of chunk-copying/removal code, in order:
5839 * - IHDR
5840 * - bKGD
5841 * - cHRM
5842 * - gAMA
5843 * - sRGB
5844 * - iCCP
5845 * - oFFs
5846 * - pCAL
5847 * - pHYs
5848 * - hIST
5849 * - tRNS
5850 * - PLTE
5851 * - sBIT
5852 * - sCAL
5853 * - sPLT
5854 * - sTER
5855 * - tEXt/zTXt/iTXt
5856 * - tIME
5857 * - unknown chunks
5858 */
5859 {
5860 int compression_method,
5861 filter_method;
5862
5863 P1( "Transferring info struct\n");
5864
5865 if (png_get_IHDR(read_ptr, read_info_ptr, &width, &height,
5866 &bit_depth, &color_type, &interlace_method,
5867 &compression_method, &filter_method))
5868 {
5869 int need_expand = 0;
5870 input_color_type = color_type;
5871 input_bit_depth = bit_depth;
5872
5873 if (output_color_type > 7)
5874 {
5875 output_color_type = input_color_type;
5876 }
5877
5878 /* if (verbose > 1 && last_trial) */
5879 if (verbose > 1 && trial == 0)
5880 {
5881 fprintf(STDERR, " IHDR chunk data:\n");
5882 fprintf(STDERR,
5883 " Width=%lu, height=%lu\n",
5884 (unsigned long)width,
5885 (unsigned long)height);
5886 fprintf(STDERR, " Bit depth =%d\n",
5887 bit_depth);
5888 fprintf(STDERR, " Color type=%d\n",
5889 color_type);
5890 if (output_color_type != color_type)
5891 fprintf(STDERR,
5892 " Output color type=%d\n",
5893 output_color_type);
5894 fprintf(STDERR, " Interlace =%d\n",
5895 interlace_method);
5896 }
5897
5898 output_bit_depth = input_bit_depth;
5899
5900 if ((output_color_type != 3 || output_bit_depth > 8)
5901 && output_bit_depth >= 8
5902 && output_bit_depth > input_bit_depth)
5903 need_expand = 1;
5904
5905 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
5906 if ((color_type == 2 ||
5907 color_type == 6 ||
5908 color_type == 3) &&
5909 (output_color_type == 0 ||
5910 output_color_type == 4))
5911 {
5912 if (verbose > 0 && last_trial)
5913 {
5914 fprintf(STDERR, " Reducing truecolor "
5915 "image to grayscale.\n");
5916 }
5917 #ifdef PNG_FIXED_POINT_SUPPORTED
5918 png_set_rgb_to_gray_fixed(read_ptr, 1,
5919 21260, 71520);
5920 #else
5921 png_set_rgb_to_gray(read_ptr, 1,
5922 0.21260, 0.71520);
5923 #endif
5924 if (output_bit_depth < 8)
5925 output_bit_depth = 8;
5926 if (color_type == 3)
5927 need_expand = 1;
5928 }
5929 #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
5930
5931 if (color_type != 3 && output_color_type == 3)
5932 {
5933 fprintf(STDERR," Cannot change to indexed color "
5934 "(color_type 3)\n");
5935 output_color_type = input_color_type;
5936 }
5937
5938 if ((color_type == 0 || color_type == 4) &&
5939 (output_color_type == 2
5940 || output_color_type == 6))
5941 {
5942 png_set_gray_to_rgb(read_ptr);
5943 }
5944
5945 if ((color_type == 4 || color_type == 6) &&
5946 (output_color_type != 4
5947 && output_color_type != 6))
5948 {
5949 if (verbose > 0 && last_trial)
5950 {
5951 fprintf(STDERR,
5952 " Stripping existing alpha channel.\n");
5953 }
5954 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
5955 png_set_strip_alpha(read_ptr);
5956 #endif
5957 }
5958
5959 if ((output_color_type == 4
5960 || output_color_type == 6) && (color_type != 4
5961 && color_type != 6))
5962 {
5963 if (verbose > 0 && last_trial)
5964 fprintf(STDERR,
5965 " Adding an opaque alpha channel.\n");
5966 #ifdef PNG_READ_FILLER_SUPPORTED
5967 png_set_filler(read_ptr, (png_uint_32) 65535L,
5968 PNG_FILLER_AFTER);
5969 #endif
5970 need_expand = 1;
5971 }
5972
5973 if (output_color_type != 0 && output_color_type != 3 &&
5974 output_bit_depth < 8)
5975 output_bit_depth = 8;
5976
5977 if ((output_color_type == 2
5978 || output_color_type == 6)
5979 && color_type == 3)
5980 {
5981 if (verbose > 0 && last_trial)
5982 fprintf(STDERR,
5983 " Expanding indexed color file.\n");
5984 need_expand = 1;
5985 }
5986 #ifdef PNG_READ_EXPAND_SUPPORTED
5987 if (need_expand == 1)
5988 png_set_expand(read_ptr);
5989 #endif
5990
5991 #ifdef PNG_READ_PACK_SUPPORTED
5992 if (input_bit_depth < 8)
5993 {
5994 png_set_packing(read_ptr);
5995 }
5996
5997 if (output_color_type == 0 && output_bit_depth < 8)
5998 {
5999 png_color_8 true_bits;
6000 true_bits.gray = (png_byte) (output_bit_depth);
6001 png_set_shift(read_ptr, &true_bits);
6002 }
6003 #endif
6004
6005 if (trial > 0)
6006 {
6007 /* To do: have we got the right plte_len now? */
6008 if (plte_len > 0 && output_color_type == 3 &&
6009 force_output_bit_depth == 0)
6010 {
6011 if (plte_len <= 2)
6012 force_output_bit_depth = 1;
6013 else if (plte_len <= 4)
6014 force_output_bit_depth = 2;
6015 else if (plte_len <= 16)
6016 force_output_bit_depth = 4;
6017 else
6018 force_output_bit_depth = 8;
6019 }
6020
6021 if (make_8_bit == 1)
6022 {
6023 #if defined(PNG_READ_SCALE_16_TO_8_SUPPORTED) || \
6024 defined(PNG_READ_STRIP_16_TO_8_SUPPORTED)
6025 output_bit_depth = 8;
6026 force_output_bit_depth = 8;
6027 if (verbose > 0 && last_trial)
6028 fprintf(STDERR,
6029 " Stripping 16-bit depth to 8, trial = %d\n",
6030 trial);
6031
6032 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
6033 png_set_strip_16(read_ptr);
6034 #else
6035 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
6036 png_set_scale_16(read_ptr);
6037 #else
6038 fprintf(STDERR,
6039 " PNG_READ_STRIP_16_TO_8 NOT SUPPORTED\n");
6040 #endif
6041 #endif
6042 #endif
6043 }
6044 P1("force_output_bit_depth=%d\n",force_output_bit_depth);
6045 }
6046
6047
6048 if (last_trial == 1)
6049 {
6050 if (save_apng_chunks == 1 || found_acTL_chunk == 1)
6051 {
6052 if (save_apng_chunks == 0)
6053 {
6054 if (verbose > 0) fprintf(STDERR,
6055 " pngcrush will only save APNG chunks in an\n");
6056 if (verbose > 0) fprintf(STDERR,
6057 " output file with the \".apng\" extension\n");
6058 }
6059 if (input_color_type != output_color_type)
6060 {
6061 if (verbose > 0) fprintf(STDERR,
6062 " Cannot save APNG chunks with a color_type\n");
6063 if (verbose > 0) fprintf(STDERR,
6064 " different from that of the main image.\n");
6065 save_apng_chunks = 2;
6066 }
6067 if (input_bit_depth != output_bit_depth)
6068 {
6069 if (verbose > 0) fprintf(STDERR,
6070 " Cannot save APNG chunks with a bit_depth\n");
6071 if (verbose > 0) fprintf(STDERR,
6072 " different from that of the main image.\n");
6073 save_apng_chunks = 2;
6074 }
6075 if (save_apng_chunks != 1 && found_acTL_chunk == 1)
6076 found_acTL_chunk = 2;
6077 }
6078 }
6079
6080 if (verbose > 1)
6081 fprintf(STDERR, " Setting IHDR\n");
6082
6083 #ifdef PNGCRUSH_LOCO
6084 output_format = 0;
6085 if (do_loco)
6086 {
6087 if (output_color_type == 2
6088 || output_color_type == 6)
6089 {
6090 output_format = 1;
6091 filter_method = 64;
6092 if (nosave == 0 && last_trial == 1)
6093 png_permit_mng_features(write_ptr,
6094 PNG_FLAG_MNG_FILTER_64);
6095
6096 }
6097 } else
6098 filter_method = 0;
6099 #endif
6100
6101 png_set_IHDR(write_ptr, write_info_ptr, width,
6102 height, output_bit_depth,
6103 output_color_type, interlace_method,
6104 compression_method, filter_method);
6105
6106 } /* IHDR */
6107 }
6108
6109 if (premultiply == 1 || premultiply == 2)
6110 {
6111
6112 #ifdef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
6113 /* 0: not premultipled
6114 * 1: premultiplied input (input has .pngp suffix and the
6115 * PNGP chunk is present)
6116 * 2: premultiplied output (output has .pngp suffix and the
6117 * -premultiply option is present; PNGP chunk is added)
6118 * 3: premultiplied input and output (both have .pngp suffix)
6119 */
6120 P1("Calling png_set_premultiply_alpha\n");
6121 png_set_premultiply_alpha(read_ptr,output_bit_depth);
6122 #endif
6123 }
6124
6125
6126 /* Handle ancillary chunks */
6127 if (last_trial == 1)
6128 {
6129 #if defined(PNG_READ_bKGD_SUPPORTED) && defined(PNG_WRITE_bKGD_SUPPORTED)
6130 {
6131 png_color_16p background;
6132 if (!have_bkgd
6133 && png_get_bKGD(read_ptr, read_info_ptr,
6134 &background))
6135 {
6136 if (keep_chunk("bKGD", argv))
6137 {
6138 if ((input_color_type == 2 ||
6139 input_color_type == 6) &&
6140 (output_color_type == 0 ||
6141 output_color_type == 4))
6142 background->gray = background->green;
6143
6144 png_set_bKGD(write_ptr, write_info_ptr,
6145 background);
6146 }
6147 }
6148 if (have_bkgd)
6149 {
6150 /* If we are reducing an RGB image to grayscale, but
6151 * the background color isn't gray, the green channel
6152 * is written. That's not spec-compliant. We should
6153 * really check for a non-gray bKGD and refuse to do
6154 * the reduction if one is present.
6155 */
6156 png_color_16 backgd;
6157 png_color_16p backgrnd = &backgd;
6158 backgrnd->red = bkgd_red;
6159 backgrnd->green = bkgd_green;
6160 backgrnd->blue = bkgd_blue;
6161 backgrnd->gray = backgrnd->green;
6162 backgrnd->index = bkgd_index;
6163 png_set_bKGD(write_ptr, write_info_ptr,
6164 backgrnd);
6165 }
6166 }
6167 #endif /* PNG_READ_bKGD_SUPPORTED && PNG_WRITE_bKGD_SUPPORTED */
6168
6169 #if defined(PNG_READ_cHRM_SUPPORTED) && defined(PNG_WRITE_cHRM_SUPPORTED)
6170 #ifdef PNG_FIXED_POINT_SUPPORTED
6171 {
6172 png_fixed_point white_x, white_y, red_x, red_y,
6173 green_x, green_y, blue_x, blue_y;
6174
6175 if (found_cHRM && png_get_cHRM_fixed
6176 (read_ptr, read_info_ptr, &white_x, &white_y,
6177 &red_x, &red_y, &green_x, &green_y, &blue_x,
6178 &blue_y))
6179 {
6180 if (keep_chunk("cHRM", argv))
6181 {
6182 png_set_cHRM_fixed(write_ptr,
6183 write_info_ptr, white_x,
6184 white_y, red_x, red_y,
6185 green_x, green_y,
6186 blue_x, blue_y);
6187 }
6188 }
6189 }
6190 #else
6191 {
6192 double white_x, white_y, red_x, red_y, green_x,
6193 green_y, blue_x, blue_y;
6194
6195 if (found_cHRM && png_get_cHRM
6196 (read_ptr, read_info_ptr, &white_x, &white_y,
6197 &red_x, &red_y, &green_x, &green_y, &blue_x,
6198 &blue_y)) {
6199 if (keep_chunk("cHRM", argv))
6200 {
6201 png_set_cHRM(write_ptr, write_info_ptr,
6202 white_x, white_y, red_x,
6203 red_y, green_x, green_y,
6204 blue_x, blue_y);
6205 }
6206 }
6207 }
6208 #endif /* PNG_FIXED_POINT_SUPPORTED */
6209 #endif /* PNG_READ_cHRM_SUPPORTED && PNG_WRITE_cHRM_SUPPORTED */
6210
6211 #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_WRITE_gAMA_SUPPORTED)
6212 {
6213 if (force_specified_gamma)
6214 {
6215 if (last_trial)
6216 {
6217 if (verbose > 0)
6218 fprintf(STDERR, " Inserting gAMA chunk with "
6219 #ifdef PNG_FIXED_POINT_SUPPORTED
6220 "gamma=(%d/100000)\n",
6221 #else
6222 "gamma=%f\n",
6223 #endif
6224 force_specified_gamma);
6225 }
6226 #ifdef PNG_FIXED_POINT_SUPPORTED
6227 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6228 (png_fixed_point)
6229 force_specified_gamma);
6230 file_gamma =
6231 (png_fixed_point) force_specified_gamma;
6232 #else
6233 png_set_gAMA(write_ptr, write_info_ptr,
6234 force_specified_gamma);
6235 file_gamma = force_specified_gamma;
6236 #endif
6237 }
6238 #ifdef PNG_FIXED_POINT_SUPPORTED
6239 else if (found_gAMA && png_get_gAMA_fixed
6240 (read_ptr, read_info_ptr, &file_gamma))
6241 #else
6242 else if (found_gAMA && png_get_gAMA
6243 (read_ptr, read_info_ptr, &file_gamma))
6244 #endif
6245 {
6246 if (keep_chunk("gAMA", argv))
6247 {
6248 if (image_specified_gamma)
6249 file_gamma = image_specified_gamma;
6250 if (verbose > 1 && last_trial)
6251 #ifdef PNG_FIXED_POINT_SUPPORTED
6252 fprintf(STDERR, " gamma=(%d/100000)\n",
6253 (int) file_gamma);
6254 if (double_gamma)
6255 file_gamma += file_gamma;
6256 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6257 file_gamma);
6258 #else
6259 fprintf(STDERR, " gamma=%f\n",
6260 file_gamma);
6261 if (double_gamma)
6262 file_gamma += file_gamma;
6263 png_set_gAMA(write_ptr, write_info_ptr,
6264 file_gamma);
6265 #endif
6266 }
6267 }
6268 else if (specified_gamma)
6269 {
6270 if (last_trial)
6271 {
6272 if (verbose > 0)
6273 fprintf(STDERR, " Inserting gAMA chunk with "
6274 #ifdef PNG_FIXED_POINT_SUPPORTED
6275 "gamma=(%d/100000)\n",
6276 #else
6277 "gamma=%f\n",
6278 #endif
6279 specified_gamma);
6280 }
6281 #ifdef PNG_FIXED_POINT_SUPPORTED
6282 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6283 specified_gamma);
6284 file_gamma = (png_fixed_point) specified_gamma;
6285 #else
6286 png_set_gAMA(write_ptr, write_info_ptr,
6287 specified_gamma);
6288 file_gamma = specified_gamma;
6289 #endif
6290 }
6291 }
6292 #endif /* PNG_READ_gAMA_SUPPORTED && PNG_WRITE_gAMA_SUPPORTED */
6293
6294 #if defined(PNG_READ_sRGB_SUPPORTED) && defined(PNG_WRITE_sRGB_SUPPORTED)
6295 {
6296 int file_intent;
6297
6298 if (png_get_sRGB
6299 (read_ptr, read_info_ptr, &file_intent))
6300 {
6301 if (keep_chunk("sRGB", argv))
6302 {
6303 png_set_sRGB(write_ptr, write_info_ptr,
6304 file_intent);
6305 intent = file_intent;
6306 }
6307 }
6308 else if (found_sRGB)
6309 {
6310 #ifdef PNG_gAMA_SUPPORTED
6311 # ifdef PNG_FIXED_POINT_SUPPORTED
6312 if (file_gamma >= 45000L && file_gamma <= 46000L)
6313 # else
6314 if (file_gamma >= 0.45000 && file_gamma <= 0.46000)
6315 # endif
6316 {
6317 if (verbose > 0 && last_trial)
6318 fprintf(STDERR,
6319 " Inserting sRGB chunk with intent=%d\n",
6320 intent);
6321 png_set_sRGB(write_ptr, write_info_ptr,
6322 intent);
6323 }
6324 else if (file_gamma != 0)
6325 {
6326 if (verbose > 0 && last_trial)
6327 {
6328 fprintf(STDERR, " Ignoring sRGB request; "
6329 # ifdef PNG_FIXED_POINT_SUPPORTED
6330 "gamma=(%lu/100000)"
6331 " is not approx. 0.455\n",
6332 (unsigned long)file_gamma);
6333 # else
6334 "gamma=%f"
6335 " is not approx. 0.455\n",
6336 file_gamma);
6337 # endif
6338 }
6339 }
6340 #endif /* PNG_gAMA_SUPPORTED */
6341 }
6342 }
6343 #endif /* PNG_READ_sRGB_SUPPORTED && PNG_WRITE_sRGB_SUPPORTED */
6344
6345 #if defined(PNG_READ_iCCP_SUPPORTED) && defined(PNG_WRITE_iCCP_SUPPORTED)
6346 if (intent < 0) { /* ignore iCCP if sRGB is being written */
6347 png_charp name;
6348 #if PNGCRUSH_LIBPNG_VER < 10500
6349 png_charp profile;
6350 #else
6351 png_bytep profile;
6352 #endif
6353 png_uint_32 proflen;
6354 int compression_method;
6355
6356 if (found_iCCP && png_get_iCCP
6357 (read_ptr, read_info_ptr, &name,
6358 &compression_method, &profile, &proflen))
6359 {
6360 P1("Got iCCP chunk, proflen=%lu\n",
6361 (unsigned long)proflen);
6362 if (iccp_length)
6363 P0("Will not replace existing iCCP chunk.\n");
6364 if (keep_chunk("iCCP", argv))
6365 png_set_iCCP(write_ptr, write_info_ptr,
6366 #if PNGCRUSH_LIBPNG_VER < 10500
6367 name,
6368 #else
6369 (png_const_charp) name,
6370 #endif
6371 compression_method, profile,
6372 proflen);
6373
6374 }
6375 #ifdef PNG_iCCP_SUPPORTED
6376 else if (iccp_length)
6377 {
6378 png_set_iCCP(write_ptr, write_info_ptr, iccp_name,
6379 0,
6380 #if PNGCRUSH_LIBPNG_VER < 10500
6381 iccp_text,
6382 #else
6383 (png_const_bytep) iccp_text,
6384 #endif
6385 iccp_length);
6386 P1("Wrote iCCP chunk, proflen=%d\n", iccp_length);
6387 }
6388 #endif /* PNG_iCCP_SUPPORTED */
6389
6390 }
6391 #endif /* PNG_READ_iCCP_SUPPORTED && PNG_WRITE_iCCP_SUPPORTED */
6392
6393 #if defined(PNG_READ_oFFs_SUPPORTED) && defined(PNG_WRITE_oFFs_SUPPORTED)
6394 {
6395 png_int_32 offset_x, offset_y;
6396 int unit_type;
6397
6398 if (png_get_oFFs
6399 (read_ptr, read_info_ptr, &offset_x, &offset_y,
6400 &unit_type)) {
6401 if (offset_x == 0 && offset_y == 0)
6402 {
6403 if (verbose > 0 && last_trial)
6404 fprintf(STDERR,
6405 " Deleting useless oFFs 0 0 chunk\n");
6406 }
6407 else
6408 {
6409 if (keep_chunk("oFFs", argv))
6410 png_set_oFFs(write_ptr, write_info_ptr,
6411 offset_x, offset_y,
6412 unit_type);
6413 }
6414 }
6415 }
6416 #endif /* PNG_READ_oFFs_SUPPORTED && PNG_WRITE_oFFs_SUPPORTED */
6417
6418 #if defined(PNG_READ_pCAL_SUPPORTED) && defined(PNG_WRITE_pCAL_SUPPORTED)
6419 {
6420 png_charp purpose, units;
6421 png_charpp params;
6422 png_int_32 X0, X1;
6423 int type, nparams;
6424
6425 if (png_get_pCAL
6426 (read_ptr, read_info_ptr, &purpose, &X0, &X1,
6427 &type, &nparams, &units, &params))
6428 {
6429 if (keep_chunk("pCAL", argv))
6430 png_set_pCAL(write_ptr, write_info_ptr,
6431 purpose, X0, X1, type, nparams,
6432 units, params);
6433 }
6434 }
6435 #endif /* pCAL_SUPPORTED */
6436
6437 #if defined(PNG_READ_pHYs_SUPPORTED) && defined(PNG_WRITE_pHYs_SUPPORTED)
6438 {
6439 png_uint_32 res_x, res_y;
6440 int unit_type;
6441
6442 if (resolution == 0)
6443 {
6444 if (png_get_pHYs
6445 (read_ptr, read_info_ptr, &res_x, &res_y,
6446 &unit_type))
6447 {
6448 if (res_x == 0 && res_y == 0)
6449 {
6450 if (verbose > 0 && last_trial)
6451 fprintf(STDERR,
6452 " Deleting useless pHYs 0 0 chunk\n");
6453 }
6454 else
6455 {
6456 if (keep_chunk("pHYs", argv))
6457 png_set_pHYs(write_ptr, write_info_ptr,
6458 res_x, res_y, unit_type);
6459 }
6460 }
6461 } else {
6462 unit_type = 1;
6463 res_x = res_y =
6464 (png_uint_32) ((resolution / .0254 + 0.5));
6465 png_set_pHYs(write_ptr, write_info_ptr, res_x,
6466 res_y, unit_type);
6467 if (verbose > 0 && last_trial)
6468 fprintf(STDERR, " Added pHYs %lu %lu 1 chunk\n",
6469 (unsigned long)res_x,
6470 (unsigned long)res_y);
6471 }
6472 }
6473 #endif
6474
6475 #if defined(PNG_READ_hIST_SUPPORTED) && defined(PNG_WRITE_hIST_SUPPORTED)
6476 {
6477 png_uint_16p hist;
6478
6479 if (png_get_hIST(read_ptr, read_info_ptr, &hist))
6480 {
6481 if (keep_chunk("hIST", argv))
6482 png_set_hIST(write_ptr, write_info_ptr, hist);
6483 }
6484 }
6485 #endif /* hIST_SUPPORTED */
6486
6487 #if defined(PNG_READ_tRNS_SUPPORTED) && defined(PNG_WRITE_tRNS_SUPPORTED)
6488 {
6489 if (png_get_tRNS
6490 (read_ptr, read_info_ptr, &trans, &num_trans,
6491 &trans_values))
6492 {
6493 if (verbose > 1 && last_trial)
6494 fprintf(STDERR,
6495 " Found tRNS chunk in input file.\n");
6496 if (have_trns == 1)
6497 {
6498 P0(" Will not overwrite existing tRNS chunk.\n");
6499 }
6500 if (keep_chunk("tRNS", argv))
6501 {
6502 int last_nonmax = -1;
6503 trns_red = trans_values->red;
6504 trns_green = trans_values->green;
6505 trns_blue = trans_values->blue;
6506 trns_gray = trans_values->gray;
6507 if (output_color_type == 3)
6508 {
6509 for (ia = 0; ia < num_trans; ia++)
6510 trns_array[ia] = trans[ia];
6511 for (; ia < 256; ia++)
6512 trns_array[ia] = 255;
6513 for (ia = 0; ia < 256; ia++)
6514 {
6515 if (trns_array[ia] != 255)
6516 last_nonmax = ia;
6517 }
6518 if (last_trial && verbose > 0)
6519 {
6520 if (last_nonmax < 0)
6521 fprintf(STDERR, " Deleting "
6522 "all-opaque tRNS chunk.\n");
6523 else if (last_nonmax + 1 < num_trans)
6524 fprintf(STDERR,
6525 " Truncating trailing opaque "
6526 "entries from tRNS chunk.\n");
6527 }
6528 num_trans = last_nonmax + 1;
6529 }
6530 else
6531 {
6532 /* color type is 0 or 2 */
6533 if (input_bit_depth == 16 &&
6534 output_bit_depth == 8)
6535 {
6536 /* zero out the high byte */
6537 trans_values->red &= 0x00ff;
6538 trans_values->green &= 0x00ff;
6539 trans_values->blue &= 0x00ff;
6540 trans_values->gray &= 0x00ff;
6541 }
6542
6543 }
6544 if (verbose > 1)
6545 fprintf(STDERR,
6546 " png_set_tRNS, num_trans=%d\n",
6547 num_trans);
6548 if (output_color_type < 3 || num_trans)
6549 png_set_tRNS(write_ptr, write_info_ptr,
6550 trans, num_trans,
6551 trans_values);
6552 }
6553 }
6554 else if (have_trns == 1)
6555 {
6556 /* will not overwrite existing trns data */
6557 png_color_16 trans_data;
6558 png_byte index_data = (png_byte) trns_index;
6559 num_trans = index_data + 1;
6560 if (verbose > 1)
6561 fprintf(STDERR, "Have_tRNS, num_trans=%d\n",
6562 num_trans);
6563 if (output_color_type == 3)
6564 {
6565 trans_values = NULL;
6566 for (ia = 0; ia < num_trans; ia++)
6567 trns_array[ia] = trans_in[ia];
6568 for (; ia < 256; ia++)
6569 trns_array[ia] = 255;
6570 } else {
6571 for (ia = 0; ia < 256; ia++)
6572 trns_array[ia] = 255;
6573 trns_array[index_data] = 0;
6574
6575 trans_data.index = index_data;
6576 trans_data.red = trns_red;
6577 trans_data.green = trns_green;
6578 trans_data.blue = trns_blue;
6579 trans_data.gray = trns_gray;
6580 trans_values = &trans_data;
6581 }
6582
6583 P0(" Adding a tRNS chunk\n");
6584 png_set_tRNS(write_ptr, write_info_ptr, trns_array,
6585 num_trans, trans_values);
6586 }
6587 else
6588 {
6589 for (ia = 0; ia < 256; ia++)
6590 trns_array[ia] = 255;
6591 }
6592 if (verbose > 1 && last_trial)
6593 {
6594 int last = -1;
6595 for (ia = 0; ia < num_palette; ia++)
6596 if (trns_array[ia] != 255)
6597 last = ia;
6598 if (last >= 0) {
6599 fprintf(STDERR, " Transparency:\n");
6600 if (output_color_type == 3)
6601 for (ia = 0; ia < num_palette; ia++)
6602 fprintf(STDERR, " %4d %4d\n", ia,
6603 trns_array[ia]);
6604 else if (output_color_type == 0)
6605 fprintf(STDERR, " %d\n", trns_gray);
6606 else if (output_color_type == 2)
6607 fprintf(STDERR, " %d %d %d\n",
6608 trns_red, trns_green, trns_blue);
6609 }
6610 }
6611 }
6612 #endif /* PNG_READ_tRNS_SUPPORTED && PNG_WRITE_tRNS_SUPPORTED */
6613 } /* End of ancillary chunk handling */
6614
6615 if (png_get_PLTE
6616 (read_ptr, read_info_ptr, &palette, &num_palette))
6617 {
6618 if (plte_len > 0)
6619 num_palette = plte_len;
6620 if (do_pplt)
6621 {
6622 fprintf(STDERR,"PPLT: %s\n", pplt_string);
6623 fprintf(STDERR,"Sorry, PPLT is not implemented yet.\n");
6624 }
6625
6626 if (nosave == 0)
6627 {
6628 if (output_color_type == 3)
6629 png_set_PLTE(write_ptr, write_info_ptr, palette,
6630 num_palette);
6631 else if (keep_chunk("PLTE", argv))
6632 png_set_PLTE(write_ptr, write_info_ptr, palette,
6633 num_palette);
6634
6635 }
6636 if (verbose > 1 && last_trial)
6637 {
6638 png_colorp p = palette;
6639 fprintf(STDERR, " Palette:\n");
6640 fprintf(STDERR,
6641 " I R G B ( color ) A\n");
6642 for (i = 0; i < num_palette; i++)
6643 {
6644 fprintf(STDERR,
6645 " %4d %4d %4d %4d (#%2.2x%2.2x%2.2x) %4d\n",
6646 i, p->red, p->green, p->blue, p->red,
6647 p->green, p->blue, trns_array[i]);
6648 p++;
6649 }
6650 }
6651 }
6652
6653
6654 /* Handle ancillary chunks */
6655 if (last_trial == 1)
6656 {
6657 #if defined(PNG_READ_sBIT_SUPPORTED) && defined(PNG_WRITE_sBIT_SUPPORTED)
6658 {
6659 png_color_8p sig_bit;
6660
6661 /* If we are reducing a truecolor PNG to grayscale, and the
6662 * RGB sBIT values aren't identical, we'll lose sBIT info.
6663 */
6664 if (png_get_sBIT(read_ptr, read_info_ptr, &sig_bit))
6665 {
6666 if (keep_chunk("sBIT", argv))
6667 {
6668 if ((input_color_type == 0
6669 || input_color_type == 4)
6670 && (output_color_type == 2
6671 || output_color_type == 6
6672 || output_color_type == 3))
6673 sig_bit->red = sig_bit->green =
6674 sig_bit->blue = sig_bit->gray;
6675 if ((input_color_type == 2
6676 || input_color_type == 6
6677 || output_color_type == 3)
6678 && (output_color_type == 0
6679 || output_color_type == 4))
6680 sig_bit->gray = sig_bit->green;
6681
6682 if ((input_color_type == 0
6683 || input_color_type == 2)
6684 && (output_color_type == 4
6685 || output_color_type == 6))
6686 sig_bit->alpha = 1;
6687
6688 if (nosave == 0)
6689 png_set_sBIT(write_ptr, write_info_ptr,
6690 sig_bit);
6691 }
6692 }
6693 }
6694 #endif /* PNG_READ_sBIT_SUPPORTED)&& PNG_WRITE_sBIT_SUPPORTED */
6695
6696 #ifdef PNG_sCAL_SUPPORTED
6697 # ifdef PNG_FLOATING_POINT_SUPPORTED
6698 {
6699 int unit;
6700 double scal_width, scal_height;
6701
6702 if (png_get_sCAL
6703 (read_ptr, read_info_ptr, &unit, &scal_width,
6704 &scal_height))
6705 {
6706 png_set_sCAL(write_ptr, write_info_ptr, unit,
6707 scal_width, scal_height);
6708 }
6709 }
6710 # else
6711 # ifdef PNG_FIXED_POINT_SUPPORTED
6712 {
6713 int unit;
6714 png_charp scal_width, scal_height;
6715
6716 if (png_get_sCAL_s
6717 (read_ptr, read_info_ptr, &unit, &scal_width,
6718 &scal_height))
6719 {
6720 if (keep_chunk("sCAL", argv))
6721 png_set_sCAL_s(write_ptr, write_info_ptr, unit,
6722 scal_width, scal_height);
6723 }
6724 }
6725 # endif
6726 # endif /* PNG_FLOATING_POINT_SUPPORTED */
6727 #endif /* PNG_sCAL_SUPPORTED */
6728
6729 #ifdef PNG_sPLT_SUPPORTED
6730 {
6731 png_sPLT_tp entries;
6732 int num_entries;
6733
6734 num_entries =
6735 (int) png_get_sPLT(read_ptr, read_info_ptr,
6736 &entries);
6737 if (num_entries)
6738 {
6739 if (keep_chunk("sPLT", argv))
6740 png_set_sPLT(write_ptr, write_info_ptr,
6741 entries, num_entries);
6742 }
6743 }
6744 #endif
6745
6746 #ifdef PNG_TEXT_SUPPORTED
6747 {
6748 png_textp text_ptr;
6749 int num_text = 0;
6750
6751 if (png_get_text
6752 (read_ptr, read_info_ptr, &text_ptr, &num_text) > 0
6753 || text_inputs)
6754 {
6755 int ntext;
6756 P1( "Handling %d tEXt/zTXt chunks before IDAT\n",
6757 num_text);
6758
6759 if (verbose > 1 && last_trial && num_text > 0)
6760 {
6761 for (ntext = 0; ntext < num_text; ntext++)
6762 {
6763 fprintf(STDERR, "%d %s", ntext,
6764 text_ptr[ntext].key);
6765 if (text_ptr[ntext].text_length)
6766 fprintf(STDERR, ": %s\n",
6767 text_ptr[ntext].text);
6768 #ifdef PNG_iTXt_SUPPORTED
6769 else if (text_ptr[ntext].itxt_length)
6770 {
6771 fprintf(STDERR, " (%s: %s): \n",
6772 text_ptr[ntext].lang,
6773 text_ptr[ntext].lang_key);
6774 fprintf(STDERR, "%s\n",
6775 text_ptr[ntext].text);
6776 }
6777 #endif
6778 else
6779 fprintf(STDERR, "\n");
6780 }
6781 }
6782
6783 if (num_text > 0)
6784 {
6785 if (keep_chunk("text", argv))
6786 {
6787 int num_to_write = num_text;
6788 for (ntext = 0; ntext < num_text; ntext++)
6789 {
6790 if (last_trial)
6791 P2("Text chunk before IDAT, "
6792 "compression=%d\n",
6793 text_ptr[ntext].compression);
6794 if (text_ptr[ntext].compression ==
6795 PNG_TEXT_COMPRESSION_NONE) {
6796 if (!keep_chunk("tEXt", argv))
6797 {
6798 text_ptr[ntext].key[0] = '\0';
6799 num_to_write--;
6800 }
6801 }
6802 if (text_ptr[ntext].compression ==
6803 PNG_TEXT_COMPRESSION_zTXt)
6804 {
6805 if (!keep_chunk("zTXt", argv))
6806 {
6807 text_ptr[ntext].key[0] = '\0';
6808 num_to_write--;
6809 }
6810 }
6811 #ifdef PNG_iTXt_SUPPORTED
6812 if (text_ptr[ntext].compression ==
6813 PNG_ITXT_COMPRESSION_NONE
6814 || text_ptr[ntext].compression ==
6815 PNG_ITXT_COMPRESSION_zTXt)
6816 {
6817 if (!keep_chunk("iTXt", argv))
6818 {
6819 text_ptr[ntext].key[0] = '\0';
6820 num_to_write--;
6821 }
6822 }
6823 #endif
6824 }
6825 if (num_to_write > 0)
6826 png_set_text(write_ptr, write_info_ptr,
6827 text_ptr, num_text);
6828 }
6829 }
6830 for (ntext = 0; ntext < text_inputs; ntext++)
6831 {
6832 if (text_where[ntext] == 1)
6833 {
6834 png_textp added_text;
6835 added_text = (png_textp) png_malloc(write_ptr,
6836 (png_uint_32) sizeof(png_text));
6837 added_text[0].key = &text_keyword[ntext * 80];
6838 #ifdef PNG_iTXt_SUPPORTED
6839 added_text[0].lang = &text_lang[ntext * 80];
6840 added_text[0].lang_key =
6841 &text_lang_key[ntext * 80];
6842 #endif
6843 added_text[0].text =
6844 &text_text[ntext * STR_BUF_SIZE];
6845 added_text[0].compression =
6846 text_compression[ntext];
6847 png_set_text(write_ptr, write_info_ptr,
6848 added_text, 1);
6849 if (verbose > 0 && last_trial)
6850 {
6851 if (added_text[0].compression < 0)
6852 fprintf(STDERR,
6853 " Added a tEXt chunk.\n");
6854 else if (added_text[0].compression == 0)
6855 fprintf(STDERR,
6856 " Added a zTXt chunk.\n");
6857 #ifdef PNG_iTXt_SUPPORTED
6858 else
6859 fprintf(STDERR,
6860 " Added a%scompressed iTXt chunk"
6861 ".\n", (added_text[0].compression == 1)?
6862 "n un" : " ");
6863 #endif
6864 }
6865 png_free(write_ptr, added_text);
6866 added_text = (png_textp) NULL;
6867 }
6868 }
6869 }
6870 }
6871 #endif /* defined(PNG_TEXT_SUPPORTED) */
6872
6873 #if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
6874 {
6875 png_timep mod_time;
6876
6877 if (png_get_tIME(read_ptr, read_info_ptr, &mod_time))
6878 {
6879 if (keep_chunk("tIME", argv))
6880 png_set_tIME(write_ptr, write_info_ptr, mod_time);
6881 }
6882 }
6883 #endif
6884
6885 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
6886 /* This section handles pCAL and tIME (at least, in default
6887 * build), gIFx/gIFg/gIFt, private Fireworks chunks, etc. */
6888 {
6889 png_unknown_chunkp unknowns; /* allocated by libpng */
6890 int num_unknowns;
6891
6892 num_unknowns = (int)png_get_unknown_chunks(read_ptr,
6893 read_info_ptr, &unknowns);
6894
6895 if (nosave == 0 && ster_mode >= 0)
6896 {
6897 /* Add sTER chunk */
6898 png_unknown_chunkp ster;
6899 P1("Handling sTER as unknown chunk %d\n", num_unknowns);
6900 ster = (png_unknown_chunk*)png_malloc(read_ptr,
6901 (png_uint_32) sizeof(png_unknown_chunk));
6902 png_memcpy((char *)ster[0].name, "sTER",5);
6903 ster[0].size = 1;
6904 ster[0].data = (png_byte*)png_malloc(read_ptr, 1);
6905 ster[0].data[0] = (png_byte)ster_mode;
6906 png_set_unknown_chunks(read_ptr, read_info_ptr,
6907 ster, 1);
6908 png_free(read_ptr,ster[0].data);
6909 png_free(read_ptr,ster);
6910 num_unknowns++;
6911 }
6912
6913 #ifndef PNG_HAVE_IHDR
6914 #define PNG_HAVE_IHDR 0x01
6915 #endif
6916 if (ster_mode >= 0)
6917 png_set_unknown_chunk_location(read_ptr, read_info_ptr,
6918 num_unknowns - 1, (int)PNG_HAVE_IHDR);
6919
6920 P1("Found %d unknown chunks\n", num_unknowns);
6921
6922 if (nosave == 0 && num_unknowns)
6923 {
6924 png_unknown_chunkp unknowns_keep; /* allocated by us */
6925 int num_unknowns_keep;
6926
6927 unknowns_keep = (png_unknown_chunk*)png_malloc(
6928 write_ptr, (png_uint_32) num_unknowns
6929 *sizeof(png_unknown_chunk));
6930
6931 P1("malloc for %d unknown chunks\n", num_unknowns);
6932 num_unknowns_keep = 0;
6933
6934 /* make an array of only those chunks we want to keep */
6935 for (i = 0; i < num_unknowns; i++)
6936 {
6937 P1("Handling unknown chunk %d %s\n", i,
6938 (char *)unknowns[i].name);
6939 /* not EBCDIC-safe, but neither is keep_chunks(): */
6940 P2(" unknown[%d] = %s (%lu bytes, location %d)\n",
6941 i, unknowns[i].name,
6942 (unsigned long)unknowns[i].size,
6943 unknowns[i].location);
6944 if (keep_chunk((char *)unknowns[i].name, argv))
6945 {
6946 png_memcpy(&unknowns_keep[num_unknowns_keep],
6947 &unknowns[i], sizeof(png_unknown_chunk));
6948 ++num_unknowns_keep;
6949 }
6950 }
6951
6952 P1("Keeping %d unknown chunks\n", num_unknowns_keep);
6953 png_set_unknown_chunks(write_ptr, write_info_ptr,
6954 unknowns_keep, num_unknowns_keep);
6955
6956 /* relevant location bits:
6957 * (1) !PNG_HAVE_PLTE && !PNG_HAVE_IDAT (before PLTE)
6958 * (2) PNG_HAVE_PLTE && !PNG_HAVE_IDAT (between)
6959 * (3) PNG_AFTER_IDAT (after IDAT)
6960 * PNG_HAVE_PLTE = 0x02
6961 * PNG_HAVE_IDAT = 0x04
6962 * PNG_AFTER_IDAT = 0x08
6963 */
6964 for (i = 0; i < num_unknowns_keep; i++)
6965 {
6966 png_set_unknown_chunk_location(write_ptr,
6967 write_info_ptr, i,
6968 (int)unknowns_keep[i].location);
6969 }
6970
6971 /* png_set_unknown_chunks() makes own copy, so nuke
6972 * ours */
6973 png_free(write_ptr, unknowns_keep);
6974 }
6975 }
6976 P1( "Finished handling ancillary chunks after IDAT\n");
6977 #endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
6978 } /* End of ancillary chunk handling */
6979
6980 /* } GRR added for quick %-navigation (1) */
6981
6982 /*
6983 * Would be useful to have a libpng fix, that either exports
6984 * png_read_transform_info() or provides a generic API that
6985 * can set any png_ptr->flag, or, simpler, provides an API
6986 * to set the PNG_FLAG_ROW_INIT flag.
6987 *
6988 * Starting in libpng-1.5.6beta06, png_read_update_info()
6989 * does not check the PNG_FLAG_ROW_INIT flag and does not
6990 * initialize the row or issue a warning.
6991 *
6992 */
6993 #ifdef PNGCRUSH_H
6994 png_read_transform_info(read_ptr, read_info_ptr);
6995 #else
6996 /* Some pngcrush capabilities are lacking when the system
6997 * libpng is used instead of the one bundled with pngcrush
6998 *
6999 * To do: list those capabilities here
7000 */
7001
7002 /* pngcrush fails to read interlaced PNGs properly
7003 * when png_read_update_info() is called here.
7004 */
7005
7006 /* png_read_update_info(read_ptr, read_info_ptr); */
7007
7008 /* Workaround is to multiply rowbytes by 8/bit_depth
7009 * to allow for unpacking, wherever we allocate a
7010 * row buffer. This results in too large a value for
7011 * rowbytes under some conditions, e.g., when increasing
7012 * a sub-8-bit file to RGBA, but this is rare and harmless.
7013 */
7014 #endif
7015
7016 /* This is the default case (nosave == 1 -> perf-testing
7017 only) */
7018 if (nosave == 0)
7019 {
7020 if (filter_type == 0)
7021 png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
7022 else if (filter_type == 1)
7023 png_set_filter(write_ptr, 0, PNG_FILTER_SUB);
7024 else if (filter_type == 2)
7025 png_set_filter(write_ptr, 0, PNG_FILTER_UP);
7026 else if (filter_type == 3)
7027 png_set_filter(write_ptr, 0, PNG_FILTER_AVG);
7028 else if (filter_type == 4)
7029 png_set_filter(write_ptr, 0, PNG_FILTER_PAETH);
7030 else if (filter_type == 5)
7031 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
7032 else if (filter_type == 6) /* speedy */
7033 png_set_filter(write_ptr, 0, PNG_FILTER_NONE |
7034 PNG_FILTER_SUB | PNG_FILTER_UP);
7035 else
7036 png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
7037
7038 #ifdef PNGCRUSH_LOCO
7039 if (do_loco) {
7040 png_byte buff[30];
7041 const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
7042 png_byte mng_signature[8] =
7043 { 138, 77, 78, 71, 13, 10, 26, 10 };
7044 /* write the MNG 8-byte signature */
7045 if (outname[strlen(outname) - 3] == 'p')
7046 pngcrush_warning(read_ptr,
7047 " Writing a MNG file with a .png extension");
7048 pngcrush_write_png(write_ptr, &mng_signature[0],
7049 (png_size_t) 8);
7050 png_set_sig_bytes(write_ptr, 8);
7051
7052 /* Write a MHDR chunk */
7053
7054 buff[0] = (png_byte) ((width >> 24) & 0xff);
7055 buff[1] = (png_byte) ((width >> 16) & 0xff);
7056 buff[2] = (png_byte) ((width >> 8) & 0xff);
7057 buff[3] = (png_byte) ((width) & 0xff);
7058 buff[4] = (png_byte) ((height >> 24) & 0xff);
7059 buff[5] = (png_byte) ((height >> 16) & 0xff);
7060 buff[6] = (png_byte) ((height >> 8) & 0xff);
7061 buff[7] = (png_byte) ((height) & 0xff);
7062 for (i = 8; i < 27; i++)
7063 buff[i] = 0x00;
7064 buff[15] = 2; /* layer count */
7065 buff[19] = 1; /* frame count */
7066 if (output_color_type == 6)
7067 buff[27] = 0x09; /* profile: MNG-VLC with trans. */
7068 else
7069 buff[27] = 0x01; /* profile: MNG-VLC */
7070 png_write_chunk(write_ptr, (png_bytep) png_MHDR,
7071 buff, (png_size_t) 28);
7072 }
7073 #endif /* PNGCRUSH_LOCO */
7074
7075 pngcrush_pause();
7076
7077 if (found_CgBI)
7078 {
7079 pngcrush_warning(read_ptr,
7080 "Cannot read Xcode CgBI PNG");
7081 }
7082 P1( "\nWriting info struct\n");
7083
7084 if (copy_idat == 0)
7085 {
7086
7087 #if 0 /* doesn't work; compression level has to be the same as in IDAT */
7088 /* if zTXt other compressed chunk */
7089 png_set_compression_level(write_ptr, 9);
7090 png_set_compression_window_bits(write_ptr, 15);
7091 #endif /* 0 */
7092
7093 pngcrush_pause();
7094 {
7095 png_uint_32 zbuf_size;
7096 png_uint_32 required_window;
7097 int channels = 0;
7098 png_set_compression_strategy(write_ptr,
7099 z_strategy);
7100 png_set_compression_mem_level(write_ptr,
7101 compression_mem_level);
7102
7103 if (output_color_type == 0)
7104 channels = 1;
7105 if (output_color_type == 2)
7106 channels = 3;
7107 if (output_color_type == 3)
7108 channels = 1;
7109 if (output_color_type == 4)
7110 channels = 2;
7111 if (output_color_type == 6)
7112 channels = 4;
7113
7114 /* This method was copied from libpng to find maximum
7115 * data size. Only return sizes up to the maximum of
7116 * a png_uint_32, by limiting the width and height used
7117 * to 15 bits.
7118 */
7119 png_uint_32 rowbytes;
7120 png_uint_32 h = height;
7121
7122 /* FIX THIS, does not work with libpng-1.7.0
7123 * because info_ptr->bit_depth has not been
7124 * updated yet.
7125 */
7126 rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
7127 #ifndef PNGCRUSH_H
7128 /* We must do this because we could not call
7129 * png_read_update_info().
7130 */
7131 if (input_bit_depth < 8)
7132 rowbytes *= 8/input_bit_depth;
7133 #endif
7134 if (rowbytes < 16384 && h < 16384)
7135 {
7136 if (rowbytes * h < 16384)
7137 {
7138 if (interlace_method)
7139 {
7140 /* Interlacing makes the uncompressed data
7141 * larger because of the replication of both
7142 * the filter byte and the padding to a byte
7143 * boundary.
7144 */
7145 png_uint_32 w = width;
7146 unsigned int pd = channels * output_bit_depth;
7147 #if (PNGCRUSH_LIBPNG_VER < 10400)
7148 png_size_t cb_base;
7149 #else
7150 png_alloc_size_t cb_base;
7151 #endif
7152 int interlace_pass;
7153
7154 for (cb_base=0, interlace_pass=0;
7155 interlace_pass<=6; ++interlace_pass)
7156 {
7157 png_uint_32 pw = PNG_PASS_COLS(w,
7158 interlace_pass);
7159
7160 if (pw > 0)
7161 cb_base += (PNGCRUSH_ROWBYTES(pd, pw)+1) *
7162 PNG_PASS_ROWS(h, interlace_pass);
7163 }
7164
7165 max_bytes = cb_base;
7166 }
7167
7168 else
7169 max_bytes = (rowbytes+1) * h;
7170 }
7171 else
7172 max_bytes = 0x3fffffffU;
7173 }
7174
7175 else
7176 max_bytes = 0x3fffffffU;
7177
7178 required_window = (png_uint_32) (max_bytes + 262);
7179
7180 zbuf_size =
7181 png_get_compression_buffer_size(write_ptr);
7182
7183 /* reinitialize zbuf - compression buffer */
7184 if (zbuf_size != max_idat_size)
7185 {
7186 png_uint_32 max_possible_size =
7187 required_window;
7188 if (max_possible_size > max_idat_size)
7189 max_possible_size = max_idat_size;
7190 P2("reinitializing write zbuf to %lu.\n",
7191 (unsigned long)max_possible_size);
7192 png_set_compression_buffer_size(write_ptr,
7193 max_possible_size);
7194 }
7195
7196 if (required_window <= 512)
7197 compression_window = 9;
7198 else if (required_window <= 1024)
7199 compression_window = 10;
7200 else if (required_window <= 2048)
7201 compression_window = 11;
7202 else if (required_window <= 4096)
7203 compression_window = 12;
7204 else if (required_window <= 8192)
7205 compression_window = 13;
7206 else if (required_window <= 16384)
7207 compression_window = 14;
7208 else
7209 compression_window = 15;
7210 if (compression_window > default_compression_window
7211 || force_compression_window)
7212 compression_window =
7213 default_compression_window;
7214
7215 if (verbose > 1 && last_trial
7216 && (compression_window != 15
7217 || force_compression_window))
7218 fprintf(STDERR,
7219 " Compression window for output= %d\n",
7220 1 << compression_window);
7221
7222 png_set_compression_window_bits(write_ptr,
7223 compression_window);
7224 }
7225
7226 png_set_compression_level(write_ptr, zlib_level);
7227 } /* copy_idat */
7228
7229 png_write_info(write_ptr, write_info_ptr);
7230 P1( "\nWrote info struct\n");
7231
7232 if (copy_idat == 1)
7233 {
7234 /* No recompress, just copy IDATs. */
7235 png_set_compression_buffer_size(write_ptr,
7236 MAX_IDAT_SIZE);
7237 }
7238
7239 #ifdef PNG_WRITE_PACK_SUPPORTED
7240 if (output_bit_depth < 8)
7241 {
7242 if (output_color_type == 0)
7243 {
7244 png_color_8 true_bits;
7245 true_bits.gray = (png_byte) (output_bit_depth);
7246 png_set_shift(write_ptr, &true_bits);
7247 }
7248 png_set_packing(write_ptr);
7249 }
7250 #endif
7251 } /* no save */
7252
7253 #ifdef PNGCRUSH_MULTIPLE_ROWS
7254 rows_at_a_time = max_rows_at_a_time;
7255 if (rows_at_a_time == 0 || rows_at_a_time < height)
7256 rows_at_a_time = height;
7257 #endif
7258
7259 #ifndef PNGCRUSH_LARGE
7260 {
7261 png_uint_32 rowbytes_s;
7262 png_uint_32 rowbytes;
7263
7264 rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
7265 #ifndef PNGCRUSH_H
7266 if (input_bit_depth < 8)
7267 rowbytes *= 8/input_bit_depth;
7268 #endif
7269
7270 P2("rowbytes = %lud\n",rowbytes;
7271
7272 rowbytes_s = (png_size_t) rowbytes;
7273 if (rowbytes == (png_uint_32) rowbytes_s)
7274 # ifdef PNGCRUSH_MULTIPLE_ROWS
7275 row_buf =
7276 png_malloc(read_ptr,
7277 rows_at_a_time * rowbytes + 64);
7278 # else
7279 row_buf = png_malloc(read_ptr, rowbytes + 64);
7280 # endif
7281 else
7282 row_buf = NULL;
7283 }
7284 #else /* PNGCRUSH_LARGE */
7285 {
7286 png_uint_32 read_row_length, write_row_length;
7287 read_row_length =
7288 (png_uint_32) (png_get_rowbytes
7289 (read_ptr, read_info_ptr));
7290 write_row_length =
7291 (png_uint_32) (png_get_rowbytes
7292 (write_ptr, write_info_ptr));
7293 row_length =
7294 read_row_length >
7295 write_row_length ? read_row_length :
7296 write_row_length;
7297 #ifndef PNGCRUSH_H
7298 /* We must do this because we could not call
7299 * png_read_update_info().
7300 */
7301 if (input_bit_depth < 8)
7302 row_length *= 8/input_bit_depth;
7303 #endif
7304 # ifdef PNGCRUSH_MULTIPLE_ROWS
7305 row_buf =
7306 (png_bytep) png_malloc(read_ptr,
7307 rows_at_a_time *
7308 row_length + 64);
7309 # else
7310 row_buf =
7311 (png_bytep) png_malloc(read_ptr, row_length + 64);
7312 # endif
7313 }
7314 #endif /* PNGCRUSH_LARGE */
7315
7316 P2(" row_buf = %p\n",row_buf);
7317
7318 if (row_buf == NULL)
7319 png_error(read_ptr,
7320 "Insufficient memory to allocate row buffer");
7321
7322 {
7323 /* Check for sufficient memory: we need 2*zlib_window and,
7324 * if filter_type == 5, 4*rowbytes in separate allocations.
7325 * If it's not enough we can drop the "average" filter and
7326 * we can reduce the zlib_window for writing. We can't
7327 * change the input zlib_window because the input file
7328 * might have used the full 32K sliding window. (To do)
7329 */
7330 }
7331
7332 P2("allocated rowbuf.\n");
7333
7334 #ifdef PNGCRUSH_MULTIPLE_ROWS
7335 row_pointers = (png_bytepp) png_malloc(read_ptr,
7336 rows_at_a_time *
7337 sizeof(png_bytepp));
7338 P2("allocated row_pointers.\n");
7339
7340 for (i = 0; i < rows_at_a_time; i++)
7341 row_pointers[i] = row_buf + i * row_length;
7342 #endif
7343
7344 pngcrush_pause();
7345
7346 num_pass = png_set_interlace_handling(read_ptr);
7347 if (nosave == 0)
7348 png_set_interlace_handling(write_ptr);
7349
7350 /* START_STOP */
7351
7352 for (pass = 0; pass < num_pass; pass++)
7353 {
7354 #ifdef PNGCRUSH_MULTIPLE_ROWS
7355 png_uint_32 num_rows;
7356 #endif
7357 P1( "\nBegin interlace pass %d\n", pass);
7358 #ifdef PNGCRUSH_MULTIPLE_ROWS
7359 num_rows = rows_at_a_time;
7360 for (y = 0; y < height; y += rows_at_a_time)
7361 #else
7362 for (y = 0; y < height; y++)
7363 #endif
7364 {
7365 #if PNGCRUSH_TIMERS > 0
7366 if (verbose >= 0)
7367 {
7368 pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
7369 pngcrush_timer_start(PNGCRUSH_TIMER_DECODE);
7370 }
7371 #endif
7372 #ifdef PNGCRUSH_MULTIPLE_ROWS
7373 if (y + num_rows > height)
7374 num_rows = height - y;
7375 # ifdef BLOCKY_DEINTERLACE
7376 png_read_rows(read_ptr, (png_bytepp) NULL,
7377 row_pointers, num_rows);
7378 # else /* SPARKLE */
7379 png_read_rows(read_ptr, row_pointers,
7380 (png_bytepp) NULL, num_rows);
7381 # endif
7382 #else
7383 # ifdef BLOCKY_DEINTERLACE
7384 png_read_row(read_ptr, row_buf, (png_bytep) NULL);
7385 # else /* SPARKLE */
7386 png_read_row(read_ptr, (png_bytep) NULL, row_buf);
7387 # endif
7388 #endif
7389 if (nosave == 0)
7390 {
7391 #if PNGCRUSH_TIMERS > 0
7392 if (verbose >= 0)
7393 {
7394 pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
7395 pngcrush_timer_start(PNGCRUSH_TIMER_ENCODE);
7396 }
7397 #endif
7398 #ifdef PNGCRUSH_MULTIPLE_ROWS
7399 /* To do: zero the padding bits */
7400 png_write_rows(write_ptr, row_pointers,
7401 num_rows);
7402 #else
7403 /* To do: zero the padding bits */
7404 png_write_row(write_ptr, row_buf);
7405 #endif
7406 }
7407 #if PNGCRUSH_TIMERS > 0
7408 if (verbose >= 0)
7409 {
7410 if (nosave == 0)
7411 pngcrush_timer_stop(PNGCRUSH_TIMER_ENCODE);
7412 else
7413 pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
7414 pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
7415 }
7416 #endif
7417 /* Bail if byte count exceeds best so far */
7418 if (bail == 0 && trial != last_method &&
7419 pngcrush_write_byte_count >
7420 pngcrush_best_byte_count)
7421 {
7422 png_write_flush(write_ptr);
7423 break;
7424 }
7425 }
7426 P2( "End interlace pass %d\n\n", pass);
7427 if (bail == 0 && trial != last_method &&
7428 pngcrush_write_byte_count >
7429 pngcrush_best_byte_count)
7430 break;
7431 }
7432
7433 if (color_type == 3)
7434 {
7435 if (trial == 0 && reduce_palette == 1)
7436 {
7437 int palette_length;
7438
7439 palette_length = plte_len;
7440 P1("Measured palette length = %d\n", palette_length);
7441
7442 #ifdef PNG_READ_bKGD_SUPPORTED
7443 {
7444 png_color_16p bkgd;
7445 if (png_get_bKGD(read_ptr, read_info_ptr, &bkgd))
7446 {
7447 bkgd_index = bkgd->index;
7448 P1("bKGD index = %d\n", bkgd_index);
7449 #if 1
7450 if (bkgd_index > palette_length)
7451 {
7452 bkgd_index = palette_length;
7453 have_bkgd = 1;
7454 fprintf(STDERR,
7455 " New bKGD index = %d\n", bkgd_index);
7456 }
7457 #endif
7458 if (bkgd->index >= palette_length)
7459 palette_length = (int) bkgd_index+1;
7460 P1("Total palette length = %d\n", palette_length);
7461 }
7462 }
7463 #endif
7464 plte_len = palette_length;
7465 if (num_trans > plte_len)
7466 {
7467 num_trans = plte_len;
7468 png_set_tRNS(write_ptr, write_info_ptr, trns_array,
7469 num_trans, trans_values);
7470 }
7471 }
7472 }
7473
7474 #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) && \
7475 defined(PNG_FLOATING_POINT_SUPPORTED)
7476 if ((color_type == 2 || color_type == 6 || color_type == 3)
7477 && (output_color_type == 0 || output_color_type == 4))
7478 {
7479 png_byte rgb_error =
7480 png_get_rgb_to_gray_status(read_ptr);
7481 if (last_trial && verbose > 0 && rgb_error)
7482 fprintf(STDERR,
7483 " **** Converted non-gray image to gray. **** \n");
7484 }
7485 #endif
7486
7487 #ifdef PNG_FREE_UNKN
7488 # if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
7489 png_free_data(read_ptr, read_info_ptr, PNG_FREE_UNKN, -1);
7490 # endif
7491 # if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
7492 png_free_data(write_ptr, write_info_ptr, PNG_FREE_UNKN, -1);
7493 # endif
7494 #else
7495 # if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
7496 png_free_unknown_chunks(read_ptr, read_info_ptr, -1);
7497 # endif
7498 # if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
7499 png_free_unknown_chunks(write_ptr, write_info_ptr, -1);
7500 # endif
7501 #endif /* PNG_FREE_UNKN */
7502
7503 /* { GRR: added for %-navigation (2) */
7504 if (!(bail == 0 && trial != last_method &&
7505 pngcrush_write_byte_count >
7506 pngcrush_best_byte_count))
7507 {
7508 P1(" Reading and writing end_info data\n");
7509 png_read_end(read_ptr, end_info_ptr);
7510
7511 /* Handle ancillary chunks */
7512 if (last_trial == 1)
7513 {
7514 #if (defined(PNG_READ_tEXt_SUPPORTED) && defined(PNG_WRITE_tEXt_SUPPORTED)) \
7515 || (defined(PNG_READ_iTXt_SUPPORTED) && defined(PNG_WRITE_iTXt_SUPPORTED)) \
7516 || (defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED))
7517
7518 P1( "Check for iTXt/tEXt/zTXt chunks after IDAT\n");
7519 {
7520 png_textp text_ptr;
7521 int num_text = 0;
7522
7523 if (png_get_text (read_ptr,
7524 end_info_ptr, &text_ptr, &num_text) > 0
7525 || text_inputs)
7526 {
7527 int ntext;
7528
7529 #ifdef PNG_iTXt_SUPPORTED
7530 P1( "Handling %d tEXt/zTXt/iTXt chunks after IDAT\n",
7531 #else
7532 P1( "Handling %d tEXt/zTXt chunks after IDAT\n",
7533 #endif
7534 num_text);
7535
7536 if (verbose > 1 && last_trial && num_text > 0)
7537 {
7538 for (ntext = 0; ntext < num_text; ntext++)
7539 {
7540 fprintf(STDERR, "%d %s", ntext,
7541 text_ptr[ntext].key);
7542 if (text_ptr[ntext].text_length)
7543 fprintf(STDERR, ": %s\n",
7544 text_ptr[ntext].text);
7545 #ifdef PNG_iTXt_SUPPORTED
7546 else if (text_ptr[ntext].itxt_length)
7547 {
7548 fprintf(STDERR, " (%s: %s): \n",
7549 text_ptr[ntext].lang,
7550 text_ptr[ntext].lang_key);
7551 fprintf(STDERR, "%s\n",
7552 text_ptr[ntext].text);
7553 }
7554 #endif
7555 else
7556 fprintf(STDERR, "\n");
7557 }
7558 }
7559
7560 if (last_trial)
7561 {
7562 if (num_text > 0)
7563 {
7564 if (keep_chunk("text", argv))
7565 {
7566 int num_to_write = num_text;
7567 for (ntext = 0; ntext < num_text; ntext++)
7568 {
7569 if (verbose > 1)
7570 P2("Text chunk after IDAT, "
7571 "compression=%d\n",
7572 text_ptr[ntext].compression);
7573 if (text_ptr[ntext].compression ==
7574 PNG_TEXT_COMPRESSION_NONE)
7575 {
7576 if (!keep_chunk("tEXt", argv))
7577 {
7578 text_ptr[ntext].key[0] = '\0';
7579 num_to_write--;
7580 }
7581 }
7582 if (text_ptr[ntext].compression ==
7583 PNG_TEXT_COMPRESSION_zTXt)
7584 {
7585 if (!keep_chunk("zTXt", argv))
7586 {
7587 text_ptr[ntext].key[0] = '\0';
7588 num_to_write--;
7589 }
7590 }
7591 #ifdef PNG_iTXt_SUPPORTED
7592 if (text_ptr[ntext].compression ==
7593 PNG_ITXT_COMPRESSION_NONE
7594 || text_ptr[ntext].compression ==
7595 PNG_ITXT_COMPRESSION_zTXt)
7596 {
7597 if (!keep_chunk("iTXt", argv))
7598 {
7599 text_ptr[ntext].key[0] = '\0';
7600 num_to_write--;
7601 }
7602 }
7603 #endif
7604 }
7605 if (num_to_write > 0)
7606 png_set_text(write_ptr,
7607 write_end_info_ptr,
7608 text_ptr, num_text);
7609 }
7610 }
7611
7612 P1( "text_inputs=%d\n",text_inputs);
7613 for (ntext = 0; ntext < text_inputs; ntext++)
7614 {
7615 P1( " ntext=%d\n",ntext);
7616 if (text_where[ntext] == 2)
7617 {
7618 png_textp added_text;
7619 added_text = (png_textp)
7620 png_malloc(write_ptr,
7621 (png_uint_32)
7622 sizeof(png_text));
7623 added_text[0].key =
7624 &text_keyword[ntext * 80];
7625 #ifdef PNG_iTXt_SUPPORTED
7626 added_text[0].lang =
7627 &text_lang[ntext * 80];
7628 added_text[0].lang_key =
7629 &text_lang_key[ntext * 80];
7630 #endif
7631 added_text[0].text =
7632 &text_text[ntext * STR_BUF_SIZE];
7633 added_text[0].compression =
7634 text_compression[ntext];
7635 png_set_text(write_ptr, write_end_info_ptr,
7636 added_text, 1);
7637
7638 if (verbose > 0 && last_trial)
7639 {
7640 if (added_text[0].compression < 0)
7641 fprintf(STDERR,
7642 " Added a tEXt chunk.\n");
7643 else if (added_text[0].compression == 0)
7644 fprintf(STDERR,
7645 " Added a zTXt chunk.\n");
7646 #ifdef PNG_iTXt_SUPPORTED
7647 else if (added_text[0].compression == 1)
7648 fprintf(STDERR,
7649 " Added an uncompressed iTXt "
7650 "chunk.\n");
7651 else
7652 fprintf(STDERR,
7653 " Added a compressed iTXt "
7654 "chunk.\n");
7655 #endif
7656 }
7657 png_free(write_ptr, added_text);
7658 added_text = (png_textp) NULL;
7659 }
7660 }
7661 } /* end of nosave block */
7662 }
7663 }
7664 #endif /* (PNG_READ_tEXt_SUPPORTED and PNG_WRITE_tEXt_SUPPORTED) or */
7665 /* (PNG_READ_iTXt_SUPPORTED and PNG_WRITE_iTXt_SUPPORTED) or */
7666 /* (PNG_READ_zTXt_SUPPORTED and PNG_WRITE_zTXt_SUPPORTED) */
7667 #if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
7668 {
7669 png_timep mod_time;
7670
7671 if (png_get_tIME(read_ptr, end_info_ptr, &mod_time))
7672 {
7673 P1( "Handling tIME chunk after IDAT\n");
7674 if (keep_chunk("tIME", argv))
7675 png_set_tIME(write_ptr, write_end_info_ptr,
7676 mod_time);
7677 }
7678 }
7679 #endif
7680
7681 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
7682 /* GRR FIXME? this block may need same fix as above */
7683 {
7684 png_unknown_chunkp unknowns;
7685 int num_unknowns =
7686 (int) png_get_unknown_chunks(read_ptr,
7687 end_info_ptr,
7688 &unknowns);
7689 if (num_unknowns && nosave == 0)
7690 {
7691 fprintf(STDERR,
7692 "Handling %d unknown chunks after IDAT\n",
7693 num_unknowns);
7694 png_set_unknown_chunks(write_ptr,
7695 write_end_info_ptr,
7696 unknowns, num_unknowns);
7697 for (i = 0; i < num_unknowns; i++)
7698 png_set_unknown_chunk_location(write_ptr,
7699 write_end_info_ptr,
7700 i,
7701 (int)
7702 unknowns[i].
7703 location);
7704 }
7705 }
7706 #endif
7707 } /* End of ancillary chunk handling */
7708
7709 if (nosave == 0) {
7710 #if 0 /* doesn't work; compression level has to be the same as in IDAT */
7711 /* if zTXt other compressed chunk */
7712 png_set_compression_level(write_ptr, 9);
7713 png_set_compression_window_bits(write_ptr, 15);
7714 png_set_compression_buffer_size(write_ptr,
7715 PNG_ZBUF_SIZE);
7716 png_set_compression_strategy(write_ptr, 0);
7717 #endif /* 0 */
7718 png_write_end(write_ptr, write_end_info_ptr);
7719 }
7720 }
7721 /* } GRR: added for %-navigation (2) */
7722
7723 P1( "Destroying read data structs\n");
7724 if (row_buf != (png_bytep) NULL)
7725 {
7726 P2(" row_buf = %p\n",row_buf);
7727 P2( "Destroying row_buf\n");
7728 /* Crash has been observed here when using the
7729 * system libpng instead of the bundled one.
7730 * It seems to have to do with the workaround for
7731 * png_read_transform_info() not being exported
7732 * in libpng-1.5.6 and later.
7733 */
7734 png_free(read_ptr, row_buf);
7735 row_buf = (png_bytep) NULL;
7736 }
7737 P2( "Destroyed data row_buf\n");
7738 #ifdef PNGCRUSH_MULTIPLE_ROWS
7739 if (row_pointers != (png_bytepp) NULL)
7740 {
7741 P1( "Destroying row_pointers\n");
7742 png_free(read_ptr, row_pointers);
7743 row_pointers = (png_bytepp) NULL;
7744 }
7745 P2( "Destroyed data row_pointers\n");
7746 #endif
7747 png_destroy_read_struct(&read_ptr, &read_info_ptr,
7748 &end_info_ptr);
7749 P2( "Destroyed data structs\n");
7750 if (nosave == 0)
7751 {
7752 #ifdef PNGCRUSH_LOCO
7753 if (do_loco)
7754 {
7755 const png_byte png_MEND[5] =
7756 { 77, 69, 78, 68, '\0' };
7757 /* write the MNG MEND chunk */
7758 png_write_chunk(write_ptr, (png_bytep) png_MEND,
7759 NULL, (png_size_t) 0);
7760 }
7761 #endif
7762 png_destroy_info_struct(write_ptr,
7763 &write_end_info_ptr);
7764 png_destroy_write_struct(&write_ptr, &write_info_ptr);
7765 }
7766 }
7767 Catch(msg) {
7768 if (nosave == 0)
7769 fprintf(stderr, "While converting %s to %s:\n", inname,
7770 outname);
7771 else
7772 fprintf(stderr, "While reading %s:\n", inname);
7773 fprintf(stderr,
7774 " pngcrush caught libpng error:\n %s\n\n", msg);
7775 if (row_buf)
7776 {
7777 png_free(read_ptr, row_buf);
7778 row_buf = (png_bytep) NULL;
7779 }
7780 #ifdef PNGCRUSH_MULTIPLE_ROWS
7781 if (row_pointers != (png_bytepp) NULL)
7782 {
7783 png_free(read_ptr, row_pointers);
7784 row_pointers = (png_bytepp) NULL;
7785 }
7786 #endif
7787 if (nosave == 0)
7788 {
7789 png_destroy_info_struct(write_ptr,
7790 &write_end_info_ptr);
7791 png_destroy_write_struct(&write_ptr, &write_info_ptr);
7792 setfiletype(outname);
7793 }
7794 png_destroy_read_struct(&read_ptr, &read_info_ptr,
7795 &end_info_ptr);
7796 if (verbose > 1)
7797 fprintf(stderr, "returning after cleanup\n");
7798 trial = last_method + 1;
7799 }
7800
7801 read_ptr = NULL;
7802 write_ptr = NULL;
7803 FCLOSE(fpin);
7804 if (last_trial && nosave == 0)
7805 {
7806 FCLOSE(fpout);
7807 setfiletype(outname);
7808 }
7809
7810 if (nosave)
7811 break;
7812
7813 if (trial == 0)
7814 continue;
7815
7816 idat_length[trial] = pngcrush_write_byte_count;
7817
7818 if (pngcrush_write_byte_count < pngcrush_best_byte_count)
7819 pngcrush_best_byte_count = pngcrush_write_byte_count;
7820
7821 if (verbose > 0 && trial != last_method)
7822 {
7823 if (bail == 0 &&
7824 pngcrush_write_byte_count > pngcrush_best_byte_count)
7825 fprintf(STDERR,
7826 " Critical chunk length, method %3d"
7827 " (ws %d fm %d zl %d zs %d) >%10lu\n",
7828 trial, compression_window,
7829 filter_type, zlib_level, z_strategy,
7830 (unsigned long)pngcrush_best_byte_count);
7831 else
7832 fprintf(STDERR,
7833 " Critical chunk length, method %3d"
7834 " (ws %d fm %d zl %d zs %d) =%10lu\n",
7835 trial, compression_window,
7836 filter_type, zlib_level, z_strategy,
7837 (unsigned long)idat_length[trial]);
7838 fflush(STDERR);
7839 }
7840
7841 } /* end of trial-loop */
7842
7843 P1("\n\nFINISHED MAIN LOOP OVER %d METHODS\n\n\n", last_method);
7844
7845 /* ////////////////////////////////////////////////////////////////////
7846 ////////////////// ////////////////////
7847 ////////////////// END OF MAIN LOOP OVER METHODS ////////////////////
7848 ////////////////// ////////////////////
7849 //////////////////////////////////////////////////////////////////// */
7850 }
7851
7852 if (fpin)
7853 {
7854 FCLOSE(fpin);
7855 }
7856 if (last_trial && nosave == 0 && fpout)
7857 {
7858 FCLOSE(fpout);
7859 setfiletype(outname);
7860 }
7861
7862 if (last_trial && nosave == 0 && overwrite != 0)
7863 {
7864 /* rename the new file , outname = inname */
7865 if (
7866 #if (defined(_Windows) || defined(_WINDOWS) || defined(WIN32) || \
7867 defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || \
7868 defined(__DJGPP__) || defined(CYGWIN))
7869 remove(inname) != 0 ||
7870 #endif
7871 rename(outname, inname) != 0 )
7872 {
7873 fprintf(STDERR,
7874 "error while renaming \"%s\" to \"%s\" \n",outname,inname);
7875 exit (1);
7876 }
7877 else
7878 P2("rename %s to %s complete.\n",outname,inname);
7879 }
7880
7881 if (last_trial && nosave == 0)
7882 {
7883 png_uint_32 output_length;
7884 #ifndef __riscos
7885 struct stat stat_buf;
7886 struct utimbuf utim;
7887
7888 stat(inname, &stat_buf);
7889 utim.actime = stat_buf.st_atime;
7890 utim.modtime = stat_buf.st_mtime;
7891 stat(outname, &stat_buf);
7892 output_length = (unsigned long) stat_buf.st_size;
7893 if (new_time_stamp == 0)
7894 {
7895 /* set file timestamp (no big deal if fails) */
7896 utime(outname, &utim);
7897 }
7898 #else
7899 output_length = (unsigned long) filesize(outname);
7900 #endif
7901 if (verbose >= 0 && bench < 2)
7902 {
7903 total_input_length += input_length + output_length;
7904
7905 if (best == 0)
7906 {
7907 fprintf(STDERR,
7908 " Best pngcrush method = 0 (settings undetermined)\n");
7909 }
7910
7911 #if 0 /* disabled */
7912 else if (!already_crushed && !image_is_immutable)
7913 #else
7914 else if (!image_is_immutable)
7915 #endif
7916 {
7917 fprintf(STDERR,
7918 " Best pngcrush method = %3d "
7919 "(ws %d fm %d zl %d zs %d) =%10lu\n",
7920 best, compression_window, fm[best], lv[best], zs[best],
7921 (unsigned long)idat_length[best]);
7922 }
7923
7924 if (verbose > 0)
7925 {
7926 if (idat_length[0] == idat_length[best])
7927 fprintf(STDERR, " (no critical chunk change)\n");
7928 else if (idat_length[0] > idat_length[best])
7929 fprintf(STDERR, " (%4.2f%% critical chunk reduction)\n",
7930 (100.0 - (100.0 * idat_length[best]) / idat_length[0]));
7931 else
7932 fprintf(STDERR, " (%4.2f%% critical chunk increase)\n",
7933 -(100.0 - (100.0 * idat_length[best]) / idat_length[0]));
7934 if (input_length == output_length)
7935 fprintf(STDERR, " (no filesize change)\n\n");
7936 else if (input_length > output_length)
7937 fprintf(STDERR, " (%4.2f%% filesize reduction)\n\n",
7938 (100.0 - (100.0 * output_length) / input_length));
7939 else
7940 fprintf(STDERR, " (%4.2f%% filesize increase)\n\n",
7941 -(100.0 - (100.0 * output_length) / input_length));
7942
7943 if (verbose > 2)
7944 fprintf(STDERR, " Number of open files=%d\n",
7945 number_of_open_files);
7946
7947 }
7948 }
7949 }
7950
7951 if (pngcrush_mode == DEFAULT_MODE || pngcrush_mode == OVERWRITE_MODE)
7952 {
7953 if (png_row_filters != NULL)
7954 {
7955 free(png_row_filters);
7956 png_row_filters = NULL;
7957 }
7958 #if PNGCRUSH_TIMERS > 0
7959 pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
7960 pngcrush_timer_stop(PNGCRUSH_TIMER_TOTAL);
7961 #endif
7962 if (verbose >= 0)
7963 {
7964 show_result();
7965 }
7966 #ifdef PNG_iCCP_SUPPORTED
7967 if (iccp_length)
7968 {
7969 free(iccp_text);
7970 iccp_text = NULL;
7971 iccp_length = 0;
7972 }
7973 #endif
7974 break;
7975 }
7976 } /* end of loop on input files */
7977
7978 #if PNGCRUSH_TIMERS > 0
7979 for (pc_timer = 0; pc_timer < PNGCRUSH_TIMERS; pc_timer++)
7980 {
7981 unsigned long ts,tn;
7982
7983 ts=pngcrush_timer_get_seconds(pc_timer);
7984 tn=pngcrush_timer_get_nanoseconds(pc_timer);
7985 if (ts < pngcrush_timer_min_secs[pc_timer])
7986 {
7987 pngcrush_timer_min_secs[pc_timer] = ts;
7988 pngcrush_timer_min_nsec[pc_timer] = tn;
7989 }
7990 else
7991 {
7992 if (tn < pngcrush_timer_min_nsec[pc_timer])
7993 pngcrush_timer_min_nsec[pc_timer] = tn;
7994 }
7995
7996 pngcrush_timer_reset(pc_timer);
7997 }
7998 #endif
7999
8000 } /* end of benchmark_iteration loop */
8001 if (verbose >= 0)
8002 {
8003 #if (PNGCRUSH_TIMERS > 0)
8004 for (pc_timer=0;pc_timer < PNGCRUSH_TIMERS; pc_timer++)
8005 {
8006 filter_count[pc_timer]+=pngcrush_timer_get_hits(pc_timer);
8007 t_sec=pngcrush_timer_min_secs[pc_timer];
8008 t_nsec=pngcrush_timer_min_nsec[pc_timer];
8009 t_filter[pc_timer] = (float)t_nsec/1000000000.;
8010 if (t_sec)
8011 t_filter[pc_timer] += (float)t_sec;
8012 }
8013
8014 # if PNGCRUSH_TIMERS >= 3
8015 fprintf(STDERR, "CPU time decode %.6f,", t_filter[1]);
8016 fprintf(STDERR, " encode %.6f,", t_filter[2]);
8017 fprintf(STDERR, " other %.6f,", t_filter[3]);
8018 fprintf(STDERR, " total %.6f sec\n", t_filter[0]);
8019 # endif
8020
8021 # if PNGCRUSH_USE_CLOCK_GETTIME != 0
8022 if (benchmark_iterations > 0)
8023 {
8024 # if PNGCRUSH_TIMERS > 9
8025 {
8026 float total_t_filter=0;
8027 float total_filter_count=0;
8028 for (pc_timer = 5; pc_timer < 10; pc_timer++)
8029 {
8030 total_t_filter+=t_filter[pc_timer];
8031 total_filter_count+=filter_count[pc_timer];
8032 }
8033 if (total_filter_count > 0)
8034 {
8035 for (pc_timer = 5; pc_timer < 10; pc_timer++)
8036 {
8037 fprintf(STDERR, " filter[%u] defilter time = %15.9f, count = %lu\n",
8038 pc_timer-5, t_filter[pc_timer],
8039 (unsigned long)filter_count[pc_timer]);
8040 }
8041 fprintf(STDERR, " total defilter time = %15.9f, count = %lu\n",
8042 total_t_filter, (unsigned long) total_filter_count);
8043 }
8044 }
8045 # endif
8046 # if PNGCRUSH_TIMERS > 4
8047 {
8048 if (filter_count[4] > 0)
8049 fprintf(STDERR, " deinterlace time = %15.9f, count = %lu\n",
8050 t_filter[4], (unsigned long)filter_count[4]);
8051 }
8052 # endif
8053 # if PNGCRUSH_TIMERS > 1
8054 {
8055 fprintf(STDERR, " total decode time = %15.9f, count = %lu\n",
8056 t_filter[1], (unsigned long)filter_count[1]);
8057 }
8058 # endif
8059 # if PNGCRUSH_TIMERS > 10
8060 {
8061 if (filter_count[10] > 0)
8062 fprintf(STDERR, " filter setup time = %15.9f, count = %lu\n",
8063 t_filter[10], (unsigned long)filter_count[10]);
8064 }
8065 # endif
8066 # if PNGCRUSH_TIMERS > 2
8067 {
8068 fprintf(STDERR, " total encode time = %15.9f, count = %lu\n",
8069 t_filter[2], (unsigned long)filter_count[2]);
8070 }
8071 # endif
8072 # if PNGCRUSH_TIMERS > 3
8073 {
8074 fprintf(STDERR, " total misc time = %15.9f, count = %lu\n",
8075 t_filter[3], (unsigned long)filter_count[3]);
8076 }
8077 # endif
8078 # if PNGCRUSH_TIMERS > 0
8079 {
8080 fprintf(STDERR, " total time = %15.9f, count = %lu\n",
8081 t_filter[0], (unsigned long)filter_count[0]);
8082 }
8083 # endif
8084 }
8085 #endif
8086 #endif
8087 }
8088
8089 if (pngcrush_must_exit)
8090 exit(0);
8091 return 0; /* just in case */
8092
8093 } /* end of main() */
8094
8095
8096
8097
8098 png_uint_32 measure_idats(FILE * fp_in)
8099 {
8100 /* Copyright (C) 1999-2002, 2006-2015 Glenn Randers-Pehrson
8101 (glennrp at users.sf.net). See notice in pngcrush.c for conditions of
8102 use and distribution */
8103 P2("\nmeasure_idats:\n");
8104 P1( "Allocating read structure\n");
8105 /* OK to ignore any warning about the address of exception__prev in "Try" */
8106 Try {
8107 read_ptr =
8108 png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL,
8109 (png_error_ptr) pngcrush_cexcept_error,
8110 (png_error_ptr) NULL);
8111 P1( "Allocating read_info, end_info structures\n");
8112 read_info_ptr = png_create_info_struct(read_ptr);
8113 end_info_ptr = png_create_info_struct(read_ptr);
8114
8115 #ifdef PNG_STDIO_SUPPORTED
8116 png_init_io(read_ptr, fp_in);
8117 #else
8118 png_set_read_fn(read_ptr, (png_voidp) fp_in, (png_rw_ptr) NULL);
8119 #endif
8120
8121 png_set_sig_bytes(read_ptr, 0);
8122 measured_idat_length = pngcrush_measure_idat(read_ptr);
8123 P2("measure_idats: IDAT length=%lu\n",
8124 (unsigned long)measured_idat_length);
8125 P1( "Destroying data structs\n");
8126 png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
8127 }
8128 Catch(msg) {
8129 fprintf(STDERR, "\nWhile measuring IDATs in %s ", inname);
8130 fprintf(STDERR, "pngcrush caught libpng error:\n %s\n\n", msg);
8131 png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
8132 P1( "Destroyed data structs\n");
8133 measured_idat_length = 0;
8134 }
8135 return measured_idat_length;
8136 }
8137
8138
8139
8140
8141 #define PNGCRUSH_a 97
8142 #define PNGCRUSH_z 122
8143 #define PNGCRUSH_A 65
8144 #define PNGCRUSH_Z 90
8145
8146 png_uint_32 pngcrush_measure_idat(png_structp png_ptr)
8147 {
8148 /* Copyright (C) 1999-2002, 2006-2015 Glenn Randers-Pehrson
8149 (glennrp at users.sf.net)
8150 See notice in pngcrush.c for conditions of use and distribution */
8151
8152 /* Signature + IHDR + IEND; we'll add PLTE + IDAT lengths */
8153 png_uint_32 sum_idat_length = 45;
8154
8155 png_byte *bb = NULL;
8156 png_uint_32 malloced_length=0;
8157
8158 {
8159 png_byte png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
8160 #ifdef PNGCRUSH_LOCO
8161 png_byte mng_signature[8] = { 138, 77, 78, 71, 13, 10, 26, 10 };
8162 #endif
8163
8164 pngcrush_default_read_data(png_ptr, png_signature, 8);
8165 png_set_sig_bytes(png_ptr, 8);
8166
8167 #ifdef PNGCRUSH_LOCO
8168 if (!(int) (png_memcmp(mng_signature, png_signature, 8)))
8169 {
8170 const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
8171
8172 int ib;
8173 png_byte buff[28] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8174 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8175 0, 0, 0, 0, 0, 0, 0, 0 };
8176 unsigned long length;
8177 /* read the MHDR */
8178 pngcrush_default_read_data(png_ptr, buff, 4);
8179
8180 length = pngcrush_get_uint_31(png_ptr,buff);
8181 if (length > 28)
8182 png_error(png_ptr, "MHDR length too long");
8183
8184 pngcrush_default_read_data(png_ptr, buff, 4);
8185
8186 /* To do: combine with checking for valid PNG chunk_name, below */
8187 /* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
8188 if (!(((buff[0] >= PNGCRUSH_a && buff[0] <= PNGCRUSH_z) ||
8189 (buff[0] >= PNGCRUSH_A && buff[0] <= PNGCRUSH_Z)) &&
8190 ((buff[1] >= PNGCRUSH_a && buff[1] <= PNGCRUSH_z) ||
8191 (buff[1] >= PNGCRUSH_A && buff[1] <= PNGCRUSH_Z)) &&
8192 ((buff[2] >= PNGCRUSH_A && buff[2] <= PNGCRUSH_Z)) &&
8193 ((buff[3] >= PNGCRUSH_a && buff[3] <= PNGCRUSH_z) ||
8194 (buff[3] >= PNGCRUSH_A && buff[3] <= PNGCRUSH_Z))))
8195 {
8196 int i;
8197 fprintf (STDERR,"Invalid MNG chunk name: \"");
8198 for (i=0; i<4; i++)
8199 {
8200 if ((buff[i] >= PNGCRUSH_a && buff[i] <= PNGCRUSH_z) ||
8201 (buff[i] >= PNGCRUSH_A && buff[i] <= PNGCRUSH_Z) ||
8202 (buff[i] >= '0' && buff[i] <= '9'))
8203 fprintf(STDERR,"%c",buff[i]);
8204 else
8205 fprintf(STDERR,"?");
8206 }
8207 fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
8208 buff[0],buff[1],buff[2],buff[3]);
8209 }
8210 else
8211 if (verbose > 1)
8212 printf(" Reading %c%c%c%c chunk.\n",buff[0],buff[1],buff[2],
8213 buff[3]);
8214
8215 pngcrush_default_read_data(png_ptr, buff, length);
8216
8217 if (length < 28)
8218 for (ib=27; ib >= length; ib--)
8219 buff[ib] = 0;
8220
8221 if (verbose > 0) {
8222 printf(" width=%lu\n",
8223 (unsigned long) pngcrush_get_uint_31(png_ptr,buff));
8224 printf(" height=%lu\n",
8225 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[4]));
8226 printf(" ticksps=%lu\n",
8227 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[8]));
8228 printf(" nomlayc=%lu\n",
8229 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[12]));
8230 printf(" nomfram=%lu\n",
8231 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[16]));
8232 printf(" nomplay=%lu\n",
8233 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[20]));
8234 printf(" profile=%lu\n",
8235 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[24]));
8236 }
8237
8238 if (new_mng)
8239 {
8240 /* write the MNG 8-byte signature */
8241 pngcrush_write_png(mng_ptr, &mng_signature[0],
8242 (png_size_t) 8);
8243
8244 /* Write a MHDR chunk */
8245 png_write_chunk(mng_ptr, (png_bytep) png_MHDR,
8246 buff, (png_size_t) 28);
8247 }
8248
8249 pngcrush_default_read_data(png_ptr, buff, 4);
8250 input_format = 1;
8251
8252 }
8253 else
8254 #endif
8255 if (png_sig_cmp(png_signature, 0, 8))
8256 {
8257 if (png_sig_cmp(png_signature, 0, 4))
8258 png_error(png_ptr, "Not a PNG file..");
8259 else
8260 png_error(png_ptr,
8261 "PNG file corrupted by ASCII conversion");
8262 }
8263 }
8264
8265 if (salvage)
8266 {
8267 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8268 /* The warning here about deprecated access to png_ptr->zstream
8269 * is unavoidable. This will not work with libpng-1.5.x and later.
8270 */
8271 inflateUndermine(&png_ptr->zstream, 1);
8272 #endif
8273 }
8274
8275 for (;;)
8276 {
8277 #ifndef PNG_UINT_IDAT
8278 # ifdef PNG_USE_LOCAL_ARRAYS
8279 PNG_IDAT;
8280 PNG_IEND;
8281 PNG_IHDR;
8282 PNG_acTL;
8283 # ifdef PNG_iCCP_SUPPORTED
8284 PNG_iCCP;
8285 # endif
8286 # else
8287 # ifdef PNG_iCCP_SUPPORTED
8288 const png_byte png_iCCP[5] = { 105, 67, 67, 80, '\0' };
8289 # endif
8290 const png_byte png_acTL[5] = { 97, 99, 84, 76, '\0' };
8291 # endif
8292 #endif
8293
8294 png_byte chunk_name[5];
8295 png_byte chunk_length[4];
8296 png_byte buff[32];
8297 png_uint_32 length;
8298
8299 pngcrush_default_read_data(png_ptr, chunk_length, 4);
8300 length = pngcrush_get_uint_31(png_ptr,chunk_length);
8301
8302 pngcrush_reset_crc(png_ptr);
8303 pngcrush_crc_read(png_ptr, chunk_name, 4);
8304 chunk_name[4]='\0';
8305
8306 /* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
8307 if (!(((chunk_name[0] >= PNGCRUSH_a && chunk_name[0] <= PNGCRUSH_z) ||
8308 (chunk_name[0] >= PNGCRUSH_A && chunk_name[0] <= PNGCRUSH_Z)) &&
8309 ((chunk_name[1] >= PNGCRUSH_a && chunk_name[1] <= PNGCRUSH_z) ||
8310 (chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
8311 ((chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
8312 ((chunk_name[3] >= PNGCRUSH_a && chunk_name[3] <= PNGCRUSH_z) ||
8313 (chunk_name[3] >= PNGCRUSH_A && chunk_name[3] <= PNGCRUSH_Z))))
8314 {
8315 int i;
8316
8317 fprintf (STDERR,"Invalid chunk name: \"");
8318 for (i=0; i<4; i++)
8319 {
8320 if ((chunk_name[i] >= PNGCRUSH_a &&
8321 chunk_name[i] <= PNGCRUSH_z) ||
8322 (chunk_name[i] >= PNGCRUSH_A &&
8323 chunk_name[i] <= PNGCRUSH_Z)||
8324 (chunk_name[i] >= '0' &&
8325 chunk_name[i] <= '9'))
8326 fprintf(STDERR,"%c",chunk_name[i]);
8327 else
8328 fprintf(STDERR,"?");
8329 }
8330 fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
8331 chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
8332 }
8333 else
8334 if (verbose > 1)
8335 printf(" Reading %c%c%c%c chunk.\n",
8336 chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
8337
8338 if (new_mng)
8339 {
8340 const png_byte png_DHDR[5] = { 68, 72, 68, 82, '\0' };
8341 const png_byte png_DEFI[5] = { 68, 69, 70, 73, '\0' };
8342 const png_byte png_FRAM[5] = { 70, 82, 65, 77, '\0' };
8343 const png_byte png_nEED[5] = { 110, 69, 69, 68, '\0' };
8344
8345 if (!png_memcmp(chunk_name, png_nEED, 4))
8346 {
8347 /* Skip the nEED chunk */
8348 if (verbose > 0)
8349 printf (" skipping MNG %c%c%c%c chunk, %lu bytes\n",
8350 chunk_name[0],
8351 chunk_name[1],chunk_name[2],chunk_name[3],
8352 (unsigned long)length);
8353 }
8354 else
8355 {
8356 /* copy the chunk. */
8357 if (verbose > 0)
8358 printf (" reading MNG %c%c%c%c chunk, %lu bytes\n",
8359 chunk_name[0],
8360 chunk_name[1],chunk_name[2],chunk_name[3],
8361 (unsigned long)length);
8362 if (length+1 > malloced_length)
8363 {
8364 png_free(mng_ptr,bb);
8365 if (verbose > 0)
8366 printf (" png_malloc %lu bytes.\n",(unsigned long)length);
8367 bb=(png_byte*)png_malloc(mng_ptr, length+1);
8368 malloced_length=length+1;
8369 }
8370 pngcrush_crc_read(png_ptr, bb, length);
8371 bb[length]='\0';
8372 png_write_chunk(mng_ptr, chunk_name,
8373 bb, (png_size_t) length);
8374
8375 if (verbose > 1 && !png_memcmp(chunk_name, png_DHDR, 4))
8376 {
8377 if (length > 19)
8378 {
8379 printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
8380 printf(" itype=%lu\n",(unsigned long)(bb[2]));
8381 printf(" dtype=%lu\n",(unsigned long)(bb[3]));
8382 printf(" width=%lu\n",
8383 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[4]));
8384 printf(" height=%lu\n",
8385 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[8]));
8386 printf(" xloc=%lu\n",
8387 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
8388 printf(" yloc=%lu\n",
8389 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
8390 }
8391 }
8392
8393 if (verbose > 1 && !png_memcmp(chunk_name, png_DEFI, 4))
8394 {
8395 if (length > 3)
8396 {
8397 printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
8398 printf(" do_not_show=%lu\n",(unsigned long)(bb[2]));
8399 printf(" concrete=%lu\n",(unsigned long)(bb[3]));
8400 }
8401 if (length > 19)
8402 {
8403 printf(" xloc=%lu\n",
8404 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
8405 printf(" yloc=%lu\n",
8406 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
8407 if (length > 28)
8408 {
8409 printf(" l_cb=%lu\n",
8410 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[20]));
8411 printf(" r_cb=%lu\n",
8412 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[24]));
8413 }
8414 }
8415 }
8416 if (verbose > 1 && !png_memcmp(chunk_name, png_FRAM, 4))
8417 {
8418 printf(" mode=%lu\n",(unsigned long)bb[0]);
8419 if (length > 1)
8420 {
8421 int ib;
8422 printf(" name = ");
8423 bb[length]='\0';
8424 for (ib=0; bb[ib]; ib++)
8425 {
8426 printf ("%c", bb[ib]);
8427 }
8428 printf ("\n");
8429 }
8430 length=0;
8431 }
8432 }
8433 }
8434
8435 #ifdef PNG_UINT_acTL
8436 else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_acTL)
8437 #else
8438 else if (!png_memcmp(chunk_name, png_acTL, 4))
8439 #endif
8440 {
8441 found_acTL_chunk = 1;
8442 }
8443
8444 #ifdef PNG_UINT_IDAT
8445 if ((pngcrush_get_uint_32(chunk_name) == PNG_UINT_IDAT) ||
8446 #endif
8447 #ifndef PNG_UINT_IDAT
8448 if ((!png_memcmp(chunk_name, png_IDAT, 4)) ||
8449 #endif
8450 #ifdef PNG_UINT_PLTE
8451 (pngcrush_get_uint_32(chunk_name) == PNG_UINT_PLTE))
8452 #endif
8453 #ifndef PNG_UINT_PLTE
8454 (!png_memcmp(chunk_name, png_PLTE, 4)))
8455 #endif
8456 {
8457 sum_idat_length += (length + 12);
8458 #if 0 /* disabled */
8459 if (length > crushed_idat_size)
8460 already_crushed++;
8461 #endif
8462 }
8463
8464 if (verbose > 1)
8465 {
8466 chunk_name[4] = '\0';
8467 fprintf(STDERR, " Reading %s chunk, length = %lu.\n",
8468 chunk_name, (unsigned long)length);
8469 }
8470
8471 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_CgBI)
8472 {
8473 fprintf(STDERR,
8474 " This is an Xcode CgBI file, not a PNG file.\n");
8475 if (salvage)
8476 {
8477 fprintf (STDERR, " Removing the CgBI chunk.\n");
8478 }
8479 else
8480 {
8481 fprintf (STDERR,
8482 " Try \"pngcrush -fix ...\" to attempt to read it.\n");
8483 }
8484 found_CgBI++;
8485 nosave++;
8486 }
8487
8488
8489 #ifdef PNG_UINT_IHDR
8490 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IHDR)
8491 #else
8492 if (!png_memcmp(chunk_name, png_IHDR, 4))
8493 #endif
8494 {
8495 /* get the color type */
8496 pngcrush_crc_read(png_ptr, buff, 13);
8497 length -= 13;
8498 input_color_type = buff[9];
8499 }
8500 else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_dSIG)
8501 {
8502 if (found_any_chunk == 0 && !all_chunks_are_safe)
8503 {
8504 image_is_immutable=1;
8505 }
8506 }
8507 else
8508 found_any_chunk=1;
8509
8510 #ifdef PNG_gAMA_SUPPORTED
8511 #ifdef PNG_UINT_gAMA
8512 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_gAMA)
8513 #else
8514 if (!png_memcmp(chunk_name, png_gAMA, 4))
8515 #endif
8516 found_gAMA=1;
8517 #endif /* PNG_gAMA_SUPPORTED */
8518
8519 #ifdef PNG_bKGD_SUPPORTED
8520 #ifdef PNG_UINT_bKGD
8521 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_bKGD)
8522 #else
8523 if (!png_memcmp(chunk_name, png_bKGD, 4))
8524 #endif
8525 if (length == 6)
8526 {
8527 /* Set found_color_bKGD if the components are different,
8528 * so we do not do reduction of color-type from color to gray
8529 */
8530 pngcrush_crc_read(png_ptr, buff, 6);
8531 length -= 6;
8532 if ((buff[0] != buff[2]) && (buff[0] != buff[4]) &&
8533 (buff[1] != buff[3]) && (buff[0] != buff[5]))
8534 found_color_bKGD=1;
8535 }
8536 #endif /* PNG_bKGD_SUPPORTED */
8537
8538 #ifdef PNG_cHRM_SUPPORTED
8539 #ifdef PNG_UINT_cHRM
8540 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_cHRM)
8541 #else
8542 if (!png_memcmp(chunk_name, png_cHRM, 4))
8543 #endif
8544 found_cHRM=1;
8545 #endif /* PNG_cHRM_SUPPORTED */
8546
8547 #ifdef PNG_hIST_SUPPORTED
8548 #ifdef PNG_UINT_hIST
8549 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_hIST)
8550 #else
8551 if (!png_memcmp(chunk_name, png_hIST, 4))
8552 #endif
8553 found_hIST=1;
8554 #endif /* PNG_hIST_SUPPORTED */
8555
8556 #ifdef PNG_iCCP_SUPPORTED
8557 /* check for bad Photoshop iCCP chunk */
8558 #ifdef PNG_UINT_iCCP
8559 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_iCCP)
8560 #else
8561 if (!png_memcmp(chunk_name, png_iCCP, 4))
8562 #endif
8563 {
8564 found_iCCP = 1;
8565
8566 /* Check for bad Photoshop iCCP chunk. Libpng will reject the
8567 * bad chunk because the Adler-32 bytes are missing, but we check
8568 * here to see if it's really the sRGB profile, and if so, set the
8569 * "intent" flag and gamma so pngcrush will write an sRGB chunk
8570 * and a gamma chunk.
8571 */
8572 if (length == 2615)
8573 {
8574 pngcrush_crc_read(png_ptr, buff, 22);
8575 length -= 22;
8576 buff[23] = 0;
8577 if (!strncmp((png_const_charp) buff, "Photoshop ICC profile",
8578 21))
8579 {
8580 fprintf(STDERR,
8581 " Replacing bad Photoshop iCCP chunk with an "
8582 "sRGB chunk\n");
8583 #ifdef PNG_gAMA_SUPPORTED
8584 # ifdef PNG_FIXED_POINT_SUPPORTED
8585 image_specified_gamma = 45455L;
8586 # else
8587 image_specified_gamma = 0.45455;
8588 # endif
8589 #endif /* PNG_gAMA_SUPPORTED */
8590 found_iCCP = 0;
8591 found_sRGB = 1;
8592 intent = 0;
8593 }
8594 }
8595 /* To do: recognize other sRGB iCCP chunks and replace them with
8596 * sRGB chunk
8597 */
8598 }
8599 #endif /* PNG_iCCP_SUPPORTED */
8600
8601 #ifdef PNG_sBIT_SUPPORTED
8602 #ifdef PNG_UINT_sBIT
8603 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_sBIT)
8604 #else
8605 if (!png_memcmp(chunk_name, png_sBIT, 4))
8606 #endif
8607 {
8608 if (length <= 4)
8609 {
8610 int i;
8611 pngcrush_crc_read(png_ptr, buff, length);
8612 found_sBIT_max=0;
8613 for (i=length; i; i--)
8614 if (buff[i] > found_sBIT_max)
8615 found_sBIT_max=buff[i];
8616
8617 if (length > 2)
8618 if (buff[0] != buff[1] || buff[0] != buff[2])
8619 found_sBIT_different_RGB_bits = 1;
8620
8621 found_sBIT = 1;
8622 length = 0;
8623 }
8624 }
8625 #endif /* PNG_sBIT_SUPPORTED */
8626
8627 #ifdef PNG_tRNS_SUPPORTED
8628 #ifdef PNG_UINT_tRNS
8629 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_tRNS)
8630 #else
8631 if (!png_memcmp(chunk_name, png_tRNS, 4))
8632 #endif
8633 found_tRNS=1;
8634 #endif /* PNG_tRNS_SUPPORTED */
8635
8636 pngcrush_crc_finish(png_ptr, length);
8637
8638 #ifdef PNGCRUSH_LOCO
8639 # ifdef PNG_UINT_MEND
8640 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_MEND)
8641 return sum_idat_length;
8642 # else
8643 {
8644 const png_byte png_MEND[5] =
8645 { 77, 69, 78, 68, '\0' };
8646 if (!png_memcmp(chunk_name, png_MEND, 4))
8647 {
8648 if (new_mng)
8649 {
8650 png_free(mng_ptr,bb);
8651 return (0);
8652 }
8653 return sum_idat_length;
8654 }
8655 }
8656 # endif
8657 #endif
8658
8659
8660 #ifdef PNGCRUSH_LOCO
8661 if (input_format == 0)
8662 #endif
8663 {
8664 #ifdef PNG_UINT_IEND
8665 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IEND)
8666 #else
8667 if (!png_memcmp(chunk_name, png_IEND, 4))
8668 #endif
8669 {
8670 if (!salvage && found_CgBI)
8671 return 0;
8672 else
8673 return sum_idat_length;
8674 }
8675 }
8676 }
8677 }
8678
8679
8680 void print_version_info(void)
8681 {
8682 char *zlib_copyright;
8683
8684 #ifndef ZLIB_VERNUM /* This became available in zlib-1.2 */
8685 zlib_copyright=" (or later)";
8686 #else
8687 switch (ZLIB_VERNUM)
8688 {
8689 case 0x1220:
8690 zlib_copyright="-2004";
8691 break;
8692 case 0x1230:
8693 zlib_copyright="-2005";
8694 break;
8695 case 0x1240:
8696 case 0x1250:
8697 zlib_copyright="-2010";
8698 break;
8699 case 0x1260:
8700 case 0x1270:
8701 zlib_copyright="-2012";
8702 break;
8703 case 0x1271:
8704 case 0x1280:
8705 zlib_copyright="-2013";
8706 break;
8707 case 0x1290:
8708 case 0x12a0:
8709 case 0x12b0:
8710 zlib_copyright="-2017";
8711 break;
8712 default:
8713 zlib_copyright=" (or later)";
8714 break;
8715 }
8716 #endif
8717
8718 #ifdef PNGCRUSH_H
8719 # define BUNDLED_LIB "bundled"
8720 #else
8721 # define BUNDLED_LIB "system"
8722 #endif
8723
8724 fprintf(STDERR,
8725 "\n"
8726 " | pngcrush-%s\n"
8727 /* If you have modified this source, you may insert additional notices
8728 * immediately after this sentence: */
8729 " | Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson\n"
8730 " | Portions Copyright (C) 2005 Greg Roelofs\n"
8731 " | This is a free, open-source program. Permission is irrevocably\n"
8732 " | granted to everyone to use this version of pngcrush without\n"
8733 " | payment of any fee.\n"
8734 " | Executable name is %s\n"
8735 " | It was built with %s libpng-%s\n"
8736 " | and is running with %s libpng-%s\n"
8737 " | Copyright (C) 1998-2004, 2006-2017 Glenn Randers-Pehrson,\n"
8738 " | Copyright (C) 1996, 1997 Andreas Dilger,\n"
8739 " | Copyright (C) 1995, Guy Eric Schalnat, Group 42 Inc.,\n"
8740 " | and %s zlib-%s, Copyright (C) 1995%s,\n"
8741 " | Jean-loup Gailly and Mark Adler",
8742 PNGCRUSH_VERSION, progname,
8743 BUNDLED_LIB,PNG_LIBPNG_VER_STRING,
8744 BUNDLED_LIB,png_get_header_ver(NULL),
8745 BUNDLED_LIB,ZLIB_VERSION,
8746 zlib_copyright);
8747
8748 #if PNGCRUSH_TIMERS > 0
8749 fprintf(STDERR,
8750 ",\n | and using \"%s\".\n",PNGCRUSH_USING_CLOCK);
8751 #else
8752 fprintf(STDERR,"\n");
8753 #endif
8754 if (strcmp(png_libpng_ver, PNG_LIBPNG_VER_STRING))
8755 {
8756 fprintf(STDERR,
8757 "Warning: versions are different between png.h and png.c\n");
8758 fprintf(STDERR, " png.h version: %s\n", PNG_LIBPNG_VER_STRING);
8759 fprintf(STDERR, " png.c version: %s\n\n", png_libpng_ver);
8760 }
8761
8762 #if defined(__GNUC__)
8763 fprintf(STDERR,
8764 " | It was compiled with gcc version %s", __VERSION__);
8765 # if defined(__DJGPP__)
8766 fprintf(STDERR,
8767 "\n"
8768 " | under DJGPP %d.%d, Copyright (C) 1995, DJ Delorie\n"
8769 " | and loaded with PMODE/DJ, by Thomas Pytel and Matthias Grimrath\n"
8770 " | Copyright (C) 1996, Matthias Grimrath.\n",
8771 __DJGPP__, __DJGPP_MINOR__);
8772 # else
8773 fprintf(STDERR, "\n");
8774 # endif
8775 #endif
8776
8777 #if PNG_ARM_NEON_OPT > 0
8778 fprintf(STDERR," | using ARM_NEON optimizations.\n");
8779 #endif
8780 #if PNG_MIPS_MSA_OPT > 0
8781 fprintf(STDERR," | using MIPS_MSA optimizations.\n");
8782 #endif
8783 #if PNG_POWERPC_VSX_OPT > 0
8784 fprintf(STDERR," | using POWERPC_VSX optimizations.\n");
8785 #endif
8786 #if PNG_INTEL_SSE_OPT > 0
8787 fprintf(STDERR," | using INTEL_SSE optimizations.\n");
8788 #endif
8789
8790 fprintf(STDERR, "\n");
8791 }
8792
8793
8794
8795
8796
8797 static const char *pngcrush_legal[] = {
8798 "",
8799 "If you have modified this source, you may insert additional notices",
8800 "immediately after this sentence.",
8801 "Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson",
8802 "Portions Copyright (C) 2005 Greg Roelofs",
8803 "",
8804 "DISCLAIMER: The pngcrush computer program is supplied \"AS IS\".",
8805 "The Author disclaims all warranties, expressed or implied, including,",
8806 "without limitation, the warranties of merchantability and of fitness",
8807 "for any purpose. The Author assumes no liability for direct, indirect,",
8808 "incidental, special, exemplary, or consequential damages, which may",
8809 "result from the use of the computer program, even if advised of the",
8810 "possibility of such damage. There is no warranty against interference",
8811 "with your enjoyment of the computer program or against infringement.",
8812 "There is no warranty that my efforts or the computer program will",
8813 "fulfill any of your particular purposes or needs. This computer",
8814 "program is provided with all faults, and the entire risk of satisfactory",
8815 "quality, performance, accuracy, and effort is with the user.",
8816 "",
8817 "LICENSE: Permission is hereby irrevocably granted to everyone to use,",
8818 "copy, modify, and distribute this computer program, or portions hereof,",
8819 "purpose, without payment of any fee, subject to the following",
8820 "restrictions:",
8821 "",
8822 "1. The origin of this binary or source code must not be misrepresented.",
8823 "",
8824 "2. Altered versions must be plainly marked as such and must not be",
8825 "misrepresented as being the original binary or source.",
8826 "",
8827 "3. The Copyright notice, disclaimer, and license may not be removed",
8828 "or altered from any source, binary, or altered source distribution.",
8829 ""
8830 };
8831
8832 static const char *pngcrush_usage[] = {
8833 "\nusage: %s [options except for -e -d] infile.png outfile.png\n",
8834 " %s -e ext [other options] file.png ...\n",
8835 " %s -d dir/ [other options] file.png ...\n",
8836 " %s -ow [other options] file.png [tempfile.png]\n",
8837 " %s -n -v file.png ...\n"
8838 };
8839
8840 struct options_help pngcrush_options[] = {
8841
8842 {0, " -bail (bail out of trial when size exceeds best size found"},
8843 {2, ""},
8844 {2, " Default is to bail out and simply report that the"},
8845 {2, " filesize for the trial would be greater than the"},
8846 {2, " best filesize achieved so far. Use the \"-nobail\""},
8847 {2, " option to prevent that."},
8848 {2, ""},
8849
8850 {0, " -blacken (zero samples underlying fully-transparent pixels)"},
8851 {2, ""},
8852 {2, " Changing the color samples to zero can improve the"},
8853 {2, " compressibility. Since this is a lossy operation,"},
8854 {2, " blackening is off by default."},
8855 {2, ""},
8856
8857 #ifdef Z_RLE
8858 {0, " -brute (use brute-force: try 176 different methods)"},
8859 #else
8860 {0, " -brute (use brute-force: try 166 different methods)"},
8861 #endif
8862 {2, ""},
8863 {2, " Very time-consuming and generally not worthwhile."},
8864 {2, " You can restrict this option to certain filter types,"},
8865 {2, " compression levels, or strategies by following it"},
8866 {2, " with \"-f filter\", \"-l level\", or \"-z strategy\"."},
8867 {2, ""},
8868
8869 {0, FAKE_PAUSE_STRING},
8870
8871 {0, " -c color_type of output file [0, 2, 4, or 6]"},
8872 {2, ""},
8873 {2, " Color type for the output file. Future versions"},
8874 {2, " will also allow color_type 3, if there are 256 or"},
8875 {2, " fewer colors present in the input file. Color types"},
8876 {2, " 4 and 6 are padded with an opaque alpha channel if"},
8877 {2, " the input file does not have alpha information."},
8878 {2, " You can use 0 or 4 to convert color to grayscale."},
8879 {2, " Use 0 or 2 to delete an unwanted alpha channel."},
8880 {2, " Default is to use same color type as the input file."},
8881 {2, ""},
8882
8883 {0, " -check (check CRC and ADLER32 checksums)"},
8884 {2, ""},
8885 {2, " Use \"-nocheck\" (default) to skip checking them"},
8886 {2, ""},
8887
8888 {0, " -d directory_name/ (where output files will go)"},
8889 {2, ""},
8890 {2, " If a directory name is given, then the output"},
8891 {2, " files are placed in it, with the same filenames as"},
8892 {2, " those of the original files. For example,"},
8893 {2, " you would type 'pngcrush -directory CRUSHED/ *.png'"},
8894 {2, " to get *.png => CRUSHED/*.png. The trailing slash is"},
8895 {2, " optional, but if pngcrush appends the wrong kind of"},
8896 {2, " slash or backslash, please include the correct one"},
8897 {2, " at the end of the directory_name, as shown."},
8898 {2, ""},
8899
8900 {0, FAKE_PAUSE_STRING},
8901
8902 {0, " -e extension (used for creating output filename)"},
8903 {2, ""},
8904 {2, " e.g., -ext .new means *.png => *.new"},
8905 {2, " and -e _pc.png means *.png => *_pc.png"},
8906 {2, ""},
8907
8908 {0, " -f user_filter [0-5] for specified method"},
8909 {2, ""},
8910 {2, " filter to use with the method specified in the"},
8911 {2, " preceding '-m method' or '-brute_force' argument."},
8912 {2, " 0: none; 1-4: use specified filter; 5: adaptive."},
8913 {2, ""},
8914
8915 {0, FAKE_PAUSE_STRING},
8916
8917 {0, " -fix (salvage PNG with otherwise fatal conditions)"},
8918 {2, ""},
8919 {2, " Fixes bad CRCs, bad adaptive filter bytes,"},
8920 {2, " or bad CMF bytes in the IDAT chunk that cause"},
8921 {2, " the \"Too far back\" error"},
8922 {2, ""},
8923
8924 {0, " -force (write output even if IDAT is larger)"},
8925 {2, ""},
8926
8927 #ifdef PNG_FIXED_POINT_SUPPORTED
8928 {0, " -g gamma (float or fixed*100000, e.g., 0.45455 or 45455)"},
8929 #else
8930 {0, " -g gamma (float, e.g., 0.45455)"},
8931 #endif
8932 {2, ""},
8933 {2, " Value to insert in gAMA chunk, only if the input"},
8934 {2, " file has no gAMA chunk. To replace an existing"},
8935 {2, " gAMA chunk, use the '-replace_gamma' option."},
8936 {2, ""},
8937
8938 {0, FAKE_PAUSE_STRING},
8939
8940 {0, " -huffman (use only zlib strategy 2, Huffman-only)"},
8941 {2, ""},
8942 {2, " Fast, but almost never very effective except for"},
8943 {2, " certain rare image types."},
8944 {2, ""},
8945
8946 #ifdef PNG_iCCP_SUPPORTED
8947 {0, " -iccp length \"Profile Name\" iccp_file"},
8948 {2, ""},
8949 {2, " file with ICC profile to insert in an iCCP chunk."},
8950 {2, ""},
8951 #endif
8952
8953 #ifdef PNG_iTXt_SUPPORTED
8954 {0, " -itxt b[efore_IDAT]|a[fter_IDAT] \"keyword\""},
8955 {2, " \"language_code\" \"translated_keyword\" \"text\""},
8956 {2, ""},
8957 {2, " Uncompressed iTXt chunk to insert (see -text)."},
8958 {2, ""},
8959 #endif
8960
8961 {0, " -keep chunk_name"},
8962 {2, ""},
8963 {2, " keep named chunk even when pngcrush makes"},
8964 {2, " changes to the PNG datastream that cause it"},
8965 {2, " to become invalid. Currently only dSIG is"},
8966 {2, " recognized as a chunk to be kept."},
8967 {2, ""},
8968
8969
8970 {0, " -l zlib_compression_level [0-9] for specified method"},
8971 {2, ""},
8972 {2, " zlib compression level to use with method specified"},
8973 {2, " with the preceding '-m method' or '-brute_force'"},
8974 {2, " argument."},
8975 {2, ""},
8976
8977 #ifdef PNGCRUSH_LOCO
8978 {0, FAKE_PAUSE_STRING},
8979
8980 {0, " -loco (\"loco crush\" truecolor PNGs)"},
8981 {2, ""},
8982 {2, " Make the file more compressible by performing a"},
8983 {2, " lossless, reversible, color transformation."},
8984 {2, " The resulting file is a MNG, not a PNG, and should"},
8985 {2, " be given the \".mng\" file extension. The"},
8986 {2, " \"loco\" option has no effect on grayscale or"},
8987 {2, " indexed-color PNG files."},
8988 {2, ""},
8989 #endif
8990
8991 {0, " -m method [1 through " STRNGIFY(MAX_METHODS) "]"},
8992 {2, ""},
8993 {2, " pngcrush method to try. Can be repeated as in"},
8994 {2, " '-m 1 -m 4 -m 7'. This can be useful if pngcrush"},
8995 {2, " runs out of memory when it tries methods 2, 3, 5,"},
8996 {2, " 6, 8, 9, or 10 which use filtering and are memory-"},
8997 {2, " intensive. Methods 1, 4, and 7 use no filtering;"},
8998 {2, " methods 11 and up use a specified filter,"},
8999 {2, " compression level, and strategy."},
9000 {2, ""},
9001 {2, FAKE_PAUSE_STRING},
9002
9003 {0, " -max maximum_IDAT_size [default "STRNGIFY(MAX_IDAT_SIZE)"]"},
9004 {2, ""},
9005
9006 #ifdef PNGCRUSH_LOCO
9007 {0, " -mng (write a new MNG, do not crush embedded PNGs)"},
9008 {2, ""},
9009 #endif
9010
9011 {0, " -n (no save; doesn't do compression or write output PNG)"},
9012 {2, ""},
9013 {2, " Useful in conjunction with -v option to get info."},
9014 {2, ""},
9015
9016 {0, " -new (Use new default settings (-reduce))"},
9017 {2, ""},
9018
9019 {0, " -newtimestamp (Reset file modification time [default])"},
9020 {2, ""},
9021
9022 {0, " -nobail (do not bail out early from trial -- see \"-bail\")"},
9023 {2, ""},
9024 {2, " Use this if you want to get a report of the"},
9025 {2, " exact filesize achieved by each trial."},
9026 {2, ""},
9027
9028 {0, " -nocheck (do not check CRC and ADLER32 checksums)"},
9029 {2, ""},
9030 {2, " Use \"-check\" to check them"},
9031 {2, ""},
9032
9033 {0, FAKE_PAUSE_STRING},
9034
9035 {0, " -nofilecheck (do not check for infile.png == outfile.png)"},
9036 {2, ""},
9037 {2, " To avoid false hits from MSVC-compiled code. Note"},
9038 {2, " that if you use this option, you are responsible for"},
9039 {2, " ensuring that the input file is not the output file."},
9040 {2, ""},
9041
9042 {0, " -noforce (default; do not write output when IDAT is larger)"},
9043 {2, ""},
9044
9045 {0, " -nolimits (turns off limits on width, height, cache, malloc)"},
9046 {2, ""},
9047 {2, " Instead, the user limits are inherited from libpng."},
9048 {2, ""},
9049
9050 {0, " -noreduce (turns off all \"-reduce\" operations)"},
9051 {2, ""},
9052
9053 {0, "-noreduce_palette (turns off \"-reduce_palette\" operation)"},
9054 {2, ""},
9055
9056 {0, " -old (Use old default settings (no -reduce))"},
9057 {2, ""},
9058
9059 {0, " -oldtimestamp (Do not reset file modification time)"},
9060 {2, ""},
9061
9062 {0, " -ow (Overwrite)"},
9063 {2, ""},
9064 {2, " Overwrite the input file. The input file is removed"},
9065 {2, " and the temporary file (default \"pngout.png\")"},
9066 {2, " is renamed to the input file after recompression"},
9067 {2, " and therefore they must reside on the same"},
9068 {2, " filesystem."},
9069 {2, ""},
9070 {2, " CAUTION: If you are running multiple instances"},
9071 {2, " of pngcrush in parallel, you must specify a"},
9072 {2, " different temporary filename for each instance,"},
9073 {2, " to avoid collisions."},
9074 {2, ""},
9075
9076 {0, " -q (quiet) suppresses console output except for warnings"},
9077 {2, ""},
9078 {2, " and summary of results."},
9079 {2, ""},
9080
9081 {0, " -reduce (do lossless color-type or bit-depth reduction)"},
9082 {2, ""},
9083 {2, " (if possible). Also reduces palette length if"},
9084 {2, " possible. Currently only attempts to reduce the"},
9085 {2, " bit depth from 16 to 8. Reduces all-gray RGB"},
9086 {2, " or RGBA image to gray or gray-alpha. Reduces"},
9087 {2, " all-opaque RGBA or GA image to RGB or grayscale."},
9088 {2, " Since pngcrush version 1.8.0, -reduce is on by"},
9089 {2, " default, and you can disable it with -noreduce."},
9090 {2, ""},
9091
9092 {0, " -rem chunkname (or \"alla\" or \"allb\")"},
9093 {2, ""},
9094 {2, " Name of an ancillary chunk or optional PLTE to be"},
9095 {2, " removed. Be careful with this. Don't use this"},
9096 {2, " feature to remove transparency, gamma, copyright,"},
9097 {2, " or other valuable information. To remove several"},
9098 {2, " different chunks, repeat: -rem tEXt -rem pHYs."},
9099 {2, " Known chunks (those in the PNG 1.1 spec or extensions"},
9100 {2, " document) can be named with all lower-case letters,"},
9101 {2, " so \"-rem bkgd\" is equivalent to \"-rem bKGD\". But"},
9102 {2, " note: \"-rem text\" removes all forms of text chunks;"},
9103 {2, " Exact case is required to remove unknown chunks."},
9104 {2, " To do surgery with a chain-saw, \"-rem alla\" removes"},
9105 {2, " all known ancillary chunks except for tRNS, and"},
9106 {2, " \"-rem allb\" removes all but tRNS and gAMA."},
9107 {2, ""},
9108
9109 {0, FAKE_PAUSE_STRING},
9110
9111 #ifdef PNG_FIXED_POINT_SUPPORTED
9112 {0, "-replace_gamma gamma (float or fixed*100000) even if it is present."},
9113 #else
9114 {0, "-replace_gamma gamma (float, e.g. 0.45455) even if it is present."},
9115 #endif
9116 {2, ""},
9117
9118 {0, " -res resolution in dpi"},
9119 {2, ""},
9120 {2, " Write a pHYs chunk with the given resolution in dpi"},
9121 {2, " written as pixels per meter in x and y directions."},
9122 {2, ""},
9123
9124 #ifdef Z_RLE
9125 {0, " -rle (use only zlib strategy 3, RLE-only)"},
9126 {2, ""},
9127 {2, " A relatively fast subset of the \"-brute\" methods,"},
9128 {2, " generally more effective than \"-huffman\" on PNG,"},
9129 {2, " images (and quite effective on black-and-white"},
9130 {2, " images) but not necessarily worth the bother"},
9131 {2, " otherwise."},
9132 {2, ""},
9133 #endif
9134
9135 {0, " -s (silent) suppresses console output including warnings"},
9136 {2, ""},
9137 {2, " benchmark timing, and summary of results."},
9138 {2, " (Use \"-warn\" to show only warnings"},
9139 {2, ""},
9140
9141 {0, " -save (keep all copy-unsafe PNG chunks)"},
9142 {2, ""},
9143 {2, " Save otherwise unknown ancillary chunks that would"},
9144 {2, " be considered copy-unsafe. This option makes"},
9145 {2, " chunks 'known' to pngcrush, so they can be copied."},
9146 {2, " It also causes the dSIG chunk to be saved, even when"},
9147 {2, " it becomes invalid due to datastream changes."},
9148 {2, " This option does not affect APNG chunks. These"},
9149 {2, " chunks (acTL, fcTL, and fdAT) will be saved only"},
9150 {2, " if the output file has the \".apng\" extension"},
9151 {2, " and the color_type and bit_depth are not changed."},
9152 {2, ""},
9153
9154 {0, FAKE_PAUSE_STRING},
9155
9156 {0, " -speed Avoid the AVG and PAETH filters, for decoding speed"},
9157 {2, ""},
9158 {2, " Useful for compressing PNG files that are expected"},
9159 {2, " to be cached or otherwise to exist on the computer"},
9160 {2, " where they will be used rather than being downloaded,"},
9161 {2, " so filesize is therefore less important than CPU"},
9162 {2, " time expended in defiltering."},
9163 {2, ""},
9164
9165 {0, " -srgb [0, 1, 2, or 3]"},
9166 {2, ""},
9167 {2, " Value of 'rendering intent' for sRGB chunk."},
9168 {2, ""},
9169
9170 {0, " -ster [0 or 1]"},
9171 {2, ""},
9172 {2, " Value of 'stereo mode' for sTER chunk."},
9173 {2, " 0: cross-fused; 1: divergent-fused"},
9174 {2, ""},
9175
9176 {0, " -text b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
9177 {2, ""},
9178 {2, " tEXt chunk to insert. keyword < 80 chars,"},
9179 {2, " text < 2048 chars. For now, you can add no more than"},
9180 {2, " ten tEXt, iTXt, or zTXt chunks per pngcrush run."},
9181 {2, ""},
9182
9183 #ifdef PNG_tRNS_SUPPORTED
9184 {0, " -trns_array n trns[0] trns[1] .. trns[n-1]"},
9185 {2, ""},
9186 {2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
9187 {2, " Values are for the tRNS array in indexed-color PNG."},
9188 {2, ""},
9189
9190 {0, " -trns index red green blue gray"},
9191 {2, ""},
9192 {2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
9193 {2, " You must give all five parameters regardless of the"},
9194 {2, " color type, scaled to the output bit depth."},
9195 {2, ""},
9196 #endif
9197
9198 {0, FAKE_PAUSE_STRING},
9199
9200 {0, " -v (display more detailed information)"},
9201 {2, ""},
9202 {2, " Repeat the option (use \"-v -v\") for even more."},
9203 {2, ""},
9204
9205 {0, " -version (display the pngcrush version)"},
9206 {2, ""},
9207 {2, " Look for the most recent version of pngcrush at"},
9208 {2, " http://pmt.sf.net"},
9209 {2, ""},
9210
9211 {0, " -warn (only show warnings)"},
9212 {2, ""},
9213
9214 {0, " -w compression_window_size [32, 16, 8, 4, 2, 1, 512]"},
9215 {2, ""},
9216 {2, " Size of the sliding compression window, in kbytes"},
9217 {2, " (or bytes, in case of 512). It's best to"},
9218 {2, " use the default (32) unless you run out of memory."},
9219 {2, " The program will use a smaller window anyway when"},
9220 {2, " the uncompressed file is smaller than 16k."},
9221 {2, ""},
9222
9223 #ifdef Z_RLE
9224 {0, " -z zlib_strategy [0, 1, 2, or 3] for specified method"},
9225 #else
9226 {0, " -z zlib_strategy [0, 1, or 2] for specified method"},
9227 #endif
9228 {2, ""},
9229 {2, " zlib compression strategy to use with the preceding"},
9230 {2, " '-m method' argument."},
9231 {2, ""},
9232
9233 {0, " -zmem zlib_compression_mem_level [1-9, default 9]"},
9234 {2, ""},
9235
9236 #ifdef PNG_iTXt_SUPPORTED
9237 {0, " -zitxt b|a \"keyword\" \"lcode\" \"tkey\" \"text\""},
9238 {2, ""},
9239 {2, " (where \"lcode\"==language_code and"},
9240 {2, " \"tkey\"==translated_keyword)\""},
9241 {2, " Compressed iTXt chunk to insert (see -text)."},
9242 {2, ""},
9243 #endif
9244
9245 {0, " -ztxt b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
9246 {2, ""},
9247 {2, " zTXt chunk to insert (see -text)."},
9248 {2, ""},
9249 {2, FAKE_PAUSE_STRING},
9250
9251 {0, " -h (help and legal notices)"},
9252 {2, ""},
9253 {2, " Display this information."},
9254 {2, ""},
9255
9256 {0, " -p (pause)"}
9257 };
9258
9259
9260
9261
9262
9263 void print_usage(int retval)
9264 {
9265 int j, jmax;
9266
9267 if (verbose > 0)
9268 {
9269 jmax = sizeof(pngcrush_legal) / sizeof(char *);
9270 for (j = 0; j < jmax; ++j)
9271 fprintf(STDERR, "%s\n", pngcrush_legal[j]);
9272
9273 jmax = sizeof(pngcrush_usage) / sizeof(char *);
9274 for (j = 0; j < jmax; ++j)
9275 fprintf(STDERR, pngcrush_usage[j], progname); /* special case */
9276 }
9277
9278 /* This block is also handled specially due to the "else" clause... */
9279 if (verbose > 1)
9280 {
9281 pngcrush_pause();
9282 fprintf(STDERR,
9283 "\n"
9284 "options (Note: any option can be spelled out for clarity, e.g.,\n"
9285 " \"pngcrush -dir New -method 7 -remove bkgd *.png\"\n"
9286 " is the same as \"pngcrush -d New/ -m 7 -rem bkgd *.png\"):"
9287 "\n\n");
9288 }
9289 else
9290 fprintf(STDERR, "options:\n");
9291
9292 /* This is the main part of the help screen; it is more complex than the
9293 * other blocks due to the mix of verbose and non-verbose lines
9294 */
9295 jmax = sizeof(pngcrush_options) / sizeof(struct options_help);
9296 for (j = 0; j < jmax; ++j)
9297 {
9298 if (verbose >= pngcrush_options[j].verbosity)
9299 {
9300 if (pngcrush_options[j].textline[0] == FAKE_PAUSE_STRING[0])
9301 pngcrush_pause();
9302 else
9303 fprintf(STDERR, "%s\n", pngcrush_options[j].textline);
9304 }
9305 }
9306
9307 /* due to progname, the verbose part of the -p option is handled explicitly
9308 * (fortunately, it's the very last option anyway)
9309 */
9310 if (verbose > 1)
9311 {
9312 fprintf(STDERR, "\n"
9313 " Wait for [enter] key before continuing display.\n"
9314 " e.g., type '%s -pause -help', if the help\n"
9315 " screen scrolls out of sight.\n\n", progname);
9316 }
9317
9318 exit(retval);
9319 }
9320
9321 #endif /* PNGCRUSH_LIBPNG_VER < 10800 || defined(PNGCRUSH_H) */