Debian Codegraph @

pngcrush.c

raw symbols ◀ ▶
Source reconstructed at patch state 2 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 # ifdef PNG_IGNORE_ADLER32
5516 png_set_option(read_ptr, PNG_IGNORE_ADLER32,
5517 PNG_OPTION_ON);
5518 # endif
5519 png_set_crc_action(read_ptr, PNG_CRC_QUIET_USE,
5520 PNG_CRC_QUIET_USE);
5521 }
5522 #endif
5523
5524 #ifndef PNGCRUSH_CHECK_ADLER32
5525 # ifdef PNG_IGNORE_ADLER32
5526 if (last_trial == 0)
5527 {
5528 /* During trials other than the final output, avoid
5529 * calculating CRC and ADLER32 checksums (just write
5530 * a DEFLATE datastream)
5531 */
5532 png_set_option(write_ptr, PNG_IGNORE_ADLER32,
5533 PNG_OPTION_ON);
5534 }
5535 # endif
5536 #endif
5537
5538 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
5539 /* Only run this test (new in libpng-1.5.10) during the
5540 * 0th and last trial
5541 */
5542 if ((input_color_type == 3) &&
5543 ((last_trial && reduce_palette == 0) ||
5544 (trial == 0 && reduce_palette == 1)))
5545 {
5546 P1(" Check the read palette\n");
5547 png_set_check_for_invalid_index (read_ptr, 1);
5548 }
5549 #endif
5550 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
5551 if (last_trial && nosave == 0 && output_color_type == 3)
5552 {
5553 P1(" Check the written palette\n");
5554 png_set_check_for_invalid_index (write_ptr, 1);
5555 }
5556 #endif
5557
5558 if (last_trial == 1)
5559 {
5560
5561 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
5562 png_set_keep_unknown_chunks(read_ptr, PNG_HANDLE_CHUNK_ALWAYS,
5563 (png_bytep) NULL, 0);
5564 #endif
5565
5566 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
5567 if (nosave == 0)
5568 {
5569 if (save_apng_chunks == 1)
5570 {
5571 /* To do: Why use write_ptr not read_ptr here? */
5572 png_set_keep_unknown_chunks(write_ptr,
5573 PNG_HANDLE_CHUNK_ALWAYS,
5574 (png_bytep) "acTL", 1);
5575 png_set_keep_unknown_chunks(write_ptr,
5576 PNG_HANDLE_CHUNK_ALWAYS,
5577 (png_bytep) "fcTL", 1);
5578 png_set_keep_unknown_chunks(write_ptr,
5579 PNG_HANDLE_CHUNK_ALWAYS,
5580 (png_bytep) "fdAT", 1);
5581 }
5582
5583 if (found_any_chunk == 1)
5584 png_set_keep_unknown_chunks(write_ptr,
5585 PNG_HANDLE_CHUNK_ALWAYS,
5586 (png_bytep) "dSIG", 1);
5587 if (all_chunks_are_safe)
5588 {
5589 png_set_keep_unknown_chunks(write_ptr,
5590 PNG_HANDLE_CHUNK_ALWAYS,
5591 (png_bytep) NULL, 0);
5592 printf("while saving, all_chunks_are_safe=\n");
5593 if (save_apng_chunks == 0)
5594 {
5595 png_set_keep_unknown_chunks(write_ptr,
5596 PNG_HANDLE_CHUNK_ALWAYS,
5597 (png_bytep) "acTL", 1);
5598 png_set_keep_unknown_chunks(write_ptr,
5599 PNG_HANDLE_CHUNK_ALWAYS,
5600 (png_bytep) "fcTL", 1);
5601 png_set_keep_unknown_chunks(write_ptr,
5602 PNG_HANDLE_CHUNK_ALWAYS,
5603 (png_bytep) "fdAT", 1);
5604 }
5605 }
5606
5607 else
5608 {
5609 #if !defined(PNG_cHRM_SUPPORTED) || !defined(PNG_hIST_SUPPORTED) || \
5610 !defined(PNG_iCCP_SUPPORTED) || !defined(PNG_sCAL_SUPPORTED) || \
5611 !defined(PNG_pCAL_SUPPORTED) || !defined(PNG_sPLT_SUPPORTED) || \
5612 !defined(PNG_sTER_SUPPORTED) || !defined(PNG_tIME_SUPPORTED)
5613 png_byte chunk_name[5];
5614 chunk_name[4] = '\0';
5615 #endif
5616
5617 /* To do: Why use write_ptr not read_ptr here? */
5618
5619 if (keep_unknown_chunk("alla", argv) &&
5620 keep_unknown_chunk("allb", argv))
5621 png_set_keep_unknown_chunks(write_ptr,
5622 PNG_HANDLE_CHUNK_IF_SAFE,
5623 (png_bytep) NULL,
5624 0);
5625 else
5626 png_set_keep_unknown_chunks(write_ptr,
5627 PNG_HANDLE_CHUNK_NEVER,
5628 (png_bytep) NULL,
5629 0);
5630
5631 #ifndef PNG_cHRM_SUPPORTED
5632 if (keep_unknown_chunk("cHRM", argv))
5633 {
5634 pngcrush_save_uint_32(chunk_name, PNG_UINT_cHRM);
5635 png_set_keep_unknown_chunks(write_ptr,
5636 PNG_HANDLE_CHUNK_ALWAYS,
5637 chunk_name, 1);
5638 }
5639 #endif
5640 #ifndef PNG_hIST_SUPPORTED
5641 if (keep_unknown_chunk("hIST", argv))
5642 {
5643 pngcrush_save_uint_32(chunk_name, PNG_UINT_hIST);
5644 png_set_keep_unknown_chunks(write_ptr,
5645 PNG_HANDLE_CHUNK_ALWAYS,
5646 chunk_name, 1);
5647 }
5648 #endif
5649 #ifndef PNG_iCCP_SUPPORTED
5650 if (keep_unknown_chunk("iCCP", argv))
5651 {
5652 pngcrush_save_uint_32(chunk_name, PNG_UINT_iCCP);
5653 png_set_keep_unknown_chunks(write_ptr,
5654 PNG_HANDLE_CHUNK_ALWAYS,
5655 chunk_name, 1);
5656 }
5657 #endif
5658 #ifndef PNG_iTXt_SUPPORTED
5659 if (keep_unknown_chunk("iTXt", argv))
5660 {
5661 pngcrush_save_uint_32(chunk_name, PNG_UINT_iTXt);
5662 png_set_keep_unknown_chunks(write_ptr,
5663 PNG_HANDLE_CHUNK_ALWAYS,
5664 chunk_name, 1);
5665 }
5666 #endif
5667 #ifndef PNG_sCAL_SUPPORTED
5668 if (keep_unknown_chunk("sCAL", argv))
5669 {
5670 pngcrush_save_uint_32(chunk_name, PNG_UINT_sCAL);
5671 png_set_keep_unknown_chunks(write_ptr,
5672 PNG_HANDLE_CHUNK_ALWAYS,
5673 chunk_name, 1);
5674 }
5675 #endif
5676 #ifndef PNG_pCAL_SUPPORTED
5677 if (keep_unknown_chunk("pCAL", argv))
5678 {
5679 pngcrush_save_uint_32(chunk_name, PNG_UINT_pCAL);
5680 png_set_keep_unknown_chunks(write_ptr,
5681 PNG_HANDLE_CHUNK_ALWAYS,
5682 chunk_name, 1);
5683 }
5684 #endif
5685 #ifndef PNG_sPLT_SUPPORTED
5686 if (keep_unknown_chunk("sPLT", argv))
5687 {
5688 pngcrush_save_uint_32(chunk_name, PNG_UINT_sPLT);
5689 png_set_keep_unknown_chunks(write_ptr,
5690 PNG_HANDLE_CHUNK_ALWAYS,
5691 chunk_name, 1);
5692 }
5693 #endif
5694 #ifndef PNG_sTER_SUPPORTED
5695 if (keep_unknown_chunk("sTER", argv))
5696 {
5697 pngcrush_save_uint_32(chunk_name, PNG_UINT_sTER);
5698 png_set_keep_unknown_chunks(write_ptr,
5699 PNG_HANDLE_CHUNK_ALWAYS,
5700 chunk_name, 1);
5701 }
5702 #endif
5703 #ifndef PNG_tIME_SUPPORTED
5704 if (keep_unknown_chunk("tIME", argv))
5705 {
5706 pngcrush_save_uint_32(chunk_name, PNG_UINT_tIME);
5707 png_set_keep_unknown_chunks(write_ptr,
5708 PNG_HANDLE_CHUNK_ALWAYS,
5709 chunk_name, 1);
5710 }
5711 #endif
5712 }
5713 } /* nosave == 0 */
5714 #endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
5715 } /* last trial */
5716
5717 /* To do: Remove this? We already did this in measure_idats */
5718 P1(" Reading signature bytes\n");
5719 {
5720 #ifdef PNGCRUSH_LOCO
5721 png_byte mng_signature[8] =
5722 { 138, 77, 78, 71, 13, 10, 26, 10 };
5723 #endif
5724 png_byte png_signature[8] =
5725 { 137, 80, 78, 71, 13, 10, 26, 10 };
5726
5727 pngcrush_default_read_data(read_ptr, png_signature, 8);
5728 png_set_sig_bytes(read_ptr, 8);
5729
5730 #ifdef PNGCRUSH_LOCO
5731 if (!(int)(png_memcmp(mng_signature, png_signature, 8)))
5732 {
5733 /* Skip the MHDR */
5734 png_permit_mng_features(read_ptr,
5735 PNG_FLAG_MNG_FILTER_64);
5736 png_skip_chunk(read_ptr);
5737 input_format = 1;
5738 }
5739
5740 else
5741 #endif
5742 if (png_sig_cmp(png_signature, 0, 8))
5743 {
5744 if (png_sig_cmp(png_signature, 0, 4))
5745 png_error(read_ptr, "Not a PNG file!");
5746 else
5747 png_error(read_ptr,
5748 "PNG file corrupted by ASCII conversion");
5749 }
5750 if (salvage && found_CgBI)
5751 {
5752 /* Skip the CgBI chunk */
5753
5754 png_skip_chunk(read_ptr);
5755
5756 /* iCCP and zTXt are probably unreadable
5757 * because of the nonstandard deflate */
5758
5759 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
5760 png_set_keep_unknown_chunks(read_ptr,
5761 PNG_HANDLE_CHUNK_NEVER,
5762 (png_bytep)"iCCP", 1);
5763 png_set_keep_unknown_chunks(read_ptr,
5764 PNG_HANDLE_CHUNK_NEVER,
5765 (png_bytep)"zTXt", 1);
5766 #endif
5767 }
5768 }
5769
5770 #ifndef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
5771 if (premultiply)
5772 png_error(read_ptr, "Premultiplied alpha is not supported");
5773 #endif
5774
5775 P1( " Reading info struct\n");
5776 png_read_info(read_ptr, read_info_ptr);
5777
5778 if (trial != 0)
5779 {
5780 if (make_opaque == 1)
5781 {
5782 P1(" Remove all-opaque alpha channel\n");
5783 if (output_color_type == 4)
5784 output_color_type = 0;
5785 if (output_color_type == 6)
5786 output_color_type = 2;
5787 }
5788 P1(" make_opaque= %d\n",make_opaque);
5789
5790 if (make_gray == 1)
5791 {
5792 /* Note: Take care that iCCP, sBIT, and bKGD data are not
5793 * lost or become invalid when reducing images from
5794 * truecolor to grayscale or when reducing the bit depth.
5795 * (To do: test this; it's probably OK)
5796 */
5797 /* To do: check bKGD color */
5798
5799 P1(" Encode all-gray image with a gray colortype\n");
5800 if (output_color_type == 6)
5801 output_color_type = 4;
5802 if (output_color_type == 2)
5803 output_color_type = 0;
5804 }
5805 P1(" make_gray= %d\n",make_gray);
5806
5807 if (make_8_bit == 1)
5808 {
5809 /* Note: Take care that sBIT and bKGD data are not
5810 * lost or become invalid when reducing the bit depth.
5811 * (To do: test this; it's probably OK)
5812 */
5813 P1(" Reduce 16-bit image losslessly to 8-bit\n");
5814 }
5815 P1(" make_8_bit= %d\n",make_8_bit);
5816
5817 if (make_opaque != 1 && blacken == 2)
5818 {
5819 P1(" Blacken the fully transparent pixels\n");
5820 png_set_read_user_transform_fn(read_ptr,
5821 pngcrush_transform_pixels_fn);
5822 }
5823 P1(" make_opaque= %d\n",make_opaque);
5824 P1(" blacken= %d\n",blacken);
5825
5826 if (reduce_palette == 1)
5827 {
5828 /* Note: Take care that sBIT and bKGD data are not
5829 * lost or become invalid when reducing the bit depth.
5830 * (To do: test this; it's probably OK)
5831 */
5832 P1(" Reduce palette by truncating unused entries\n");
5833 }
5834 P1(" reduce_palette= %d\n",reduce_palette);
5835 P1(" new plte_len = %d\n",plte_len);
5836 }
5837
5838 /* { GRR added for quick %-navigation (1) */
5839
5840 /* Start of chunk-copying/removal code, in order:
5841 * - IHDR
5842 * - bKGD
5843 * - cHRM
5844 * - gAMA
5845 * - sRGB
5846 * - iCCP
5847 * - oFFs
5848 * - pCAL
5849 * - pHYs
5850 * - hIST
5851 * - tRNS
5852 * - PLTE
5853 * - sBIT
5854 * - sCAL
5855 * - sPLT
5856 * - sTER
5857 * - tEXt/zTXt/iTXt
5858 * - tIME
5859 * - unknown chunks
5860 */
5861 {
5862 int compression_method,
5863 filter_method;
5864
5865 P1( "Transferring info struct\n");
5866
5867 if (png_get_IHDR(read_ptr, read_info_ptr, &width, &height,
5868 &bit_depth, &color_type, &interlace_method,
5869 &compression_method, &filter_method))
5870 {
5871 int need_expand = 0;
5872 input_color_type = color_type;
5873 input_bit_depth = bit_depth;
5874
5875 if (output_color_type > 7)
5876 {
5877 output_color_type = input_color_type;
5878 }
5879
5880 /* if (verbose > 1 && last_trial) */
5881 if (verbose > 1 && trial == 0)
5882 {
5883 fprintf(STDERR, " IHDR chunk data:\n");
5884 fprintf(STDERR,
5885 " Width=%lu, height=%lu\n",
5886 (unsigned long)width,
5887 (unsigned long)height);
5888 fprintf(STDERR, " Bit depth =%d\n",
5889 bit_depth);
5890 fprintf(STDERR, " Color type=%d\n",
5891 color_type);
5892 if (output_color_type != color_type)
5893 fprintf(STDERR,
5894 " Output color type=%d\n",
5895 output_color_type);
5896 fprintf(STDERR, " Interlace =%d\n",
5897 interlace_method);
5898 }
5899
5900 output_bit_depth = input_bit_depth;
5901
5902 if ((output_color_type != 3 || output_bit_depth > 8)
5903 && output_bit_depth >= 8
5904 && output_bit_depth > input_bit_depth)
5905 need_expand = 1;
5906
5907 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
5908 if ((color_type == 2 ||
5909 color_type == 6 ||
5910 color_type == 3) &&
5911 (output_color_type == 0 ||
5912 output_color_type == 4))
5913 {
5914 if (verbose > 0 && last_trial)
5915 {
5916 fprintf(STDERR, " Reducing truecolor "
5917 "image to grayscale.\n");
5918 }
5919 #ifdef PNG_FIXED_POINT_SUPPORTED
5920 png_set_rgb_to_gray_fixed(read_ptr, 1,
5921 21260, 71520);
5922 #else
5923 png_set_rgb_to_gray(read_ptr, 1,
5924 0.21260, 0.71520);
5925 #endif
5926 if (output_bit_depth < 8)
5927 output_bit_depth = 8;
5928 if (color_type == 3)
5929 need_expand = 1;
5930 }
5931 #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
5932
5933 if (color_type != 3 && output_color_type == 3)
5934 {
5935 fprintf(STDERR," Cannot change to indexed color "
5936 "(color_type 3)\n");
5937 output_color_type = input_color_type;
5938 }
5939
5940 if ((color_type == 0 || color_type == 4) &&
5941 (output_color_type == 2
5942 || output_color_type == 6))
5943 {
5944 png_set_gray_to_rgb(read_ptr);
5945 }
5946
5947 if ((color_type == 4 || color_type == 6) &&
5948 (output_color_type != 4
5949 && output_color_type != 6))
5950 {
5951 if (verbose > 0 && last_trial)
5952 {
5953 fprintf(STDERR,
5954 " Stripping existing alpha channel.\n");
5955 }
5956 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
5957 png_set_strip_alpha(read_ptr);
5958 #endif
5959 }
5960
5961 if ((output_color_type == 4
5962 || output_color_type == 6) && (color_type != 4
5963 && color_type != 6))
5964 {
5965 if (verbose > 0 && last_trial)
5966 fprintf(STDERR,
5967 " Adding an opaque alpha channel.\n");
5968 #ifdef PNG_READ_FILLER_SUPPORTED
5969 png_set_filler(read_ptr, (png_uint_32) 65535L,
5970 PNG_FILLER_AFTER);
5971 #endif
5972 need_expand = 1;
5973 }
5974
5975 if (output_color_type != 0 && output_color_type != 3 &&
5976 output_bit_depth < 8)
5977 output_bit_depth = 8;
5978
5979 if ((output_color_type == 2
5980 || output_color_type == 6)
5981 && color_type == 3)
5982 {
5983 if (verbose > 0 && last_trial)
5984 fprintf(STDERR,
5985 " Expanding indexed color file.\n");
5986 need_expand = 1;
5987 }
5988 #ifdef PNG_READ_EXPAND_SUPPORTED
5989 if (need_expand == 1)
5990 png_set_expand(read_ptr);
5991 #endif
5992
5993 #ifdef PNG_READ_PACK_SUPPORTED
5994 if (input_bit_depth < 8)
5995 {
5996 png_set_packing(read_ptr);
5997 }
5998
5999 if (output_color_type == 0 && output_bit_depth < 8)
6000 {
6001 png_color_8 true_bits;
6002 true_bits.gray = (png_byte) (output_bit_depth);
6003 png_set_shift(read_ptr, &true_bits);
6004 }
6005 #endif
6006
6007 if (trial > 0)
6008 {
6009 /* To do: have we got the right plte_len now? */
6010 if (plte_len > 0 && output_color_type == 3 &&
6011 force_output_bit_depth == 0)
6012 {
6013 if (plte_len <= 2)
6014 force_output_bit_depth = 1;
6015 else if (plte_len <= 4)
6016 force_output_bit_depth = 2;
6017 else if (plte_len <= 16)
6018 force_output_bit_depth = 4;
6019 else
6020 force_output_bit_depth = 8;
6021 }
6022
6023 if (make_8_bit == 1)
6024 {
6025 #if defined(PNG_READ_SCALE_16_TO_8_SUPPORTED) || \
6026 defined(PNG_READ_STRIP_16_TO_8_SUPPORTED)
6027 output_bit_depth = 8;
6028 force_output_bit_depth = 8;
6029 if (verbose > 0 && last_trial)
6030 fprintf(STDERR,
6031 " Stripping 16-bit depth to 8, trial = %d\n",
6032 trial);
6033
6034 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
6035 png_set_strip_16(read_ptr);
6036 #else
6037 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
6038 png_set_scale_16(read_ptr);
6039 #else
6040 fprintf(STDERR,
6041 " PNG_READ_STRIP_16_TO_8 NOT SUPPORTED\n");
6042 #endif
6043 #endif
6044 #endif
6045 }
6046 P1("force_output_bit_depth=%d\n",force_output_bit_depth);
6047 }
6048
6049
6050 if (last_trial == 1)
6051 {
6052 if (save_apng_chunks == 1 || found_acTL_chunk == 1)
6053 {
6054 if (save_apng_chunks == 0)
6055 {
6056 if (verbose > 0) fprintf(STDERR,
6057 " pngcrush will only save APNG chunks in an\n");
6058 if (verbose > 0) fprintf(STDERR,
6059 " output file with the \".apng\" extension\n");
6060 }
6061 if (input_color_type != output_color_type)
6062 {
6063 if (verbose > 0) fprintf(STDERR,
6064 " Cannot save APNG chunks with a color_type\n");
6065 if (verbose > 0) fprintf(STDERR,
6066 " different from that of the main image.\n");
6067 save_apng_chunks = 2;
6068 }
6069 if (input_bit_depth != output_bit_depth)
6070 {
6071 if (verbose > 0) fprintf(STDERR,
6072 " Cannot save APNG chunks with a bit_depth\n");
6073 if (verbose > 0) fprintf(STDERR,
6074 " different from that of the main image.\n");
6075 save_apng_chunks = 2;
6076 }
6077 if (save_apng_chunks != 1 && found_acTL_chunk == 1)
6078 found_acTL_chunk = 2;
6079 }
6080 }
6081
6082 if (verbose > 1)
6083 fprintf(STDERR, " Setting IHDR\n");
6084
6085 #ifdef PNGCRUSH_LOCO
6086 output_format = 0;
6087 if (do_loco)
6088 {
6089 if (output_color_type == 2
6090 || output_color_type == 6)
6091 {
6092 output_format = 1;
6093 filter_method = 64;
6094 if (nosave == 0 && last_trial == 1)
6095 png_permit_mng_features(write_ptr,
6096 PNG_FLAG_MNG_FILTER_64);
6097
6098 }
6099 } else
6100 filter_method = 0;
6101 #endif
6102
6103 png_set_IHDR(write_ptr, write_info_ptr, width,
6104 height, output_bit_depth,
6105 output_color_type, interlace_method,
6106 compression_method, filter_method);
6107
6108 } /* IHDR */
6109 }
6110
6111 if (premultiply == 1 || premultiply == 2)
6112 {
6113
6114 #ifdef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
6115 /* 0: not premultipled
6116 * 1: premultiplied input (input has .pngp suffix and the
6117 * PNGP chunk is present)
6118 * 2: premultiplied output (output has .pngp suffix and the
6119 * -premultiply option is present; PNGP chunk is added)
6120 * 3: premultiplied input and output (both have .pngp suffix)
6121 */
6122 P1("Calling png_set_premultiply_alpha\n");
6123 png_set_premultiply_alpha(read_ptr,output_bit_depth);
6124 #endif
6125 }
6126
6127
6128 /* Handle ancillary chunks */
6129 if (last_trial == 1)
6130 {
6131 #if defined(PNG_READ_bKGD_SUPPORTED) && defined(PNG_WRITE_bKGD_SUPPORTED)
6132 {
6133 png_color_16p background;
6134 if (!have_bkgd
6135 && png_get_bKGD(read_ptr, read_info_ptr,
6136 &background))
6137 {
6138 if (keep_chunk("bKGD", argv))
6139 {
6140 if ((input_color_type == 2 ||
6141 input_color_type == 6) &&
6142 (output_color_type == 0 ||
6143 output_color_type == 4))
6144 background->gray = background->green;
6145
6146 png_set_bKGD(write_ptr, write_info_ptr,
6147 background);
6148 }
6149 }
6150 if (have_bkgd)
6151 {
6152 /* If we are reducing an RGB image to grayscale, but
6153 * the background color isn't gray, the green channel
6154 * is written. That's not spec-compliant. We should
6155 * really check for a non-gray bKGD and refuse to do
6156 * the reduction if one is present.
6157 */
6158 png_color_16 backgd;
6159 png_color_16p backgrnd = &backgd;
6160 backgrnd->red = bkgd_red;
6161 backgrnd->green = bkgd_green;
6162 backgrnd->blue = bkgd_blue;
6163 backgrnd->gray = backgrnd->green;
6164 backgrnd->index = bkgd_index;
6165 png_set_bKGD(write_ptr, write_info_ptr,
6166 backgrnd);
6167 }
6168 }
6169 #endif /* PNG_READ_bKGD_SUPPORTED && PNG_WRITE_bKGD_SUPPORTED */
6170
6171 #if defined(PNG_READ_cHRM_SUPPORTED) && defined(PNG_WRITE_cHRM_SUPPORTED)
6172 #ifdef PNG_FIXED_POINT_SUPPORTED
6173 {
6174 png_fixed_point white_x, white_y, red_x, red_y,
6175 green_x, green_y, blue_x, blue_y;
6176
6177 if (found_cHRM && png_get_cHRM_fixed
6178 (read_ptr, read_info_ptr, &white_x, &white_y,
6179 &red_x, &red_y, &green_x, &green_y, &blue_x,
6180 &blue_y))
6181 {
6182 if (keep_chunk("cHRM", argv))
6183 {
6184 png_set_cHRM_fixed(write_ptr,
6185 write_info_ptr, white_x,
6186 white_y, red_x, red_y,
6187 green_x, green_y,
6188 blue_x, blue_y);
6189 }
6190 }
6191 }
6192 #else
6193 {
6194 double white_x, white_y, red_x, red_y, green_x,
6195 green_y, blue_x, blue_y;
6196
6197 if (found_cHRM && png_get_cHRM
6198 (read_ptr, read_info_ptr, &white_x, &white_y,
6199 &red_x, &red_y, &green_x, &green_y, &blue_x,
6200 &blue_y)) {
6201 if (keep_chunk("cHRM", argv))
6202 {
6203 png_set_cHRM(write_ptr, write_info_ptr,
6204 white_x, white_y, red_x,
6205 red_y, green_x, green_y,
6206 blue_x, blue_y);
6207 }
6208 }
6209 }
6210 #endif /* PNG_FIXED_POINT_SUPPORTED */
6211 #endif /* PNG_READ_cHRM_SUPPORTED && PNG_WRITE_cHRM_SUPPORTED */
6212
6213 #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_WRITE_gAMA_SUPPORTED)
6214 {
6215 if (force_specified_gamma)
6216 {
6217 if (last_trial)
6218 {
6219 if (verbose > 0)
6220 fprintf(STDERR, " Inserting gAMA chunk with "
6221 #ifdef PNG_FIXED_POINT_SUPPORTED
6222 "gamma=(%d/100000)\n",
6223 #else
6224 "gamma=%f\n",
6225 #endif
6226 force_specified_gamma);
6227 }
6228 #ifdef PNG_FIXED_POINT_SUPPORTED
6229 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6230 (png_fixed_point)
6231 force_specified_gamma);
6232 file_gamma =
6233 (png_fixed_point) force_specified_gamma;
6234 #else
6235 png_set_gAMA(write_ptr, write_info_ptr,
6236 force_specified_gamma);
6237 file_gamma = force_specified_gamma;
6238 #endif
6239 }
6240 #ifdef PNG_FIXED_POINT_SUPPORTED
6241 else if (found_gAMA && png_get_gAMA_fixed
6242 (read_ptr, read_info_ptr, &file_gamma))
6243 #else
6244 else if (found_gAMA && png_get_gAMA
6245 (read_ptr, read_info_ptr, &file_gamma))
6246 #endif
6247 {
6248 if (keep_chunk("gAMA", argv))
6249 {
6250 if (image_specified_gamma)
6251 file_gamma = image_specified_gamma;
6252 if (verbose > 1 && last_trial)
6253 #ifdef PNG_FIXED_POINT_SUPPORTED
6254 fprintf(STDERR, " gamma=(%d/100000)\n",
6255 (int) file_gamma);
6256 if (double_gamma)
6257 file_gamma += file_gamma;
6258 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6259 file_gamma);
6260 #else
6261 fprintf(STDERR, " gamma=%f\n",
6262 file_gamma);
6263 if (double_gamma)
6264 file_gamma += file_gamma;
6265 png_set_gAMA(write_ptr, write_info_ptr,
6266 file_gamma);
6267 #endif
6268 }
6269 }
6270 else if (specified_gamma)
6271 {
6272 if (last_trial)
6273 {
6274 if (verbose > 0)
6275 fprintf(STDERR, " Inserting gAMA chunk with "
6276 #ifdef PNG_FIXED_POINT_SUPPORTED
6277 "gamma=(%d/100000)\n",
6278 #else
6279 "gamma=%f\n",
6280 #endif
6281 specified_gamma);
6282 }
6283 #ifdef PNG_FIXED_POINT_SUPPORTED
6284 png_set_gAMA_fixed(write_ptr, write_info_ptr,
6285 specified_gamma);
6286 file_gamma = (png_fixed_point) specified_gamma;
6287 #else
6288 png_set_gAMA(write_ptr, write_info_ptr,
6289 specified_gamma);
6290 file_gamma = specified_gamma;
6291 #endif
6292 }
6293 }
6294 #endif /* PNG_READ_gAMA_SUPPORTED && PNG_WRITE_gAMA_SUPPORTED */
6295
6296 #if defined(PNG_READ_sRGB_SUPPORTED) && defined(PNG_WRITE_sRGB_SUPPORTED)
6297 {
6298 int file_intent;
6299
6300 if (png_get_sRGB
6301 (read_ptr, read_info_ptr, &file_intent))
6302 {
6303 if (keep_chunk("sRGB", argv))
6304 {
6305 png_set_sRGB(write_ptr, write_info_ptr,
6306 file_intent);
6307 intent = file_intent;
6308 }
6309 }
6310 else if (found_sRGB)
6311 {
6312 #ifdef PNG_gAMA_SUPPORTED
6313 # ifdef PNG_FIXED_POINT_SUPPORTED
6314 if (file_gamma >= 45000L && file_gamma <= 46000L)
6315 # else
6316 if (file_gamma >= 0.45000 && file_gamma <= 0.46000)
6317 # endif
6318 {
6319 if (verbose > 0 && last_trial)
6320 fprintf(STDERR,
6321 " Inserting sRGB chunk with intent=%d\n",
6322 intent);
6323 png_set_sRGB(write_ptr, write_info_ptr,
6324 intent);
6325 }
6326 else if (file_gamma != 0)
6327 {
6328 if (verbose > 0 && last_trial)
6329 {
6330 fprintf(STDERR, " Ignoring sRGB request; "
6331 # ifdef PNG_FIXED_POINT_SUPPORTED
6332 "gamma=(%lu/100000)"
6333 " is not approx. 0.455\n",
6334 (unsigned long)file_gamma);
6335 # else
6336 "gamma=%f"
6337 " is not approx. 0.455\n",
6338 file_gamma);
6339 # endif
6340 }
6341 }
6342 #endif /* PNG_gAMA_SUPPORTED */
6343 }
6344 }
6345 #endif /* PNG_READ_sRGB_SUPPORTED && PNG_WRITE_sRGB_SUPPORTED */
6346
6347 #if defined(PNG_READ_iCCP_SUPPORTED) && defined(PNG_WRITE_iCCP_SUPPORTED)
6348 if (intent < 0) { /* ignore iCCP if sRGB is being written */
6349 png_charp name;
6350 #if PNGCRUSH_LIBPNG_VER < 10500
6351 png_charp profile;
6352 #else
6353 png_bytep profile;
6354 #endif
6355 png_uint_32 proflen;
6356 int compression_method;
6357
6358 if (found_iCCP && png_get_iCCP
6359 (read_ptr, read_info_ptr, &name,
6360 &compression_method, &profile, &proflen))
6361 {
6362 P1("Got iCCP chunk, proflen=%lu\n",
6363 (unsigned long)proflen);
6364 if (iccp_length)
6365 P0("Will not replace existing iCCP chunk.\n");
6366 if (keep_chunk("iCCP", argv))
6367 png_set_iCCP(write_ptr, write_info_ptr,
6368 #if PNGCRUSH_LIBPNG_VER < 10500
6369 name,
6370 #else
6371 (png_const_charp) name,
6372 #endif
6373 compression_method, profile,
6374 proflen);
6375
6376 }
6377 #ifdef PNG_iCCP_SUPPORTED
6378 else if (iccp_length)
6379 {
6380 png_set_iCCP(write_ptr, write_info_ptr, iccp_name,
6381 0,
6382 #if PNGCRUSH_LIBPNG_VER < 10500
6383 iccp_text,
6384 #else
6385 (png_const_bytep) iccp_text,
6386 #endif
6387 iccp_length);
6388 P1("Wrote iCCP chunk, proflen=%d\n", iccp_length);
6389 }
6390 #endif /* PNG_iCCP_SUPPORTED */
6391
6392 }
6393 #endif /* PNG_READ_iCCP_SUPPORTED && PNG_WRITE_iCCP_SUPPORTED */
6394
6395 #if defined(PNG_READ_oFFs_SUPPORTED) && defined(PNG_WRITE_oFFs_SUPPORTED)
6396 {
6397 png_int_32 offset_x, offset_y;
6398 int unit_type;
6399
6400 if (png_get_oFFs
6401 (read_ptr, read_info_ptr, &offset_x, &offset_y,
6402 &unit_type)) {
6403 if (offset_x == 0 && offset_y == 0)
6404 {
6405 if (verbose > 0 && last_trial)
6406 fprintf(STDERR,
6407 " Deleting useless oFFs 0 0 chunk\n");
6408 }
6409 else
6410 {
6411 if (keep_chunk("oFFs", argv))
6412 png_set_oFFs(write_ptr, write_info_ptr,
6413 offset_x, offset_y,
6414 unit_type);
6415 }
6416 }
6417 }
6418 #endif /* PNG_READ_oFFs_SUPPORTED && PNG_WRITE_oFFs_SUPPORTED */
6419
6420 #if defined(PNG_READ_pCAL_SUPPORTED) && defined(PNG_WRITE_pCAL_SUPPORTED)
6421 {
6422 png_charp purpose, units;
6423 png_charpp params;
6424 png_int_32 X0, X1;
6425 int type, nparams;
6426
6427 if (png_get_pCAL
6428 (read_ptr, read_info_ptr, &purpose, &X0, &X1,
6429 &type, &nparams, &units, &params))
6430 {
6431 if (keep_chunk("pCAL", argv))
6432 png_set_pCAL(write_ptr, write_info_ptr,
6433 purpose, X0, X1, type, nparams,
6434 units, params);
6435 }
6436 }
6437 #endif /* pCAL_SUPPORTED */
6438
6439 #if defined(PNG_READ_pHYs_SUPPORTED) && defined(PNG_WRITE_pHYs_SUPPORTED)
6440 {
6441 png_uint_32 res_x, res_y;
6442 int unit_type;
6443
6444 if (resolution == 0)
6445 {
6446 if (png_get_pHYs
6447 (read_ptr, read_info_ptr, &res_x, &res_y,
6448 &unit_type))
6449 {
6450 if (res_x == 0 && res_y == 0)
6451 {
6452 if (verbose > 0 && last_trial)
6453 fprintf(STDERR,
6454 " Deleting useless pHYs 0 0 chunk\n");
6455 }
6456 else
6457 {
6458 if (keep_chunk("pHYs", argv))
6459 png_set_pHYs(write_ptr, write_info_ptr,
6460 res_x, res_y, unit_type);
6461 }
6462 }
6463 } else {
6464 unit_type = 1;
6465 res_x = res_y =
6466 (png_uint_32) ((resolution / .0254 + 0.5));
6467 png_set_pHYs(write_ptr, write_info_ptr, res_x,
6468 res_y, unit_type);
6469 if (verbose > 0 && last_trial)
6470 fprintf(STDERR, " Added pHYs %lu %lu 1 chunk\n",
6471 (unsigned long)res_x,
6472 (unsigned long)res_y);
6473 }
6474 }
6475 #endif
6476
6477 #if defined(PNG_READ_hIST_SUPPORTED) && defined(PNG_WRITE_hIST_SUPPORTED)
6478 {
6479 png_uint_16p hist;
6480
6481 if (png_get_hIST(read_ptr, read_info_ptr, &hist))
6482 {
6483 if (keep_chunk("hIST", argv))
6484 png_set_hIST(write_ptr, write_info_ptr, hist);
6485 }
6486 }
6487 #endif /* hIST_SUPPORTED */
6488
6489 #if defined(PNG_READ_tRNS_SUPPORTED) && defined(PNG_WRITE_tRNS_SUPPORTED)
6490 {
6491 if (png_get_tRNS
6492 (read_ptr, read_info_ptr, &trans, &num_trans,
6493 &trans_values))
6494 {
6495 if (verbose > 1 && last_trial)
6496 fprintf(STDERR,
6497 " Found tRNS chunk in input file.\n");
6498 if (have_trns == 1)
6499 {
6500 P0(" Will not overwrite existing tRNS chunk.\n");
6501 }
6502 if (keep_chunk("tRNS", argv))
6503 {
6504 int last_nonmax = -1;
6505 trns_red = trans_values->red;
6506 trns_green = trans_values->green;
6507 trns_blue = trans_values->blue;
6508 trns_gray = trans_values->gray;
6509 if (output_color_type == 3)
6510 {
6511 for (ia = 0; ia < num_trans; ia++)
6512 trns_array[ia] = trans[ia];
6513 for (; ia < 256; ia++)
6514 trns_array[ia] = 255;
6515 for (ia = 0; ia < 256; ia++)
6516 {
6517 if (trns_array[ia] != 255)
6518 last_nonmax = ia;
6519 }
6520 if (last_trial && verbose > 0)
6521 {
6522 if (last_nonmax < 0)
6523 fprintf(STDERR, " Deleting "
6524 "all-opaque tRNS chunk.\n");
6525 else if (last_nonmax + 1 < num_trans)
6526 fprintf(STDERR,
6527 " Truncating trailing opaque "
6528 "entries from tRNS chunk.\n");
6529 }
6530 num_trans = last_nonmax + 1;
6531 }
6532 else
6533 {
6534 /* color type is 0 or 2 */
6535 if (input_bit_depth == 16 &&
6536 output_bit_depth == 8)
6537 {
6538 /* zero out the high byte */
6539 trans_values->red &= 0x00ff;
6540 trans_values->green &= 0x00ff;
6541 trans_values->blue &= 0x00ff;
6542 trans_values->gray &= 0x00ff;
6543 }
6544
6545 }
6546 if (verbose > 1)
6547 fprintf(STDERR,
6548 " png_set_tRNS, num_trans=%d\n",
6549 num_trans);
6550 if (output_color_type < 3 || num_trans)
6551 png_set_tRNS(write_ptr, write_info_ptr,
6552 trans, num_trans,
6553 trans_values);
6554 }
6555 }
6556 else if (have_trns == 1)
6557 {
6558 /* will not overwrite existing trns data */
6559 png_color_16 trans_data;
6560 png_byte index_data = (png_byte) trns_index;
6561 num_trans = index_data + 1;
6562 if (verbose > 1)
6563 fprintf(STDERR, "Have_tRNS, num_trans=%d\n",
6564 num_trans);
6565 if (output_color_type == 3)
6566 {
6567 trans_values = NULL;
6568 for (ia = 0; ia < num_trans; ia++)
6569 trns_array[ia] = trans_in[ia];
6570 for (; ia < 256; ia++)
6571 trns_array[ia] = 255;
6572 } else {
6573 for (ia = 0; ia < 256; ia++)
6574 trns_array[ia] = 255;
6575 trns_array[index_data] = 0;
6576
6577 trans_data.index = index_data;
6578 trans_data.red = trns_red;
6579 trans_data.green = trns_green;
6580 trans_data.blue = trns_blue;
6581 trans_data.gray = trns_gray;
6582 trans_values = &trans_data;
6583 }
6584
6585 P0(" Adding a tRNS chunk\n");
6586 png_set_tRNS(write_ptr, write_info_ptr, trns_array,
6587 num_trans, trans_values);
6588 }
6589 else
6590 {
6591 for (ia = 0; ia < 256; ia++)
6592 trns_array[ia] = 255;
6593 }
6594 if (verbose > 1 && last_trial)
6595 {
6596 int last = -1;
6597 for (ia = 0; ia < num_palette; ia++)
6598 if (trns_array[ia] != 255)
6599 last = ia;
6600 if (last >= 0) {
6601 fprintf(STDERR, " Transparency:\n");
6602 if (output_color_type == 3)
6603 for (ia = 0; ia < num_palette; ia++)
6604 fprintf(STDERR, " %4d %4d\n", ia,
6605 trns_array[ia]);
6606 else if (output_color_type == 0)
6607 fprintf(STDERR, " %d\n", trns_gray);
6608 else if (output_color_type == 2)
6609 fprintf(STDERR, " %d %d %d\n",
6610 trns_red, trns_green, trns_blue);
6611 }
6612 }
6613 }
6614 #endif /* PNG_READ_tRNS_SUPPORTED && PNG_WRITE_tRNS_SUPPORTED */
6615 } /* End of ancillary chunk handling */
6616
6617 if (png_get_PLTE
6618 (read_ptr, read_info_ptr, &palette, &num_palette))
6619 {
6620 if (plte_len > 0)
6621 num_palette = plte_len;
6622 if (do_pplt)
6623 {
6624 fprintf(STDERR,"PPLT: %s\n", pplt_string);
6625 fprintf(STDERR,"Sorry, PPLT is not implemented yet.\n");
6626 }
6627
6628 if (nosave == 0)
6629 {
6630 if (output_color_type == 3)
6631 png_set_PLTE(write_ptr, write_info_ptr, palette,
6632 num_palette);
6633 else if (keep_chunk("PLTE", argv))
6634 png_set_PLTE(write_ptr, write_info_ptr, palette,
6635 num_palette);
6636
6637 }
6638 if (verbose > 1 && last_trial)
6639 {
6640 png_colorp p = palette;
6641 fprintf(STDERR, " Palette:\n");
6642 fprintf(STDERR,
6643 " I R G B ( color ) A\n");
6644 for (i = 0; i < num_palette; i++)
6645 {
6646 fprintf(STDERR,
6647 " %4d %4d %4d %4d (#%2.2x%2.2x%2.2x) %4d\n",
6648 i, p->red, p->green, p->blue, p->red,
6649 p->green, p->blue, trns_array[i]);
6650 p++;
6651 }
6652 }
6653 }
6654
6655
6656 /* Handle ancillary chunks */
6657 if (last_trial == 1)
6658 {
6659 #if defined(PNG_READ_sBIT_SUPPORTED) && defined(PNG_WRITE_sBIT_SUPPORTED)
6660 {
6661 png_color_8p sig_bit;
6662
6663 /* If we are reducing a truecolor PNG to grayscale, and the
6664 * RGB sBIT values aren't identical, we'll lose sBIT info.
6665 */
6666 if (png_get_sBIT(read_ptr, read_info_ptr, &sig_bit))
6667 {
6668 if (keep_chunk("sBIT", argv))
6669 {
6670 if ((input_color_type == 0
6671 || input_color_type == 4)
6672 && (output_color_type == 2
6673 || output_color_type == 6
6674 || output_color_type == 3))
6675 sig_bit->red = sig_bit->green =
6676 sig_bit->blue = sig_bit->gray;
6677 if ((input_color_type == 2
6678 || input_color_type == 6
6679 || output_color_type == 3)
6680 && (output_color_type == 0
6681 || output_color_type == 4))
6682 sig_bit->gray = sig_bit->green;
6683
6684 if ((input_color_type == 0
6685 || input_color_type == 2)
6686 && (output_color_type == 4
6687 || output_color_type == 6))
6688 sig_bit->alpha = 1;
6689
6690 if (nosave == 0)
6691 png_set_sBIT(write_ptr, write_info_ptr,
6692 sig_bit);
6693 }
6694 }
6695 }
6696 #endif /* PNG_READ_sBIT_SUPPORTED)&& PNG_WRITE_sBIT_SUPPORTED */
6697
6698 #ifdef PNG_sCAL_SUPPORTED
6699 # ifdef PNG_FLOATING_POINT_SUPPORTED
6700 {
6701 int unit;
6702 double scal_width, scal_height;
6703
6704 if (png_get_sCAL
6705 (read_ptr, read_info_ptr, &unit, &scal_width,
6706 &scal_height))
6707 {
6708 png_set_sCAL(write_ptr, write_info_ptr, unit,
6709 scal_width, scal_height);
6710 }
6711 }
6712 # else
6713 # ifdef PNG_FIXED_POINT_SUPPORTED
6714 {
6715 int unit;
6716 png_charp scal_width, scal_height;
6717
6718 if (png_get_sCAL_s
6719 (read_ptr, read_info_ptr, &unit, &scal_width,
6720 &scal_height))
6721 {
6722 if (keep_chunk("sCAL", argv))
6723 png_set_sCAL_s(write_ptr, write_info_ptr, unit,
6724 scal_width, scal_height);
6725 }
6726 }
6727 # endif
6728 # endif /* PNG_FLOATING_POINT_SUPPORTED */
6729 #endif /* PNG_sCAL_SUPPORTED */
6730
6731 #ifdef PNG_sPLT_SUPPORTED
6732 {
6733 png_sPLT_tp entries;
6734 int num_entries;
6735
6736 num_entries =
6737 (int) png_get_sPLT(read_ptr, read_info_ptr,
6738 &entries);
6739 if (num_entries)
6740 {
6741 if (keep_chunk("sPLT", argv))
6742 png_set_sPLT(write_ptr, write_info_ptr,
6743 entries, num_entries);
6744 }
6745 }
6746 #endif
6747
6748 #ifdef PNG_TEXT_SUPPORTED
6749 {
6750 png_textp text_ptr;
6751 int num_text = 0;
6752
6753 if (png_get_text
6754 (read_ptr, read_info_ptr, &text_ptr, &num_text) > 0
6755 || text_inputs)
6756 {
6757 int ntext;
6758 P1( "Handling %d tEXt/zTXt chunks before IDAT\n",
6759 num_text);
6760
6761 if (verbose > 1 && last_trial && num_text > 0)
6762 {
6763 for (ntext = 0; ntext < num_text; ntext++)
6764 {
6765 fprintf(STDERR, "%d %s", ntext,
6766 text_ptr[ntext].key);
6767 if (text_ptr[ntext].text_length)
6768 fprintf(STDERR, ": %s\n",
6769 text_ptr[ntext].text);
6770 #ifdef PNG_iTXt_SUPPORTED
6771 else if (text_ptr[ntext].itxt_length)
6772 {
6773 fprintf(STDERR, " (%s: %s): \n",
6774 text_ptr[ntext].lang,
6775 text_ptr[ntext].lang_key);
6776 fprintf(STDERR, "%s\n",
6777 text_ptr[ntext].text);
6778 }
6779 #endif
6780 else
6781 fprintf(STDERR, "\n");
6782 }
6783 }
6784
6785 if (num_text > 0)
6786 {
6787 if (keep_chunk("text", argv))
6788 {
6789 int num_to_write = num_text;
6790 for (ntext = 0; ntext < num_text; ntext++)
6791 {
6792 if (last_trial)
6793 P2("Text chunk before IDAT, "
6794 "compression=%d\n",
6795 text_ptr[ntext].compression);
6796 if (text_ptr[ntext].compression ==
6797 PNG_TEXT_COMPRESSION_NONE) {
6798 if (!keep_chunk("tEXt", argv))
6799 {
6800 text_ptr[ntext].key[0] = '\0';
6801 num_to_write--;
6802 }
6803 }
6804 if (text_ptr[ntext].compression ==
6805 PNG_TEXT_COMPRESSION_zTXt)
6806 {
6807 if (!keep_chunk("zTXt", argv))
6808 {
6809 text_ptr[ntext].key[0] = '\0';
6810 num_to_write--;
6811 }
6812 }
6813 #ifdef PNG_iTXt_SUPPORTED
6814 if (text_ptr[ntext].compression ==
6815 PNG_ITXT_COMPRESSION_NONE
6816 || text_ptr[ntext].compression ==
6817 PNG_ITXT_COMPRESSION_zTXt)
6818 {
6819 if (!keep_chunk("iTXt", argv))
6820 {
6821 text_ptr[ntext].key[0] = '\0';
6822 num_to_write--;
6823 }
6824 }
6825 #endif
6826 }
6827 if (num_to_write > 0)
6828 png_set_text(write_ptr, write_info_ptr,
6829 text_ptr, num_text);
6830 }
6831 }
6832 for (ntext = 0; ntext < text_inputs; ntext++)
6833 {
6834 if (text_where[ntext] == 1)
6835 {
6836 png_textp added_text;
6837 added_text = (png_textp) png_malloc(write_ptr,
6838 (png_uint_32) sizeof(png_text));
6839 added_text[0].key = &text_keyword[ntext * 80];
6840 #ifdef PNG_iTXt_SUPPORTED
6841 added_text[0].lang = &text_lang[ntext * 80];
6842 added_text[0].lang_key =
6843 &text_lang_key[ntext * 80];
6844 #endif
6845 added_text[0].text =
6846 &text_text[ntext * STR_BUF_SIZE];
6847 added_text[0].compression =
6848 text_compression[ntext];
6849 png_set_text(write_ptr, write_info_ptr,
6850 added_text, 1);
6851 if (verbose > 0 && last_trial)
6852 {
6853 if (added_text[0].compression < 0)
6854 fprintf(STDERR,
6855 " Added a tEXt chunk.\n");
6856 else if (added_text[0].compression == 0)
6857 fprintf(STDERR,
6858 " Added a zTXt chunk.\n");
6859 #ifdef PNG_iTXt_SUPPORTED
6860 else
6861 fprintf(STDERR,
6862 " Added a%scompressed iTXt chunk"
6863 ".\n", (added_text[0].compression == 1)?
6864 "n un" : " ");
6865 #endif
6866 }
6867 png_free(write_ptr, added_text);
6868 added_text = (png_textp) NULL;
6869 }
6870 }
6871 }
6872 }
6873 #endif /* defined(PNG_TEXT_SUPPORTED) */
6874
6875 #if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
6876 {
6877 png_timep mod_time;
6878
6879 if (png_get_tIME(read_ptr, read_info_ptr, &mod_time))
6880 {
6881 if (keep_chunk("tIME", argv))
6882 png_set_tIME(write_ptr, write_info_ptr, mod_time);
6883 }
6884 }
6885 #endif
6886
6887 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
6888 /* This section handles pCAL and tIME (at least, in default
6889 * build), gIFx/gIFg/gIFt, private Fireworks chunks, etc. */
6890 {
6891 png_unknown_chunkp unknowns; /* allocated by libpng */
6892 int num_unknowns;
6893
6894 num_unknowns = (int)png_get_unknown_chunks(read_ptr,
6895 read_info_ptr, &unknowns);
6896
6897 if (nosave == 0 && ster_mode >= 0)
6898 {
6899 /* Add sTER chunk */
6900 png_unknown_chunkp ster;
6901 P1("Handling sTER as unknown chunk %d\n", num_unknowns);
6902 ster = (png_unknown_chunk*)png_malloc(read_ptr,
6903 (png_uint_32) sizeof(png_unknown_chunk));
6904 png_memcpy((char *)ster[0].name, "sTER",5);
6905 ster[0].size = 1;
6906 ster[0].data = (png_byte*)png_malloc(read_ptr, 1);
6907 ster[0].data[0] = (png_byte)ster_mode;
6908 png_set_unknown_chunks(read_ptr, read_info_ptr,
6909 ster, 1);
6910 png_free(read_ptr,ster[0].data);
6911 png_free(read_ptr,ster);
6912 num_unknowns++;
6913 }
6914
6915 #ifndef PNG_HAVE_IHDR
6916 #define PNG_HAVE_IHDR 0x01
6917 #endif
6918 if (ster_mode >= 0)
6919 png_set_unknown_chunk_location(read_ptr, read_info_ptr,
6920 num_unknowns - 1, (int)PNG_HAVE_IHDR);
6921
6922 P1("Found %d unknown chunks\n", num_unknowns);
6923
6924 if (nosave == 0 && num_unknowns)
6925 {
6926 png_unknown_chunkp unknowns_keep; /* allocated by us */
6927 int num_unknowns_keep;
6928
6929 unknowns_keep = (png_unknown_chunk*)png_malloc(
6930 write_ptr, (png_uint_32) num_unknowns
6931 *sizeof(png_unknown_chunk));
6932
6933 P1("malloc for %d unknown chunks\n", num_unknowns);
6934 num_unknowns_keep = 0;
6935
6936 /* make an array of only those chunks we want to keep */
6937 for (i = 0; i < num_unknowns; i++)
6938 {
6939 P1("Handling unknown chunk %d %s\n", i,
6940 (char *)unknowns[i].name);
6941 /* not EBCDIC-safe, but neither is keep_chunks(): */
6942 P2(" unknown[%d] = %s (%lu bytes, location %d)\n",
6943 i, unknowns[i].name,
6944 (unsigned long)unknowns[i].size,
6945 unknowns[i].location);
6946 if (keep_chunk((char *)unknowns[i].name, argv))
6947 {
6948 png_memcpy(&unknowns_keep[num_unknowns_keep],
6949 &unknowns[i], sizeof(png_unknown_chunk));
6950 ++num_unknowns_keep;
6951 }
6952 }
6953
6954 P1("Keeping %d unknown chunks\n", num_unknowns_keep);
6955 png_set_unknown_chunks(write_ptr, write_info_ptr,
6956 unknowns_keep, num_unknowns_keep);
6957
6958 /* relevant location bits:
6959 * (1) !PNG_HAVE_PLTE && !PNG_HAVE_IDAT (before PLTE)
6960 * (2) PNG_HAVE_PLTE && !PNG_HAVE_IDAT (between)
6961 * (3) PNG_AFTER_IDAT (after IDAT)
6962 * PNG_HAVE_PLTE = 0x02
6963 * PNG_HAVE_IDAT = 0x04
6964 * PNG_AFTER_IDAT = 0x08
6965 */
6966 for (i = 0; i < num_unknowns_keep; i++)
6967 {
6968 png_set_unknown_chunk_location(write_ptr,
6969 write_info_ptr, i,
6970 (int)unknowns_keep[i].location);
6971 }
6972
6973 /* png_set_unknown_chunks() makes own copy, so nuke
6974 * ours */
6975 png_free(write_ptr, unknowns_keep);
6976 }
6977 }
6978 P1( "Finished handling ancillary chunks after IDAT\n");
6979 #endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
6980 } /* End of ancillary chunk handling */
6981
6982 /* } GRR added for quick %-navigation (1) */
6983
6984 /*
6985 * Would be useful to have a libpng fix, that either exports
6986 * png_read_transform_info() or provides a generic API that
6987 * can set any png_ptr->flag, or, simpler, provides an API
6988 * to set the PNG_FLAG_ROW_INIT flag.
6989 *
6990 * Starting in libpng-1.5.6beta06, png_read_update_info()
6991 * does not check the PNG_FLAG_ROW_INIT flag and does not
6992 * initialize the row or issue a warning.
6993 *
6994 */
6995 #ifdef PNGCRUSH_H
6996 png_read_transform_info(read_ptr, read_info_ptr);
6997 #else
6998 /* Some pngcrush capabilities are lacking when the system
6999 * libpng is used instead of the one bundled with pngcrush
7000 *
7001 * To do: list those capabilities here
7002 */
7003
7004 /* pngcrush fails to read interlaced PNGs properly
7005 * when png_read_update_info() is called here.
7006 */
7007
7008 /* png_read_update_info(read_ptr, read_info_ptr); */
7009
7010 /* Workaround is to multiply rowbytes by 8/bit_depth
7011 * to allow for unpacking, wherever we allocate a
7012 * row buffer. This results in too large a value for
7013 * rowbytes under some conditions, e.g., when increasing
7014 * a sub-8-bit file to RGBA, but this is rare and harmless.
7015 */
7016 #endif
7017
7018 /* This is the default case (nosave == 1 -> perf-testing
7019 only) */
7020 if (nosave == 0)
7021 {
7022 if (filter_type == 0)
7023 png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
7024 else if (filter_type == 1)
7025 png_set_filter(write_ptr, 0, PNG_FILTER_SUB);
7026 else if (filter_type == 2)
7027 png_set_filter(write_ptr, 0, PNG_FILTER_UP);
7028 else if (filter_type == 3)
7029 png_set_filter(write_ptr, 0, PNG_FILTER_AVG);
7030 else if (filter_type == 4)
7031 png_set_filter(write_ptr, 0, PNG_FILTER_PAETH);
7032 else if (filter_type == 5)
7033 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
7034 else if (filter_type == 6) /* speedy */
7035 png_set_filter(write_ptr, 0, PNG_FILTER_NONE |
7036 PNG_FILTER_SUB | PNG_FILTER_UP);
7037 else
7038 png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
7039
7040 #ifdef PNGCRUSH_LOCO
7041 if (do_loco) {
7042 png_byte buff[30];
7043 const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
7044 png_byte mng_signature[8] =
7045 { 138, 77, 78, 71, 13, 10, 26, 10 };
7046 /* write the MNG 8-byte signature */
7047 if (outname[strlen(outname) - 3] == 'p')
7048 pngcrush_warning(read_ptr,
7049 " Writing a MNG file with a .png extension");
7050 pngcrush_write_png(write_ptr, &mng_signature[0],
7051 (png_size_t) 8);
7052 png_set_sig_bytes(write_ptr, 8);
7053
7054 /* Write a MHDR chunk */
7055
7056 buff[0] = (png_byte) ((width >> 24) & 0xff);
7057 buff[1] = (png_byte) ((width >> 16) & 0xff);
7058 buff[2] = (png_byte) ((width >> 8) & 0xff);
7059 buff[3] = (png_byte) ((width) & 0xff);
7060 buff[4] = (png_byte) ((height >> 24) & 0xff);
7061 buff[5] = (png_byte) ((height >> 16) & 0xff);
7062 buff[6] = (png_byte) ((height >> 8) & 0xff);
7063 buff[7] = (png_byte) ((height) & 0xff);
7064 for (i = 8; i < 27; i++)
7065 buff[i] = 0x00;
7066 buff[15] = 2; /* layer count */
7067 buff[19] = 1; /* frame count */
7068 if (output_color_type == 6)
7069 buff[27] = 0x09; /* profile: MNG-VLC with trans. */
7070 else
7071 buff[27] = 0x01; /* profile: MNG-VLC */
7072 png_write_chunk(write_ptr, (png_bytep) png_MHDR,
7073 buff, (png_size_t) 28);
7074 }
7075 #endif /* PNGCRUSH_LOCO */
7076
7077 pngcrush_pause();
7078
7079 if (found_CgBI)
7080 {
7081 pngcrush_warning(read_ptr,
7082 "Cannot read Xcode CgBI PNG");
7083 }
7084 P1( "\nWriting info struct\n");
7085
7086 if (copy_idat == 0)
7087 {
7088
7089 #if 0 /* doesn't work; compression level has to be the same as in IDAT */
7090 /* if zTXt other compressed chunk */
7091 png_set_compression_level(write_ptr, 9);
7092 png_set_compression_window_bits(write_ptr, 15);
7093 #endif /* 0 */
7094
7095 pngcrush_pause();
7096 {
7097 png_uint_32 zbuf_size;
7098 png_uint_32 required_window;
7099 int channels = 0;
7100 png_set_compression_strategy(write_ptr,
7101 z_strategy);
7102 png_set_compression_mem_level(write_ptr,
7103 compression_mem_level);
7104
7105 if (output_color_type == 0)
7106 channels = 1;
7107 if (output_color_type == 2)
7108 channels = 3;
7109 if (output_color_type == 3)
7110 channels = 1;
7111 if (output_color_type == 4)
7112 channels = 2;
7113 if (output_color_type == 6)
7114 channels = 4;
7115
7116 /* This method was copied from libpng to find maximum
7117 * data size. Only return sizes up to the maximum of
7118 * a png_uint_32, by limiting the width and height used
7119 * to 15 bits.
7120 */
7121 png_uint_32 rowbytes;
7122 png_uint_32 h = height;
7123
7124 /* FIX THIS, does not work with libpng-1.7.0
7125 * because info_ptr->bit_depth has not been
7126 * updated yet.
7127 */
7128 rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
7129 #ifndef PNGCRUSH_H
7130 /* We must do this because we could not call
7131 * png_read_update_info().
7132 */
7133 if (input_bit_depth < 8)
7134 rowbytes *= 8/input_bit_depth;
7135 #endif
7136 if (rowbytes < 16384 && h < 16384)
7137 {
7138 if (rowbytes * h < 16384)
7139 {
7140 if (interlace_method)
7141 {
7142 /* Interlacing makes the uncompressed data
7143 * larger because of the replication of both
7144 * the filter byte and the padding to a byte
7145 * boundary.
7146 */
7147 png_uint_32 w = width;
7148 unsigned int pd = channels * output_bit_depth;
7149 #if (PNGCRUSH_LIBPNG_VER < 10400)
7150 png_size_t cb_base;
7151 #else
7152 png_alloc_size_t cb_base;
7153 #endif
7154 int interlace_pass;
7155
7156 for (cb_base=0, interlace_pass=0;
7157 interlace_pass<=6; ++interlace_pass)
7158 {
7159 png_uint_32 pw = PNG_PASS_COLS(w,
7160 interlace_pass);
7161
7162 if (pw > 0)
7163 cb_base += (PNGCRUSH_ROWBYTES(pd, pw)+1) *
7164 PNG_PASS_ROWS(h, interlace_pass);
7165 }
7166
7167 max_bytes = cb_base;
7168 }
7169
7170 else
7171 max_bytes = (rowbytes+1) * h;
7172 }
7173 else
7174 max_bytes = 0x3fffffffU;
7175 }
7176
7177 else
7178 max_bytes = 0x3fffffffU;
7179
7180 required_window = (png_uint_32) (max_bytes + 262);
7181
7182 zbuf_size =
7183 png_get_compression_buffer_size(write_ptr);
7184
7185 /* reinitialize zbuf - compression buffer */
7186 if (zbuf_size != max_idat_size)
7187 {
7188 png_uint_32 max_possible_size =
7189 required_window;
7190 if (max_possible_size > max_idat_size)
7191 max_possible_size = max_idat_size;
7192 P2("reinitializing write zbuf to %lu.\n",
7193 (unsigned long)max_possible_size);
7194 png_set_compression_buffer_size(write_ptr,
7195 max_possible_size);
7196 }
7197
7198 if (required_window <= 512)
7199 compression_window = 9;
7200 else if (required_window <= 1024)
7201 compression_window = 10;
7202 else if (required_window <= 2048)
7203 compression_window = 11;
7204 else if (required_window <= 4096)
7205 compression_window = 12;
7206 else if (required_window <= 8192)
7207 compression_window = 13;
7208 else if (required_window <= 16384)
7209 compression_window = 14;
7210 else
7211 compression_window = 15;
7212 if (compression_window > default_compression_window
7213 || force_compression_window)
7214 compression_window =
7215 default_compression_window;
7216
7217 if (verbose > 1 && last_trial
7218 && (compression_window != 15
7219 || force_compression_window))
7220 fprintf(STDERR,
7221 " Compression window for output= %d\n",
7222 1 << compression_window);
7223
7224 png_set_compression_window_bits(write_ptr,
7225 compression_window);
7226 }
7227
7228 png_set_compression_level(write_ptr, zlib_level);
7229 } /* copy_idat */
7230
7231 png_write_info(write_ptr, write_info_ptr);
7232 P1( "\nWrote info struct\n");
7233
7234 if (copy_idat == 1)
7235 {
7236 /* No recompress, just copy IDATs. */
7237 png_set_compression_buffer_size(write_ptr,
7238 MAX_IDAT_SIZE);
7239 }
7240
7241 #ifdef PNG_WRITE_PACK_SUPPORTED
7242 if (output_bit_depth < 8)
7243 {
7244 if (output_color_type == 0)
7245 {
7246 png_color_8 true_bits;
7247 true_bits.gray = (png_byte) (output_bit_depth);
7248 png_set_shift(write_ptr, &true_bits);
7249 }
7250 png_set_packing(write_ptr);
7251 }
7252 #endif
7253 } /* no save */
7254
7255 #ifdef PNGCRUSH_MULTIPLE_ROWS
7256 rows_at_a_time = max_rows_at_a_time;
7257 if (rows_at_a_time == 0 || rows_at_a_time < height)
7258 rows_at_a_time = height;
7259 #endif
7260
7261 #ifndef PNGCRUSH_LARGE
7262 {
7263 png_uint_32 rowbytes_s;
7264 png_uint_32 rowbytes;
7265
7266 rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
7267 #ifndef PNGCRUSH_H
7268 if (input_bit_depth < 8)
7269 rowbytes *= 8/input_bit_depth;
7270 #endif
7271
7272 P2("rowbytes = %lud\n",rowbytes;
7273
7274 rowbytes_s = (png_size_t) rowbytes;
7275 if (rowbytes == (png_uint_32) rowbytes_s)
7276 # ifdef PNGCRUSH_MULTIPLE_ROWS
7277 row_buf =
7278 png_malloc(read_ptr,
7279 rows_at_a_time * rowbytes + 64);
7280 # else
7281 row_buf = png_malloc(read_ptr, rowbytes + 64);
7282 # endif
7283 else
7284 row_buf = NULL;
7285 }
7286 #else /* PNGCRUSH_LARGE */
7287 {
7288 png_uint_32 read_row_length, write_row_length;
7289 read_row_length =
7290 (png_uint_32) (png_get_rowbytes
7291 (read_ptr, read_info_ptr));
7292 write_row_length =
7293 (png_uint_32) (png_get_rowbytes
7294 (write_ptr, write_info_ptr));
7295 row_length =
7296 read_row_length >
7297 write_row_length ? read_row_length :
7298 write_row_length;
7299 #ifndef PNGCRUSH_H
7300 /* We must do this because we could not call
7301 * png_read_update_info().
7302 */
7303 if (input_bit_depth < 8)
7304 row_length *= 8/input_bit_depth;
7305 #endif
7306 # ifdef PNGCRUSH_MULTIPLE_ROWS
7307 row_buf =
7308 (png_bytep) png_malloc(read_ptr,
7309 rows_at_a_time *
7310 row_length + 64);
7311 # else
7312 row_buf =
7313 (png_bytep) png_malloc(read_ptr, row_length + 64);
7314 # endif
7315 }
7316 #endif /* PNGCRUSH_LARGE */
7317
7318 P2(" row_buf = %p\n",row_buf);
7319
7320 if (row_buf == NULL)
7321 png_error(read_ptr,
7322 "Insufficient memory to allocate row buffer");
7323
7324 {
7325 /* Check for sufficient memory: we need 2*zlib_window and,
7326 * if filter_type == 5, 4*rowbytes in separate allocations.
7327 * If it's not enough we can drop the "average" filter and
7328 * we can reduce the zlib_window for writing. We can't
7329 * change the input zlib_window because the input file
7330 * might have used the full 32K sliding window. (To do)
7331 */
7332 }
7333
7334 P2("allocated rowbuf.\n");
7335
7336 #ifdef PNGCRUSH_MULTIPLE_ROWS
7337 row_pointers = (png_bytepp) png_malloc(read_ptr,
7338 rows_at_a_time *
7339 sizeof(png_bytepp));
7340 P2("allocated row_pointers.\n");
7341
7342 for (i = 0; i < rows_at_a_time; i++)
7343 row_pointers[i] = row_buf + i * row_length;
7344 #endif
7345
7346 pngcrush_pause();
7347
7348 num_pass = png_set_interlace_handling(read_ptr);
7349 if (nosave == 0)
7350 png_set_interlace_handling(write_ptr);
7351
7352 /* START_STOP */
7353
7354 for (pass = 0; pass < num_pass; pass++)
7355 {
7356 #ifdef PNGCRUSH_MULTIPLE_ROWS
7357 png_uint_32 num_rows;
7358 #endif
7359 P1( "\nBegin interlace pass %d\n", pass);
7360 #ifdef PNGCRUSH_MULTIPLE_ROWS
7361 num_rows = rows_at_a_time;
7362 for (y = 0; y < height; y += rows_at_a_time)
7363 #else
7364 for (y = 0; y < height; y++)
7365 #endif
7366 {
7367 #if PNGCRUSH_TIMERS > 0
7368 if (verbose >= 0)
7369 {
7370 pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
7371 pngcrush_timer_start(PNGCRUSH_TIMER_DECODE);
7372 }
7373 #endif
7374 #ifdef PNGCRUSH_MULTIPLE_ROWS
7375 if (y + num_rows > height)
7376 num_rows = height - y;
7377 # ifdef BLOCKY_DEINTERLACE
7378 png_read_rows(read_ptr, (png_bytepp) NULL,
7379 row_pointers, num_rows);
7380 # else /* SPARKLE */
7381 png_read_rows(read_ptr, row_pointers,
7382 (png_bytepp) NULL, num_rows);
7383 # endif
7384 #else
7385 # ifdef BLOCKY_DEINTERLACE
7386 png_read_row(read_ptr, row_buf, (png_bytep) NULL);
7387 # else /* SPARKLE */
7388 png_read_row(read_ptr, (png_bytep) NULL, row_buf);
7389 # endif
7390 #endif
7391 if (nosave == 0)
7392 {
7393 #if PNGCRUSH_TIMERS > 0
7394 if (verbose >= 0)
7395 {
7396 pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
7397 pngcrush_timer_start(PNGCRUSH_TIMER_ENCODE);
7398 }
7399 #endif
7400 #ifdef PNGCRUSH_MULTIPLE_ROWS
7401 /* To do: zero the padding bits */
7402 png_write_rows(write_ptr, row_pointers,
7403 num_rows);
7404 #else
7405 /* To do: zero the padding bits */
7406 png_write_row(write_ptr, row_buf);
7407 #endif
7408 }
7409 #if PNGCRUSH_TIMERS > 0
7410 if (verbose >= 0)
7411 {
7412 if (nosave == 0)
7413 pngcrush_timer_stop(PNGCRUSH_TIMER_ENCODE);
7414 else
7415 pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
7416 pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
7417 }
7418 #endif
7419 /* Bail if byte count exceeds best so far */
7420 if (bail == 0 && trial != last_method &&
7421 pngcrush_write_byte_count >
7422 pngcrush_best_byte_count)
7423 {
7424 png_write_flush(write_ptr);
7425 break;
7426 }
7427 }
7428 P2( "End interlace pass %d\n\n", pass);
7429 if (bail == 0 && trial != last_method &&
7430 pngcrush_write_byte_count >
7431 pngcrush_best_byte_count)
7432 break;
7433 }
7434
7435 if (color_type == 3)
7436 {
7437 if (trial == 0 && reduce_palette == 1)
7438 {
7439 int palette_length;
7440
7441 palette_length = plte_len;
7442 P1("Measured palette length = %d\n", palette_length);
7443
7444 #ifdef PNG_READ_bKGD_SUPPORTED
7445 {
7446 png_color_16p bkgd;
7447 if (png_get_bKGD(read_ptr, read_info_ptr, &bkgd))
7448 {
7449 bkgd_index = bkgd->index;
7450 P1("bKGD index = %d\n", bkgd_index);
7451 #if 1
7452 if (bkgd_index > palette_length)
7453 {
7454 bkgd_index = palette_length;
7455 have_bkgd = 1;
7456 fprintf(STDERR,
7457 " New bKGD index = %d\n", bkgd_index);
7458 }
7459 #endif
7460 if (bkgd->index >= palette_length)
7461 palette_length = (int) bkgd_index+1;
7462 P1("Total palette length = %d\n", palette_length);
7463 }
7464 }
7465 #endif
7466 plte_len = palette_length;
7467 if (num_trans > plte_len)
7468 {
7469 num_trans = plte_len;
7470 png_set_tRNS(write_ptr, write_info_ptr, trns_array,
7471 num_trans, trans_values);
7472 }
7473 }
7474 }
7475
7476 #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) && \
7477 defined(PNG_FLOATING_POINT_SUPPORTED)
7478 if ((color_type == 2 || color_type == 6 || color_type == 3)
7479 && (output_color_type == 0 || output_color_type == 4))
7480 {
7481 png_byte rgb_error =
7482 png_get_rgb_to_gray_status(read_ptr);
7483 if (last_trial && verbose > 0 && rgb_error)
7484 fprintf(STDERR,
7485 " **** Converted non-gray image to gray. **** \n");
7486 }
7487 #endif
7488
7489 #ifdef PNG_FREE_UNKN
7490 # if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
7491 png_free_data(read_ptr, read_info_ptr, PNG_FREE_UNKN, -1);
7492 # endif
7493 # if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
7494 png_free_data(write_ptr, write_info_ptr, PNG_FREE_UNKN, -1);
7495 # endif
7496 #else
7497 # if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
7498 png_free_unknown_chunks(read_ptr, read_info_ptr, -1);
7499 # endif
7500 # if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
7501 png_free_unknown_chunks(write_ptr, write_info_ptr, -1);
7502 # endif
7503 #endif /* PNG_FREE_UNKN */
7504
7505 /* { GRR: added for %-navigation (2) */
7506 if (!(bail == 0 && trial != last_method &&
7507 pngcrush_write_byte_count >
7508 pngcrush_best_byte_count))
7509 {
7510 P1(" Reading and writing end_info data\n");
7511 png_read_end(read_ptr, end_info_ptr);
7512
7513 /* Handle ancillary chunks */
7514 if (last_trial == 1)
7515 {
7516 #if (defined(PNG_READ_tEXt_SUPPORTED) && defined(PNG_WRITE_tEXt_SUPPORTED)) \
7517 || (defined(PNG_READ_iTXt_SUPPORTED) && defined(PNG_WRITE_iTXt_SUPPORTED)) \
7518 || (defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED))
7519
7520 P1( "Check for iTXt/tEXt/zTXt chunks after IDAT\n");
7521 {
7522 png_textp text_ptr;
7523 int num_text = 0;
7524
7525 if (png_get_text (read_ptr,
7526 end_info_ptr, &text_ptr, &num_text) > 0
7527 || text_inputs)
7528 {
7529 int ntext;
7530
7531 #ifdef PNG_iTXt_SUPPORTED
7532 P1( "Handling %d tEXt/zTXt/iTXt chunks after IDAT\n",
7533 #else
7534 P1( "Handling %d tEXt/zTXt chunks after IDAT\n",
7535 #endif
7536 num_text);
7537
7538 if (verbose > 1 && last_trial && num_text > 0)
7539 {
7540 for (ntext = 0; ntext < num_text; ntext++)
7541 {
7542 fprintf(STDERR, "%d %s", ntext,
7543 text_ptr[ntext].key);
7544 if (text_ptr[ntext].text_length)
7545 fprintf(STDERR, ": %s\n",
7546 text_ptr[ntext].text);
7547 #ifdef PNG_iTXt_SUPPORTED
7548 else if (text_ptr[ntext].itxt_length)
7549 {
7550 fprintf(STDERR, " (%s: %s): \n",
7551 text_ptr[ntext].lang,
7552 text_ptr[ntext].lang_key);
7553 fprintf(STDERR, "%s\n",
7554 text_ptr[ntext].text);
7555 }
7556 #endif
7557 else
7558 fprintf(STDERR, "\n");
7559 }
7560 }
7561
7562 if (last_trial)
7563 {
7564 if (num_text > 0)
7565 {
7566 if (keep_chunk("text", argv))
7567 {
7568 int num_to_write = num_text;
7569 for (ntext = 0; ntext < num_text; ntext++)
7570 {
7571 if (verbose > 1)
7572 P2("Text chunk after IDAT, "
7573 "compression=%d\n",
7574 text_ptr[ntext].compression);
7575 if (text_ptr[ntext].compression ==
7576 PNG_TEXT_COMPRESSION_NONE)
7577 {
7578 if (!keep_chunk("tEXt", argv))
7579 {
7580 text_ptr[ntext].key[0] = '\0';
7581 num_to_write--;
7582 }
7583 }
7584 if (text_ptr[ntext].compression ==
7585 PNG_TEXT_COMPRESSION_zTXt)
7586 {
7587 if (!keep_chunk("zTXt", argv))
7588 {
7589 text_ptr[ntext].key[0] = '\0';
7590 num_to_write--;
7591 }
7592 }
7593 #ifdef PNG_iTXt_SUPPORTED
7594 if (text_ptr[ntext].compression ==
7595 PNG_ITXT_COMPRESSION_NONE
7596 || text_ptr[ntext].compression ==
7597 PNG_ITXT_COMPRESSION_zTXt)
7598 {
7599 if (!keep_chunk("iTXt", argv))
7600 {
7601 text_ptr[ntext].key[0] = '\0';
7602 num_to_write--;
7603 }
7604 }
7605 #endif
7606 }
7607 if (num_to_write > 0)
7608 png_set_text(write_ptr,
7609 write_end_info_ptr,
7610 text_ptr, num_text);
7611 }
7612 }
7613
7614 P1( "text_inputs=%d\n",text_inputs);
7615 for (ntext = 0; ntext < text_inputs; ntext++)
7616 {
7617 P1( " ntext=%d\n",ntext);
7618 if (text_where[ntext] == 2)
7619 {
7620 png_textp added_text;
7621 added_text = (png_textp)
7622 png_malloc(write_ptr,
7623 (png_uint_32)
7624 sizeof(png_text));
7625 added_text[0].key =
7626 &text_keyword[ntext * 80];
7627 #ifdef PNG_iTXt_SUPPORTED
7628 added_text[0].lang =
7629 &text_lang[ntext * 80];
7630 added_text[0].lang_key =
7631 &text_lang_key[ntext * 80];
7632 #endif
7633 added_text[0].text =
7634 &text_text[ntext * STR_BUF_SIZE];
7635 added_text[0].compression =
7636 text_compression[ntext];
7637 png_set_text(write_ptr, write_end_info_ptr,
7638 added_text, 1);
7639
7640 if (verbose > 0 && last_trial)
7641 {
7642 if (added_text[0].compression < 0)
7643 fprintf(STDERR,
7644 " Added a tEXt chunk.\n");
7645 else if (added_text[0].compression == 0)
7646 fprintf(STDERR,
7647 " Added a zTXt chunk.\n");
7648 #ifdef PNG_iTXt_SUPPORTED
7649 else if (added_text[0].compression == 1)
7650 fprintf(STDERR,
7651 " Added an uncompressed iTXt "
7652 "chunk.\n");
7653 else
7654 fprintf(STDERR,
7655 " Added a compressed iTXt "
7656 "chunk.\n");
7657 #endif
7658 }
7659 png_free(write_ptr, added_text);
7660 added_text = (png_textp) NULL;
7661 }
7662 }
7663 } /* end of nosave block */
7664 }
7665 }
7666 #endif /* (PNG_READ_tEXt_SUPPORTED and PNG_WRITE_tEXt_SUPPORTED) or */
7667 /* (PNG_READ_iTXt_SUPPORTED and PNG_WRITE_iTXt_SUPPORTED) or */
7668 /* (PNG_READ_zTXt_SUPPORTED and PNG_WRITE_zTXt_SUPPORTED) */
7669 #if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
7670 {
7671 png_timep mod_time;
7672
7673 if (png_get_tIME(read_ptr, end_info_ptr, &mod_time))
7674 {
7675 P1( "Handling tIME chunk after IDAT\n");
7676 if (keep_chunk("tIME", argv))
7677 png_set_tIME(write_ptr, write_end_info_ptr,
7678 mod_time);
7679 }
7680 }
7681 #endif
7682
7683 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
7684 /* GRR FIXME? this block may need same fix as above */
7685 {
7686 png_unknown_chunkp unknowns;
7687 int num_unknowns =
7688 (int) png_get_unknown_chunks(read_ptr,
7689 end_info_ptr,
7690 &unknowns);
7691 if (num_unknowns && nosave == 0)
7692 {
7693 fprintf(STDERR,
7694 "Handling %d unknown chunks after IDAT\n",
7695 num_unknowns);
7696 png_set_unknown_chunks(write_ptr,
7697 write_end_info_ptr,
7698 unknowns, num_unknowns);
7699 for (i = 0; i < num_unknowns; i++)
7700 png_set_unknown_chunk_location(write_ptr,
7701 write_end_info_ptr,
7702 i,
7703 (int)
7704 unknowns[i].
7705 location);
7706 }
7707 }
7708 #endif
7709 } /* End of ancillary chunk handling */
7710
7711 if (nosave == 0) {
7712 #if 0 /* doesn't work; compression level has to be the same as in IDAT */
7713 /* if zTXt other compressed chunk */
7714 png_set_compression_level(write_ptr, 9);
7715 png_set_compression_window_bits(write_ptr, 15);
7716 png_set_compression_buffer_size(write_ptr,
7717 PNG_ZBUF_SIZE);
7718 png_set_compression_strategy(write_ptr, 0);
7719 #endif /* 0 */
7720 png_write_end(write_ptr, write_end_info_ptr);
7721 }
7722 }
7723 /* } GRR: added for %-navigation (2) */
7724
7725 P1( "Destroying read data structs\n");
7726 if (row_buf != (png_bytep) NULL)
7727 {
7728 P2(" row_buf = %p\n",row_buf);
7729 P2( "Destroying row_buf\n");
7730 /* Crash has been observed here when using the
7731 * system libpng instead of the bundled one.
7732 * It seems to have to do with the workaround for
7733 * png_read_transform_info() not being exported
7734 * in libpng-1.5.6 and later.
7735 */
7736 png_free(read_ptr, row_buf);
7737 row_buf = (png_bytep) NULL;
7738 }
7739 P2( "Destroyed data row_buf\n");
7740 #ifdef PNGCRUSH_MULTIPLE_ROWS
7741 if (row_pointers != (png_bytepp) NULL)
7742 {
7743 P1( "Destroying row_pointers\n");
7744 png_free(read_ptr, row_pointers);
7745 row_pointers = (png_bytepp) NULL;
7746 }
7747 P2( "Destroyed data row_pointers\n");
7748 #endif
7749 png_destroy_read_struct(&read_ptr, &read_info_ptr,
7750 &end_info_ptr);
7751 P2( "Destroyed data structs\n");
7752 if (nosave == 0)
7753 {
7754 #ifdef PNGCRUSH_LOCO
7755 if (do_loco)
7756 {
7757 const png_byte png_MEND[5] =
7758 { 77, 69, 78, 68, '\0' };
7759 /* write the MNG MEND chunk */
7760 png_write_chunk(write_ptr, (png_bytep) png_MEND,
7761 NULL, (png_size_t) 0);
7762 }
7763 #endif
7764 png_destroy_info_struct(write_ptr,
7765 &write_end_info_ptr);
7766 png_destroy_write_struct(&write_ptr, &write_info_ptr);
7767 }
7768 }
7769 Catch(msg) {
7770 if (nosave == 0)
7771 fprintf(stderr, "While converting %s to %s:\n", inname,
7772 outname);
7773 else
7774 fprintf(stderr, "While reading %s:\n", inname);
7775 fprintf(stderr,
7776 " pngcrush caught libpng error:\n %s\n\n", msg);
7777 if (row_buf)
7778 {
7779 png_free(read_ptr, row_buf);
7780 row_buf = (png_bytep) NULL;
7781 }
7782 #ifdef PNGCRUSH_MULTIPLE_ROWS
7783 if (row_pointers != (png_bytepp) NULL)
7784 {
7785 png_free(read_ptr, row_pointers);
7786 row_pointers = (png_bytepp) NULL;
7787 }
7788 #endif
7789 if (nosave == 0)
7790 {
7791 png_destroy_info_struct(write_ptr,
7792 &write_end_info_ptr);
7793 png_destroy_write_struct(&write_ptr, &write_info_ptr);
7794 setfiletype(outname);
7795 }
7796 png_destroy_read_struct(&read_ptr, &read_info_ptr,
7797 &end_info_ptr);
7798 if (verbose > 1)
7799 fprintf(stderr, "returning after cleanup\n");
7800 trial = last_method + 1;
7801 }
7802
7803 read_ptr = NULL;
7804 write_ptr = NULL;
7805 FCLOSE(fpin);
7806 if (last_trial && nosave == 0)
7807 {
7808 FCLOSE(fpout);
7809 setfiletype(outname);
7810 }
7811
7812 if (nosave)
7813 break;
7814
7815 if (trial == 0)
7816 continue;
7817
7818 idat_length[trial] = pngcrush_write_byte_count;
7819
7820 if (pngcrush_write_byte_count < pngcrush_best_byte_count)
7821 pngcrush_best_byte_count = pngcrush_write_byte_count;
7822
7823 if (verbose > 0 && trial != last_method)
7824 {
7825 if (bail == 0 &&
7826 pngcrush_write_byte_count > pngcrush_best_byte_count)
7827 fprintf(STDERR,
7828 " Critical chunk length, method %3d"
7829 " (ws %d fm %d zl %d zs %d) >%10lu\n",
7830 trial, compression_window,
7831 filter_type, zlib_level, z_strategy,
7832 (unsigned long)pngcrush_best_byte_count);
7833 else
7834 fprintf(STDERR,
7835 " Critical chunk length, method %3d"
7836 " (ws %d fm %d zl %d zs %d) =%10lu\n",
7837 trial, compression_window,
7838 filter_type, zlib_level, z_strategy,
7839 (unsigned long)idat_length[trial]);
7840 fflush(STDERR);
7841 }
7842
7843 } /* end of trial-loop */
7844
7845 P1("\n\nFINISHED MAIN LOOP OVER %d METHODS\n\n\n", last_method);
7846
7847 /* ////////////////////////////////////////////////////////////////////
7848 ////////////////// ////////////////////
7849 ////////////////// END OF MAIN LOOP OVER METHODS ////////////////////
7850 ////////////////// ////////////////////
7851 //////////////////////////////////////////////////////////////////// */
7852 }
7853
7854 if (fpin)
7855 {
7856 FCLOSE(fpin);
7857 }
7858 if (last_trial && nosave == 0 && fpout)
7859 {
7860 FCLOSE(fpout);
7861 setfiletype(outname);
7862 }
7863
7864 if (last_trial && nosave == 0 && overwrite != 0)
7865 {
7866 /* rename the new file , outname = inname */
7867 if (
7868 #if (defined(_Windows) || defined(_WINDOWS) || defined(WIN32) || \
7869 defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || \
7870 defined(__DJGPP__) || defined(CYGWIN))
7871 remove(inname) != 0 ||
7872 #endif
7873 rename(outname, inname) != 0 )
7874 {
7875 fprintf(STDERR,
7876 "error while renaming \"%s\" to \"%s\" \n",outname,inname);
7877 exit (1);
7878 }
7879 else
7880 P2("rename %s to %s complete.\n",outname,inname);
7881 }
7882
7883 if (last_trial && nosave == 0)
7884 {
7885 png_uint_32 output_length;
7886 #ifndef __riscos
7887 struct stat stat_buf;
7888 struct utimbuf utim;
7889
7890 stat(inname, &stat_buf);
7891 utim.actime = stat_buf.st_atime;
7892 utim.modtime = stat_buf.st_mtime;
7893 stat(outname, &stat_buf);
7894 output_length = (unsigned long) stat_buf.st_size;
7895 if (new_time_stamp == 0)
7896 {
7897 /* set file timestamp (no big deal if fails) */
7898 utime(outname, &utim);
7899 }
7900 #else
7901 output_length = (unsigned long) filesize(outname);
7902 #endif
7903 if (verbose >= 0 && bench < 2)
7904 {
7905 total_input_length += input_length + output_length;
7906
7907 if (best == 0)
7908 {
7909 fprintf(STDERR,
7910 " Best pngcrush method = 0 (settings undetermined)\n");
7911 }
7912
7913 #if 0 /* disabled */
7914 else if (!already_crushed && !image_is_immutable)
7915 #else
7916 else if (!image_is_immutable)
7917 #endif
7918 {
7919 fprintf(STDERR,
7920 " Best pngcrush method = %3d "
7921 "(ws %d fm %d zl %d zs %d) =%10lu\n",
7922 best, compression_window, fm[best], lv[best], zs[best],
7923 (unsigned long)idat_length[best]);
7924 }
7925
7926 if (verbose > 0)
7927 {
7928 if (idat_length[0] == idat_length[best])
7929 fprintf(STDERR, " (no critical chunk change)\n");
7930 else if (idat_length[0] > idat_length[best])
7931 fprintf(STDERR, " (%4.2f%% critical chunk reduction)\n",
7932 (100.0 - (100.0 * idat_length[best]) / idat_length[0]));
7933 else
7934 fprintf(STDERR, " (%4.2f%% critical chunk increase)\n",
7935 -(100.0 - (100.0 * idat_length[best]) / idat_length[0]));
7936 if (input_length == output_length)
7937 fprintf(STDERR, " (no filesize change)\n\n");
7938 else if (input_length > output_length)
7939 fprintf(STDERR, " (%4.2f%% filesize reduction)\n\n",
7940 (100.0 - (100.0 * output_length) / input_length));
7941 else
7942 fprintf(STDERR, " (%4.2f%% filesize increase)\n\n",
7943 -(100.0 - (100.0 * output_length) / input_length));
7944
7945 if (verbose > 2)
7946 fprintf(STDERR, " Number of open files=%d\n",
7947 number_of_open_files);
7948
7949 }
7950 }
7951 }
7952
7953 if (pngcrush_mode == DEFAULT_MODE || pngcrush_mode == OVERWRITE_MODE)
7954 {
7955 if (png_row_filters != NULL)
7956 {
7957 free(png_row_filters);
7958 png_row_filters = NULL;
7959 }
7960 #if PNGCRUSH_TIMERS > 0
7961 pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
7962 pngcrush_timer_stop(PNGCRUSH_TIMER_TOTAL);
7963 #endif
7964 if (verbose >= 0)
7965 {
7966 show_result();
7967 }
7968 #ifdef PNG_iCCP_SUPPORTED
7969 if (iccp_length)
7970 {
7971 free(iccp_text);
7972 iccp_text = NULL;
7973 iccp_length = 0;
7974 }
7975 #endif
7976 break;
7977 }
7978 } /* end of loop on input files */
7979
7980 #if PNGCRUSH_TIMERS > 0
7981 for (pc_timer = 0; pc_timer < PNGCRUSH_TIMERS; pc_timer++)
7982 {
7983 unsigned long ts,tn;
7984
7985 ts=pngcrush_timer_get_seconds(pc_timer);
7986 tn=pngcrush_timer_get_nanoseconds(pc_timer);
7987 if (ts < pngcrush_timer_min_secs[pc_timer])
7988 {
7989 pngcrush_timer_min_secs[pc_timer] = ts;
7990 pngcrush_timer_min_nsec[pc_timer] = tn;
7991 }
7992 else
7993 {
7994 if (tn < pngcrush_timer_min_nsec[pc_timer])
7995 pngcrush_timer_min_nsec[pc_timer] = tn;
7996 }
7997
7998 pngcrush_timer_reset(pc_timer);
7999 }
8000 #endif
8001
8002 } /* end of benchmark_iteration loop */
8003 if (verbose >= 0)
8004 {
8005 #if (PNGCRUSH_TIMERS > 0)
8006 for (pc_timer=0;pc_timer < PNGCRUSH_TIMERS; pc_timer++)
8007 {
8008 filter_count[pc_timer]+=pngcrush_timer_get_hits(pc_timer);
8009 t_sec=pngcrush_timer_min_secs[pc_timer];
8010 t_nsec=pngcrush_timer_min_nsec[pc_timer];
8011 t_filter[pc_timer] = (float)t_nsec/1000000000.;
8012 if (t_sec)
8013 t_filter[pc_timer] += (float)t_sec;
8014 }
8015
8016 # if PNGCRUSH_TIMERS >= 3
8017 fprintf(STDERR, "CPU time decode %.6f,", t_filter[1]);
8018 fprintf(STDERR, " encode %.6f,", t_filter[2]);
8019 fprintf(STDERR, " other %.6f,", t_filter[3]);
8020 fprintf(STDERR, " total %.6f sec\n", t_filter[0]);
8021 # endif
8022
8023 # if PNGCRUSH_USE_CLOCK_GETTIME != 0
8024 if (benchmark_iterations > 0)
8025 {
8026 # if PNGCRUSH_TIMERS > 9
8027 {
8028 float total_t_filter=0;
8029 float total_filter_count=0;
8030 for (pc_timer = 5; pc_timer < 10; pc_timer++)
8031 {
8032 total_t_filter+=t_filter[pc_timer];
8033 total_filter_count+=filter_count[pc_timer];
8034 }
8035 if (total_filter_count > 0)
8036 {
8037 for (pc_timer = 5; pc_timer < 10; pc_timer++)
8038 {
8039 fprintf(STDERR, " filter[%u] defilter time = %15.9f, count = %lu\n",
8040 pc_timer-5, t_filter[pc_timer],
8041 (unsigned long)filter_count[pc_timer]);
8042 }
8043 fprintf(STDERR, " total defilter time = %15.9f, count = %lu\n",
8044 total_t_filter, (unsigned long) total_filter_count);
8045 }
8046 }
8047 # endif
8048 # if PNGCRUSH_TIMERS > 4
8049 {
8050 if (filter_count[4] > 0)
8051 fprintf(STDERR, " deinterlace time = %15.9f, count = %lu\n",
8052 t_filter[4], (unsigned long)filter_count[4]);
8053 }
8054 # endif
8055 # if PNGCRUSH_TIMERS > 1
8056 {
8057 fprintf(STDERR, " total decode time = %15.9f, count = %lu\n",
8058 t_filter[1], (unsigned long)filter_count[1]);
8059 }
8060 # endif
8061 # if PNGCRUSH_TIMERS > 10
8062 {
8063 if (filter_count[10] > 0)
8064 fprintf(STDERR, " filter setup time = %15.9f, count = %lu\n",
8065 t_filter[10], (unsigned long)filter_count[10]);
8066 }
8067 # endif
8068 # if PNGCRUSH_TIMERS > 2
8069 {
8070 fprintf(STDERR, " total encode time = %15.9f, count = %lu\n",
8071 t_filter[2], (unsigned long)filter_count[2]);
8072 }
8073 # endif
8074 # if PNGCRUSH_TIMERS > 3
8075 {
8076 fprintf(STDERR, " total misc time = %15.9f, count = %lu\n",
8077 t_filter[3], (unsigned long)filter_count[3]);
8078 }
8079 # endif
8080 # if PNGCRUSH_TIMERS > 0
8081 {
8082 fprintf(STDERR, " total time = %15.9f, count = %lu\n",
8083 t_filter[0], (unsigned long)filter_count[0]);
8084 }
8085 # endif
8086 }
8087 #endif
8088 #endif
8089 }
8090
8091 if (pngcrush_must_exit)
8092 exit(0);
8093 return 0; /* just in case */
8094
8095 } /* end of main() */
8096
8097
8098
8099
8100 png_uint_32 measure_idats(FILE * fp_in)
8101 {
8102 /* Copyright (C) 1999-2002, 2006-2015 Glenn Randers-Pehrson
8103 (glennrp at users.sf.net). See notice in pngcrush.c for conditions of
8104 use and distribution */
8105 P2("\nmeasure_idats:\n");
8106 P1( "Allocating read structure\n");
8107 /* OK to ignore any warning about the address of exception__prev in "Try" */
8108 Try {
8109 read_ptr =
8110 png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL,
8111 (png_error_ptr) pngcrush_cexcept_error,
8112 (png_error_ptr) NULL);
8113 P1( "Allocating read_info, end_info structures\n");
8114 read_info_ptr = png_create_info_struct(read_ptr);
8115 end_info_ptr = png_create_info_struct(read_ptr);
8116
8117 #ifdef PNG_STDIO_SUPPORTED
8118 png_init_io(read_ptr, fp_in);
8119 #else
8120 png_set_read_fn(read_ptr, (png_voidp) fp_in, (png_rw_ptr) NULL);
8121 #endif
8122
8123 png_set_sig_bytes(read_ptr, 0);
8124 measured_idat_length = pngcrush_measure_idat(read_ptr);
8125 P2("measure_idats: IDAT length=%lu\n",
8126 (unsigned long)measured_idat_length);
8127 P1( "Destroying data structs\n");
8128 png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
8129 }
8130 Catch(msg) {
8131 fprintf(STDERR, "\nWhile measuring IDATs in %s ", inname);
8132 fprintf(STDERR, "pngcrush caught libpng error:\n %s\n\n", msg);
8133 png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
8134 P1( "Destroyed data structs\n");
8135 measured_idat_length = 0;
8136 }
8137 return measured_idat_length;
8138 }
8139
8140
8141
8142
8143 #define PNGCRUSH_a 97
8144 #define PNGCRUSH_z 122
8145 #define PNGCRUSH_A 65
8146 #define PNGCRUSH_Z 90
8147
8148 png_uint_32 pngcrush_measure_idat(png_structp png_ptr)
8149 {
8150 /* Copyright (C) 1999-2002, 2006-2015 Glenn Randers-Pehrson
8151 (glennrp at users.sf.net)
8152 See notice in pngcrush.c for conditions of use and distribution */
8153
8154 /* Signature + IHDR + IEND; we'll add PLTE + IDAT lengths */
8155 png_uint_32 sum_idat_length = 45;
8156
8157 png_byte *bb = NULL;
8158 png_uint_32 malloced_length=0;
8159
8160 {
8161 png_byte png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
8162 #ifdef PNGCRUSH_LOCO
8163 png_byte mng_signature[8] = { 138, 77, 78, 71, 13, 10, 26, 10 };
8164 #endif
8165
8166 pngcrush_default_read_data(png_ptr, png_signature, 8);
8167 png_set_sig_bytes(png_ptr, 8);
8168
8169 #ifdef PNGCRUSH_LOCO
8170 if (!(int) (png_memcmp(mng_signature, png_signature, 8)))
8171 {
8172 const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
8173
8174 int ib;
8175 png_byte buff[28] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8177 0, 0, 0, 0, 0, 0, 0, 0 };
8178 unsigned long length;
8179 /* read the MHDR */
8180 pngcrush_default_read_data(png_ptr, buff, 4);
8181
8182 length = pngcrush_get_uint_31(png_ptr,buff);
8183 if (length > 28)
8184 png_error(png_ptr, "MHDR length too long");
8185
8186 pngcrush_default_read_data(png_ptr, buff, 4);
8187
8188 /* To do: combine with checking for valid PNG chunk_name, below */
8189 /* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
8190 if (!(((buff[0] >= PNGCRUSH_a && buff[0] <= PNGCRUSH_z) ||
8191 (buff[0] >= PNGCRUSH_A && buff[0] <= PNGCRUSH_Z)) &&
8192 ((buff[1] >= PNGCRUSH_a && buff[1] <= PNGCRUSH_z) ||
8193 (buff[1] >= PNGCRUSH_A && buff[1] <= PNGCRUSH_Z)) &&
8194 ((buff[2] >= PNGCRUSH_A && buff[2] <= PNGCRUSH_Z)) &&
8195 ((buff[3] >= PNGCRUSH_a && buff[3] <= PNGCRUSH_z) ||
8196 (buff[3] >= PNGCRUSH_A && buff[3] <= PNGCRUSH_Z))))
8197 {
8198 int i;
8199 fprintf (STDERR,"Invalid MNG chunk name: \"");
8200 for (i=0; i<4; i++)
8201 {
8202 if ((buff[i] >= PNGCRUSH_a && buff[i] <= PNGCRUSH_z) ||
8203 (buff[i] >= PNGCRUSH_A && buff[i] <= PNGCRUSH_Z) ||
8204 (buff[i] >= '0' && buff[i] <= '9'))
8205 fprintf(STDERR,"%c",buff[i]);
8206 else
8207 fprintf(STDERR,"?");
8208 }
8209 fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
8210 buff[0],buff[1],buff[2],buff[3]);
8211 }
8212 else
8213 if (verbose > 1)
8214 printf(" Reading %c%c%c%c chunk.\n",buff[0],buff[1],buff[2],
8215 buff[3]);
8216
8217 pngcrush_default_read_data(png_ptr, buff, length);
8218
8219 if (length < 28)
8220 for (ib=27; ib >= length; ib--)
8221 buff[ib] = 0;
8222
8223 if (verbose > 0) {
8224 printf(" width=%lu\n",
8225 (unsigned long) pngcrush_get_uint_31(png_ptr,buff));
8226 printf(" height=%lu\n",
8227 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[4]));
8228 printf(" ticksps=%lu\n",
8229 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[8]));
8230 printf(" nomlayc=%lu\n",
8231 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[12]));
8232 printf(" nomfram=%lu\n",
8233 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[16]));
8234 printf(" nomplay=%lu\n",
8235 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[20]));
8236 printf(" profile=%lu\n",
8237 (unsigned long) pngcrush_get_uint_31(png_ptr,&buff[24]));
8238 }
8239
8240 if (new_mng)
8241 {
8242 /* write the MNG 8-byte signature */
8243 pngcrush_write_png(mng_ptr, &mng_signature[0],
8244 (png_size_t) 8);
8245
8246 /* Write a MHDR chunk */
8247 png_write_chunk(mng_ptr, (png_bytep) png_MHDR,
8248 buff, (png_size_t) 28);
8249 }
8250
8251 pngcrush_default_read_data(png_ptr, buff, 4);
8252 input_format = 1;
8253
8254 }
8255 else
8256 #endif
8257 if (png_sig_cmp(png_signature, 0, 8))
8258 {
8259 if (png_sig_cmp(png_signature, 0, 4))
8260 png_error(png_ptr, "Not a PNG file..");
8261 else
8262 png_error(png_ptr,
8263 "PNG file corrupted by ASCII conversion");
8264 }
8265 }
8266
8267 if (salvage)
8268 {
8269 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8270 /* The warning here about deprecated access to png_ptr->zstream
8271 * is unavoidable. This will not work with libpng-1.5.x and later.
8272 */
8273 inflateUndermine(&png_ptr->zstream, 1);
8274 #endif
8275 }
8276
8277 for (;;)
8278 {
8279 #ifndef PNG_UINT_IDAT
8280 # ifdef PNG_USE_LOCAL_ARRAYS
8281 PNG_IDAT;
8282 PNG_IEND;
8283 PNG_IHDR;
8284 PNG_acTL;
8285 # ifdef PNG_iCCP_SUPPORTED
8286 PNG_iCCP;
8287 # endif
8288 # else
8289 # ifdef PNG_iCCP_SUPPORTED
8290 const png_byte png_iCCP[5] = { 105, 67, 67, 80, '\0' };
8291 # endif
8292 const png_byte png_acTL[5] = { 97, 99, 84, 76, '\0' };
8293 # endif
8294 #endif
8295
8296 png_byte chunk_name[5];
8297 png_byte chunk_length[4];
8298 png_byte buff[32];
8299 png_uint_32 length;
8300
8301 pngcrush_default_read_data(png_ptr, chunk_length, 4);
8302 length = pngcrush_get_uint_31(png_ptr,chunk_length);
8303
8304 pngcrush_reset_crc(png_ptr);
8305 pngcrush_crc_read(png_ptr, chunk_name, 4);
8306 chunk_name[4]='\0';
8307
8308 /* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
8309 if (!(((chunk_name[0] >= PNGCRUSH_a && chunk_name[0] <= PNGCRUSH_z) ||
8310 (chunk_name[0] >= PNGCRUSH_A && chunk_name[0] <= PNGCRUSH_Z)) &&
8311 ((chunk_name[1] >= PNGCRUSH_a && chunk_name[1] <= PNGCRUSH_z) ||
8312 (chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
8313 ((chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
8314 ((chunk_name[3] >= PNGCRUSH_a && chunk_name[3] <= PNGCRUSH_z) ||
8315 (chunk_name[3] >= PNGCRUSH_A && chunk_name[3] <= PNGCRUSH_Z))))
8316 {
8317 int i;
8318
8319 fprintf (STDERR,"Invalid chunk name: \"");
8320 for (i=0; i<4; i++)
8321 {
8322 if ((chunk_name[i] >= PNGCRUSH_a &&
8323 chunk_name[i] <= PNGCRUSH_z) ||
8324 (chunk_name[i] >= PNGCRUSH_A &&
8325 chunk_name[i] <= PNGCRUSH_Z)||
8326 (chunk_name[i] >= '0' &&
8327 chunk_name[i] <= '9'))
8328 fprintf(STDERR,"%c",chunk_name[i]);
8329 else
8330 fprintf(STDERR,"?");
8331 }
8332 fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
8333 chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
8334 }
8335 else
8336 if (verbose > 1)
8337 printf(" Reading %c%c%c%c chunk.\n",
8338 chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
8339
8340 if (new_mng)
8341 {
8342 const png_byte png_DHDR[5] = { 68, 72, 68, 82, '\0' };
8343 const png_byte png_DEFI[5] = { 68, 69, 70, 73, '\0' };
8344 const png_byte png_FRAM[5] = { 70, 82, 65, 77, '\0' };
8345 const png_byte png_nEED[5] = { 110, 69, 69, 68, '\0' };
8346
8347 if (!png_memcmp(chunk_name, png_nEED, 4))
8348 {
8349 /* Skip the nEED chunk */
8350 if (verbose > 0)
8351 printf (" skipping MNG %c%c%c%c chunk, %lu bytes\n",
8352 chunk_name[0],
8353 chunk_name[1],chunk_name[2],chunk_name[3],
8354 (unsigned long)length);
8355 }
8356 else
8357 {
8358 /* copy the chunk. */
8359 if (verbose > 0)
8360 printf (" reading MNG %c%c%c%c chunk, %lu bytes\n",
8361 chunk_name[0],
8362 chunk_name[1],chunk_name[2],chunk_name[3],
8363 (unsigned long)length);
8364 if (length+1 > malloced_length)
8365 {
8366 png_free(mng_ptr,bb);
8367 if (verbose > 0)
8368 printf (" png_malloc %lu bytes.\n",(unsigned long)length);
8369 bb=(png_byte*)png_malloc(mng_ptr, length+1);
8370 malloced_length=length+1;
8371 }
8372 pngcrush_crc_read(png_ptr, bb, length);
8373 bb[length]='\0';
8374 png_write_chunk(mng_ptr, chunk_name,
8375 bb, (png_size_t) length);
8376
8377 if (verbose > 1 && !png_memcmp(chunk_name, png_DHDR, 4))
8378 {
8379 if (length > 19)
8380 {
8381 printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
8382 printf(" itype=%lu\n",(unsigned long)(bb[2]));
8383 printf(" dtype=%lu\n",(unsigned long)(bb[3]));
8384 printf(" width=%lu\n",
8385 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[4]));
8386 printf(" height=%lu\n",
8387 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[8]));
8388 printf(" xloc=%lu\n",
8389 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
8390 printf(" yloc=%lu\n",
8391 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
8392 }
8393 }
8394
8395 if (verbose > 1 && !png_memcmp(chunk_name, png_DEFI, 4))
8396 {
8397 if (length > 3)
8398 {
8399 printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
8400 printf(" do_not_show=%lu\n",(unsigned long)(bb[2]));
8401 printf(" concrete=%lu\n",(unsigned long)(bb[3]));
8402 }
8403 if (length > 19)
8404 {
8405 printf(" xloc=%lu\n",
8406 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
8407 printf(" yloc=%lu\n",
8408 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
8409 if (length > 28)
8410 {
8411 printf(" l_cb=%lu\n",
8412 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[20]));
8413 printf(" r_cb=%lu\n",
8414 (unsigned long) pngcrush_get_uint_31(png_ptr,&bb[24]));
8415 }
8416 }
8417 }
8418 if (verbose > 1 && !png_memcmp(chunk_name, png_FRAM, 4))
8419 {
8420 printf(" mode=%lu\n",(unsigned long)bb[0]);
8421 if (length > 1)
8422 {
8423 int ib;
8424 printf(" name = ");
8425 bb[length]='\0';
8426 for (ib=0; bb[ib]; ib++)
8427 {
8428 printf ("%c", bb[ib]);
8429 }
8430 printf ("\n");
8431 }
8432 length=0;
8433 }
8434 }
8435 }
8436
8437 #ifdef PNG_UINT_acTL
8438 else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_acTL)
8439 #else
8440 else if (!png_memcmp(chunk_name, png_acTL, 4))
8441 #endif
8442 {
8443 found_acTL_chunk = 1;
8444 }
8445
8446 #ifdef PNG_UINT_IDAT
8447 if ((pngcrush_get_uint_32(chunk_name) == PNG_UINT_IDAT) ||
8448 #endif
8449 #ifndef PNG_UINT_IDAT
8450 if ((!png_memcmp(chunk_name, png_IDAT, 4)) ||
8451 #endif
8452 #ifdef PNG_UINT_PLTE
8453 (pngcrush_get_uint_32(chunk_name) == PNG_UINT_PLTE))
8454 #endif
8455 #ifndef PNG_UINT_PLTE
8456 (!png_memcmp(chunk_name, png_PLTE, 4)))
8457 #endif
8458 {
8459 sum_idat_length += (length + 12);
8460 #if 0 /* disabled */
8461 if (length > crushed_idat_size)
8462 already_crushed++;
8463 #endif
8464 }
8465
8466 if (verbose > 1)
8467 {
8468 chunk_name[4] = '\0';
8469 fprintf(STDERR, " Reading %s chunk, length = %lu.\n",
8470 chunk_name, (unsigned long)length);
8471 }
8472
8473 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_CgBI)
8474 {
8475 fprintf(STDERR,
8476 " This is an Xcode CgBI file, not a PNG file.\n");
8477 if (salvage)
8478 {
8479 fprintf (STDERR, " Removing the CgBI chunk.\n");
8480 }
8481 else
8482 {
8483 fprintf (STDERR,
8484 " Try \"pngcrush -fix ...\" to attempt to read it.\n");
8485 }
8486 found_CgBI++;
8487 nosave++;
8488 }
8489
8490
8491 #ifdef PNG_UINT_IHDR
8492 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IHDR)
8493 #else
8494 if (!png_memcmp(chunk_name, png_IHDR, 4))
8495 #endif
8496 {
8497 /* get the color type */
8498 pngcrush_crc_read(png_ptr, buff, 13);
8499 length -= 13;
8500 input_color_type = buff[9];
8501 }
8502 else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_dSIG)
8503 {
8504 if (found_any_chunk == 0 && !all_chunks_are_safe)
8505 {
8506 image_is_immutable=1;
8507 }
8508 }
8509 else
8510 found_any_chunk=1;
8511
8512 #ifdef PNG_gAMA_SUPPORTED
8513 #ifdef PNG_UINT_gAMA
8514 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_gAMA)
8515 #else
8516 if (!png_memcmp(chunk_name, png_gAMA, 4))
8517 #endif
8518 found_gAMA=1;
8519 #endif /* PNG_gAMA_SUPPORTED */
8520
8521 #ifdef PNG_bKGD_SUPPORTED
8522 #ifdef PNG_UINT_bKGD
8523 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_bKGD)
8524 #else
8525 if (!png_memcmp(chunk_name, png_bKGD, 4))
8526 #endif
8527 if (length == 6)
8528 {
8529 /* Set found_color_bKGD if the components are different,
8530 * so we do not do reduction of color-type from color to gray
8531 */
8532 pngcrush_crc_read(png_ptr, buff, 6);
8533 length -= 6;
8534 if ((buff[0] != buff[2]) && (buff[0] != buff[4]) &&
8535 (buff[1] != buff[3]) && (buff[0] != buff[5]))
8536 found_color_bKGD=1;
8537 }
8538 #endif /* PNG_bKGD_SUPPORTED */
8539
8540 #ifdef PNG_cHRM_SUPPORTED
8541 #ifdef PNG_UINT_cHRM
8542 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_cHRM)
8543 #else
8544 if (!png_memcmp(chunk_name, png_cHRM, 4))
8545 #endif
8546 found_cHRM=1;
8547 #endif /* PNG_cHRM_SUPPORTED */
8548
8549 #ifdef PNG_hIST_SUPPORTED
8550 #ifdef PNG_UINT_hIST
8551 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_hIST)
8552 #else
8553 if (!png_memcmp(chunk_name, png_hIST, 4))
8554 #endif
8555 found_hIST=1;
8556 #endif /* PNG_hIST_SUPPORTED */
8557
8558 #ifdef PNG_iCCP_SUPPORTED
8559 /* check for bad Photoshop iCCP chunk */
8560 #ifdef PNG_UINT_iCCP
8561 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_iCCP)
8562 #else
8563 if (!png_memcmp(chunk_name, png_iCCP, 4))
8564 #endif
8565 {
8566 found_iCCP = 1;
8567
8568 /* Check for bad Photoshop iCCP chunk. Libpng will reject the
8569 * bad chunk because the Adler-32 bytes are missing, but we check
8570 * here to see if it's really the sRGB profile, and if so, set the
8571 * "intent" flag and gamma so pngcrush will write an sRGB chunk
8572 * and a gamma chunk.
8573 */
8574 if (length == 2615)
8575 {
8576 pngcrush_crc_read(png_ptr, buff, 22);
8577 length -= 22;
8578 buff[23] = 0;
8579 if (!strncmp((png_const_charp) buff, "Photoshop ICC profile",
8580 21))
8581 {
8582 fprintf(STDERR,
8583 " Replacing bad Photoshop iCCP chunk with an "
8584 "sRGB chunk\n");
8585 #ifdef PNG_gAMA_SUPPORTED
8586 # ifdef PNG_FIXED_POINT_SUPPORTED
8587 image_specified_gamma = 45455L;
8588 # else
8589 image_specified_gamma = 0.45455;
8590 # endif
8591 #endif /* PNG_gAMA_SUPPORTED */
8592 found_iCCP = 0;
8593 found_sRGB = 1;
8594 intent = 0;
8595 }
8596 }
8597 /* To do: recognize other sRGB iCCP chunks and replace them with
8598 * sRGB chunk
8599 */
8600 }
8601 #endif /* PNG_iCCP_SUPPORTED */
8602
8603 #ifdef PNG_sBIT_SUPPORTED
8604 #ifdef PNG_UINT_sBIT
8605 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_sBIT)
8606 #else
8607 if (!png_memcmp(chunk_name, png_sBIT, 4))
8608 #endif
8609 {
8610 if (length <= 4)
8611 {
8612 int i;
8613 pngcrush_crc_read(png_ptr, buff, length);
8614 found_sBIT_max=0;
8615 for (i=length; i; i--)
8616 if (buff[i] > found_sBIT_max)
8617 found_sBIT_max=buff[i];
8618
8619 if (length > 2)
8620 if (buff[0] != buff[1] || buff[0] != buff[2])
8621 found_sBIT_different_RGB_bits = 1;
8622
8623 found_sBIT = 1;
8624 length = 0;
8625 }
8626 }
8627 #endif /* PNG_sBIT_SUPPORTED */
8628
8629 #ifdef PNG_tRNS_SUPPORTED
8630 #ifdef PNG_UINT_tRNS
8631 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_tRNS)
8632 #else
8633 if (!png_memcmp(chunk_name, png_tRNS, 4))
8634 #endif
8635 found_tRNS=1;
8636 #endif /* PNG_tRNS_SUPPORTED */
8637
8638 pngcrush_crc_finish(png_ptr, length);
8639
8640 #ifdef PNGCRUSH_LOCO
8641 # ifdef PNG_UINT_MEND
8642 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_MEND)
8643 return sum_idat_length;
8644 # else
8645 {
8646 const png_byte png_MEND[5] =
8647 { 77, 69, 78, 68, '\0' };
8648 if (!png_memcmp(chunk_name, png_MEND, 4))
8649 {
8650 if (new_mng)
8651 {
8652 png_free(mng_ptr,bb);
8653 return (0);
8654 }
8655 return sum_idat_length;
8656 }
8657 }
8658 # endif
8659 #endif
8660
8661
8662 #ifdef PNGCRUSH_LOCO
8663 if (input_format == 0)
8664 #endif
8665 {
8666 #ifdef PNG_UINT_IEND
8667 if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IEND)
8668 #else
8669 if (!png_memcmp(chunk_name, png_IEND, 4))
8670 #endif
8671 {
8672 if (!salvage && found_CgBI)
8673 return 0;
8674 else
8675 return sum_idat_length;
8676 }
8677 }
8678 }
8679 }
8680
8681
8682 void print_version_info(void)
8683 {
8684 char *zlib_copyright;
8685
8686 #ifndef ZLIB_VERNUM /* This became available in zlib-1.2 */
8687 zlib_copyright=" (or later)";
8688 #else
8689 switch (ZLIB_VERNUM)
8690 {
8691 case 0x1220:
8692 zlib_copyright="-2004";
8693 break;
8694 case 0x1230:
8695 zlib_copyright="-2005";
8696 break;
8697 case 0x1240:
8698 case 0x1250:
8699 zlib_copyright="-2010";
8700 break;
8701 case 0x1260:
8702 case 0x1270:
8703 zlib_copyright="-2012";
8704 break;
8705 case 0x1271:
8706 case 0x1280:
8707 zlib_copyright="-2013";
8708 break;
8709 case 0x1290:
8710 case 0x12a0:
8711 case 0x12b0:
8712 zlib_copyright="-2017";
8713 break;
8714 default:
8715 zlib_copyright=" (or later)";
8716 break;
8717 }
8718 #endif
8719
8720 #ifdef PNGCRUSH_H
8721 # define BUNDLED_LIB "bundled"
8722 #else
8723 # define BUNDLED_LIB "system"
8724 #endif
8725
8726 fprintf(STDERR,
8727 "\n"
8728 " | pngcrush-%s\n"
8729 /* If you have modified this source, you may insert additional notices
8730 * immediately after this sentence: */
8731 " | Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson\n"
8732 " | Portions Copyright (C) 2005 Greg Roelofs\n"
8733 " | This is a free, open-source program. Permission is irrevocably\n"
8734 " | granted to everyone to use this version of pngcrush without\n"
8735 " | payment of any fee.\n"
8736 " | Executable name is %s\n"
8737 " | It was built with %s libpng-%s\n"
8738 " | and is running with %s libpng-%s\n"
8739 " | Copyright (C) 1998-2004, 2006-2017 Glenn Randers-Pehrson,\n"
8740 " | Copyright (C) 1996, 1997 Andreas Dilger,\n"
8741 " | Copyright (C) 1995, Guy Eric Schalnat, Group 42 Inc.,\n"
8742 " | and %s zlib-%s, Copyright (C) 1995%s,\n"
8743 " | Jean-loup Gailly and Mark Adler",
8744 PNGCRUSH_VERSION, progname,
8745 BUNDLED_LIB,PNG_LIBPNG_VER_STRING,
8746 BUNDLED_LIB,png_get_header_ver(NULL),
8747 BUNDLED_LIB,ZLIB_VERSION,
8748 zlib_copyright);
8749
8750 #if PNGCRUSH_TIMERS > 0
8751 fprintf(STDERR,
8752 ",\n | and using \"%s\".\n",PNGCRUSH_USING_CLOCK);
8753 #else
8754 fprintf(STDERR,"\n");
8755 #endif
8756 if (strcmp(png_libpng_ver, PNG_LIBPNG_VER_STRING))
8757 {
8758 fprintf(STDERR,
8759 "Warning: versions are different between png.h and png.c\n");
8760 fprintf(STDERR, " png.h version: %s\n", PNG_LIBPNG_VER_STRING);
8761 fprintf(STDERR, " png.c version: %s\n\n", png_libpng_ver);
8762 }
8763
8764 #if defined(__GNUC__)
8765 fprintf(STDERR,
8766 " | It was compiled with gcc version %s", __VERSION__);
8767 # if defined(__DJGPP__)
8768 fprintf(STDERR,
8769 "\n"
8770 " | under DJGPP %d.%d, Copyright (C) 1995, DJ Delorie\n"
8771 " | and loaded with PMODE/DJ, by Thomas Pytel and Matthias Grimrath\n"
8772 " | Copyright (C) 1996, Matthias Grimrath.\n",
8773 __DJGPP__, __DJGPP_MINOR__);
8774 # else
8775 fprintf(STDERR, "\n");
8776 # endif
8777 #endif
8778
8779 #if PNG_ARM_NEON_OPT > 0
8780 fprintf(STDERR," | using ARM_NEON optimizations.\n");
8781 #endif
8782 #if PNG_MIPS_MSA_OPT > 0
8783 fprintf(STDERR," | using MIPS_MSA optimizations.\n");
8784 #endif
8785 #if PNG_POWERPC_VSX_OPT > 0
8786 fprintf(STDERR," | using POWERPC_VSX optimizations.\n");
8787 #endif
8788 #if PNG_INTEL_SSE_OPT > 0
8789 fprintf(STDERR," | using INTEL_SSE optimizations.\n");
8790 #endif
8791
8792 fprintf(STDERR, "\n");
8793 }
8794
8795
8796
8797
8798
8799 static const char *pngcrush_legal[] = {
8800 "",
8801 "If you have modified this source, you may insert additional notices",
8802 "immediately after this sentence.",
8803 "Copyright (C) 1998-2002, 2006-2017 Glenn Randers-Pehrson",
8804 "Portions Copyright (C) 2005 Greg Roelofs",
8805 "",
8806 "DISCLAIMER: The pngcrush computer program is supplied \"AS IS\".",
8807 "The Author disclaims all warranties, expressed or implied, including,",
8808 "without limitation, the warranties of merchantability and of fitness",
8809 "for any purpose. The Author assumes no liability for direct, indirect,",
8810 "incidental, special, exemplary, or consequential damages, which may",
8811 "result from the use of the computer program, even if advised of the",
8812 "possibility of such damage. There is no warranty against interference",
8813 "with your enjoyment of the computer program or against infringement.",
8814 "There is no warranty that my efforts or the computer program will",
8815 "fulfill any of your particular purposes or needs. This computer",
8816 "program is provided with all faults, and the entire risk of satisfactory",
8817 "quality, performance, accuracy, and effort is with the user.",
8818 "",
8819 "LICENSE: Permission is hereby irrevocably granted to everyone to use,",
8820 "copy, modify, and distribute this computer program, or portions hereof,",
8821 "purpose, without payment of any fee, subject to the following",
8822 "restrictions:",
8823 "",
8824 "1. The origin of this binary or source code must not be misrepresented.",
8825 "",
8826 "2. Altered versions must be plainly marked as such and must not be",
8827 "misrepresented as being the original binary or source.",
8828 "",
8829 "3. The Copyright notice, disclaimer, and license may not be removed",
8830 "or altered from any source, binary, or altered source distribution.",
8831 ""
8832 };
8833
8834 static const char *pngcrush_usage[] = {
8835 "\nusage: %s [options except for -e -d] infile.png outfile.png\n",
8836 " %s -e ext [other options] file.png ...\n",
8837 " %s -d dir/ [other options] file.png ...\n",
8838 " %s -ow [other options] file.png [tempfile.png]\n",
8839 " %s -n -v file.png ...\n"
8840 };
8841
8842 struct options_help pngcrush_options[] = {
8843
8844 {0, " -bail (bail out of trial when size exceeds best size found"},
8845 {2, ""},
8846 {2, " Default is to bail out and simply report that the"},
8847 {2, " filesize for the trial would be greater than the"},
8848 {2, " best filesize achieved so far. Use the \"-nobail\""},
8849 {2, " option to prevent that."},
8850 {2, ""},
8851
8852 {0, " -blacken (zero samples underlying fully-transparent pixels)"},
8853 {2, ""},
8854 {2, " Changing the color samples to zero can improve the"},
8855 {2, " compressibility. Since this is a lossy operation,"},
8856 {2, " blackening is off by default."},
8857 {2, ""},
8858
8859 #ifdef Z_RLE
8860 {0, " -brute (use brute-force: try 176 different methods)"},
8861 #else
8862 {0, " -brute (use brute-force: try 166 different methods)"},
8863 #endif
8864 {2, ""},
8865 {2, " Very time-consuming and generally not worthwhile."},
8866 {2, " You can restrict this option to certain filter types,"},
8867 {2, " compression levels, or strategies by following it"},
8868 {2, " with \"-f filter\", \"-l level\", or \"-z strategy\"."},
8869 {2, ""},
8870
8871 {0, FAKE_PAUSE_STRING},
8872
8873 {0, " -c color_type of output file [0, 2, 4, or 6]"},
8874 {2, ""},
8875 {2, " Color type for the output file. Future versions"},
8876 {2, " will also allow color_type 3, if there are 256 or"},
8877 {2, " fewer colors present in the input file. Color types"},
8878 {2, " 4 and 6 are padded with an opaque alpha channel if"},
8879 {2, " the input file does not have alpha information."},
8880 {2, " You can use 0 or 4 to convert color to grayscale."},
8881 {2, " Use 0 or 2 to delete an unwanted alpha channel."},
8882 {2, " Default is to use same color type as the input file."},
8883 {2, ""},
8884
8885 {0, " -check (check CRC and ADLER32 checksums)"},
8886 {2, ""},
8887 {2, " Use \"-nocheck\" (default) to skip checking them"},
8888 {2, ""},
8889
8890 {0, " -d directory_name/ (where output files will go)"},
8891 {2, ""},
8892 {2, " If a directory name is given, then the output"},
8893 {2, " files are placed in it, with the same filenames as"},
8894 {2, " those of the original files. For example,"},
8895 {2, " you would type 'pngcrush -directory CRUSHED/ *.png'"},
8896 {2, " to get *.png => CRUSHED/*.png. The trailing slash is"},
8897 {2, " optional, but if pngcrush appends the wrong kind of"},
8898 {2, " slash or backslash, please include the correct one"},
8899 {2, " at the end of the directory_name, as shown."},
8900 {2, ""},
8901
8902 {0, FAKE_PAUSE_STRING},
8903
8904 {0, " -e extension (used for creating output filename)"},
8905 {2, ""},
8906 {2, " e.g., -ext .new means *.png => *.new"},
8907 {2, " and -e _pc.png means *.png => *_pc.png"},
8908 {2, ""},
8909
8910 {0, " -f user_filter [0-5] for specified method"},
8911 {2, ""},
8912 {2, " filter to use with the method specified in the"},
8913 {2, " preceding '-m method' or '-brute_force' argument."},
8914 {2, " 0: none; 1-4: use specified filter; 5: adaptive."},
8915 {2, ""},
8916
8917 {0, FAKE_PAUSE_STRING},
8918
8919 {0, " -fix (salvage PNG with otherwise fatal conditions)"},
8920 {2, ""},
8921 {2, " Fixes bad CRCs, bad adaptive filter bytes,"},
8922 {2, " or bad CMF bytes in the IDAT chunk that cause"},
8923 {2, " the \"Too far back\" error"},
8924 {2, ""},
8925
8926 {0, " -force (write output even if IDAT is larger)"},
8927 {2, ""},
8928
8929 #ifdef PNG_FIXED_POINT_SUPPORTED
8930 {0, " -g gamma (float or fixed*100000, e.g., 0.45455 or 45455)"},
8931 #else
8932 {0, " -g gamma (float, e.g., 0.45455)"},
8933 #endif
8934 {2, ""},
8935 {2, " Value to insert in gAMA chunk, only if the input"},
8936 {2, " file has no gAMA chunk. To replace an existing"},
8937 {2, " gAMA chunk, use the '-replace_gamma' option."},
8938 {2, ""},
8939
8940 {0, FAKE_PAUSE_STRING},
8941
8942 {0, " -huffman (use only zlib strategy 2, Huffman-only)"},
8943 {2, ""},
8944 {2, " Fast, but almost never very effective except for"},
8945 {2, " certain rare image types."},
8946 {2, ""},
8947
8948 #ifdef PNG_iCCP_SUPPORTED
8949 {0, " -iccp length \"Profile Name\" iccp_file"},
8950 {2, ""},
8951 {2, " file with ICC profile to insert in an iCCP chunk."},
8952 {2, ""},
8953 #endif
8954
8955 #ifdef PNG_iTXt_SUPPORTED
8956 {0, " -itxt b[efore_IDAT]|a[fter_IDAT] \"keyword\""},
8957 {2, " \"language_code\" \"translated_keyword\" \"text\""},
8958 {2, ""},
8959 {2, " Uncompressed iTXt chunk to insert (see -text)."},
8960 {2, ""},
8961 #endif
8962
8963 {0, " -keep chunk_name"},
8964 {2, ""},
8965 {2, " keep named chunk even when pngcrush makes"},
8966 {2, " changes to the PNG datastream that cause it"},
8967 {2, " to become invalid. Currently only dSIG is"},
8968 {2, " recognized as a chunk to be kept."},
8969 {2, ""},
8970
8971
8972 {0, " -l zlib_compression_level [0-9] for specified method"},
8973 {2, ""},
8974 {2, " zlib compression level to use with method specified"},
8975 {2, " with the preceding '-m method' or '-brute_force'"},
8976 {2, " argument."},
8977 {2, ""},
8978
8979 #ifdef PNGCRUSH_LOCO
8980 {0, FAKE_PAUSE_STRING},
8981
8982 {0, " -loco (\"loco crush\" truecolor PNGs)"},
8983 {2, ""},
8984 {2, " Make the file more compressible by performing a"},
8985 {2, " lossless, reversible, color transformation."},
8986 {2, " The resulting file is a MNG, not a PNG, and should"},
8987 {2, " be given the \".mng\" file extension. The"},
8988 {2, " \"loco\" option has no effect on grayscale or"},
8989 {2, " indexed-color PNG files."},
8990 {2, ""},
8991 #endif
8992
8993 {0, " -m method [1 through " STRNGIFY(MAX_METHODS) "]"},
8994 {2, ""},
8995 {2, " pngcrush method to try. Can be repeated as in"},
8996 {2, " '-m 1 -m 4 -m 7'. This can be useful if pngcrush"},
8997 {2, " runs out of memory when it tries methods 2, 3, 5,"},
8998 {2, " 6, 8, 9, or 10 which use filtering and are memory-"},
8999 {2, " intensive. Methods 1, 4, and 7 use no filtering;"},
9000 {2, " methods 11 and up use a specified filter,"},
9001 {2, " compression level, and strategy."},
9002 {2, ""},
9003 {2, FAKE_PAUSE_STRING},
9004
9005 {0, " -max maximum_IDAT_size [default "STRNGIFY(MAX_IDAT_SIZE)"]"},
9006 {2, ""},
9007
9008 #ifdef PNGCRUSH_LOCO
9009 {0, " -mng (write a new MNG, do not crush embedded PNGs)"},
9010 {2, ""},
9011 #endif
9012
9013 {0, " -n (no save; doesn't do compression or write output PNG)"},
9014 {2, ""},
9015 {2, " Useful in conjunction with -v option to get info."},
9016 {2, ""},
9017
9018 {0, " -new (Use new default settings (-reduce))"},
9019 {2, ""},
9020
9021 {0, " -newtimestamp (Reset file modification time [default])"},
9022 {2, ""},
9023
9024 {0, " -nobail (do not bail out early from trial -- see \"-bail\")"},
9025 {2, ""},
9026 {2, " Use this if you want to get a report of the"},
9027 {2, " exact filesize achieved by each trial."},
9028 {2, ""},
9029
9030 {0, " -nocheck (do not check CRC and ADLER32 checksums)"},
9031 {2, ""},
9032 {2, " Use \"-check\" to check them"},
9033 {2, ""},
9034
9035 {0, FAKE_PAUSE_STRING},
9036
9037 {0, " -nofilecheck (do not check for infile.png == outfile.png)"},
9038 {2, ""},
9039 {2, " To avoid false hits from MSVC-compiled code. Note"},
9040 {2, " that if you use this option, you are responsible for"},
9041 {2, " ensuring that the input file is not the output file."},
9042 {2, ""},
9043
9044 {0, " -noforce (default; do not write output when IDAT is larger)"},
9045 {2, ""},
9046
9047 {0, " -nolimits (turns off limits on width, height, cache, malloc)"},
9048 {2, ""},
9049 {2, " Instead, the user limits are inherited from libpng."},
9050 {2, ""},
9051
9052 {0, " -noreduce (turns off all \"-reduce\" operations)"},
9053 {2, ""},
9054
9055 {0, "-noreduce_palette (turns off \"-reduce_palette\" operation)"},
9056 {2, ""},
9057
9058 {0, " -old (Use old default settings (no -reduce))"},
9059 {2, ""},
9060
9061 {0, " -oldtimestamp (Do not reset file modification time)"},
9062 {2, ""},
9063
9064 {0, " -ow (Overwrite)"},
9065 {2, ""},
9066 {2, " Overwrite the input file. The input file is removed"},
9067 {2, " and the temporary file (default \"pngout.png\")"},
9068 {2, " is renamed to the input file after recompression"},
9069 {2, " and therefore they must reside on the same"},
9070 {2, " filesystem."},
9071 {2, ""},
9072 {2, " CAUTION: If you are running multiple instances"},
9073 {2, " of pngcrush in parallel, you must specify a"},
9074 {2, " different temporary filename for each instance,"},
9075 {2, " to avoid collisions."},
9076 {2, ""},
9077
9078 {0, " -q (quiet) suppresses console output except for warnings"},
9079 {2, ""},
9080 {2, " and summary of results."},
9081 {2, ""},
9082
9083 {0, " -reduce (do lossless color-type or bit-depth reduction)"},
9084 {2, ""},
9085 {2, " (if possible). Also reduces palette length if"},
9086 {2, " possible. Currently only attempts to reduce the"},
9087 {2, " bit depth from 16 to 8. Reduces all-gray RGB"},
9088 {2, " or RGBA image to gray or gray-alpha. Reduces"},
9089 {2, " all-opaque RGBA or GA image to RGB or grayscale."},
9090 {2, " Since pngcrush version 1.8.0, -reduce is on by"},
9091 {2, " default, and you can disable it with -noreduce."},
9092 {2, ""},
9093
9094 {0, " -rem chunkname (or \"alla\" or \"allb\")"},
9095 {2, ""},
9096 {2, " Name of an ancillary chunk or optional PLTE to be"},
9097 {2, " removed. Be careful with this. Don't use this"},
9098 {2, " feature to remove transparency, gamma, copyright,"},
9099 {2, " or other valuable information. To remove several"},
9100 {2, " different chunks, repeat: -rem tEXt -rem pHYs."},
9101 {2, " Known chunks (those in the PNG 1.1 spec or extensions"},
9102 {2, " document) can be named with all lower-case letters,"},
9103 {2, " so \"-rem bkgd\" is equivalent to \"-rem bKGD\". But"},
9104 {2, " note: \"-rem text\" removes all forms of text chunks;"},
9105 {2, " Exact case is required to remove unknown chunks."},
9106 {2, " To do surgery with a chain-saw, \"-rem alla\" removes"},
9107 {2, " all known ancillary chunks except for tRNS, and"},
9108 {2, " \"-rem allb\" removes all but tRNS and gAMA."},
9109 {2, ""},
9110
9111 {0, FAKE_PAUSE_STRING},
9112
9113 #ifdef PNG_FIXED_POINT_SUPPORTED
9114 {0, "-replace_gamma gamma (float or fixed*100000) even if it is present."},
9115 #else
9116 {0, "-replace_gamma gamma (float, e.g. 0.45455) even if it is present."},
9117 #endif
9118 {2, ""},
9119
9120 {0, " -res resolution in dpi"},
9121 {2, ""},
9122 {2, " Write a pHYs chunk with the given resolution in dpi"},
9123 {2, " written as pixels per meter in x and y directions."},
9124 {2, ""},
9125
9126 #ifdef Z_RLE
9127 {0, " -rle (use only zlib strategy 3, RLE-only)"},
9128 {2, ""},
9129 {2, " A relatively fast subset of the \"-brute\" methods,"},
9130 {2, " generally more effective than \"-huffman\" on PNG,"},
9131 {2, " images (and quite effective on black-and-white"},
9132 {2, " images) but not necessarily worth the bother"},
9133 {2, " otherwise."},
9134 {2, ""},
9135 #endif
9136
9137 {0, " -s (silent) suppresses console output including warnings"},
9138 {2, ""},
9139 {2, " benchmark timing, and summary of results."},
9140 {2, " (Use \"-warn\" to show only warnings"},
9141 {2, ""},
9142
9143 {0, " -save (keep all copy-unsafe PNG chunks)"},
9144 {2, ""},
9145 {2, " Save otherwise unknown ancillary chunks that would"},
9146 {2, " be considered copy-unsafe. This option makes"},
9147 {2, " chunks 'known' to pngcrush, so they can be copied."},
9148 {2, " It also causes the dSIG chunk to be saved, even when"},
9149 {2, " it becomes invalid due to datastream changes."},
9150 {2, " This option does not affect APNG chunks. These"},
9151 {2, " chunks (acTL, fcTL, and fdAT) will be saved only"},
9152 {2, " if the output file has the \".apng\" extension"},
9153 {2, " and the color_type and bit_depth are not changed."},
9154 {2, ""},
9155
9156 {0, FAKE_PAUSE_STRING},
9157
9158 {0, " -speed Avoid the AVG and PAETH filters, for decoding speed"},
9159 {2, ""},
9160 {2, " Useful for compressing PNG files that are expected"},
9161 {2, " to be cached or otherwise to exist on the computer"},
9162 {2, " where they will be used rather than being downloaded,"},
9163 {2, " so filesize is therefore less important than CPU"},
9164 {2, " time expended in defiltering."},
9165 {2, ""},
9166
9167 {0, " -srgb [0, 1, 2, or 3]"},
9168 {2, ""},
9169 {2, " Value of 'rendering intent' for sRGB chunk."},
9170 {2, ""},
9171
9172 {0, " -ster [0 or 1]"},
9173 {2, ""},
9174 {2, " Value of 'stereo mode' for sTER chunk."},
9175 {2, " 0: cross-fused; 1: divergent-fused"},
9176 {2, ""},
9177
9178 {0, " -text b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
9179 {2, ""},
9180 {2, " tEXt chunk to insert. keyword < 80 chars,"},
9181 {2, " text < 2048 chars. For now, you can add no more than"},
9182 {2, " ten tEXt, iTXt, or zTXt chunks per pngcrush run."},
9183 {2, ""},
9184
9185 #ifdef PNG_tRNS_SUPPORTED
9186 {0, " -trns_array n trns[0] trns[1] .. trns[n-1]"},
9187 {2, ""},
9188 {2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
9189 {2, " Values are for the tRNS array in indexed-color PNG."},
9190 {2, ""},
9191
9192 {0, " -trns index red green blue gray"},
9193 {2, ""},
9194 {2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
9195 {2, " You must give all five parameters regardless of the"},
9196 {2, " color type, scaled to the output bit depth."},
9197 {2, ""},
9198 #endif
9199
9200 {0, FAKE_PAUSE_STRING},
9201
9202 {0, " -v (display more detailed information)"},
9203 {2, ""},
9204 {2, " Repeat the option (use \"-v -v\") for even more."},
9205 {2, ""},
9206
9207 {0, " -version (display the pngcrush version)"},
9208 {2, ""},
9209 {2, " Look for the most recent version of pngcrush at"},
9210 {2, " http://pmt.sf.net"},
9211 {2, ""},
9212
9213 {0, " -warn (only show warnings)"},
9214 {2, ""},
9215
9216 {0, " -w compression_window_size [32, 16, 8, 4, 2, 1, 512]"},
9217 {2, ""},
9218 {2, " Size of the sliding compression window, in kbytes"},
9219 {2, " (or bytes, in case of 512). It's best to"},
9220 {2, " use the default (32) unless you run out of memory."},
9221 {2, " The program will use a smaller window anyway when"},
9222 {2, " the uncompressed file is smaller than 16k."},
9223 {2, ""},
9224
9225 #ifdef Z_RLE
9226 {0, " -z zlib_strategy [0, 1, 2, or 3] for specified method"},
9227 #else
9228 {0, " -z zlib_strategy [0, 1, or 2] for specified method"},
9229 #endif
9230 {2, ""},
9231 {2, " zlib compression strategy to use with the preceding"},
9232 {2, " '-m method' argument."},
9233 {2, ""},
9234
9235 {0, " -zmem zlib_compression_mem_level [1-9, default 9]"},
9236 {2, ""},
9237
9238 #ifdef PNG_iTXt_SUPPORTED
9239 {0, " -zitxt b|a \"keyword\" \"lcode\" \"tkey\" \"text\""},
9240 {2, ""},
9241 {2, " (where \"lcode\"==language_code and"},
9242 {2, " \"tkey\"==translated_keyword)\""},
9243 {2, " Compressed iTXt chunk to insert (see -text)."},
9244 {2, ""},
9245 #endif
9246
9247 {0, " -ztxt b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
9248 {2, ""},
9249 {2, " zTXt chunk to insert (see -text)."},
9250 {2, ""},
9251 {2, FAKE_PAUSE_STRING},
9252
9253 {0, " -h (help and legal notices)"},
9254 {2, ""},
9255 {2, " Display this information."},
9256 {2, ""},
9257
9258 {0, " -p (pause)"}
9259 };
9260
9261
9262
9263
9264
9265 void print_usage(int retval)
9266 {
9267 int j, jmax;
9268
9269 if (verbose > 0)
9270 {
9271 jmax = sizeof(pngcrush_legal) / sizeof(char *);
9272 for (j = 0; j < jmax; ++j)
9273 fprintf(STDERR, "%s\n", pngcrush_legal[j]);
9274
9275 jmax = sizeof(pngcrush_usage) / sizeof(char *);
9276 for (j = 0; j < jmax; ++j)
9277 fprintf(STDERR, pngcrush_usage[j], progname); /* special case */
9278 }
9279
9280 /* This block is also handled specially due to the "else" clause... */
9281 if (verbose > 1)
9282 {
9283 pngcrush_pause();
9284 fprintf(STDERR,
9285 "\n"
9286 "options (Note: any option can be spelled out for clarity, e.g.,\n"
9287 " \"pngcrush -dir New -method 7 -remove bkgd *.png\"\n"
9288 " is the same as \"pngcrush -d New/ -m 7 -rem bkgd *.png\"):"
9289 "\n\n");
9290 }
9291 else
9292 fprintf(STDERR, "options:\n");
9293
9294 /* This is the main part of the help screen; it is more complex than the
9295 * other blocks due to the mix of verbose and non-verbose lines
9296 */
9297 jmax = sizeof(pngcrush_options) / sizeof(struct options_help);
9298 for (j = 0; j < jmax; ++j)
9299 {
9300 if (verbose >= pngcrush_options[j].verbosity)
9301 {
9302 if (pngcrush_options[j].textline[0] == FAKE_PAUSE_STRING[0])
9303 pngcrush_pause();
9304 else
9305 fprintf(STDERR, "%s\n", pngcrush_options[j].textline);
9306 }
9307 }
9308
9309 /* due to progname, the verbose part of the -p option is handled explicitly
9310 * (fortunately, it's the very last option anyway)
9311 */
9312 if (verbose > 1)
9313 {
9314 fprintf(STDERR, "\n"
9315 " Wait for [enter] key before continuing display.\n"
9316 " e.g., type '%s -pause -help', if the help\n"
9317 " screen scrolls out of sight.\n\n", progname);
9318 }
9319
9320 exit(retval);
9321 }
9322
9323 #endif /* PNGCRUSH_LIBPNG_VER < 10800 || defined(PNGCRUSH_H) */