PageRenderTime 91ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 1ms

/lib_png/base/libpng-1.6.16/contrib/libtests/pngvalid.c

https://bitbucket.org/xixs/lua
C | 10595 lines | 7015 code | 1570 blank | 2010 comment | 1600 complexity | e1d608dbe15242bcd4d13bdfda584db7 MD5 | raw file
Possible License(s): Zlib, BSD-3-Clause, CC0-1.0, GPL-3.0, GPL-2.0, CPL-1.0, MPL-2.0-no-copyleft-exception, LGPL-2.0, LGPL-2.1, LGPL-3.0, 0BSD, Cube
  1. /* pngvalid.c - validate libpng by constructing then reading png files.
  2. *
  3. * Last changed in libpng 1.6.14 [October 23, 2014]
  4. * Copyright (c) 2014 Glenn Randers-Pehrson
  5. * Written by John Cunningham Bowler
  6. *
  7. * This code is released under the libpng license.
  8. * For conditions of distribution and use, see the disclaimer
  9. * and license in png.h
  10. *
  11. * NOTES:
  12. * This is a C program that is intended to be linked against libpng. It
  13. * generates bitmaps internally, stores them as PNG files (using the
  14. * sequential write code) then reads them back (using the sequential
  15. * read code) and validates that the result has the correct data.
  16. *
  17. * The program can be modified and extended to test the correctness of
  18. * transformations performed by libpng.
  19. */
  20. #define _POSIX_SOURCE 1
  21. #define _ISOC99_SOURCE 1 /* For floating point */
  22. #define _GNU_SOURCE 1 /* For the floating point exception extension */
  23. #include <signal.h>
  24. #include <stdio.h>
  25. #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
  26. # include <config.h>
  27. #endif
  28. #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
  29. # include <fenv.h>
  30. #endif
  31. #ifndef FE_DIVBYZERO
  32. # define FE_DIVBYZERO 0
  33. #endif
  34. #ifndef FE_INVALID
  35. # define FE_INVALID 0
  36. #endif
  37. #ifndef FE_OVERFLOW
  38. # define FE_OVERFLOW 0
  39. #endif
  40. /* Define the following to use this test against your installed libpng, rather
  41. * than the one being built here:
  42. */
  43. #ifdef PNG_FREESTANDING_TESTS
  44. # include <png.h>
  45. #else
  46. # include "../../png.h"
  47. #endif
  48. #ifdef PNG_ZLIB_HEADER
  49. # include PNG_ZLIB_HEADER
  50. #else
  51. # include <zlib.h> /* For crc32 */
  52. #endif
  53. /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
  54. * a skipped test, in earlier versions we need to succeed on a skipped test, so:
  55. */
  56. #if PNG_LIBPNG_VER < 10601
  57. # define SKIP 0
  58. #else
  59. # define SKIP 77
  60. #endif
  61. /* pngvalid requires write support and one of the fixed or floating point APIs.
  62. */
  63. #if defined(PNG_WRITE_SUPPORTED) &&\
  64. (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED))
  65. #if PNG_LIBPNG_VER < 10500
  66. /* This deliberately lacks the PNG_CONST. */
  67. typedef png_byte *png_const_bytep;
  68. /* This is copied from 1.5.1 png.h: */
  69. #define PNG_INTERLACE_ADAM7_PASSES 7
  70. #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
  71. #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
  72. #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
  73. #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
  74. #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
  75. -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
  76. #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
  77. -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
  78. #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
  79. (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
  80. #define PNG_COL_FROM_PASS_COL(xIn, pass) \
  81. (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
  82. #define PNG_PASS_MASK(pass,off) ( \
  83. ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
  84. ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
  85. #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
  86. ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
  87. #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
  88. ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
  89. /* These are needed too for the default build: */
  90. #define PNG_WRITE_16BIT_SUPPORTED
  91. #define PNG_READ_16BIT_SUPPORTED
  92. /* This comes from pnglibconf.h afer 1.5: */
  93. #define PNG_FP_1 100000
  94. #define PNG_GAMMA_THRESHOLD_FIXED\
  95. ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
  96. #endif
  97. #if PNG_LIBPNG_VER < 10600
  98. /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
  99. * compiled against earlier versions.
  100. */
  101. # define png_const_structp png_structp
  102. #endif
  103. #include <float.h> /* For floating point constants */
  104. #include <stdlib.h> /* For malloc */
  105. #include <string.h> /* For memcpy, memset */
  106. #include <math.h> /* For floor */
  107. /* Unused formal parameter errors are removed using the following macro which is
  108. * expected to have no bad effects on performance.
  109. */
  110. #ifndef UNUSED
  111. # if defined(__GNUC__) || defined(_MSC_VER)
  112. # define UNUSED(param) (void)param;
  113. # else
  114. # define UNUSED(param)
  115. # endif
  116. #endif
  117. /***************************** EXCEPTION HANDLING *****************************/
  118. #ifdef PNG_FREESTANDING_TESTS
  119. # include <cexcept.h>
  120. #else
  121. # include "../visupng/cexcept.h"
  122. #endif
  123. #ifdef __cplusplus
  124. # define this not_the_cpp_this
  125. # define new not_the_cpp_new
  126. # define voidcast(type, value) static_cast<type>(value)
  127. #else
  128. # define voidcast(type, value) (value)
  129. #endif /* __cplusplus */
  130. struct png_store;
  131. define_exception_type(struct png_store*);
  132. /* The following are macros to reduce typing everywhere where the well known
  133. * name 'the_exception_context' must be defined.
  134. */
  135. #define anon_context(ps) struct exception_context *the_exception_context = \
  136. &(ps)->exception_context
  137. #define context(ps,fault) anon_context(ps); png_store *fault
  138. /* This macro returns the number of elements in an array as an (unsigned int),
  139. * it is necessary to avoid the inability of certain versions of GCC to use
  140. * the value of a compile-time constant when performing range checks. It must
  141. * be passed an array name.
  142. */
  143. #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
  144. /******************************* UTILITIES ************************************/
  145. /* Error handling is particularly problematic in production code - error
  146. * handlers often themselves have bugs which lead to programs that detect
  147. * minor errors crashing. The following functions deal with one very
  148. * common class of errors in error handlers - attempting to format error or
  149. * warning messages into buffers that are too small.
  150. */
  151. static size_t safecat(char *buffer, size_t bufsize, size_t pos,
  152. PNG_CONST char *cat)
  153. {
  154. while (pos < bufsize && cat != NULL && *cat != 0)
  155. buffer[pos++] = *cat++;
  156. if (pos >= bufsize)
  157. pos = bufsize-1;
  158. buffer[pos] = 0;
  159. return pos;
  160. }
  161. static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
  162. {
  163. char number[64];
  164. sprintf(number, "%d", n);
  165. return safecat(buffer, bufsize, pos, number);
  166. }
  167. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  168. static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
  169. int precision)
  170. {
  171. char number[64];
  172. sprintf(number, "%.*f", precision, d);
  173. return safecat(buffer, bufsize, pos, number);
  174. }
  175. #endif
  176. static PNG_CONST char invalid[] = "invalid";
  177. static PNG_CONST char sep[] = ": ";
  178. static PNG_CONST char *colour_types[8] =
  179. {
  180. "grayscale", invalid, "truecolour", "indexed-colour",
  181. "grayscale with alpha", invalid, "truecolour with alpha", invalid
  182. };
  183. #ifdef PNG_READ_SUPPORTED
  184. /* Convert a double precision value to fixed point. */
  185. static png_fixed_point
  186. fix(double d)
  187. {
  188. d = floor(d * PNG_FP_1 + .5);
  189. return (png_fixed_point)d;
  190. }
  191. #endif /* PNG_READ_SUPPORTED */
  192. /* Generate random bytes. This uses a boring repeatable algorithm and it
  193. * is implemented here so that it gives the same set of numbers on every
  194. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  195. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  196. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  197. * Generation.)
  198. */
  199. static void
  200. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  201. {
  202. png_uint_32 u0 = seed[0], u1 = seed[1];
  203. png_bytep bytes = voidcast(png_bytep, pv);
  204. /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
  205. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  206. */
  207. size_t i;
  208. for (i=0; i<size; ++i)
  209. {
  210. /* First generate 8 new bits then shift them in at the end. */
  211. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  212. u1 <<= 8;
  213. u1 |= u0 >> 24;
  214. u0 <<= 8;
  215. u0 |= u;
  216. *bytes++ = (png_byte)u;
  217. }
  218. seed[0] = u0;
  219. seed[1] = u1;
  220. }
  221. static void
  222. make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
  223. {
  224. make_random_bytes(seed, bytes, 4);
  225. }
  226. #ifdef PNG_READ_SUPPORTED
  227. static void
  228. randomize(void *pv, size_t size)
  229. {
  230. static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
  231. make_random_bytes(random_seed, pv, size);
  232. }
  233. #define RANDOMIZE(this) randomize(&(this), sizeof (this))
  234. static unsigned int
  235. random_mod(unsigned int max)
  236. {
  237. unsigned int x;
  238. RANDOMIZE(x);
  239. return x % max; /* 0 .. max-1 */
  240. }
  241. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  242. static int
  243. random_choice(void)
  244. {
  245. unsigned char x;
  246. RANDOMIZE(x);
  247. return x & 1;
  248. }
  249. #endif
  250. #endif /* PNG_READ_SUPPORTED */
  251. /* A numeric ID based on PNG file characteristics. The 'do_interlace' field
  252. * simply records whether pngvalid did the interlace itself or whether it
  253. * was done by libpng. Width and height must be less than 256. 'palette' is an
  254. * index of the palette to use for formats with a palette (0 otherwise.)
  255. */
  256. #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
  257. ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
  258. (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
  259. #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
  260. #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
  261. #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
  262. #define INTERLACE_FROM_ID(id) ((int)(((id) >> 13) & 0x3))
  263. #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
  264. #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
  265. #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
  266. /* Utility to construct a standard name for a standard image. */
  267. static size_t
  268. standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
  269. int bit_depth, unsigned int npalette, int interlace_type,
  270. png_uint_32 w, png_uint_32 h, int do_interlace)
  271. {
  272. pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
  273. if (npalette > 0)
  274. {
  275. pos = safecat(buffer, bufsize, pos, "[");
  276. pos = safecatn(buffer, bufsize, pos, npalette);
  277. pos = safecat(buffer, bufsize, pos, "]");
  278. }
  279. pos = safecat(buffer, bufsize, pos, " ");
  280. pos = safecatn(buffer, bufsize, pos, bit_depth);
  281. pos = safecat(buffer, bufsize, pos, " bit");
  282. if (interlace_type != PNG_INTERLACE_NONE)
  283. {
  284. pos = safecat(buffer, bufsize, pos, " interlaced");
  285. if (do_interlace)
  286. pos = safecat(buffer, bufsize, pos, "(pngvalid)");
  287. else
  288. pos = safecat(buffer, bufsize, pos, "(libpng)");
  289. }
  290. if (w > 0 || h > 0)
  291. {
  292. pos = safecat(buffer, bufsize, pos, " ");
  293. pos = safecatn(buffer, bufsize, pos, w);
  294. pos = safecat(buffer, bufsize, pos, "x");
  295. pos = safecatn(buffer, bufsize, pos, h);
  296. }
  297. return pos;
  298. }
  299. static size_t
  300. standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
  301. {
  302. return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
  303. DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
  304. WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
  305. }
  306. /* Convenience API and defines to list valid formats. Note that 16 bit read and
  307. * write support is required to do 16 bit read tests (we must be able to make a
  308. * 16 bit image to test!)
  309. */
  310. #ifdef PNG_WRITE_16BIT_SUPPORTED
  311. # define WRITE_BDHI 4
  312. # ifdef PNG_READ_16BIT_SUPPORTED
  313. # define READ_BDHI 4
  314. # define DO_16BIT
  315. # endif
  316. #else
  317. # define WRITE_BDHI 3
  318. #endif
  319. #ifndef DO_16BIT
  320. # define READ_BDHI 3
  321. #endif
  322. /* The following defines the number of different palettes to generate for
  323. * each log bit depth of a colour type 3 standard image.
  324. */
  325. #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
  326. static int
  327. next_format(png_bytep colour_type, png_bytep bit_depth,
  328. unsigned int* palette_number, int no_low_depth_gray)
  329. {
  330. if (*bit_depth == 0)
  331. {
  332. *colour_type = 0;
  333. if (no_low_depth_gray)
  334. *bit_depth = 8;
  335. else
  336. *bit_depth = 1;
  337. *palette_number = 0;
  338. return 1;
  339. }
  340. if (*colour_type == 3)
  341. {
  342. /* Add multiple palettes for colour type 3. */
  343. if (++*palette_number < PALETTE_COUNT(*bit_depth))
  344. return 1;
  345. *palette_number = 0;
  346. }
  347. *bit_depth = (png_byte)(*bit_depth << 1);
  348. /* Palette images are restricted to 8 bit depth */
  349. if (*bit_depth <= 8
  350. #ifdef DO_16BIT
  351. || (*colour_type != 3 && *bit_depth <= 16)
  352. #endif
  353. )
  354. return 1;
  355. /* Move to the next color type, or return 0 at the end. */
  356. switch (*colour_type)
  357. {
  358. case 0:
  359. *colour_type = 2;
  360. *bit_depth = 8;
  361. return 1;
  362. case 2:
  363. *colour_type = 3;
  364. *bit_depth = 1;
  365. return 1;
  366. case 3:
  367. *colour_type = 4;
  368. *bit_depth = 8;
  369. return 1;
  370. case 4:
  371. *colour_type = 6;
  372. *bit_depth = 8;
  373. return 1;
  374. default:
  375. return 0;
  376. }
  377. }
  378. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  379. static unsigned int
  380. sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
  381. png_uint_32 x, unsigned int sample_index)
  382. {
  383. png_uint_32 bit_index, result;
  384. /* Find a sample index for the desired sample: */
  385. x *= bit_depth;
  386. bit_index = x;
  387. if ((colour_type & 1) == 0) /* !palette */
  388. {
  389. if (colour_type & 2)
  390. bit_index *= 3;
  391. if (colour_type & 4)
  392. bit_index += x; /* Alpha channel */
  393. /* Multiple channels; select one: */
  394. if (colour_type & (2+4))
  395. bit_index += sample_index * bit_depth;
  396. }
  397. /* Return the sample from the row as an integer. */
  398. row += bit_index >> 3;
  399. result = *row;
  400. if (bit_depth == 8)
  401. return result;
  402. else if (bit_depth > 8)
  403. return (result << 8) + *++row;
  404. /* Less than 8 bits per sample. */
  405. bit_index &= 7;
  406. return (result >> (8-bit_index-bit_depth)) & ((1U<<bit_depth)-1);
  407. }
  408. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  409. /* Copy a single pixel, of a given size, from one buffer to another -
  410. * while this is basically bit addressed there is an implicit assumption
  411. * that pixels 8 or more bits in size are byte aligned and that pixels
  412. * do not otherwise cross byte boundaries. (This is, so far as I know,
  413. * universally true in bitmap computer graphics. [JCB 20101212])
  414. *
  415. * NOTE: The to and from buffers may be the same.
  416. */
  417. static void
  418. pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
  419. png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize)
  420. {
  421. /* Assume we can multiply by 'size' without overflow because we are
  422. * just working in a single buffer.
  423. */
  424. toIndex *= pixelSize;
  425. fromIndex *= pixelSize;
  426. if (pixelSize < 8) /* Sub-byte */
  427. {
  428. /* Mask to select the location of the copied pixel: */
  429. unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7));
  430. /* The following read the entire pixels and clears the extra: */
  431. unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
  432. unsigned int sourceByte = fromBuffer[fromIndex >> 3];
  433. /* Don't rely on << or >> supporting '0' here, just in case: */
  434. fromIndex &= 7;
  435. if (fromIndex > 0) sourceByte <<= fromIndex;
  436. if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
  437. toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
  438. }
  439. else /* One or more bytes */
  440. memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
  441. }
  442. #ifdef PNG_READ_SUPPORTED
  443. /* Copy a complete row of pixels, taking into account potential partial
  444. * bytes at the end.
  445. */
  446. static void
  447. row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth)
  448. {
  449. memcpy(toBuffer, fromBuffer, bitWidth >> 3);
  450. if ((bitWidth & 7) != 0)
  451. {
  452. unsigned int mask;
  453. toBuffer += bitWidth >> 3;
  454. fromBuffer += bitWidth >> 3;
  455. /* The remaining bits are in the top of the byte, the mask is the bits to
  456. * retain.
  457. */
  458. mask = 0xff >> (bitWidth & 7);
  459. *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
  460. }
  461. }
  462. /* Compare pixels - they are assumed to start at the first byte in the
  463. * given buffers.
  464. */
  465. static int
  466. pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
  467. {
  468. #if PNG_LIBPNG_VER < 10506
  469. if (memcmp(pa, pb, bit_width>>3) == 0)
  470. {
  471. png_uint_32 p;
  472. if ((bit_width & 7) == 0) return 0;
  473. /* Ok, any differences? */
  474. p = pa[bit_width >> 3];
  475. p ^= pb[bit_width >> 3];
  476. if (p == 0) return 0;
  477. /* There are, but they may not be significant, remove the bits
  478. * after the end (the low order bits in PNG.)
  479. */
  480. bit_width &= 7;
  481. p >>= 8-bit_width;
  482. if (p == 0) return 0;
  483. }
  484. #else
  485. /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
  486. * bits too:
  487. */
  488. if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
  489. return 0;
  490. #endif
  491. /* Return the index of the changed byte. */
  492. {
  493. png_uint_32 where = 0;
  494. while (pa[where] == pb[where]) ++where;
  495. return 1+where;
  496. }
  497. }
  498. #endif /* PNG_READ_SUPPORTED */
  499. /*************************** BASIC PNG FILE WRITING ***************************/
  500. /* A png_store takes data from the sequential writer or provides data
  501. * to the sequential reader. It can also store the result of a PNG
  502. * write for later retrieval.
  503. */
  504. #define STORE_BUFFER_SIZE 500 /* arbitrary */
  505. typedef struct png_store_buffer
  506. {
  507. struct png_store_buffer* prev; /* NOTE: stored in reverse order */
  508. png_byte buffer[STORE_BUFFER_SIZE];
  509. } png_store_buffer;
  510. #define FILE_NAME_SIZE 64
  511. typedef struct store_palette_entry /* record of a single palette entry */
  512. {
  513. png_byte red;
  514. png_byte green;
  515. png_byte blue;
  516. png_byte alpha;
  517. } store_palette_entry, store_palette[256];
  518. typedef struct png_store_file
  519. {
  520. struct png_store_file* next; /* as many as you like... */
  521. char name[FILE_NAME_SIZE];
  522. png_uint_32 id; /* must be correct (see FILEID) */
  523. png_size_t datacount; /* In this (the last) buffer */
  524. png_store_buffer data; /* Last buffer in file */
  525. int npalette; /* Number of entries in palette */
  526. store_palette_entry* palette; /* May be NULL */
  527. } png_store_file;
  528. /* The following is a pool of memory allocated by a single libpng read or write
  529. * operation.
  530. */
  531. typedef struct store_pool
  532. {
  533. struct png_store *store; /* Back pointer */
  534. struct store_memory *list; /* List of allocated memory */
  535. png_byte mark[4]; /* Before and after data */
  536. /* Statistics for this run. */
  537. png_alloc_size_t max; /* Maximum single allocation */
  538. png_alloc_size_t current; /* Current allocation */
  539. png_alloc_size_t limit; /* Highest current allocation */
  540. png_alloc_size_t total; /* Total allocation */
  541. /* Overall statistics (retained across successive runs). */
  542. png_alloc_size_t max_max;
  543. png_alloc_size_t max_limit;
  544. png_alloc_size_t max_total;
  545. } store_pool;
  546. typedef struct png_store
  547. {
  548. /* For cexcept.h exception handling - simply store one of these;
  549. * the context is a self pointer but it may point to a different
  550. * png_store (in fact it never does in this program.)
  551. */
  552. struct exception_context
  553. exception_context;
  554. unsigned int verbose :1;
  555. unsigned int treat_warnings_as_errors :1;
  556. unsigned int expect_error :1;
  557. unsigned int expect_warning :1;
  558. unsigned int saw_warning :1;
  559. unsigned int speed :1;
  560. unsigned int progressive :1; /* use progressive read */
  561. unsigned int validated :1; /* used as a temporary flag */
  562. int nerrors;
  563. int nwarnings;
  564. int noptions; /* number of options below: */
  565. struct {
  566. unsigned char option; /* option number, 0..30 */
  567. unsigned char setting; /* setting (unset,invalid,on,off) */
  568. } options[16];
  569. char test[128]; /* Name of test */
  570. char error[256];
  571. /* Read fields */
  572. png_structp pread; /* Used to read a saved file */
  573. png_infop piread;
  574. png_store_file* current; /* Set when reading */
  575. png_store_buffer* next; /* Set when reading */
  576. png_size_t readpos; /* Position in *next */
  577. png_byte* image; /* Buffer for reading interlaced images */
  578. png_size_t cb_image; /* Size of this buffer */
  579. png_size_t cb_row; /* Row size of the image(s) */
  580. png_uint_32 image_h; /* Number of rows in a single image */
  581. store_pool read_memory_pool;
  582. /* Write fields */
  583. png_store_file* saved;
  584. png_structp pwrite; /* Used when writing a new file */
  585. png_infop piwrite;
  586. png_size_t writepos; /* Position in .new */
  587. char wname[FILE_NAME_SIZE];
  588. png_store_buffer new; /* The end of the new PNG file being written. */
  589. store_pool write_memory_pool;
  590. store_palette_entry* palette;
  591. int npalette;
  592. } png_store;
  593. /* Initialization and cleanup */
  594. static void
  595. store_pool_mark(png_bytep mark)
  596. {
  597. static png_uint_32 store_seed[2] = { 0x12345678, 1};
  598. make_four_random_bytes(store_seed, mark);
  599. }
  600. #ifdef PNG_READ_SUPPORTED
  601. /* Use this for random 32 bit values; this function makes sure the result is
  602. * non-zero.
  603. */
  604. static png_uint_32
  605. random_32(void)
  606. {
  607. for (;;)
  608. {
  609. png_byte mark[4];
  610. png_uint_32 result;
  611. store_pool_mark(mark);
  612. result = png_get_uint_32(mark);
  613. if (result != 0)
  614. return result;
  615. }
  616. }
  617. #endif /* PNG_READ_SUPPORTED */
  618. static void
  619. store_pool_init(png_store *ps, store_pool *pool)
  620. {
  621. memset(pool, 0, sizeof *pool);
  622. pool->store = ps;
  623. pool->list = NULL;
  624. pool->max = pool->current = pool->limit = pool->total = 0;
  625. pool->max_max = pool->max_limit = pool->max_total = 0;
  626. store_pool_mark(pool->mark);
  627. }
  628. static void
  629. store_init(png_store* ps)
  630. {
  631. memset(ps, 0, sizeof *ps);
  632. init_exception_context(&ps->exception_context);
  633. store_pool_init(ps, &ps->read_memory_pool);
  634. store_pool_init(ps, &ps->write_memory_pool);
  635. ps->verbose = 0;
  636. ps->treat_warnings_as_errors = 0;
  637. ps->expect_error = 0;
  638. ps->expect_warning = 0;
  639. ps->saw_warning = 0;
  640. ps->speed = 0;
  641. ps->progressive = 0;
  642. ps->validated = 0;
  643. ps->nerrors = ps->nwarnings = 0;
  644. ps->pread = NULL;
  645. ps->piread = NULL;
  646. ps->saved = ps->current = NULL;
  647. ps->next = NULL;
  648. ps->readpos = 0;
  649. ps->image = NULL;
  650. ps->cb_image = 0;
  651. ps->cb_row = 0;
  652. ps->image_h = 0;
  653. ps->pwrite = NULL;
  654. ps->piwrite = NULL;
  655. ps->writepos = 0;
  656. ps->new.prev = NULL;
  657. ps->palette = NULL;
  658. ps->npalette = 0;
  659. ps->noptions = 0;
  660. }
  661. static void
  662. store_freebuffer(png_store_buffer* psb)
  663. {
  664. if (psb->prev)
  665. {
  666. store_freebuffer(psb->prev);
  667. free(psb->prev);
  668. psb->prev = NULL;
  669. }
  670. }
  671. static void
  672. store_freenew(png_store *ps)
  673. {
  674. store_freebuffer(&ps->new);
  675. ps->writepos = 0;
  676. if (ps->palette != NULL)
  677. {
  678. free(ps->palette);
  679. ps->palette = NULL;
  680. ps->npalette = 0;
  681. }
  682. }
  683. static void
  684. store_storenew(png_store *ps)
  685. {
  686. png_store_buffer *pb;
  687. if (ps->writepos != STORE_BUFFER_SIZE)
  688. png_error(ps->pwrite, "invalid store call");
  689. pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
  690. if (pb == NULL)
  691. png_error(ps->pwrite, "store new: OOM");
  692. *pb = ps->new;
  693. ps->new.prev = pb;
  694. ps->writepos = 0;
  695. }
  696. static void
  697. store_freefile(png_store_file **ppf)
  698. {
  699. if (*ppf != NULL)
  700. {
  701. store_freefile(&(*ppf)->next);
  702. store_freebuffer(&(*ppf)->data);
  703. (*ppf)->datacount = 0;
  704. if ((*ppf)->palette != NULL)
  705. {
  706. free((*ppf)->palette);
  707. (*ppf)->palette = NULL;
  708. (*ppf)->npalette = 0;
  709. }
  710. free(*ppf);
  711. *ppf = NULL;
  712. }
  713. }
  714. /* Main interface to file storeage, after writing a new PNG file (see the API
  715. * below) call store_storefile to store the result with the given name and id.
  716. */
  717. static void
  718. store_storefile(png_store *ps, png_uint_32 id)
  719. {
  720. png_store_file *pf = voidcast(png_store_file*, malloc(sizeof *pf));
  721. if (pf == NULL)
  722. png_error(ps->pwrite, "storefile: OOM");
  723. safecat(pf->name, sizeof pf->name, 0, ps->wname);
  724. pf->id = id;
  725. pf->data = ps->new;
  726. pf->datacount = ps->writepos;
  727. ps->new.prev = NULL;
  728. ps->writepos = 0;
  729. pf->palette = ps->palette;
  730. pf->npalette = ps->npalette;
  731. ps->palette = 0;
  732. ps->npalette = 0;
  733. /* And save it. */
  734. pf->next = ps->saved;
  735. ps->saved = pf;
  736. }
  737. /* Generate an error message (in the given buffer) */
  738. static size_t
  739. store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
  740. size_t pos, PNG_CONST char *msg)
  741. {
  742. if (pp != NULL && pp == ps->pread)
  743. {
  744. /* Reading a file */
  745. pos = safecat(buffer, bufsize, pos, "read: ");
  746. if (ps->current != NULL)
  747. {
  748. pos = safecat(buffer, bufsize, pos, ps->current->name);
  749. pos = safecat(buffer, bufsize, pos, sep);
  750. }
  751. }
  752. else if (pp != NULL && pp == ps->pwrite)
  753. {
  754. /* Writing a file */
  755. pos = safecat(buffer, bufsize, pos, "write: ");
  756. pos = safecat(buffer, bufsize, pos, ps->wname);
  757. pos = safecat(buffer, bufsize, pos, sep);
  758. }
  759. else
  760. {
  761. /* Neither reading nor writing (or a memory error in struct delete) */
  762. pos = safecat(buffer, bufsize, pos, "pngvalid: ");
  763. }
  764. if (ps->test[0] != 0)
  765. {
  766. pos = safecat(buffer, bufsize, pos, ps->test);
  767. pos = safecat(buffer, bufsize, pos, sep);
  768. }
  769. pos = safecat(buffer, bufsize, pos, msg);
  770. return pos;
  771. }
  772. /* Verbose output to the error stream: */
  773. static void
  774. store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
  775. png_const_charp message)
  776. {
  777. char buffer[512];
  778. if (prefix)
  779. fputs(prefix, stderr);
  780. (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
  781. fputs(buffer, stderr);
  782. fputc('\n', stderr);
  783. }
  784. /* Log an error or warning - the relevant count is always incremented. */
  785. static void
  786. store_log(png_store* ps, png_const_structp pp, png_const_charp message,
  787. int is_error)
  788. {
  789. /* The warning is copied to the error buffer if there are no errors and it is
  790. * the first warning. The error is copied to the error buffer if it is the
  791. * first error (overwriting any prior warnings).
  792. */
  793. if (is_error ? (ps->nerrors)++ == 0 :
  794. (ps->nwarnings)++ == 0 && ps->nerrors == 0)
  795. store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
  796. if (ps->verbose)
  797. store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
  798. }
  799. #ifdef PNG_READ_SUPPORTED
  800. /* Internal error function, called with a png_store but no libpng stuff. */
  801. static void
  802. internal_error(png_store *ps, png_const_charp message)
  803. {
  804. store_log(ps, NULL, message, 1 /* error */);
  805. /* And finally throw an exception. */
  806. {
  807. struct exception_context *the_exception_context = &ps->exception_context;
  808. Throw ps;
  809. }
  810. }
  811. #endif /* PNG_READ_SUPPORTED */
  812. /* Functions to use as PNG callbacks. */
  813. static void PNGCBAPI
  814. store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
  815. {
  816. png_const_structp pp = ppIn;
  817. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  818. if (!ps->expect_error)
  819. store_log(ps, pp, message, 1 /* error */);
  820. /* And finally throw an exception. */
  821. {
  822. struct exception_context *the_exception_context = &ps->exception_context;
  823. Throw ps;
  824. }
  825. }
  826. static void PNGCBAPI
  827. store_warning(png_structp ppIn, png_const_charp message)
  828. {
  829. png_const_structp pp = ppIn;
  830. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  831. if (!ps->expect_warning)
  832. store_log(ps, pp, message, 0 /* warning */);
  833. else
  834. ps->saw_warning = 1;
  835. }
  836. /* These somewhat odd functions are used when reading an image to ensure that
  837. * the buffer is big enough, the png_structp is for errors.
  838. */
  839. /* Return a single row from the correct image. */
  840. static png_bytep
  841. store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
  842. png_uint_32 y)
  843. {
  844. png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
  845. if (ps->image == NULL)
  846. png_error(pp, "no allocated image");
  847. if (coffset + ps->cb_row + 3 > ps->cb_image)
  848. png_error(pp, "image too small");
  849. return ps->image + coffset;
  850. }
  851. static void
  852. store_image_free(png_store *ps, png_const_structp pp)
  853. {
  854. if (ps->image != NULL)
  855. {
  856. png_bytep image = ps->image;
  857. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  858. {
  859. if (pp != NULL)
  860. png_error(pp, "png_store image overwrite (1)");
  861. else
  862. store_log(ps, NULL, "png_store image overwrite (2)", 1);
  863. }
  864. ps->image = NULL;
  865. ps->cb_image = 0;
  866. --image;
  867. free(image);
  868. }
  869. }
  870. static void
  871. store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
  872. png_size_t cbRow, png_uint_32 cRows)
  873. {
  874. png_size_t cb = nImages * cRows * (cbRow + 5);
  875. if (ps->cb_image < cb)
  876. {
  877. png_bytep image;
  878. store_image_free(ps, pp);
  879. /* The buffer is deliberately mis-aligned. */
  880. image = voidcast(png_bytep, malloc(cb+2));
  881. if (image == NULL)
  882. {
  883. /* Called from the startup - ignore the error for the moment. */
  884. if (pp == NULL)
  885. return;
  886. png_error(pp, "OOM allocating image buffer");
  887. }
  888. /* These magic tags are used to detect overwrites above. */
  889. ++image;
  890. image[-1] = 0xed;
  891. image[cb] = 0xfe;
  892. ps->image = image;
  893. ps->cb_image = cb;
  894. }
  895. /* We have an adequate sized image; lay out the rows. There are 2 bytes at
  896. * the start and three at the end of each (this ensures that the row
  897. * alignment starts out odd - 2+1 and changes for larger images on each row.)
  898. */
  899. ps->cb_row = cbRow;
  900. ps->image_h = cRows;
  901. /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
  902. * This deliberately doesn't match the bits in the size test image which are
  903. * outside the image; these are set to 0xff (all 1). To make the row
  904. * comparison work in the 'size' test case the size rows are pre-initialized
  905. * to the same value prior to calling 'standard_row'.
  906. */
  907. memset(ps->image, 178, cb);
  908. /* Then put in the marks. */
  909. while (--nImages >= 0)
  910. {
  911. png_uint_32 y;
  912. for (y=0; y<cRows; ++y)
  913. {
  914. png_bytep row = store_image_row(ps, pp, nImages, y);
  915. /* The markers: */
  916. row[-2] = 190;
  917. row[-1] = 239;
  918. row[cbRow] = 222;
  919. row[cbRow+1] = 173;
  920. row[cbRow+2] = 17;
  921. }
  922. }
  923. }
  924. #ifdef PNG_READ_SUPPORTED
  925. static void
  926. store_image_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage)
  927. {
  928. png_const_bytep image = ps->image;
  929. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  930. png_error(pp, "image overwrite");
  931. else
  932. {
  933. png_size_t cbRow = ps->cb_row;
  934. png_uint_32 rows = ps->image_h;
  935. image += iImage * (cbRow+5) * ps->image_h;
  936. image += 2; /* skip image first row markers */
  937. while (rows-- > 0)
  938. {
  939. if (image[-2] != 190 || image[-1] != 239)
  940. png_error(pp, "row start overwritten");
  941. if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
  942. image[cbRow+2] != 17)
  943. png_error(pp, "row end overwritten");
  944. image += cbRow+5;
  945. }
  946. }
  947. }
  948. #endif /* PNG_READ_SUPPORTED */
  949. static void PNGCBAPI
  950. store_write(png_structp ppIn, png_bytep pb, png_size_t st)
  951. {
  952. png_const_structp pp = ppIn;
  953. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  954. if (ps->pwrite != pp)
  955. png_error(pp, "store state damaged");
  956. while (st > 0)
  957. {
  958. size_t cb;
  959. if (ps->writepos >= STORE_BUFFER_SIZE)
  960. store_storenew(ps);
  961. cb = st;
  962. if (cb > STORE_BUFFER_SIZE - ps->writepos)
  963. cb = STORE_BUFFER_SIZE - ps->writepos;
  964. memcpy(ps->new.buffer + ps->writepos, pb, cb);
  965. pb += cb;
  966. st -= cb;
  967. ps->writepos += cb;
  968. }
  969. }
  970. static void PNGCBAPI
  971. store_flush(png_structp ppIn)
  972. {
  973. UNUSED(ppIn) /*DOES NOTHING*/
  974. }
  975. #ifdef PNG_READ_SUPPORTED
  976. static size_t
  977. store_read_buffer_size(png_store *ps)
  978. {
  979. /* Return the bytes available for read in the current buffer. */
  980. if (ps->next != &ps->current->data)
  981. return STORE_BUFFER_SIZE;
  982. return ps->current->datacount;
  983. }
  984. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  985. /* Return total bytes available for read. */
  986. static size_t
  987. store_read_buffer_avail(png_store *ps)
  988. {
  989. if (ps->current != NULL && ps->next != NULL)
  990. {
  991. png_store_buffer *next = &ps->current->data;
  992. size_t cbAvail = ps->current->datacount;
  993. while (next != ps->next && next != NULL)
  994. {
  995. next = next->prev;
  996. cbAvail += STORE_BUFFER_SIZE;
  997. }
  998. if (next != ps->next)
  999. png_error(ps->pread, "buffer read error");
  1000. if (cbAvail > ps->readpos)
  1001. return cbAvail - ps->readpos;
  1002. }
  1003. return 0;
  1004. }
  1005. #endif
  1006. static int
  1007. store_read_buffer_next(png_store *ps)
  1008. {
  1009. png_store_buffer *pbOld = ps->next;
  1010. png_store_buffer *pbNew = &ps->current->data;
  1011. if (pbOld != pbNew)
  1012. {
  1013. while (pbNew != NULL && pbNew->prev != pbOld)
  1014. pbNew = pbNew->prev;
  1015. if (pbNew != NULL)
  1016. {
  1017. ps->next = pbNew;
  1018. ps->readpos = 0;
  1019. return 1;
  1020. }
  1021. png_error(ps->pread, "buffer lost");
  1022. }
  1023. return 0; /* EOF or error */
  1024. }
  1025. /* Need separate implementation and callback to allow use of the same code
  1026. * during progressive read, where the io_ptr is set internally by libpng.
  1027. */
  1028. static void
  1029. store_read_imp(png_store *ps, png_bytep pb, png_size_t st)
  1030. {
  1031. if (ps->current == NULL || ps->next == NULL)
  1032. png_error(ps->pread, "store state damaged");
  1033. while (st > 0)
  1034. {
  1035. size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
  1036. if (cbAvail > 0)
  1037. {
  1038. if (cbAvail > st) cbAvail = st;
  1039. memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
  1040. st -= cbAvail;
  1041. pb += cbAvail;
  1042. ps->readpos += cbAvail;
  1043. }
  1044. else if (!store_read_buffer_next(ps))
  1045. png_error(ps->pread, "read beyond end of file");
  1046. }
  1047. }
  1048. static void PNGCBAPI
  1049. store_read(png_structp ppIn, png_bytep pb, png_size_t st)
  1050. {
  1051. png_const_structp pp = ppIn;
  1052. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1053. if (ps == NULL || ps->pread != pp)
  1054. png_error(pp, "bad store read call");
  1055. store_read_imp(ps, pb, st);
  1056. }
  1057. static void
  1058. store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
  1059. {
  1060. /* Notice that a call to store_read will cause this function to fail because
  1061. * readpos will be set.
  1062. */
  1063. if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
  1064. png_error(pp, "store state damaged (progressive)");
  1065. do
  1066. {
  1067. if (ps->readpos != 0)
  1068. png_error(pp, "store_read called during progressive read");
  1069. png_process_data(pp, pi, ps->next->buffer, store_read_buffer_size(ps));
  1070. }
  1071. while (store_read_buffer_next(ps));
  1072. }
  1073. #endif /* PNG_READ_SUPPORTED */
  1074. /* The caller must fill this in: */
  1075. static store_palette_entry *
  1076. store_write_palette(png_store *ps, int npalette)
  1077. {
  1078. if (ps->pwrite == NULL)
  1079. store_log(ps, NULL, "attempt to write palette without write stream", 1);
  1080. if (ps->palette != NULL)
  1081. png_error(ps->pwrite, "multiple store_write_palette calls");
  1082. /* This function can only return NULL if called with '0'! */
  1083. if (npalette > 0)
  1084. {
  1085. ps->palette = voidcast(store_palette_entry*, malloc(npalette *
  1086. sizeof *ps->palette));
  1087. if (ps->palette == NULL)
  1088. png_error(ps->pwrite, "store new palette: OOM");
  1089. ps->npalette = npalette;
  1090. }
  1091. return ps->palette;
  1092. }
  1093. #ifdef PNG_READ_SUPPORTED
  1094. static store_palette_entry *
  1095. store_current_palette(png_store *ps, int *npalette)
  1096. {
  1097. /* This is an internal error (the call has been made outside a read
  1098. * operation.)
  1099. */
  1100. if (ps->current == NULL)
  1101. store_log(ps, ps->pread, "no current stream for palette", 1);
  1102. /* The result may be null if there is no palette. */
  1103. *npalette = ps->current->npalette;
  1104. return ps->current->palette;
  1105. }
  1106. #endif /* PNG_READ_SUPPORTED */
  1107. /***************************** MEMORY MANAGEMENT*** ***************************/
  1108. #ifdef PNG_USER_MEM_SUPPORTED
  1109. /* A store_memory is simply the header for an allocated block of memory. The
  1110. * pointer returned to libpng is just after the end of the header block, the
  1111. * allocated memory is followed by a second copy of the 'mark'.
  1112. */
  1113. typedef struct store_memory
  1114. {
  1115. store_pool *pool; /* Originating pool */
  1116. struct store_memory *next; /* Singly linked list */
  1117. png_alloc_size_t size; /* Size of memory allocated */
  1118. png_byte mark[4]; /* ID marker */
  1119. } store_memory;
  1120. /* Handle a fatal error in memory allocation. This calls png_error if the
  1121. * libpng struct is non-NULL, else it outputs a message and returns. This means
  1122. * that a memory problem while libpng is running will abort (png_error) the
  1123. * handling of particular file while one in cleanup (after the destroy of the
  1124. * struct has returned) will simply keep going and free (or attempt to free)
  1125. * all the memory.
  1126. */
  1127. static void
  1128. store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg)
  1129. {
  1130. if (pp != NULL)
  1131. png_error(pp, msg);
  1132. /* Else we have to do it ourselves. png_error eventually calls store_log,
  1133. * above. store_log accepts a NULL png_structp - it just changes what gets
  1134. * output by store_message.
  1135. */
  1136. store_log(ps, pp, msg, 1 /* error */);
  1137. }
  1138. static void
  1139. store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
  1140. {
  1141. /* Note that pp may be NULL (see store_pool_delete below), the caller has
  1142. * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
  1143. * pointer (for sure), but the contents may have been trashed.
  1144. */
  1145. if (memory->pool != pool)
  1146. store_pool_error(pool->store, pp, "memory corrupted (pool)");
  1147. else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
  1148. store_pool_error(pool->store, pp, "memory corrupted (start)");
  1149. /* It should be safe to read the size field now. */
  1150. else
  1151. {
  1152. png_alloc_size_t cb = memory->size;
  1153. if (cb > pool->max)
  1154. store_pool_error(pool->store, pp, "memory corrupted (size)");
  1155. else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
  1156. != 0)
  1157. store_pool_error(pool->store, pp, "memory corrupted (end)");
  1158. /* Finally give the library a chance to find problems too: */
  1159. else
  1160. {
  1161. pool->current -= cb;
  1162. free(memory);
  1163. }
  1164. }
  1165. }
  1166. static void
  1167. store_pool_delete(png_store *ps, store_pool *pool)
  1168. {
  1169. if (pool->list != NULL)
  1170. {
  1171. fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
  1172. pool == &ps->read_memory_pool ? "read" : "write",
  1173. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1174. ps->current->name : "unknown file") : ps->wname);
  1175. ++ps->nerrors;
  1176. do
  1177. {
  1178. store_memory *next = pool->list;
  1179. pool->list = next->next;
  1180. next->next = NULL;
  1181. fprintf(stderr, "\t%lu bytes @ %p\n",
  1182. (unsigned long)next->size, (PNG_CONST void*)(next+1));
  1183. /* The NULL means this will always return, even if the memory is
  1184. * corrupted.
  1185. */
  1186. store_memory_free(NULL, pool, next);
  1187. }
  1188. while (pool->list != NULL);
  1189. }
  1190. /* And reset the other fields too for the next time. */
  1191. if (pool->max > pool->max_max) pool->max_max = pool->max;
  1192. pool->max = 0;
  1193. if (pool->current != 0) /* unexpected internal error */
  1194. fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
  1195. ps->test, pool == &ps->read_memory_pool ? "read" : "write",
  1196. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1197. ps->current->name : "unknown file") : ps->wname);
  1198. pool->current = 0;
  1199. if (pool->limit > pool->max_limit)
  1200. pool->max_limit = pool->limit;
  1201. pool->limit = 0;
  1202. if (pool->total > pool->max_total)
  1203. pool->max_total = pool->total;
  1204. pool->total = 0;
  1205. /* Get a new mark too. */
  1206. store_pool_mark(pool->mark);
  1207. }
  1208. /* The memory callbacks: */
  1209. static png_voidp PNGCBAPI
  1210. store_malloc(png_structp ppIn, png_alloc_size_t cb)
  1211. {
  1212. png_const_structp pp = ppIn;
  1213. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1214. store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
  1215. (sizeof pool->mark)));
  1216. if (new != NULL)
  1217. {
  1218. if (cb > pool->max)
  1219. pool->max = cb;
  1220. pool->current += cb;
  1221. if (pool->current > pool->limit)
  1222. pool->limit = pool->current;
  1223. pool->total += cb;
  1224. new->size = cb;
  1225. memcpy(new->mark, pool->mark, sizeof new->mark);
  1226. memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
  1227. new->pool = pool;
  1228. new->next = pool->list;
  1229. pool->list = new;
  1230. ++new;
  1231. }
  1232. else
  1233. {
  1234. /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
  1235. * other than to retrieve the allocation pointer! libpng calls the
  1236. * store_malloc callback in two basic cases:
  1237. *
  1238. * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
  1239. * returned.
  1240. * 2) From png_struct or png_info structure creation; png_malloc is
  1241. * to return so cleanup can be performed.
  1242. *
  1243. * To handle this store_malloc can log a message, but can't do anything
  1244. * else.
  1245. */
  1246. store_log(pool->store, pp, "out of memory", 1 /* is_error */);
  1247. }
  1248. return new;
  1249. }
  1250. static void PNGCBAPI
  1251. store_free(png_structp ppIn, png_voidp memory)
  1252. {
  1253. png_const_structp pp = ppIn;
  1254. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1255. store_memory *this = voidcast(store_memory*, memory), **test;
  1256. /* Because libpng calls store_free with a dummy png_struct when deleting
  1257. * png_struct or png_info via png_destroy_struct_2 it is necessary to check
  1258. * the passed in png_structp to ensure it is valid, and not pass it to
  1259. * png_error if it is not.
  1260. */
  1261. if (pp != pool->store->pread && pp != pool->store->pwrite)
  1262. pp = NULL;
  1263. /* First check that this 'memory' really is valid memory - it must be in the
  1264. * pool list. If it is, use the shared memory_free function to free it.
  1265. */
  1266. --this;
  1267. for (test = &pool->list; *test != this; test = &(*test)->next)
  1268. {
  1269. if (*test == NULL)
  1270. {
  1271. store_pool_error(pool->store, pp, "bad pointer to free");
  1272. return;
  1273. }
  1274. }
  1275. /* Unlink this entry, *test == this. */
  1276. *test = this->next;
  1277. this->next = NULL;
  1278. store_memory_free(pp, pool, this);
  1279. }
  1280. #endif /* PNG_USER_MEM_SUPPORTED */
  1281. /* Setup functions. */
  1282. /* Cleanup when aborting a write or after storing the new file. */
  1283. static void
  1284. store_write_reset(png_store *ps)
  1285. {
  1286. if (ps->pwrite != NULL)
  1287. {
  1288. anon_context(ps);
  1289. Try
  1290. png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
  1291. Catch_anonymous
  1292. {
  1293. /* memory corruption: continue. */
  1294. }
  1295. ps->pwrite = NULL;
  1296. ps->piwrite = NULL;
  1297. }
  1298. /* And make sure that all the memory has been freed - this will output
  1299. * spurious errors in the case of memory corruption above, but this is safe.
  1300. */
  1301. # ifdef PNG_USER_MEM_SUPPORTED
  1302. store_pool_delete(ps, &ps->write_memory_pool);
  1303. # endif
  1304. store_freenew(ps);
  1305. }
  1306. /* The following is the main write function, it returns a png_struct and,
  1307. * optionally, a png_info suitable for writiing a new PNG file. Use
  1308. * store_storefile above to record this file after it has been written. The
  1309. * returned libpng structures as destroyed by store_write_reset above.
  1310. */
  1311. static png_structp
  1312. set_store_for_write(png_store *ps, png_infopp ppi,
  1313. PNG_CONST char * volatile name)
  1314. {
  1315. anon_context(ps);
  1316. Try
  1317. {
  1318. if (ps->pwrite != NULL)
  1319. png_error(ps->pwrite, "write store already in use");
  1320. store_write_reset(ps);
  1321. safecat(ps->wname, sizeof ps->wname, 0, name);
  1322. /* Don't do the slow memory checks if doing a speed test, also if user
  1323. * memory is not supported we can't do it anyway.
  1324. */
  1325. # ifdef PNG_USER_MEM_SUPPORTED
  1326. if (!ps->speed)
  1327. ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
  1328. ps, store_error, store_warning, &ps->write_memory_pool,
  1329. store_malloc, store_free);
  1330. else
  1331. # endif
  1332. ps->pwrite = png_create_write_struct(png_get_libpng_ver(NULL),
  1333. ps, store_error, store_warning);
  1334. png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
  1335. # ifdef PNG_SET_OPTION_SUPPORTED
  1336. {
  1337. int opt;
  1338. for (opt=0; opt<ps->noptions; ++opt)
  1339. if (png_set_option(ps->pwrite, ps->options[opt].option,
  1340. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1341. png_error(ps->pwrite, "png option invalid");
  1342. }
  1343. # endif
  1344. if (ppi != NULL)
  1345. *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
  1346. }
  1347. Catch_anonymous
  1348. return NULL;
  1349. return ps->pwrite;
  1350. }
  1351. /* Cleanup when finished reading (either due to error or in the success case).
  1352. * This routine exists even when there is no read support to make the code
  1353. * tidier (avoid a mass of ifdefs) and so easier to maintain.
  1354. */
  1355. static void
  1356. store_read_reset(png_store *ps)
  1357. {
  1358. # ifdef PNG_READ_SUPPORTED
  1359. if (ps->pread != NULL)
  1360. {
  1361. anon_context(ps);
  1362. Try
  1363. png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
  1364. Catch_anonymous
  1365. {
  1366. /* error already output: continue */
  1367. }
  1368. ps->pread = NULL;
  1369. ps->piread = NULL;
  1370. }
  1371. # endif
  1372. # ifdef PNG_USER_MEM_SUPPORTED
  1373. /* Always do this to be safe. */
  1374. store_pool_delete(ps, &ps->read_memory_pool);
  1375. # endif
  1376. ps->current = NULL;
  1377. ps->next = NULL;
  1378. ps->readpos = 0;
  1379. ps->validated = 0;
  1380. }
  1381. #ifdef PNG_READ_SUPPORTED
  1382. static void
  1383. store_read_set(png_store *ps, png_uint_32 id)
  1384. {
  1385. png_store_file *pf = ps->saved;
  1386. while (pf != NULL)
  1387. {
  1388. if (pf->id == id)
  1389. {
  1390. ps->current = pf;
  1391. ps->next = NULL;
  1392. store_read_buffer_next(ps);
  1393. return;
  1394. }
  1395. pf = pf->next;
  1396. }
  1397. {
  1398. size_t pos;
  1399. char msg[FILE_NAME_SIZE+64];
  1400. pos = standard_name_from_id(msg, sizeof msg, 0, id);
  1401. pos = safecat(msg, sizeof msg, pos, ": file not found");
  1402. png_error(ps->pread, msg);
  1403. }
  1404. }
  1405. /* The main interface for reading a saved file - pass the id number of the file
  1406. * to retrieve. Ids must be unique or the earlier file will be hidden. The API
  1407. * returns a png_struct and, optionally, a png_info. Both of these will be
  1408. * destroyed by store_read_reset above.
  1409. */
  1410. static png_structp
  1411. set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
  1412. PNG_CONST char *name)
  1413. {
  1414. /* Set the name for png_error */
  1415. safecat(ps->test, sizeof ps->test, 0, name);
  1416. if (ps->pread != NULL)
  1417. png_error(ps->pread, "read store already in use");
  1418. store_read_reset(ps);
  1419. /* Both the create APIs can return NULL if used in their default mode
  1420. * (because there is no other way of handling an error because the jmp_buf
  1421. * by default is stored in png_struct and that has not been allocated!)
  1422. * However, given that store_error works correctly in these circumstances
  1423. * we don't ever expect NULL in this program.
  1424. */
  1425. # ifdef PNG_USER_MEM_SUPPORTED
  1426. if (!ps->speed)
  1427. ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
  1428. store_error, store_warning, &ps->read_memory_pool, store_malloc,
  1429. store_free);
  1430. else
  1431. # endif
  1432. ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
  1433. store_warning);
  1434. if (ps->pread == NULL)
  1435. {
  1436. struct exception_context *the_exception_context = &ps->exception_context;
  1437. store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
  1438. 1 /*error*/);
  1439. Throw ps;
  1440. }
  1441. # ifdef PNG_SET_OPTION_SUPPORTED
  1442. {
  1443. int opt;
  1444. for (opt=0; opt<ps->noptions; ++opt)
  1445. if (png_set_option(ps->pread, ps->options[opt].option,
  1446. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1447. png_error(ps->pread, "png option invalid");
  1448. }
  1449. # endif
  1450. store_read_set(ps, id);
  1451. if (ppi != NULL)
  1452. *ppi = ps->piread = png_create_info_struct(ps->pread);
  1453. return ps->pread;
  1454. }
  1455. #endif /* PNG_READ_SUPPORTED */
  1456. /* The overall cleanup of a store simply calls the above then removes all the
  1457. * saved files. This does not delete the store itself.
  1458. */
  1459. static void
  1460. store_delete(png_store *ps)
  1461. {
  1462. store_write_reset(ps);
  1463. store_read_reset(ps);
  1464. store_freefile(&ps->saved);
  1465. store_image_free(ps, NULL);
  1466. }
  1467. /*********************** PNG FILE MODIFICATION ON READ ************************/
  1468. /* Files may be modified on read. The following structure contains a complete
  1469. * png_store together with extra members to handle modification and a special
  1470. * read callback for libpng. To use this the 'modifications' field must be set
  1471. * to a list of png_modification structures that actually perform the
  1472. * modification, otherwise a png_modifier is functionally equivalent to a
  1473. * png_store. There is a special read function, set_modifier_for_read, which
  1474. * replaces set_store_for_read.
  1475. */
  1476. typedef enum modifier_state
  1477. {
  1478. modifier_start, /* Initial value */
  1479. modifier_signature, /* Have a signature */
  1480. modifier_IHDR /* Have an IHDR */
  1481. } modifier_state;
  1482. typedef struct CIE_color
  1483. {
  1484. /* A single CIE tristimulus value, representing the unique response of a
  1485. * standard observer to a variety of light spectra. The observer recognizes
  1486. * all spectra that produce this response as the same color, therefore this
  1487. * is effectively a description of a color.
  1488. */
  1489. double X, Y, Z;
  1490. } CIE_color;
  1491. typedef struct color_encoding
  1492. {
  1493. /* A description of an (R,G,B) encoding of color (as defined above); this
  1494. * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
  1495. * (0,0,1) plus an encoding value that is used to encode the linear
  1496. * components R, G and B to give the actual values R^gamma, G^gamma and
  1497. * B^gamma that are stored.
  1498. */
  1499. double gamma; /* Encoding (file) gamma of space */
  1500. CIE_color red, green, blue; /* End points */
  1501. } color_encoding;
  1502. #ifdef PNG_READ_SUPPORTED
  1503. static double
  1504. chromaticity_x(CIE_color c)
  1505. {
  1506. return c.X / (c.X + c.Y + c.Z);
  1507. }
  1508. static double
  1509. chromaticity_y(CIE_color c)
  1510. {
  1511. return c.Y / (c.X + c.Y + c.Z);
  1512. }
  1513. static CIE_color
  1514. white_point(PNG_CONST color_encoding *encoding)
  1515. {
  1516. CIE_color white;
  1517. white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
  1518. white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
  1519. white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
  1520. return white;
  1521. }
  1522. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1523. static void
  1524. normalize_color_encoding(color_encoding *encoding)
  1525. {
  1526. PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y +
  1527. encoding->blue.Y;
  1528. if (whiteY != 1)
  1529. {
  1530. encoding->red.X /= whiteY;
  1531. encoding->red.Y /= whiteY;
  1532. encoding->red.Z /= whiteY;
  1533. encoding->green.X /= whiteY;
  1534. encoding->green.Y /= whiteY;
  1535. encoding->green.Z /= whiteY;
  1536. encoding->blue.X /= whiteY;
  1537. encoding->blue.Y /= whiteY;
  1538. encoding->blue.Z /= whiteY;
  1539. }
  1540. }
  1541. #endif
  1542. static size_t
  1543. safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
  1544. PNG_CONST color_encoding *e, double encoding_gamma)
  1545. {
  1546. if (e != 0)
  1547. {
  1548. if (encoding_gamma != 0)
  1549. pos = safecat(buffer, bufsize, pos, "(");
  1550. pos = safecat(buffer, bufsize, pos, "R(");
  1551. pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
  1552. pos = safecat(buffer, bufsize, pos, ",");
  1553. pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
  1554. pos = safecat(buffer, bufsize, pos, ",");
  1555. pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
  1556. pos = safecat(buffer, bufsize, pos, "),G(");
  1557. pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
  1558. pos = safecat(buffer, bufsize, pos, ",");
  1559. pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
  1560. pos = safecat(buffer, bufsize, pos, ",");
  1561. pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
  1562. pos = safecat(buffer, bufsize, pos, "),B(");
  1563. pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
  1564. pos = safecat(buffer, bufsize, pos, ",");
  1565. pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
  1566. pos = safecat(buffer, bufsize, pos, ",");
  1567. pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
  1568. pos = safecat(buffer, bufsize, pos, ")");
  1569. if (encoding_gamma != 0)
  1570. pos = safecat(buffer, bufsize, pos, ")");
  1571. }
  1572. if (encoding_gamma != 0)
  1573. {
  1574. pos = safecat(buffer, bufsize, pos, "^");
  1575. pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
  1576. }
  1577. return pos;
  1578. }
  1579. #endif /* PNG_READ_SUPPORTED */
  1580. typedef struct png_modifier
  1581. {
  1582. png_store this; /* I am a png_store */
  1583. struct png_modification *modifications; /* Changes to make */
  1584. modifier_state state; /* My state */
  1585. /* Information from IHDR: */
  1586. png_byte bit_depth; /* From IHDR */
  1587. png_byte colour_type; /* From IHDR */
  1588. /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
  1589. * other chunks to be inserted.
  1590. */
  1591. png_uint_32 pending_len;
  1592. png_uint_32 pending_chunk;
  1593. /* Test values */
  1594. double *gammas;
  1595. unsigned int ngammas;
  1596. unsigned int ngamma_tests; /* Number of gamma tests to run*/
  1597. double current_gamma; /* 0 if not set */
  1598. PNG_CONST color_encoding *encodings;
  1599. unsigned int nencodings;
  1600. PNG_CONST color_encoding *current_encoding; /* If an encoding has been set */
  1601. unsigned int encoding_counter; /* For iteration */
  1602. int encoding_ignored; /* Something overwrote it */
  1603. /* Control variables used to iterate through possible encodings, the
  1604. * following must be set to 0 and tested by the function that uses the
  1605. * png_modifier because the modifier only sets it to 1 (true.)
  1606. */
  1607. unsigned int repeat :1; /* Repeat this transform test. */
  1608. unsigned int test_uses_encoding :1;
  1609. /* Lowest sbit to test (libpng fails for sbit < 8) */
  1610. png_byte sbitlow;
  1611. /* Error control - these are the limits on errors accepted by the gamma tests
  1612. * below.
  1613. */
  1614. double maxout8; /* Maximum output value error */
  1615. double maxabs8; /* Absolute sample error 0..1 */
  1616. double maxcalc8; /* Absolute sample error 0..1 */
  1617. double maxpc8; /* Percentage sample error 0..100% */
  1618. double maxout16; /* Maximum output value error */
  1619. double maxabs16; /* Absolute sample error 0..1 */
  1620. double maxcalc16;/* Absolute sample error 0..1 */
  1621. double maxcalcG; /* Absolute sample error 0..1 */
  1622. double maxpc16; /* Percentage sample error 0..100% */
  1623. /* This is set by transforms that need to allow a higher limit, it is an
  1624. * internal check on pngvalid to ensure that the calculated error limits are
  1625. * not ridiculous; without this it is too easy to make a mistake in pngvalid
  1626. * that allows any value through.
  1627. */
  1628. double limit; /* limit on error values, normally 4E-3 */
  1629. /* Log limits - values above this are logged, but not necessarily
  1630. * warned.
  1631. */
  1632. double log8; /* Absolute error in 8 bits to log */
  1633. double log16; /* Absolute error in 16 bits to log */
  1634. /* Logged 8 and 16 bit errors ('output' values): */
  1635. double error_gray_2;
  1636. double error_gray_4;
  1637. double error_gray_8;
  1638. double error_gray_16;
  1639. double error_color_8;
  1640. double error_color_16;
  1641. double error_indexed;
  1642. /* Flags: */
  1643. /* Whether to call png_read_update_info, not png_read_start_image, and how
  1644. * many times to call it.
  1645. */
  1646. int use_update_info;
  1647. /* Whether or not to interlace. */
  1648. int interlace_type :9; /* int, but must store '1' */
  1649. /* Run the standard tests? */
  1650. unsigned int test_standard :1;
  1651. /* Run the odd-sized image and interlace read/write tests? */
  1652. unsigned int test_size :1;
  1653. /* Run tests on reading with a combination of transforms, */
  1654. unsigned int test_transform :1;
  1655. /* When to use the use_input_precision option, this controls the gamma
  1656. * validation code checks. If set any value that is within the transformed
  1657. * range input-.5 to input+.5 will be accepted, otherwise the value must be
  1658. * within the normal limits. It should not be necessary to set this; the
  1659. * result should always be exact within the permitted error limits.
  1660. */
  1661. unsigned int use_input_precision :1;
  1662. unsigned int use_input_precision_sbit :1;
  1663. unsigned int use_input_precision_16to8 :1;
  1664. /* If set assume that the calculation bit depth is set by the input
  1665. * precision, not the output precision.
  1666. */
  1667. unsigned int calculations_use_input_precision :1;
  1668. /* If set assume that the calculations are done in 16 bits even if the sample
  1669. * depth is 8 bits.
  1670. */
  1671. unsigned int assume_16_bit_calculations :1;
  1672. /* Which gamma tests to run: */
  1673. unsigned int test_gamma_threshold :1;
  1674. unsigned int test_gamma_transform :1; /* main tests */
  1675. unsigned int test_gamma_sbit :1;
  1676. unsigned int test_gamma_scale16 :1;
  1677. unsigned int test_gamma_background :1;
  1678. unsigned int test_gamma_alpha_mode :1;
  1679. unsigned int test_gamma_expand16 :1;
  1680. unsigned int test_exhaustive :1;
  1681. unsigned int log :1; /* Log max error */
  1682. /* Buffer information, the buffer size limits the size of the chunks that can
  1683. * be modified - they must fit (including header and CRC) into the buffer!
  1684. */
  1685. size_t flush; /* Count of bytes to flush */
  1686. size_t buffer_count; /* Bytes in buffer */
  1687. size_t buffer_position; /* Position in buffer */
  1688. png_byte buffer[1024];
  1689. } png_modifier;
  1690. /* This returns true if the test should be stopped now because it has already
  1691. * failed and it is running silently.
  1692. */
  1693. static int fail(png_modifier *pm)
  1694. {
  1695. return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
  1696. (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
  1697. }
  1698. static void
  1699. modifier_init(png_modifier *pm)
  1700. {
  1701. memset(pm, 0, sizeof *pm);
  1702. store_init(&pm->this);
  1703. pm->modifications = NULL;
  1704. pm->state = modifier_start;
  1705. pm->sbitlow = 1U;
  1706. pm->ngammas = 0;
  1707. pm->ngamma_tests = 0;
  1708. pm->gammas = 0;
  1709. pm->current_gamma = 0;
  1710. pm->encodings = 0;
  1711. pm->nencodings = 0;
  1712. pm->current_encoding = 0;
  1713. pm->encoding_counter = 0;
  1714. pm->encoding_ignored = 0;
  1715. pm->repeat = 0;
  1716. pm->test_uses_encoding = 0;
  1717. pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
  1718. pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
  1719. pm->maxcalcG = 0;
  1720. pm->limit = 4E-3;
  1721. pm->log8 = pm->log16 = 0; /* Means 'off' */
  1722. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
  1723. pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
  1724. pm->error_indexed = 0;
  1725. pm->use_update_info = 0;
  1726. pm->interlace_type = PNG_INTERLACE_NONE;
  1727. pm->test_standard = 0;
  1728. pm->test_size = 0;
  1729. pm->test_transform = 0;
  1730. pm->use_input_precision = 0;
  1731. pm->use_input_precision_sbit = 0;
  1732. pm->use_input_precision_16to8 = 0;
  1733. pm->calculations_use_input_precision = 0;
  1734. pm->assume_16_bit_calculations = 0;
  1735. pm->test_gamma_threshold = 0;
  1736. pm->test_gamma_transform = 0;
  1737. pm->test_gamma_sbit = 0;
  1738. pm->test_gamma_scale16 = 0;
  1739. pm->test_gamma_background = 0;
  1740. pm->test_gamma_alpha_mode = 0;
  1741. pm->test_gamma_expand16 = 0;
  1742. pm->test_exhaustive = 0;
  1743. pm->log = 0;
  1744. /* Rely on the memset for all the other fields - there are no pointers */
  1745. }
  1746. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1747. /* This controls use of checks that explicitly know how libpng digitizes the
  1748. * samples in calculations; setting this circumvents simple error limit checking
  1749. * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
  1750. * algorithm.
  1751. */
  1752. #define DIGITIZE PNG_LIBPNG_VER < 10700
  1753. /* If pm->calculations_use_input_precision is set then operations will happen
  1754. * with the precision of the input, not the precision of the output depth.
  1755. *
  1756. * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
  1757. * bit precision. This only affects those of the following limits that pertain
  1758. * to a calculation - not a digitization operation - unless the following API is
  1759. * called directly.
  1760. */
  1761. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1762. #if DIGITIZE
  1763. static double digitize(double value, int depth, int do_round)
  1764. {
  1765. /* 'value' is in the range 0 to 1, the result is the same value rounded to a
  1766. * multiple of the digitization factor - 8 or 16 bits depending on both the
  1767. * sample depth and the 'assume' setting. Digitization is normally by
  1768. * rounding and 'do_round' should be 1, if it is 0 the digitized value will
  1769. * be truncated.
  1770. */
  1771. PNG_CONST unsigned int digitization_factor = (1U << depth) -1;
  1772. /* Limiting the range is done as a convenience to the caller - it's easier to
  1773. * do it once here than every time at the call site.
  1774. */
  1775. if (value <= 0)
  1776. value = 0;
  1777. else if (value >= 1)
  1778. value = 1;
  1779. value *= digitization_factor;
  1780. if (do_round) value += .5;
  1781. return floor(value)/digitization_factor;
  1782. }
  1783. #endif
  1784. #endif /* RGB_TO_GRAY */
  1785. #ifdef PNG_READ_GAMMA_SUPPORTED
  1786. static double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
  1787. {
  1788. /* Absolute error permitted in linear values - affected by the bit depth of
  1789. * the calculations.
  1790. */
  1791. if (pm->assume_16_bit_calculations ||
  1792. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1793. return pm->maxabs16;
  1794. else
  1795. return pm->maxabs8;
  1796. }
  1797. static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
  1798. {
  1799. /* Error in the linear composition arithmetic - only relevant when
  1800. * composition actually happens (0 < alpha < 1).
  1801. */
  1802. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1803. return pm->maxcalc16;
  1804. else if (pm->assume_16_bit_calculations)
  1805. return pm->maxcalcG;
  1806. else
  1807. return pm->maxcalc8;
  1808. }
  1809. static double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
  1810. {
  1811. /* Percentage error permitted in the linear values. Note that the specified
  1812. * value is a percentage but this routine returns a simple number.
  1813. */
  1814. if (pm->assume_16_bit_calculations ||
  1815. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1816. return pm->maxpc16 * .01;
  1817. else
  1818. return pm->maxpc8 * .01;
  1819. }
  1820. /* Output error - the error in the encoded value. This is determined by the
  1821. * digitization of the output so can be +/-0.5 in the actual output value. In
  1822. * the expand_16 case with the current code in libpng the expand happens after
  1823. * all the calculations are done in 8 bit arithmetic, so even though the output
  1824. * depth is 16 the output error is determined by the 8 bit calculation.
  1825. *
  1826. * This limit is not determined by the bit depth of internal calculations.
  1827. *
  1828. * The specified parameter does *not* include the base .5 digitization error but
  1829. * it is added here.
  1830. */
  1831. static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
  1832. {
  1833. /* There is a serious error in the 2 and 4 bit grayscale transform because
  1834. * the gamma table value (8 bits) is simply shifted, not rounded, so the
  1835. * error in 4 bit grayscale gamma is up to the value below. This is a hack
  1836. * to allow pngvalid to succeed:
  1837. *
  1838. * TODO: fix this in libpng
  1839. */
  1840. if (out_depth == 2)
  1841. return .73182-.5;
  1842. if (out_depth == 4)
  1843. return .90644-.5;
  1844. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1845. return pm->maxout16;
  1846. /* This is the case where the value was calculated at 8-bit precision then
  1847. * scaled to 16 bits.
  1848. */
  1849. else if (out_depth == 16)
  1850. return pm->maxout8 * 257;
  1851. else
  1852. return pm->maxout8;
  1853. }
  1854. /* This does the same thing as the above however it returns the value to log,
  1855. * rather than raising a warning. This is useful for debugging to track down
  1856. * exactly what set of parameters cause high error values.
  1857. */
  1858. static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
  1859. {
  1860. /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
  1861. * and so must be adjusted for low bit depth grayscale:
  1862. */
  1863. if (out_depth <= 8)
  1864. {
  1865. if (pm->log8 == 0) /* switched off */
  1866. return 256;
  1867. if (out_depth < 8)
  1868. return pm->log8 / 255 * ((1<<out_depth)-1);
  1869. return pm->log8;
  1870. }
  1871. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1872. {
  1873. if (pm->log16 == 0)
  1874. return 65536;
  1875. return pm->log16;
  1876. }
  1877. /* This is the case where the value was calculated at 8-bit precision then
  1878. * scaled to 16 bits.
  1879. */
  1880. if (pm->log8 == 0)
  1881. return 65536;
  1882. return pm->log8 * 257;
  1883. }
  1884. /* This complements the above by providing the appropriate quantization for the
  1885. * final value. Normally this would just be quantization to an integral value,
  1886. * but in the 8 bit calculation case it's actually quantization to a multiple of
  1887. * 257!
  1888. */
  1889. static int output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth,
  1890. int out_depth)
  1891. {
  1892. if (out_depth == 16 && in_depth != 16 &&
  1893. pm->calculations_use_input_precision)
  1894. return 257;
  1895. else
  1896. return 1;
  1897. }
  1898. #endif /* PNG_READ_GAMMA_SUPPORTED */
  1899. /* One modification structure must be provided for each chunk to be modified (in
  1900. * fact more than one can be provided if multiple separate changes are desired
  1901. * for a single chunk.) Modifications include adding a new chunk when a
  1902. * suitable chunk does not exist.
  1903. *
  1904. * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
  1905. * or 'added' as appropriate if the modify_fn returns 1 (true). If the
  1906. * modify_fn is NULL the chunk is simply removed.
  1907. */
  1908. typedef struct png_modification
  1909. {
  1910. struct png_modification *next;
  1911. png_uint_32 chunk;
  1912. /* If the following is NULL all matching chunks will be removed: */
  1913. int (*modify_fn)(struct png_modifier *pm,
  1914. struct png_modification *me, int add);
  1915. /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
  1916. * found and modified (and there is a modify_fn) the modify_fn will be called
  1917. * to add the chunk before the relevant chunk.
  1918. */
  1919. png_uint_32 add;
  1920. unsigned int modified :1; /* Chunk was modified */
  1921. unsigned int added :1; /* Chunk was added */
  1922. unsigned int removed :1; /* Chunk was removed */
  1923. } png_modification;
  1924. static void
  1925. modification_reset(png_modification *pmm)
  1926. {
  1927. if (pmm != NULL)
  1928. {
  1929. pmm->modified = 0;
  1930. pmm->added = 0;
  1931. pmm->removed = 0;
  1932. modification_reset(pmm->next);
  1933. }
  1934. }
  1935. static void
  1936. modification_init(png_modification *pmm)
  1937. {
  1938. memset(pmm, 0, sizeof *pmm);
  1939. pmm->next = NULL;
  1940. pmm->chunk = 0;
  1941. pmm->modify_fn = NULL;
  1942. pmm->add = 0;
  1943. modification_reset(pmm);
  1944. }
  1945. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1946. static void
  1947. modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
  1948. {
  1949. if (pm->current_encoding != 0)
  1950. *ce = *pm->current_encoding;
  1951. else
  1952. memset(ce, 0, sizeof *ce);
  1953. ce->gamma = pm->current_gamma;
  1954. }
  1955. #endif
  1956. static size_t
  1957. safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
  1958. PNG_CONST png_modifier *pm)
  1959. {
  1960. pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
  1961. pm->current_gamma);
  1962. if (pm->encoding_ignored)
  1963. pos = safecat(buffer, bufsize, pos, "[overridden]");
  1964. return pos;
  1965. }
  1966. /* Iterate through the usefully testable color encodings. An encoding is one
  1967. * of:
  1968. *
  1969. * 1) Nothing (no color space, no gamma).
  1970. * 2) Just a gamma value from the gamma array (including 1.0)
  1971. * 3) A color space from the encodings array with the corresponding gamma.
  1972. * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
  1973. *
  1974. * The iterator selects these in turn, the randomizer selects one at random,
  1975. * which is used depends on the setting of the 'test_exhaustive' flag. Notice
  1976. * that this function changes the colour space encoding so it must only be
  1977. * called on completion of the previous test. This is what 'modifier_reset'
  1978. * does, below.
  1979. *
  1980. * After the function has been called the 'repeat' flag will still be set; the
  1981. * caller of modifier_reset must reset it at the start of each run of the test!
  1982. */
  1983. static unsigned int
  1984. modifier_total_encodings(PNG_CONST png_modifier *pm)
  1985. {
  1986. return 1 + /* (1) nothing */
  1987. pm->ngammas + /* (2) gamma values to test */
  1988. pm->nencodings + /* (3) total number of encodings */
  1989. /* The following test only works after the first time through the
  1990. * png_modifier code because 'bit_depth' is set when the IHDR is read.
  1991. * modifier_reset, below, preserves the setting until after it has called
  1992. * the iterate function (also below.)
  1993. *
  1994. * For this reason do not rely on this function outside a call to
  1995. * modifier_reset.
  1996. */
  1997. ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
  1998. pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
  1999. }
  2000. static void
  2001. modifier_encoding_iterate(png_modifier *pm)
  2002. {
  2003. if (!pm->repeat && /* Else something needs the current encoding again. */
  2004. pm->test_uses_encoding) /* Some transform is encoding dependent */
  2005. {
  2006. if (pm->test_exhaustive)
  2007. {
  2008. if (++pm->encoding_counter >= modifier_total_encodings(pm))
  2009. pm->encoding_counter = 0; /* This will stop the repeat */
  2010. }
  2011. else
  2012. {
  2013. /* Not exhaustive - choose an encoding at random; generate a number in
  2014. * the range 1..(max-1), so the result is always non-zero:
  2015. */
  2016. if (pm->encoding_counter == 0)
  2017. pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
  2018. else
  2019. pm->encoding_counter = 0;
  2020. }
  2021. if (pm->encoding_counter > 0)
  2022. pm->repeat = 1;
  2023. }
  2024. else if (!pm->repeat)
  2025. pm->encoding_counter = 0;
  2026. }
  2027. static void
  2028. modifier_reset(png_modifier *pm)
  2029. {
  2030. store_read_reset(&pm->this);
  2031. pm->limit = 4E-3;
  2032. pm->pending_len = pm->pending_chunk = 0;
  2033. pm->flush = pm->buffer_count = pm->buffer_position = 0;
  2034. pm->modifications = NULL;
  2035. pm->state = modifier_start;
  2036. modifier_encoding_iterate(pm);
  2037. /* The following must be set in the next run. In particular
  2038. * test_uses_encodings must be set in the _ini function of each transform
  2039. * that looks at the encodings. (Not the 'add' function!)
  2040. */
  2041. pm->test_uses_encoding = 0;
  2042. pm->current_gamma = 0;
  2043. pm->current_encoding = 0;
  2044. pm->encoding_ignored = 0;
  2045. /* These only become value after IHDR is read: */
  2046. pm->bit_depth = pm->colour_type = 0;
  2047. }
  2048. /* The following must be called before anything else to get the encoding set up
  2049. * on the modifier. In particular it must be called before the transform init
  2050. * functions are called.
  2051. */
  2052. static void
  2053. modifier_set_encoding(png_modifier *pm)
  2054. {
  2055. /* Set the encoding to the one specified by the current encoding counter,
  2056. * first clear out all the settings - this corresponds to an encoding_counter
  2057. * of 0.
  2058. */
  2059. pm->current_gamma = 0;
  2060. pm->current_encoding = 0;
  2061. pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
  2062. /* Now, if required, set the gamma and encoding fields. */
  2063. if (pm->encoding_counter > 0)
  2064. {
  2065. /* The gammas[] array is an array of screen gammas, not encoding gammas,
  2066. * so we need the inverse:
  2067. */
  2068. if (pm->encoding_counter <= pm->ngammas)
  2069. pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
  2070. else
  2071. {
  2072. unsigned int i = pm->encoding_counter - pm->ngammas;
  2073. if (i >= pm->nencodings)
  2074. {
  2075. i %= pm->nencodings;
  2076. pm->current_gamma = 1; /* Linear, only in the 16 bit case */
  2077. }
  2078. else
  2079. pm->current_gamma = pm->encodings[i].gamma;
  2080. pm->current_encoding = pm->encodings + i;
  2081. }
  2082. }
  2083. }
  2084. /* Enquiry functions to find out what is set. Notice that there is an implicit
  2085. * assumption below that the first encoding in the list is the one for sRGB.
  2086. */
  2087. static int
  2088. modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
  2089. {
  2090. return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
  2091. pm->current_encoding->gamma == pm->current_gamma;
  2092. }
  2093. static int
  2094. modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
  2095. {
  2096. return pm->current_gamma != 0;
  2097. }
  2098. /* Convenience macros. */
  2099. #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
  2100. #define CHUNK_IHDR CHUNK(73,72,68,82)
  2101. #define CHUNK_PLTE CHUNK(80,76,84,69)
  2102. #define CHUNK_IDAT CHUNK(73,68,65,84)
  2103. #define CHUNK_IEND CHUNK(73,69,78,68)
  2104. #define CHUNK_cHRM CHUNK(99,72,82,77)
  2105. #define CHUNK_gAMA CHUNK(103,65,77,65)
  2106. #define CHUNK_sBIT CHUNK(115,66,73,84)
  2107. #define CHUNK_sRGB CHUNK(115,82,71,66)
  2108. /* The guts of modification are performed during a read. */
  2109. static void
  2110. modifier_crc(png_bytep buffer)
  2111. {
  2112. /* Recalculate the chunk CRC - a complete chunk must be in
  2113. * the buffer, at the start.
  2114. */
  2115. uInt datalen = png_get_uint_32(buffer);
  2116. uLong crc = crc32(0, buffer+4, datalen+4);
  2117. /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
  2118. */
  2119. png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
  2120. }
  2121. static void
  2122. modifier_setbuffer(png_modifier *pm)
  2123. {
  2124. modifier_crc(pm->buffer);
  2125. pm->buffer_count = png_get_uint_32(pm->buffer)+12;
  2126. pm->buffer_position = 0;
  2127. }
  2128. /* Separate the callback into the actual implementation (which is passed the
  2129. * png_modifier explicitly) and the callback, which gets the modifier from the
  2130. * png_struct.
  2131. */
  2132. static void
  2133. modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st)
  2134. {
  2135. while (st > 0)
  2136. {
  2137. size_t cb;
  2138. png_uint_32 len, chunk;
  2139. png_modification *mod;
  2140. if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
  2141. {
  2142. static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  2143. case modifier_start:
  2144. store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */
  2145. pm->buffer_count = 8;
  2146. pm->buffer_position = 0;
  2147. if (memcmp(pm->buffer, sign, 8) != 0)
  2148. png_error(pm->this.pread, "invalid PNG file signature");
  2149. pm->state = modifier_signature;
  2150. break;
  2151. case modifier_signature:
  2152. store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */
  2153. pm->buffer_count = 13+12;
  2154. pm->buffer_position = 0;
  2155. if (png_get_uint_32(pm->buffer) != 13 ||
  2156. png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
  2157. png_error(pm->this.pread, "invalid IHDR");
  2158. /* Check the list of modifiers for modifications to the IHDR. */
  2159. mod = pm->modifications;
  2160. while (mod != NULL)
  2161. {
  2162. if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
  2163. (*mod->modify_fn)(pm, mod, 0))
  2164. {
  2165. mod->modified = 1;
  2166. modifier_setbuffer(pm);
  2167. }
  2168. /* Ignore removal or add if IHDR! */
  2169. mod = mod->next;
  2170. }
  2171. /* Cache information from the IHDR (the modified one.) */
  2172. pm->bit_depth = pm->buffer[8+8];
  2173. pm->colour_type = pm->buffer[8+8+1];
  2174. pm->state = modifier_IHDR;
  2175. pm->flush = 0;
  2176. break;
  2177. case modifier_IHDR:
  2178. default:
  2179. /* Read a new chunk and process it until we see PLTE, IDAT or
  2180. * IEND. 'flush' indicates that there is still some data to
  2181. * output from the preceding chunk.
  2182. */
  2183. if ((cb = pm->flush) > 0)
  2184. {
  2185. if (cb > st) cb = st;
  2186. pm->flush -= cb;
  2187. store_read_imp(&pm->this, pb, cb);
  2188. pb += cb;
  2189. st -= cb;
  2190. if (st == 0) return;
  2191. }
  2192. /* No more bytes to flush, read a header, or handle a pending
  2193. * chunk.
  2194. */
  2195. if (pm->pending_chunk != 0)
  2196. {
  2197. png_save_uint_32(pm->buffer, pm->pending_len);
  2198. png_save_uint_32(pm->buffer+4, pm->pending_chunk);
  2199. pm->pending_len = 0;
  2200. pm->pending_chunk = 0;
  2201. }
  2202. else
  2203. store_read_imp(&pm->this, pm->buffer, 8);
  2204. pm->buffer_count = 8;
  2205. pm->buffer_position = 0;
  2206. /* Check for something to modify or a terminator chunk. */
  2207. len = png_get_uint_32(pm->buffer);
  2208. chunk = png_get_uint_32(pm->buffer+4);
  2209. /* Terminators first, they may have to be delayed for added
  2210. * chunks
  2211. */
  2212. if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
  2213. chunk == CHUNK_IEND)
  2214. {
  2215. mod = pm->modifications;
  2216. while (mod != NULL)
  2217. {
  2218. if ((mod->add == chunk ||
  2219. (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
  2220. mod->modify_fn != NULL && !mod->modified && !mod->added)
  2221. {
  2222. /* Regardless of what the modify function does do not run
  2223. * this again.
  2224. */
  2225. mod->added = 1;
  2226. if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
  2227. {
  2228. /* Reset the CRC on a new chunk */
  2229. if (pm->buffer_count > 0)
  2230. modifier_setbuffer(pm);
  2231. else
  2232. {
  2233. pm->buffer_position = 0;
  2234. mod->removed = 1;
  2235. }
  2236. /* The buffer has been filled with something (we assume)
  2237. * so output this. Pend the current chunk.
  2238. */
  2239. pm->pending_len = len;
  2240. pm->pending_chunk = chunk;
  2241. break; /* out of while */
  2242. }
  2243. }
  2244. mod = mod->next;
  2245. }
  2246. /* Don't do any further processing if the buffer was modified -
  2247. * otherwise the code will end up modifying a chunk that was
  2248. * just added.
  2249. */
  2250. if (mod != NULL)
  2251. break; /* out of switch */
  2252. }
  2253. /* If we get to here then this chunk may need to be modified. To
  2254. * do this it must be less than 1024 bytes in total size, otherwise
  2255. * it just gets flushed.
  2256. */
  2257. if (len+12 <= sizeof pm->buffer)
  2258. {
  2259. store_read_imp(&pm->this, pm->buffer+pm->buffer_count,
  2260. len+12-pm->buffer_count);
  2261. pm->buffer_count = len+12;
  2262. /* Check for a modification, else leave it be. */
  2263. mod = pm->modifications;
  2264. while (mod != NULL)
  2265. {
  2266. if (mod->chunk == chunk)
  2267. {
  2268. if (mod->modify_fn == NULL)
  2269. {
  2270. /* Remove this chunk */
  2271. pm->buffer_count = pm->buffer_position = 0;
  2272. mod->removed = 1;
  2273. break; /* Terminate the while loop */
  2274. }
  2275. else if ((*mod->modify_fn)(pm, mod, 0))
  2276. {
  2277. mod->modified = 1;
  2278. /* The chunk may have been removed: */
  2279. if (pm->buffer_count == 0)
  2280. {
  2281. pm->buffer_position = 0;
  2282. break;
  2283. }
  2284. modifier_setbuffer(pm);
  2285. }
  2286. }
  2287. mod = mod->next;
  2288. }
  2289. }
  2290. else
  2291. pm->flush = len+12 - pm->buffer_count; /* data + crc */
  2292. /* Take the data from the buffer (if there is any). */
  2293. break;
  2294. }
  2295. /* Here to read from the modifier buffer (not directly from
  2296. * the store, as in the flush case above.)
  2297. */
  2298. cb = pm->buffer_count - pm->buffer_position;
  2299. if (cb > st)
  2300. cb = st;
  2301. memcpy(pb, pm->buffer + pm->buffer_position, cb);
  2302. st -= cb;
  2303. pb += cb;
  2304. pm->buffer_position += cb;
  2305. }
  2306. }
  2307. /* The callback: */
  2308. static void PNGCBAPI
  2309. modifier_read(png_structp ppIn, png_bytep pb, png_size_t st)
  2310. {
  2311. png_const_structp pp = ppIn;
  2312. png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
  2313. if (pm == NULL || pm->this.pread != pp)
  2314. png_error(pp, "bad modifier_read call");
  2315. modifier_read_imp(pm, pb, st);
  2316. }
  2317. /* Like store_progressive_read but the data is getting changed as we go so we
  2318. * need a local buffer.
  2319. */
  2320. static void
  2321. modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
  2322. {
  2323. if (pm->this.pread != pp || pm->this.current == NULL ||
  2324. pm->this.next == NULL)
  2325. png_error(pp, "store state damaged (progressive)");
  2326. /* This is another Horowitz and Hill random noise generator. In this case
  2327. * the aim is to stress the progressive reader with truly horrible variable
  2328. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  2329. * is generated. We could probably just count from 1 to 32767 and get as
  2330. * good a result.
  2331. */
  2332. for (;;)
  2333. {
  2334. static png_uint_32 noise = 1;
  2335. png_size_t cb, cbAvail;
  2336. png_byte buffer[512];
  2337. /* Generate 15 more bits of stuff: */
  2338. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  2339. cb = noise & 0x1ff;
  2340. /* Check that this number of bytes are available (in the current buffer.)
  2341. * (This doesn't quite work - the modifier might delete a chunk; unlikely
  2342. * but possible, it doesn't happen at present because the modifier only
  2343. * adds chunks to standard images.)
  2344. */
  2345. cbAvail = store_read_buffer_avail(&pm->this);
  2346. if (pm->buffer_count > pm->buffer_position)
  2347. cbAvail += pm->buffer_count - pm->buffer_position;
  2348. if (cb > cbAvail)
  2349. {
  2350. /* Check for EOF: */
  2351. if (cbAvail == 0)
  2352. break;
  2353. cb = cbAvail;
  2354. }
  2355. modifier_read_imp(pm, buffer, cb);
  2356. png_process_data(pp, pi, buffer, cb);
  2357. }
  2358. /* Check the invariants at the end (if this fails it's a problem in this
  2359. * file!)
  2360. */
  2361. if (pm->buffer_count > pm->buffer_position ||
  2362. pm->this.next != &pm->this.current->data ||
  2363. pm->this.readpos < pm->this.current->datacount)
  2364. png_error(pp, "progressive read implementation error");
  2365. }
  2366. /* Set up a modifier. */
  2367. static png_structp
  2368. set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
  2369. PNG_CONST char *name)
  2370. {
  2371. /* Do this first so that the modifier fields are cleared even if an error
  2372. * happens allocating the png_struct. No allocation is done here so no
  2373. * cleanup is required.
  2374. */
  2375. pm->state = modifier_start;
  2376. pm->bit_depth = 0;
  2377. pm->colour_type = 255;
  2378. pm->pending_len = 0;
  2379. pm->pending_chunk = 0;
  2380. pm->flush = 0;
  2381. pm->buffer_count = 0;
  2382. pm->buffer_position = 0;
  2383. return set_store_for_read(&pm->this, ppi, id, name);
  2384. }
  2385. /******************************** MODIFICATIONS *******************************/
  2386. /* Standard modifications to add chunks. These do not require the _SUPPORTED
  2387. * macros because the chunks can be there regardless of whether this specific
  2388. * libpng supports them.
  2389. */
  2390. typedef struct gama_modification
  2391. {
  2392. png_modification this;
  2393. png_fixed_point gamma;
  2394. } gama_modification;
  2395. static int
  2396. gama_modify(png_modifier *pm, png_modification *me, int add)
  2397. {
  2398. UNUSED(add)
  2399. /* This simply dumps the given gamma value into the buffer. */
  2400. png_save_uint_32(pm->buffer, 4);
  2401. png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
  2402. png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
  2403. return 1;
  2404. }
  2405. static void
  2406. gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
  2407. {
  2408. double g;
  2409. modification_init(&me->this);
  2410. me->this.chunk = CHUNK_gAMA;
  2411. me->this.modify_fn = gama_modify;
  2412. me->this.add = CHUNK_PLTE;
  2413. g = fix(gammad);
  2414. me->gamma = (png_fixed_point)g;
  2415. me->this.next = pm->modifications;
  2416. pm->modifications = &me->this;
  2417. }
  2418. typedef struct chrm_modification
  2419. {
  2420. png_modification this;
  2421. PNG_CONST color_encoding *encoding;
  2422. png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
  2423. } chrm_modification;
  2424. static int
  2425. chrm_modify(png_modifier *pm, png_modification *me, int add)
  2426. {
  2427. UNUSED(add)
  2428. /* As with gAMA this just adds the required cHRM chunk to the buffer. */
  2429. png_save_uint_32(pm->buffer , 32);
  2430. png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
  2431. png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
  2432. png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
  2433. png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
  2434. png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
  2435. png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
  2436. png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
  2437. png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
  2438. png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
  2439. return 1;
  2440. }
  2441. static void
  2442. chrm_modification_init(chrm_modification *me, png_modifier *pm,
  2443. PNG_CONST color_encoding *encoding)
  2444. {
  2445. CIE_color white = white_point(encoding);
  2446. /* Original end points: */
  2447. me->encoding = encoding;
  2448. /* Chromaticities (in fixed point): */
  2449. me->wx = fix(chromaticity_x(white));
  2450. me->wy = fix(chromaticity_y(white));
  2451. me->rx = fix(chromaticity_x(encoding->red));
  2452. me->ry = fix(chromaticity_y(encoding->red));
  2453. me->gx = fix(chromaticity_x(encoding->green));
  2454. me->gy = fix(chromaticity_y(encoding->green));
  2455. me->bx = fix(chromaticity_x(encoding->blue));
  2456. me->by = fix(chromaticity_y(encoding->blue));
  2457. modification_init(&me->this);
  2458. me->this.chunk = CHUNK_cHRM;
  2459. me->this.modify_fn = chrm_modify;
  2460. me->this.add = CHUNK_PLTE;
  2461. me->this.next = pm->modifications;
  2462. pm->modifications = &me->this;
  2463. }
  2464. typedef struct srgb_modification
  2465. {
  2466. png_modification this;
  2467. png_byte intent;
  2468. } srgb_modification;
  2469. static int
  2470. srgb_modify(png_modifier *pm, png_modification *me, int add)
  2471. {
  2472. UNUSED(add)
  2473. /* As above, ignore add and just make a new chunk */
  2474. png_save_uint_32(pm->buffer, 1);
  2475. png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
  2476. pm->buffer[8] = ((srgb_modification*)me)->intent;
  2477. return 1;
  2478. }
  2479. static void
  2480. srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
  2481. {
  2482. modification_init(&me->this);
  2483. me->this.chunk = CHUNK_sBIT;
  2484. if (intent <= 3) /* if valid, else *delete* sRGB chunks */
  2485. {
  2486. me->this.modify_fn = srgb_modify;
  2487. me->this.add = CHUNK_PLTE;
  2488. me->intent = intent;
  2489. }
  2490. else
  2491. {
  2492. me->this.modify_fn = 0;
  2493. me->this.add = 0;
  2494. me->intent = 0;
  2495. }
  2496. me->this.next = pm->modifications;
  2497. pm->modifications = &me->this;
  2498. }
  2499. #ifdef PNG_READ_GAMMA_SUPPORTED
  2500. typedef struct sbit_modification
  2501. {
  2502. png_modification this;
  2503. png_byte sbit;
  2504. } sbit_modification;
  2505. static int
  2506. sbit_modify(png_modifier *pm, png_modification *me, int add)
  2507. {
  2508. png_byte sbit = ((sbit_modification*)me)->sbit;
  2509. if (pm->bit_depth > sbit)
  2510. {
  2511. int cb = 0;
  2512. switch (pm->colour_type)
  2513. {
  2514. case 0:
  2515. cb = 1;
  2516. break;
  2517. case 2:
  2518. case 3:
  2519. cb = 3;
  2520. break;
  2521. case 4:
  2522. cb = 2;
  2523. break;
  2524. case 6:
  2525. cb = 4;
  2526. break;
  2527. default:
  2528. png_error(pm->this.pread,
  2529. "unexpected colour type in sBIT modification");
  2530. }
  2531. png_save_uint_32(pm->buffer, cb);
  2532. png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
  2533. while (cb > 0)
  2534. (pm->buffer+8)[--cb] = sbit;
  2535. return 1;
  2536. }
  2537. else if (!add)
  2538. {
  2539. /* Remove the sBIT chunk */
  2540. pm->buffer_count = pm->buffer_position = 0;
  2541. return 1;
  2542. }
  2543. else
  2544. return 0; /* do nothing */
  2545. }
  2546. static void
  2547. sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
  2548. {
  2549. modification_init(&me->this);
  2550. me->this.chunk = CHUNK_sBIT;
  2551. me->this.modify_fn = sbit_modify;
  2552. me->this.add = CHUNK_PLTE;
  2553. me->sbit = sbit;
  2554. me->this.next = pm->modifications;
  2555. pm->modifications = &me->this;
  2556. }
  2557. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2558. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  2559. /***************************** STANDARD PNG FILES *****************************/
  2560. /* Standard files - write and save standard files. */
  2561. /* There are two basic forms of standard images. Those which attempt to have
  2562. * all the possible pixel values (not possible for 16bpp images, but a range of
  2563. * values are produced) and those which have a range of image sizes. The former
  2564. * are used for testing transforms, in particular gamma correction and bit
  2565. * reduction and increase. The latter are reserved for testing the behavior of
  2566. * libpng with respect to 'odd' image sizes - particularly small images where
  2567. * rows become 1 byte and interlace passes disappear.
  2568. *
  2569. * The first, most useful, set are the 'transform' images, the second set of
  2570. * small images are the 'size' images.
  2571. *
  2572. * The transform files are constructed with rows which fit into a 1024 byte row
  2573. * buffer. This makes allocation easier below. Further regardless of the file
  2574. * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
  2575. *
  2576. * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
  2577. * and with an ID derived from the colour type, bit depth and interlace type
  2578. * as above (FILEID). The width (128) and height (variable) are not stored in
  2579. * the FILEID - instead the fields are set to 0, indicating a transform file.
  2580. *
  2581. * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
  2582. * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
  2583. * height of 16 rows. The width and height are stored in the FILEID and, being
  2584. * non-zero, indicate a size file.
  2585. *
  2586. * Because the PNG filter code is typically the largest CPU consumer within
  2587. * libpng itself there is a tendency to attempt to optimize it. This results in
  2588. * special case code which needs to be validated. To cause this to happen the
  2589. * 'size' images are made to use each possible filter, in so far as this is
  2590. * possible for smaller images.
  2591. *
  2592. * For palette image (colour type 3) multiple transform images are stored with
  2593. * the same bit depth to allow testing of more colour combinations -
  2594. * particularly important for testing the gamma code because libpng uses a
  2595. * different code path for palette images. For size images a single palette is
  2596. * used.
  2597. */
  2598. /* Make a 'standard' palette. Because there are only 256 entries in a palette
  2599. * (maximum) this actually makes a random palette in the hope that enough tests
  2600. * will catch enough errors. (Note that the same palette isn't produced every
  2601. * time for the same test - it depends on what previous tests have been run -
  2602. * but a given set of arguments to pngvalid will always produce the same palette
  2603. * at the same test! This is why pseudo-random number generators are useful for
  2604. * testing.)
  2605. *
  2606. * The store must be open for write when this is called, otherwise an internal
  2607. * error will occur. This routine contains its own magic number seed, so the
  2608. * palettes generated don't change if there are intervening errors (changing the
  2609. * calls to the store_mark seed.)
  2610. */
  2611. static store_palette_entry *
  2612. make_standard_palette(png_store* ps, int npalette, int do_tRNS)
  2613. {
  2614. static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
  2615. int i = 0;
  2616. png_byte values[256][4];
  2617. /* Always put in black and white plus the six primary and secondary colors.
  2618. */
  2619. for (; i<8; ++i)
  2620. {
  2621. values[i][1] = (png_byte)((i&1) ? 255U : 0U);
  2622. values[i][2] = (png_byte)((i&2) ? 255U : 0U);
  2623. values[i][3] = (png_byte)((i&4) ? 255U : 0U);
  2624. }
  2625. /* Then add 62 grays (one quarter of the remaining 256 slots). */
  2626. {
  2627. int j = 0;
  2628. png_byte random_bytes[4];
  2629. png_byte need[256];
  2630. need[0] = 0; /*got black*/
  2631. memset(need+1, 1, (sizeof need)-2); /*need these*/
  2632. need[255] = 0; /*but not white*/
  2633. while (i<70)
  2634. {
  2635. png_byte b;
  2636. if (j==0)
  2637. {
  2638. make_four_random_bytes(palette_seed, random_bytes);
  2639. j = 4;
  2640. }
  2641. b = random_bytes[--j];
  2642. if (need[b])
  2643. {
  2644. values[i][1] = b;
  2645. values[i][2] = b;
  2646. values[i++][3] = b;
  2647. }
  2648. }
  2649. }
  2650. /* Finally add 192 colors at random - don't worry about matches to things we
  2651. * already have, chance is less than 1/65536. Don't worry about grays,
  2652. * chance is the same, so we get a duplicate or extra gray less than 1 time
  2653. * in 170.
  2654. */
  2655. for (; i<256; ++i)
  2656. make_four_random_bytes(palette_seed, values[i]);
  2657. /* Fill in the alpha values in the first byte. Just use all possible values
  2658. * (0..255) in an apparently random order:
  2659. */
  2660. {
  2661. store_palette_entry *palette;
  2662. png_byte selector[4];
  2663. make_four_random_bytes(palette_seed, selector);
  2664. if (do_tRNS)
  2665. for (i=0; i<256; ++i)
  2666. values[i][0] = (png_byte)(i ^ selector[0]);
  2667. else
  2668. for (i=0; i<256; ++i)
  2669. values[i][0] = 255; /* no transparency/tRNS chunk */
  2670. /* 'values' contains 256 ARGB values, but we only need 'npalette'.
  2671. * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
  2672. * bit depth cases select colors at random, else it is difficult to have
  2673. * a set of low bit depth palette test with any chance of a reasonable
  2674. * range of colors. Do this by randomly permuting values into the low
  2675. * 'npalette' entries using an XOR mask generated here. This also
  2676. * permutes the npalette == 256 case in a potentially useful way (there is
  2677. * no relationship between palette index and the color value therein!)
  2678. */
  2679. palette = store_write_palette(ps, npalette);
  2680. for (i=0; i<npalette; ++i)
  2681. {
  2682. palette[i].alpha = values[i ^ selector[1]][0];
  2683. palette[i].red = values[i ^ selector[1]][1];
  2684. palette[i].green = values[i ^ selector[1]][2];
  2685. palette[i].blue = values[i ^ selector[1]][3];
  2686. }
  2687. return palette;
  2688. }
  2689. }
  2690. /* Initialize a standard palette on a write stream. The 'do_tRNS' argument
  2691. * indicates whether or not to also set the tRNS chunk.
  2692. */
  2693. /* TODO: the png_structp here can probably be 'const' in the future */
  2694. static void
  2695. init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
  2696. int do_tRNS)
  2697. {
  2698. store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
  2699. {
  2700. int i;
  2701. png_color palette[256];
  2702. /* Set all entries to detect overread errors. */
  2703. for (i=0; i<npalette; ++i)
  2704. {
  2705. palette[i].red = ppal[i].red;
  2706. palette[i].green = ppal[i].green;
  2707. palette[i].blue = ppal[i].blue;
  2708. }
  2709. /* Just in case fill in the rest with detectable values: */
  2710. for (; i<256; ++i)
  2711. palette[i].red = palette[i].green = palette[i].blue = 42;
  2712. png_set_PLTE(pp, pi, palette, npalette);
  2713. }
  2714. if (do_tRNS)
  2715. {
  2716. int i, j;
  2717. png_byte tRNS[256];
  2718. /* Set all the entries, but skip trailing opaque entries */
  2719. for (i=j=0; i<npalette; ++i)
  2720. if ((tRNS[i] = ppal[i].alpha) < 255)
  2721. j = i+1;
  2722. /* Fill in the remainder with a detectable value: */
  2723. for (; i<256; ++i)
  2724. tRNS[i] = 24;
  2725. # ifdef PNG_WRITE_tRNS_SUPPORTED
  2726. if (j > 0)
  2727. png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
  2728. # endif
  2729. }
  2730. }
  2731. /* The number of passes is related to the interlace type. There was no libpng
  2732. * API to determine this prior to 1.5, so we need an inquiry function:
  2733. */
  2734. static int
  2735. npasses_from_interlace_type(png_const_structp pp, int interlace_type)
  2736. {
  2737. switch (interlace_type)
  2738. {
  2739. default:
  2740. png_error(pp, "invalid interlace type");
  2741. case PNG_INTERLACE_NONE:
  2742. return 1;
  2743. case PNG_INTERLACE_ADAM7:
  2744. return PNG_INTERLACE_ADAM7_PASSES;
  2745. }
  2746. }
  2747. static unsigned int
  2748. bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  2749. {
  2750. switch (colour_type)
  2751. {
  2752. default: png_error(pp, "invalid color type");
  2753. case 0: return bit_depth;
  2754. case 2: return 3*bit_depth;
  2755. case 3: return bit_depth;
  2756. case 4: return 2*bit_depth;
  2757. case 6: return 4*bit_depth;
  2758. }
  2759. }
  2760. #define TRANSFORM_WIDTH 128U
  2761. #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
  2762. #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
  2763. #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
  2764. #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
  2765. static size_t
  2766. transform_rowsize(png_const_structp pp, png_byte colour_type,
  2767. png_byte bit_depth)
  2768. {
  2769. return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
  2770. }
  2771. /* transform_width(pp, colour_type, bit_depth) current returns the same number
  2772. * every time, so just use a macro:
  2773. */
  2774. #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
  2775. static png_uint_32
  2776. transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  2777. {
  2778. switch (bit_size(pp, colour_type, bit_depth))
  2779. {
  2780. case 1:
  2781. case 2:
  2782. case 4:
  2783. return 1; /* Total of 128 pixels */
  2784. case 8:
  2785. return 2; /* Total of 256 pixels/bytes */
  2786. case 16:
  2787. return 512; /* Total of 65536 pixels */
  2788. case 24:
  2789. case 32:
  2790. return 512; /* 65536 pixels */
  2791. case 48:
  2792. case 64:
  2793. return 2048;/* 4 x 65536 pixels. */
  2794. # define TRANSFORM_HEIGHTMAX 2048
  2795. default:
  2796. return 0; /* Error, will be caught later */
  2797. }
  2798. }
  2799. #ifdef PNG_READ_SUPPORTED
  2800. /* The following can only be defined here, now we have the definitions
  2801. * of the transform image sizes.
  2802. */
  2803. static png_uint_32
  2804. standard_width(png_const_structp pp, png_uint_32 id)
  2805. {
  2806. png_uint_32 width = WIDTH_FROM_ID(id);
  2807. UNUSED(pp)
  2808. if (width == 0)
  2809. width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2810. return width;
  2811. }
  2812. static png_uint_32
  2813. standard_height(png_const_structp pp, png_uint_32 id)
  2814. {
  2815. png_uint_32 height = HEIGHT_FROM_ID(id);
  2816. if (height == 0)
  2817. height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2818. return height;
  2819. }
  2820. static png_uint_32
  2821. standard_rowsize(png_const_structp pp, png_uint_32 id)
  2822. {
  2823. png_uint_32 width = standard_width(pp, id);
  2824. /* This won't overflow: */
  2825. width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2826. return (width + 7) / 8;
  2827. }
  2828. #endif /* PNG_READ_SUPPORTED */
  2829. static void
  2830. transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
  2831. png_byte colour_type, png_byte bit_depth, png_uint_32 y)
  2832. {
  2833. png_uint_32 v = y << 7;
  2834. png_uint_32 i = 0;
  2835. switch (bit_size(pp, colour_type, bit_depth))
  2836. {
  2837. case 1:
  2838. while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
  2839. return;
  2840. case 2:
  2841. while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
  2842. return;
  2843. case 4:
  2844. while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
  2845. return;
  2846. case 8:
  2847. /* 256 bytes total, 128 bytes in each row set as follows: */
  2848. while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
  2849. return;
  2850. case 16:
  2851. /* Generate all 65536 pixel values in order, which includes the 8 bit
  2852. * GA case as well as the 16 bit G case.
  2853. */
  2854. while (i<128)
  2855. {
  2856. buffer[2*i] = (png_byte)((v>>8) & 0xff);
  2857. buffer[2*i+1] = (png_byte)(v & 0xff);
  2858. ++v;
  2859. ++i;
  2860. }
  2861. return;
  2862. case 24:
  2863. /* 65535 pixels, but rotate the values. */
  2864. while (i<128)
  2865. {
  2866. /* Three bytes per pixel, r, g, b, make b by r^g */
  2867. buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
  2868. buffer[3*i+1] = (png_byte)(v & 0xff);
  2869. buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
  2870. ++v;
  2871. ++i;
  2872. }
  2873. return;
  2874. case 32:
  2875. /* 65535 pixels, r, g, b, a; just replicate */
  2876. while (i<128)
  2877. {
  2878. buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
  2879. buffer[4*i+1] = (png_byte)(v & 0xff);
  2880. buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
  2881. buffer[4*i+3] = (png_byte)(v & 0xff);
  2882. ++v;
  2883. ++i;
  2884. }
  2885. return;
  2886. case 48:
  2887. /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
  2888. * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
  2889. */
  2890. while (i<128)
  2891. {
  2892. png_uint_32 t = v++;
  2893. buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
  2894. buffer[6*i+1] = (png_byte)(t & 0xff);
  2895. t *= 257;
  2896. buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
  2897. buffer[6*i+3] = (png_byte)(t & 0xff);
  2898. t *= 17;
  2899. buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
  2900. buffer[6*i+5] = (png_byte)(t & 0xff);
  2901. ++i;
  2902. }
  2903. return;
  2904. case 64:
  2905. /* As above in the 32 bit case. */
  2906. while (i<128)
  2907. {
  2908. png_uint_32 t = v++;
  2909. buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
  2910. buffer[8*i+1] = (png_byte)(t & 0xff);
  2911. buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
  2912. buffer[8*i+5] = (png_byte)(t & 0xff);
  2913. t *= 257;
  2914. buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
  2915. buffer[8*i+3] = (png_byte)(t & 0xff);
  2916. buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
  2917. buffer[8*i+7] = (png_byte)(t & 0xff);
  2918. ++i;
  2919. }
  2920. return;
  2921. default:
  2922. break;
  2923. }
  2924. png_error(pp, "internal error");
  2925. }
  2926. /* This is just to do the right cast - could be changed to a function to check
  2927. * 'bd' but there isn't much point.
  2928. */
  2929. #define DEPTH(bd) ((png_byte)(1U << (bd)))
  2930. /* This is just a helper for compiling on minimal systems with no write
  2931. * interlacing support. If there is no write interlacing we can't generate test
  2932. * cases with interlace:
  2933. */
  2934. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  2935. # define INTERLACE_LAST PNG_INTERLACE_LAST
  2936. # define check_interlace_type(type) ((void)(type))
  2937. #else
  2938. # define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
  2939. # define png_set_interlace_handling(a) (1)
  2940. static void
  2941. check_interlace_type(int PNG_CONST interlace_type)
  2942. {
  2943. if (interlace_type != PNG_INTERLACE_NONE)
  2944. {
  2945. /* This is an internal error - --interlace tests should be skipped, not
  2946. * attempted.
  2947. */
  2948. fprintf(stderr, "pngvalid: no interlace support\n");
  2949. exit(99);
  2950. }
  2951. }
  2952. #endif
  2953. /* Make a standardized image given a an image colour type, bit depth and
  2954. * interlace type. The standard images have a very restricted range of
  2955. * rows and heights and are used for testing transforms rather than image
  2956. * layout details. See make_size_images below for a way to make images
  2957. * that test odd sizes along with the libpng interlace handling.
  2958. */
  2959. static void
  2960. make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type,
  2961. png_byte PNG_CONST bit_depth, unsigned int palette_number,
  2962. int interlace_type, png_const_charp name)
  2963. {
  2964. context(ps, fault);
  2965. check_interlace_type(interlace_type);
  2966. Try
  2967. {
  2968. png_infop pi;
  2969. png_structp pp = set_store_for_write(ps, &pi, name);
  2970. png_uint_32 h;
  2971. /* In the event of a problem return control to the Catch statement below
  2972. * to do the clean up - it is not possible to 'return' directly from a Try
  2973. * block.
  2974. */
  2975. if (pp == NULL)
  2976. Throw ps;
  2977. h = transform_height(pp, colour_type, bit_depth);
  2978. png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth), h,
  2979. bit_depth, colour_type, interlace_type,
  2980. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  2981. #ifdef PNG_TEXT_SUPPORTED
  2982. # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
  2983. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
  2984. # else
  2985. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
  2986. # endif
  2987. {
  2988. static char key[] = "image name"; /* must be writeable */
  2989. size_t pos;
  2990. png_text text;
  2991. char copy[FILE_NAME_SIZE];
  2992. /* Use a compressed text string to test the correct interaction of text
  2993. * compression and IDAT compression.
  2994. */
  2995. text.compression = TEXT_COMPRESSION;
  2996. text.key = key;
  2997. /* Yuck: the text must be writable! */
  2998. pos = safecat(copy, sizeof copy, 0, ps->wname);
  2999. text.text = copy;
  3000. text.text_length = pos;
  3001. text.itxt_length = 0;
  3002. text.lang = 0;
  3003. text.lang_key = 0;
  3004. png_set_text(pp, pi, &text, 1);
  3005. }
  3006. #endif
  3007. if (colour_type == 3) /* palette */
  3008. init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
  3009. png_write_info(pp, pi);
  3010. if (png_get_rowbytes(pp, pi) !=
  3011. transform_rowsize(pp, colour_type, bit_depth))
  3012. png_error(pp, "row size incorrect");
  3013. else
  3014. {
  3015. /* Somewhat confusingly this must be called *after* png_write_info
  3016. * because if it is called before, the information in *pp has not been
  3017. * updated to reflect the interlaced image.
  3018. */
  3019. int npasses = png_set_interlace_handling(pp);
  3020. int pass;
  3021. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3022. png_error(pp, "write: png_set_interlace_handling failed");
  3023. for (pass=0; pass<npasses; ++pass)
  3024. {
  3025. png_uint_32 y;
  3026. for (y=0; y<h; ++y)
  3027. {
  3028. png_byte buffer[TRANSFORM_ROWMAX];
  3029. transform_row(pp, buffer, colour_type, bit_depth, y);
  3030. png_write_row(pp, buffer);
  3031. }
  3032. }
  3033. }
  3034. #ifdef PNG_TEXT_SUPPORTED
  3035. {
  3036. static char key[] = "end marker";
  3037. static char comment[] = "end";
  3038. png_text text;
  3039. /* Use a compressed text string to test the correct interaction of text
  3040. * compression and IDAT compression.
  3041. */
  3042. text.compression = TEXT_COMPRESSION;
  3043. text.key = key;
  3044. text.text = comment;
  3045. text.text_length = (sizeof comment)-1;
  3046. text.itxt_length = 0;
  3047. text.lang = 0;
  3048. text.lang_key = 0;
  3049. png_set_text(pp, pi, &text, 1);
  3050. }
  3051. #endif
  3052. png_write_end(pp, pi);
  3053. /* And store this under the appropriate id, then clean up. */
  3054. store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
  3055. interlace_type, 0, 0, 0));
  3056. store_write_reset(ps);
  3057. }
  3058. Catch(fault)
  3059. {
  3060. /* Use the png_store returned by the exception. This may help the compiler
  3061. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3062. * and ps will always be the same value.
  3063. */
  3064. store_write_reset(fault);
  3065. }
  3066. }
  3067. static void
  3068. make_transform_images(png_store *ps)
  3069. {
  3070. png_byte colour_type = 0;
  3071. png_byte bit_depth = 0;
  3072. unsigned int palette_number = 0;
  3073. /* This is in case of errors. */
  3074. safecat(ps->test, sizeof ps->test, 0, "make standard images");
  3075. /* Use next_format to enumerate all the combinations we test, including
  3076. * generating multiple low bit depth palette images.
  3077. */
  3078. while (next_format(&colour_type, &bit_depth, &palette_number, 0))
  3079. {
  3080. int interlace_type;
  3081. for (interlace_type = PNG_INTERLACE_NONE;
  3082. interlace_type < INTERLACE_LAST; ++interlace_type)
  3083. {
  3084. char name[FILE_NAME_SIZE];
  3085. standard_name(name, sizeof name, 0, colour_type, bit_depth,
  3086. palette_number, interlace_type, 0, 0, 0);
  3087. make_transform_image(ps, colour_type, bit_depth, palette_number,
  3088. interlace_type, name);
  3089. }
  3090. }
  3091. }
  3092. /* The following two routines use the PNG interlace support macros from
  3093. * png.h to interlace or deinterlace rows.
  3094. */
  3095. static void
  3096. interlace_row(png_bytep buffer, png_const_bytep imageRow,
  3097. unsigned int pixel_size, png_uint_32 w, int pass)
  3098. {
  3099. png_uint_32 xin, xout, xstep;
  3100. /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
  3101. * code is presented this way to make it easier to understand. In practice
  3102. * consult the code in the libpng source to see other ways of doing this.
  3103. */
  3104. xin = PNG_PASS_START_COL(pass);
  3105. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3106. for (xout=0; xin<w; xin+=xstep)
  3107. {
  3108. pixel_copy(buffer, xout, imageRow, xin, pixel_size);
  3109. ++xout;
  3110. }
  3111. }
  3112. #ifdef PNG_READ_SUPPORTED
  3113. static void
  3114. deinterlace_row(png_bytep buffer, png_const_bytep row,
  3115. unsigned int pixel_size, png_uint_32 w, int pass)
  3116. {
  3117. /* The inverse of the above, 'row' is part of row 'y' of the output image,
  3118. * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
  3119. * the pixels of row into buffer and return the number written (to allow
  3120. * this to be checked).
  3121. */
  3122. png_uint_32 xin, xout, xstep;
  3123. xout = PNG_PASS_START_COL(pass);
  3124. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3125. for (xin=0; xout<w; xout+=xstep)
  3126. {
  3127. pixel_copy(buffer, xout, row, xin, pixel_size);
  3128. ++xin;
  3129. }
  3130. }
  3131. #endif /* PNG_READ_SUPPORTED */
  3132. /* Build a single row for the 'size' test images; this fills in only the
  3133. * first bit_width bits of the sample row.
  3134. */
  3135. static void
  3136. size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
  3137. {
  3138. /* height is in the range 1 to 16, so: */
  3139. y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
  3140. /* the following ensures bits are set in small images: */
  3141. y ^= 0xA5;
  3142. while (bit_width >= 8)
  3143. *buffer++ = (png_byte)y++, bit_width -= 8;
  3144. /* There may be up to 7 remaining bits, these go in the most significant
  3145. * bits of the byte.
  3146. */
  3147. if (bit_width > 0)
  3148. {
  3149. png_uint_32 mask = (1U<<(8-bit_width))-1;
  3150. *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
  3151. }
  3152. }
  3153. static void
  3154. make_size_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type,
  3155. png_byte PNG_CONST bit_depth, int PNG_CONST interlace_type,
  3156. png_uint_32 PNG_CONST w, png_uint_32 PNG_CONST h,
  3157. int PNG_CONST do_interlace)
  3158. {
  3159. context(ps, fault);
  3160. /* At present libpng does not support the write of an interlaced image unless
  3161. * PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the code here
  3162. * does the pixel interlace itself, so:
  3163. */
  3164. check_interlace_type(interlace_type);
  3165. Try
  3166. {
  3167. png_infop pi;
  3168. png_structp pp;
  3169. unsigned int pixel_size;
  3170. /* Make a name and get an appropriate id for the store: */
  3171. char name[FILE_NAME_SIZE];
  3172. PNG_CONST png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
  3173. interlace_type, w, h, do_interlace);
  3174. standard_name_from_id(name, sizeof name, 0, id);
  3175. pp = set_store_for_write(ps, &pi, name);
  3176. /* In the event of a problem return control to the Catch statement below
  3177. * to do the clean up - it is not possible to 'return' directly from a Try
  3178. * block.
  3179. */
  3180. if (pp == NULL)
  3181. Throw ps;
  3182. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3183. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3184. #ifdef PNG_TEXT_SUPPORTED
  3185. {
  3186. static char key[] = "image name"; /* must be writeable */
  3187. size_t pos;
  3188. png_text text;
  3189. char copy[FILE_NAME_SIZE];
  3190. /* Use a compressed text string to test the correct interaction of text
  3191. * compression and IDAT compression.
  3192. */
  3193. text.compression = TEXT_COMPRESSION;
  3194. text.key = key;
  3195. /* Yuck: the text must be writable! */
  3196. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3197. text.text = copy;
  3198. text.text_length = pos;
  3199. text.itxt_length = 0;
  3200. text.lang = 0;
  3201. text.lang_key = 0;
  3202. png_set_text(pp, pi, &text, 1);
  3203. }
  3204. #endif
  3205. if (colour_type == 3) /* palette */
  3206. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3207. png_write_info(pp, pi);
  3208. /* Calculate the bit size, divide by 8 to get the byte size - this won't
  3209. * overflow because we know the w values are all small enough even for
  3210. * a system where 'unsigned int' is only 16 bits.
  3211. */
  3212. pixel_size = bit_size(pp, colour_type, bit_depth);
  3213. if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
  3214. png_error(pp, "row size incorrect");
  3215. else
  3216. {
  3217. int npasses = npasses_from_interlace_type(pp, interlace_type);
  3218. png_uint_32 y;
  3219. int pass;
  3220. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3221. int nfilter = PNG_FILTER_VALUE_LAST;
  3222. # endif
  3223. png_byte image[16][SIZE_ROWMAX];
  3224. /* To help consistent error detection make the parts of this buffer
  3225. * that aren't set below all '1':
  3226. */
  3227. memset(image, 0xff, sizeof image);
  3228. if (!do_interlace && npasses != png_set_interlace_handling(pp))
  3229. png_error(pp, "write: png_set_interlace_handling failed");
  3230. /* Prepare the whole image first to avoid making it 7 times: */
  3231. for (y=0; y<h; ++y)
  3232. size_row(image[y], w * pixel_size, y);
  3233. for (pass=0; pass<npasses; ++pass)
  3234. {
  3235. /* The following two are for checking the macros: */
  3236. PNG_CONST png_uint_32 wPass = PNG_PASS_COLS(w, pass);
  3237. /* If do_interlace is set we don't call png_write_row for every
  3238. * row because some of them are empty. In fact, for a 1x1 image,
  3239. * most of them are empty!
  3240. */
  3241. for (y=0; y<h; ++y)
  3242. {
  3243. png_const_bytep row = image[y];
  3244. png_byte tempRow[SIZE_ROWMAX];
  3245. /* If do_interlace *and* the image is interlaced we
  3246. * need a reduced interlace row; this may be reduced
  3247. * to empty.
  3248. */
  3249. if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
  3250. {
  3251. /* The row must not be written if it doesn't exist, notice
  3252. * that there are two conditions here, either the row isn't
  3253. * ever in the pass or the row would be but isn't wide
  3254. * enough to contribute any pixels. In fact the wPass test
  3255. * can be used to skip the whole y loop in this case.
  3256. */
  3257. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
  3258. {
  3259. /* Set to all 1's for error detection (libpng tends to
  3260. * set unset things to 0).
  3261. */
  3262. memset(tempRow, 0xff, sizeof tempRow);
  3263. interlace_row(tempRow, row, pixel_size, w, pass);
  3264. row = tempRow;
  3265. }
  3266. else
  3267. continue;
  3268. }
  3269. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3270. /* Only get to here if the row has some pixels in it, set the
  3271. * filters to 'all' for the very first row and thereafter to a
  3272. * single filter. It isn't well documented, but png_set_filter
  3273. * does accept a filter number (per the spec) as well as a bit
  3274. * mask.
  3275. *
  3276. * The apparent wackiness of decrementing nfilter rather than
  3277. * incrementing is so that Paeth gets used in all images bigger
  3278. * than 1 row - it's the tricky one.
  3279. */
  3280. png_set_filter(pp, 0/*method*/,
  3281. nfilter >= PNG_FILTER_VALUE_LAST ? PNG_ALL_FILTERS : nfilter);
  3282. if (nfilter-- == 0)
  3283. nfilter = PNG_FILTER_VALUE_LAST-1;
  3284. # endif
  3285. png_write_row(pp, row);
  3286. }
  3287. }
  3288. }
  3289. #ifdef PNG_TEXT_SUPPORTED
  3290. {
  3291. static char key[] = "end marker";
  3292. static char comment[] = "end";
  3293. png_text text;
  3294. /* Use a compressed text string to test the correct interaction of text
  3295. * compression and IDAT compression.
  3296. */
  3297. text.compression = TEXT_COMPRESSION;
  3298. text.key = key;
  3299. text.text = comment;
  3300. text.text_length = (sizeof comment)-1;
  3301. text.itxt_length = 0;
  3302. text.lang = 0;
  3303. text.lang_key = 0;
  3304. png_set_text(pp, pi, &text, 1);
  3305. }
  3306. #endif
  3307. png_write_end(pp, pi);
  3308. /* And store this under the appropriate id, then clean up. */
  3309. store_storefile(ps, id);
  3310. store_write_reset(ps);
  3311. }
  3312. Catch(fault)
  3313. {
  3314. /* Use the png_store returned by the exception. This may help the compiler
  3315. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3316. * and ps will always be the same value.
  3317. */
  3318. store_write_reset(fault);
  3319. }
  3320. }
  3321. static void
  3322. make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo,
  3323. int PNG_CONST bdhi)
  3324. {
  3325. for (; bdlo <= bdhi; ++bdlo)
  3326. {
  3327. png_uint_32 width;
  3328. for (width = 1; width <= 16; ++width)
  3329. {
  3330. png_uint_32 height;
  3331. for (height = 1; height <= 16; ++height)
  3332. {
  3333. /* The four combinations of DIY interlace and interlace or not -
  3334. * no interlace + DIY should be identical to no interlace with
  3335. * libpng doing it.
  3336. */
  3337. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3338. width, height, 0);
  3339. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3340. width, height, 1);
  3341. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3342. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3343. width, height, 0);
  3344. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3345. width, height, 1);
  3346. # endif
  3347. }
  3348. }
  3349. }
  3350. }
  3351. static void
  3352. make_size_images(png_store *ps)
  3353. {
  3354. /* This is in case of errors. */
  3355. safecat(ps->test, sizeof ps->test, 0, "make size images");
  3356. /* Arguments are colour_type, low bit depth, high bit depth
  3357. */
  3358. make_size(ps, 0, 0, WRITE_BDHI);
  3359. make_size(ps, 2, 3, WRITE_BDHI);
  3360. make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
  3361. make_size(ps, 4, 3, WRITE_BDHI);
  3362. make_size(ps, 6, 3, WRITE_BDHI);
  3363. }
  3364. #ifdef PNG_READ_SUPPORTED
  3365. /* Return a row based on image id and 'y' for checking: */
  3366. static void
  3367. standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
  3368. png_uint_32 id, png_uint_32 y)
  3369. {
  3370. if (WIDTH_FROM_ID(id) == 0)
  3371. transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
  3372. else
  3373. size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
  3374. DEPTH_FROM_ID(id)), y);
  3375. }
  3376. #endif /* PNG_READ_SUPPORTED */
  3377. /* Tests - individual test cases */
  3378. /* Like 'make_standard' but errors are deliberately introduced into the calls
  3379. * to ensure that they get detected - it should not be possible to write an
  3380. * invalid image with libpng!
  3381. */
  3382. /* TODO: the 'set' functions can probably all be made to take a
  3383. * png_const_structp rather than a modifiable one.
  3384. */
  3385. #ifdef PNG_WARNINGS_SUPPORTED
  3386. static void
  3387. sBIT0_error_fn(png_structp pp, png_infop pi)
  3388. {
  3389. /* 0 is invalid... */
  3390. png_color_8 bad;
  3391. bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
  3392. png_set_sBIT(pp, pi, &bad);
  3393. }
  3394. static void
  3395. sBIT_error_fn(png_structp pp, png_infop pi)
  3396. {
  3397. png_byte bit_depth;
  3398. png_color_8 bad;
  3399. if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
  3400. bit_depth = 8;
  3401. else
  3402. bit_depth = png_get_bit_depth(pp, pi);
  3403. /* Now we know the bit depth we can easily generate an invalid sBIT entry */
  3404. bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
  3405. (png_byte)(bit_depth+1);
  3406. png_set_sBIT(pp, pi, &bad);
  3407. }
  3408. static PNG_CONST struct
  3409. {
  3410. void (*fn)(png_structp, png_infop);
  3411. PNG_CONST char *msg;
  3412. unsigned int warning :1; /* the error is a warning... */
  3413. } error_test[] =
  3414. {
  3415. /* no warnings makes these errors undetectable. */
  3416. { sBIT0_error_fn, "sBIT(0): failed to detect error", 1 },
  3417. { sBIT_error_fn, "sBIT(too big): failed to detect error", 1 },
  3418. };
  3419. static void
  3420. make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type,
  3421. png_byte bit_depth, int interlace_type, int test, png_const_charp name)
  3422. {
  3423. png_store * volatile ps = psIn;
  3424. context(ps, fault);
  3425. check_interlace_type(interlace_type);
  3426. Try
  3427. {
  3428. png_structp pp;
  3429. png_infop pi;
  3430. pp = set_store_for_write(ps, &pi, name);
  3431. if (pp == NULL)
  3432. Throw ps;
  3433. png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth),
  3434. transform_height(pp, colour_type, bit_depth), bit_depth, colour_type,
  3435. interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3436. if (colour_type == 3) /* palette */
  3437. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3438. /* Time for a few errors; these are in various optional chunks, the
  3439. * standard tests test the standard chunks pretty well.
  3440. */
  3441. # define exception__prev exception_prev_1
  3442. # define exception__env exception_env_1
  3443. Try
  3444. {
  3445. /* Expect this to throw: */
  3446. ps->expect_error = !error_test[test].warning;
  3447. ps->expect_warning = error_test[test].warning;
  3448. ps->saw_warning = 0;
  3449. error_test[test].fn(pp, pi);
  3450. /* Normally the error is only detected here: */
  3451. png_write_info(pp, pi);
  3452. /* And handle the case where it was only a warning: */
  3453. if (ps->expect_warning && ps->saw_warning)
  3454. Throw ps;
  3455. /* If we get here there is a problem, we have success - no error or
  3456. * no warning - when we shouldn't have success. Log an error.
  3457. */
  3458. store_log(ps, pp, error_test[test].msg, 1 /*error*/);
  3459. }
  3460. Catch (fault)
  3461. ps = fault; /* expected exit, make sure ps is not clobbered */
  3462. #undef exception__prev
  3463. #undef exception__env
  3464. /* And clear these flags */
  3465. ps->expect_error = 0;
  3466. ps->expect_warning = 0;
  3467. /* Now write the whole image, just to make sure that the detected, or
  3468. * undetected, errro has not created problems inside libpng.
  3469. */
  3470. if (png_get_rowbytes(pp, pi) !=
  3471. transform_rowsize(pp, colour_type, bit_depth))
  3472. png_error(pp, "row size incorrect");
  3473. else
  3474. {
  3475. png_uint_32 h = transform_height(pp, colour_type, bit_depth);
  3476. int npasses = png_set_interlace_handling(pp);
  3477. int pass;
  3478. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3479. png_error(pp, "write: png_set_interlace_handling failed");
  3480. for (pass=0; pass<npasses; ++pass)
  3481. {
  3482. png_uint_32 y;
  3483. for (y=0; y<h; ++y)
  3484. {
  3485. png_byte buffer[TRANSFORM_ROWMAX];
  3486. transform_row(pp, buffer, colour_type, bit_depth, y);
  3487. png_write_row(pp, buffer);
  3488. }
  3489. }
  3490. }
  3491. png_write_end(pp, pi);
  3492. /* The following deletes the file that was just written. */
  3493. store_write_reset(ps);
  3494. }
  3495. Catch(fault)
  3496. {
  3497. store_write_reset(fault);
  3498. }
  3499. }
  3500. static int
  3501. make_errors(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type,
  3502. int bdlo, int PNG_CONST bdhi)
  3503. {
  3504. for (; bdlo <= bdhi; ++bdlo)
  3505. {
  3506. int interlace_type;
  3507. for (interlace_type = PNG_INTERLACE_NONE;
  3508. interlace_type < INTERLACE_LAST; ++interlace_type)
  3509. {
  3510. unsigned int test;
  3511. char name[FILE_NAME_SIZE];
  3512. standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
  3513. interlace_type, 0, 0, 0);
  3514. for (test=0; test<ARRAY_SIZE(error_test); ++test)
  3515. {
  3516. make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
  3517. test, name);
  3518. if (fail(pm))
  3519. return 0;
  3520. }
  3521. }
  3522. }
  3523. return 1; /* keep going */
  3524. }
  3525. #endif /* PNG_WARNINGS_SUPPORTED */
  3526. static void
  3527. perform_error_test(png_modifier *pm)
  3528. {
  3529. #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
  3530. /* Need to do this here because we just write in this test. */
  3531. safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
  3532. if (!make_errors(pm, 0, 0, WRITE_BDHI))
  3533. return;
  3534. if (!make_errors(pm, 2, 3, WRITE_BDHI))
  3535. return;
  3536. if (!make_errors(pm, 3, 0, 3))
  3537. return;
  3538. if (!make_errors(pm, 4, 3, WRITE_BDHI))
  3539. return;
  3540. if (!make_errors(pm, 6, 3, WRITE_BDHI))
  3541. return;
  3542. #else
  3543. UNUSED(pm)
  3544. #endif
  3545. }
  3546. /* This is just to validate the internal PNG formatting code - if this fails
  3547. * then the warning messages the library outputs will probably be garbage.
  3548. */
  3549. static void
  3550. perform_formatting_test(png_store *volatile ps)
  3551. {
  3552. #ifdef PNG_TIME_RFC1123_SUPPORTED
  3553. /* The handle into the formatting code is the RFC1123 support; this test does
  3554. * nothing if that is compiled out.
  3555. */
  3556. context(ps, fault);
  3557. Try
  3558. {
  3559. png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
  3560. png_const_charp result;
  3561. # if PNG_LIBPNG_VER >= 10600
  3562. char timestring[29];
  3563. # endif
  3564. png_structp pp;
  3565. png_time pt;
  3566. pp = set_store_for_write(ps, NULL, "libpng formatting test");
  3567. if (pp == NULL)
  3568. Throw ps;
  3569. /* Arbitrary settings: */
  3570. pt.year = 2079;
  3571. pt.month = 8;
  3572. pt.day = 29;
  3573. pt.hour = 13;
  3574. pt.minute = 53;
  3575. pt.second = 60; /* a leap second */
  3576. # if PNG_LIBPNG_VER < 10600
  3577. result = png_convert_to_rfc1123(pp, &pt);
  3578. # else
  3579. if (png_convert_to_rfc1123_buffer(timestring, &pt))
  3580. result = timestring;
  3581. else
  3582. result = NULL;
  3583. # endif
  3584. if (result == NULL)
  3585. png_error(pp, "png_convert_to_rfc1123 failed");
  3586. if (strcmp(result, correct) != 0)
  3587. {
  3588. size_t pos = 0;
  3589. char msg[128];
  3590. pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
  3591. pos = safecat(msg, sizeof msg, pos, correct);
  3592. pos = safecat(msg, sizeof msg, pos, ") returned: '");
  3593. pos = safecat(msg, sizeof msg, pos, result);
  3594. pos = safecat(msg, sizeof msg, pos, "'");
  3595. png_error(pp, msg);
  3596. }
  3597. store_write_reset(ps);
  3598. }
  3599. Catch(fault)
  3600. {
  3601. store_write_reset(fault);
  3602. }
  3603. #else
  3604. UNUSED(ps)
  3605. #endif
  3606. }
  3607. #ifdef PNG_READ_SUPPORTED
  3608. /* Because we want to use the same code in both the progressive reader and the
  3609. * sequential reader it is necessary to deal with the fact that the progressive
  3610. * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
  3611. * must contain all the test parameters and all the local variables directly
  3612. * accessible to the sequential reader implementation.
  3613. *
  3614. * The technique adopted is to reinvent part of what Dijkstra termed a
  3615. * 'display'; an array of pointers to the stack frames of enclosing functions so
  3616. * that a nested function definition can access the local (C auto) variables of
  3617. * the functions that contain its definition. In fact C provides the first
  3618. * pointer (the local variables - the stack frame pointer) and the last (the
  3619. * global variables - the BCPL global vector typically implemented as global
  3620. * addresses), this code requires one more pointer to make the display - the
  3621. * local variables (and function call parameters) of the function that actually
  3622. * invokes either the progressive or sequential reader.
  3623. *
  3624. * Perhaps confusingly this technique is confounded with classes - the
  3625. * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
  3626. * A gamma_display is a standard_display, taking advantage of the ANSI-C
  3627. * requirement that the pointer to the first member of a structure must be the
  3628. * same as the pointer to the structure. This allows us to reuse standard_
  3629. * functions in the gamma test code; something that could not be done with
  3630. * nested functions!
  3631. */
  3632. typedef struct standard_display
  3633. {
  3634. png_store* ps; /* Test parameters (passed to the function) */
  3635. png_byte colour_type;
  3636. png_byte bit_depth;
  3637. png_byte red_sBIT; /* Input data sBIT values. */
  3638. png_byte green_sBIT;
  3639. png_byte blue_sBIT;
  3640. png_byte alpha_sBIT;
  3641. int interlace_type;
  3642. png_uint_32 id; /* Calculated file ID */
  3643. png_uint_32 w; /* Width of image */
  3644. png_uint_32 h; /* Height of image */
  3645. int npasses; /* Number of interlaced passes */
  3646. png_uint_32 pixel_size; /* Width of one pixel in bits */
  3647. png_uint_32 bit_width; /* Width of output row in bits */
  3648. size_t cbRow; /* Bytes in a row of the output image */
  3649. int do_interlace; /* Do interlacing internally */
  3650. int is_transparent; /* Transparency information was present. */
  3651. int speed; /* Doing a speed test */
  3652. int use_update_info;/* Call update_info, not start_image */
  3653. struct
  3654. {
  3655. png_uint_16 red;
  3656. png_uint_16 green;
  3657. png_uint_16 blue;
  3658. } transparent; /* The transparent color, if set. */
  3659. int npalette; /* Number of entries in the palette. */
  3660. store_palette
  3661. palette;
  3662. } standard_display;
  3663. static void
  3664. standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
  3665. int do_interlace, int use_update_info)
  3666. {
  3667. memset(dp, 0, sizeof *dp);
  3668. dp->ps = ps;
  3669. dp->colour_type = COL_FROM_ID(id);
  3670. dp->bit_depth = DEPTH_FROM_ID(id);
  3671. if (dp->bit_depth < 1 || dp->bit_depth > 16)
  3672. internal_error(ps, "internal: bad bit depth");
  3673. if (dp->colour_type == 3)
  3674. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
  3675. else
  3676. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
  3677. dp->bit_depth;
  3678. dp->interlace_type = INTERLACE_FROM_ID(id);
  3679. check_interlace_type(dp->interlace_type);
  3680. dp->id = id;
  3681. /* All the rest are filled in after the read_info: */
  3682. dp->w = 0;
  3683. dp->h = 0;
  3684. dp->npasses = 0;
  3685. dp->pixel_size = 0;
  3686. dp->bit_width = 0;
  3687. dp->cbRow = 0;
  3688. dp->do_interlace = do_interlace;
  3689. dp->is_transparent = 0;
  3690. dp->speed = ps->speed;
  3691. dp->use_update_info = use_update_info;
  3692. dp->npalette = 0;
  3693. /* Preset the transparent color to black: */
  3694. memset(&dp->transparent, 0, sizeof dp->transparent);
  3695. /* Preset the palette to full intensity/opaque througout: */
  3696. memset(dp->palette, 0xff, sizeof dp->palette);
  3697. }
  3698. /* Initialize the palette fields - this must be done later because the palette
  3699. * comes from the particular png_store_file that is selected.
  3700. */
  3701. static void
  3702. standard_palette_init(standard_display *dp)
  3703. {
  3704. store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
  3705. /* The remaining entries remain white/opaque. */
  3706. if (dp->npalette > 0)
  3707. {
  3708. int i = dp->npalette;
  3709. memcpy(dp->palette, palette, i * sizeof *palette);
  3710. /* Check for a non-opaque palette entry: */
  3711. while (--i >= 0)
  3712. if (palette[i].alpha < 255)
  3713. break;
  3714. # ifdef __GNUC__
  3715. /* GCC can't handle the more obviously optimizable version. */
  3716. if (i >= 0)
  3717. dp->is_transparent = 1;
  3718. else
  3719. dp->is_transparent = 0;
  3720. # else
  3721. dp->is_transparent = (i >= 0);
  3722. # endif
  3723. }
  3724. }
  3725. /* Utility to read the palette from the PNG file and convert it into
  3726. * store_palette format. This returns 1 if there is any transparency in the
  3727. * palette (it does not check for a transparent colour in the non-palette case.)
  3728. */
  3729. static int
  3730. read_palette(store_palette palette, int *npalette, png_const_structp pp,
  3731. png_infop pi)
  3732. {
  3733. png_colorp pal;
  3734. png_bytep trans_alpha;
  3735. int num;
  3736. pal = 0;
  3737. *npalette = -1;
  3738. if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
  3739. {
  3740. int i = *npalette;
  3741. if (i <= 0 || i > 256)
  3742. png_error(pp, "validate: invalid PLTE count");
  3743. while (--i >= 0)
  3744. {
  3745. palette[i].red = pal[i].red;
  3746. palette[i].green = pal[i].green;
  3747. palette[i].blue = pal[i].blue;
  3748. }
  3749. /* Mark the remainder of the entries with a flag value (other than
  3750. * white/opaque which is the flag value stored above.)
  3751. */
  3752. memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
  3753. }
  3754. else /* !png_get_PLTE */
  3755. {
  3756. if (*npalette != (-1))
  3757. png_error(pp, "validate: invalid PLTE result");
  3758. /* But there is no palette, so record this: */
  3759. *npalette = 0;
  3760. memset(palette, 113, sizeof (store_palette));
  3761. }
  3762. trans_alpha = 0;
  3763. num = 2; /* force error below */
  3764. if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
  3765. (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
  3766. /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
  3767. * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
  3768. * so in the above call we get a success, we get a pointer (who knows what
  3769. * to) and we get num_trans == 0:
  3770. */
  3771. !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
  3772. {
  3773. int i;
  3774. /* Any of these are crash-worthy - given the implementation of
  3775. * png_get_tRNS up to 1.5 an app won't crash if it just checks the
  3776. * result above and fails to check that the variables it passed have
  3777. * actually been filled in! Note that if the app were to pass the
  3778. * last, png_color_16p, variable too it couldn't rely on this.
  3779. */
  3780. if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
  3781. png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
  3782. for (i=0; i<num; ++i)
  3783. palette[i].alpha = trans_alpha[i];
  3784. for (num=*npalette; i<num; ++i)
  3785. palette[i].alpha = 255;
  3786. for (; i<256; ++i)
  3787. palette[i].alpha = 33; /* flag value */
  3788. return 1; /* transparency */
  3789. }
  3790. else
  3791. {
  3792. /* No palette transparency - just set the alpha channel to opaque. */
  3793. int i;
  3794. for (i=0, num=*npalette; i<num; ++i)
  3795. palette[i].alpha = 255;
  3796. for (; i<256; ++i)
  3797. palette[i].alpha = 55; /* flag value */
  3798. return 0; /* no transparency */
  3799. }
  3800. }
  3801. /* Utility to validate the palette if it should not have changed (the
  3802. * non-transform case).
  3803. */
  3804. static void
  3805. standard_palette_validate(standard_display *dp, png_const_structp pp,
  3806. png_infop pi)
  3807. {
  3808. int npalette;
  3809. store_palette palette;
  3810. if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
  3811. png_error(pp, "validate: palette transparency changed");
  3812. if (npalette != dp->npalette)
  3813. {
  3814. size_t pos = 0;
  3815. char msg[64];
  3816. pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
  3817. pos = safecatn(msg, sizeof msg, pos, dp->npalette);
  3818. pos = safecat(msg, sizeof msg, pos, " -> ");
  3819. pos = safecatn(msg, sizeof msg, pos, npalette);
  3820. png_error(pp, msg);
  3821. }
  3822. {
  3823. int i = npalette; /* npalette is aliased */
  3824. while (--i >= 0)
  3825. if (palette[i].red != dp->palette[i].red ||
  3826. palette[i].green != dp->palette[i].green ||
  3827. palette[i].blue != dp->palette[i].blue ||
  3828. palette[i].alpha != dp->palette[i].alpha)
  3829. png_error(pp, "validate: PLTE or tRNS chunk changed");
  3830. }
  3831. }
  3832. /* By passing a 'standard_display' the progressive callbacks can be used
  3833. * directly by the sequential code, the functions suffixed "_imp" are the
  3834. * implementations, the functions without the suffix are the callbacks.
  3835. *
  3836. * The code for the info callback is split into two because this callback calls
  3837. * png_read_update_info or png_start_read_image and what gets called depends on
  3838. * whether the info needs updating (we want to test both calls in pngvalid.)
  3839. */
  3840. static void
  3841. standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
  3842. {
  3843. if (png_get_bit_depth(pp, pi) != dp->bit_depth)
  3844. png_error(pp, "validate: bit depth changed");
  3845. if (png_get_color_type(pp, pi) != dp->colour_type)
  3846. png_error(pp, "validate: color type changed");
  3847. if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
  3848. png_error(pp, "validate: filter type changed");
  3849. if (png_get_interlace_type(pp, pi) != dp->interlace_type)
  3850. png_error(pp, "validate: interlacing changed");
  3851. if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
  3852. png_error(pp, "validate: compression type changed");
  3853. dp->w = png_get_image_width(pp, pi);
  3854. if (dp->w != standard_width(pp, dp->id))
  3855. png_error(pp, "validate: image width changed");
  3856. dp->h = png_get_image_height(pp, pi);
  3857. if (dp->h != standard_height(pp, dp->id))
  3858. png_error(pp, "validate: image height changed");
  3859. /* Record (but don't check at present) the input sBIT according to the colour
  3860. * type information.
  3861. */
  3862. {
  3863. png_color_8p sBIT = 0;
  3864. if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
  3865. {
  3866. int sBIT_invalid = 0;
  3867. if (sBIT == 0)
  3868. png_error(pp, "validate: unexpected png_get_sBIT result");
  3869. if (dp->colour_type & PNG_COLOR_MASK_COLOR)
  3870. {
  3871. if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
  3872. sBIT_invalid = 1;
  3873. else
  3874. dp->red_sBIT = sBIT->red;
  3875. if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
  3876. sBIT_invalid = 1;
  3877. else
  3878. dp->green_sBIT = sBIT->green;
  3879. if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
  3880. sBIT_invalid = 1;
  3881. else
  3882. dp->blue_sBIT = sBIT->blue;
  3883. }
  3884. else /* !COLOR */
  3885. {
  3886. if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
  3887. sBIT_invalid = 1;
  3888. else
  3889. dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
  3890. }
  3891. /* All 8 bits in tRNS for a palette image are significant - see the
  3892. * spec.
  3893. */
  3894. if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
  3895. {
  3896. if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
  3897. sBIT_invalid = 1;
  3898. else
  3899. dp->alpha_sBIT = sBIT->alpha;
  3900. }
  3901. if (sBIT_invalid)
  3902. png_error(pp, "validate: sBIT value out of range");
  3903. }
  3904. }
  3905. /* Important: this is validating the value *before* any transforms have been
  3906. * put in place. It doesn't matter for the standard tests, where there are
  3907. * no transforms, but it does for other tests where rowbytes may change after
  3908. * png_read_update_info.
  3909. */
  3910. if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
  3911. png_error(pp, "validate: row size changed");
  3912. /* Validate the colour type 3 palette (this can be present on other color
  3913. * types.)
  3914. */
  3915. standard_palette_validate(dp, pp, pi);
  3916. /* In any case always check for a tranparent color (notice that the
  3917. * colour type 3 case must not give a successful return on the get_tRNS call
  3918. * with these arguments!)
  3919. */
  3920. {
  3921. png_color_16p trans_color = 0;
  3922. if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
  3923. {
  3924. if (trans_color == 0)
  3925. png_error(pp, "validate: unexpected png_get_tRNS (color) result");
  3926. switch (dp->colour_type)
  3927. {
  3928. case 0:
  3929. dp->transparent.red = dp->transparent.green = dp->transparent.blue =
  3930. trans_color->gray;
  3931. dp->is_transparent = 1;
  3932. break;
  3933. case 2:
  3934. dp->transparent.red = trans_color->red;
  3935. dp->transparent.green = trans_color->green;
  3936. dp->transparent.blue = trans_color->blue;
  3937. dp->is_transparent = 1;
  3938. break;
  3939. case 3:
  3940. /* Not expected because it should result in the array case
  3941. * above.
  3942. */
  3943. png_error(pp, "validate: unexpected png_get_tRNS result");
  3944. break;
  3945. default:
  3946. png_error(pp, "validate: invalid tRNS chunk with alpha image");
  3947. }
  3948. }
  3949. }
  3950. /* Read the number of passes - expected to match the value used when
  3951. * creating the image (interlaced or not). This has the side effect of
  3952. * turning on interlace handling (if do_interlace is not set.)
  3953. */
  3954. dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
  3955. if (!dp->do_interlace && dp->npasses != png_set_interlace_handling(pp))
  3956. png_error(pp, "validate: file changed interlace type");
  3957. /* Caller calls png_read_update_info or png_start_read_image now, then calls
  3958. * part2.
  3959. */
  3960. }
  3961. /* This must be called *after* the png_read_update_info call to get the correct
  3962. * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
  3963. * image.
  3964. */
  3965. static void
  3966. standard_info_part2(standard_display *dp, png_const_structp pp,
  3967. png_const_infop pi, int nImages)
  3968. {
  3969. /* Record cbRow now that it can be found. */
  3970. dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi),
  3971. png_get_bit_depth(pp, pi));
  3972. dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
  3973. dp->cbRow = png_get_rowbytes(pp, pi);
  3974. /* Validate the rowbytes here again. */
  3975. if (dp->cbRow != (dp->bit_width+7)/8)
  3976. png_error(pp, "bad png_get_rowbytes calculation");
  3977. /* Then ensure there is enough space for the output image(s). */
  3978. store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
  3979. }
  3980. static void
  3981. standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
  3982. int nImages)
  3983. {
  3984. /* Note that the validation routine has the side effect of turning on
  3985. * interlace handling in the subsequent code.
  3986. */
  3987. standard_info_part1(dp, pp, pi);
  3988. /* And the info callback has to call this (or png_read_update_info - see
  3989. * below in the png_modifier code for that variant.
  3990. */
  3991. if (dp->use_update_info)
  3992. {
  3993. /* For debugging the effect of multiple calls: */
  3994. int i = dp->use_update_info;
  3995. while (i-- > 0)
  3996. png_read_update_info(pp, pi);
  3997. }
  3998. else
  3999. png_start_read_image(pp);
  4000. /* Validate the height, width and rowbytes plus ensure that sufficient buffer
  4001. * exists for decoding the image.
  4002. */
  4003. standard_info_part2(dp, pp, pi, nImages);
  4004. }
  4005. static void PNGCBAPI
  4006. standard_info(png_structp pp, png_infop pi)
  4007. {
  4008. standard_display *dp = voidcast(standard_display*,
  4009. png_get_progressive_ptr(pp));
  4010. /* Call with nImages==1 because the progressive reader can only produce one
  4011. * image.
  4012. */
  4013. standard_info_imp(dp, pp, pi, 1 /*only one image*/);
  4014. }
  4015. static void PNGCBAPI
  4016. progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
  4017. {
  4018. png_const_structp pp = ppIn;
  4019. PNG_CONST standard_display *dp = voidcast(standard_display*,
  4020. png_get_progressive_ptr(pp));
  4021. /* When handling interlacing some rows will be absent in each pass, the
  4022. * callback still gets called, but with a NULL pointer. This is checked
  4023. * in the 'else' clause below. We need our own 'cbRow', but we can't call
  4024. * png_get_rowbytes because we got no info structure.
  4025. */
  4026. if (new_row != NULL)
  4027. {
  4028. png_bytep row;
  4029. /* In the case where the reader doesn't do the interlace it gives
  4030. * us the y in the sub-image:
  4031. */
  4032. if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
  4033. {
  4034. #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
  4035. /* Use this opportunity to validate the png 'current' APIs: */
  4036. if (y != png_get_current_row_number(pp))
  4037. png_error(pp, "png_get_current_row_number is broken");
  4038. if (pass != png_get_current_pass_number(pp))
  4039. png_error(pp, "png_get_current_pass_number is broken");
  4040. #endif
  4041. y = PNG_ROW_FROM_PASS_ROW(y, pass);
  4042. }
  4043. /* Validate this just in case. */
  4044. if (y >= dp->h)
  4045. png_error(pp, "invalid y to progressive row callback");
  4046. row = store_image_row(dp->ps, pp, 0, y);
  4047. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4048. /* Combine the new row into the old: */
  4049. if (dp->do_interlace)
  4050. {
  4051. if (dp->interlace_type == PNG_INTERLACE_ADAM7)
  4052. deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass);
  4053. else
  4054. row_copy(row, new_row, dp->pixel_size * dp->w);
  4055. }
  4056. else
  4057. png_progressive_combine_row(pp, row, new_row);
  4058. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  4059. }
  4060. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4061. else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
  4062. PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4063. PNG_PASS_COLS(dp->w, pass) > 0)
  4064. png_error(pp, "missing row in progressive de-interlacing");
  4065. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  4066. }
  4067. static void
  4068. sequential_row(standard_display *dp, png_structp pp, png_infop pi,
  4069. PNG_CONST int iImage, PNG_CONST int iDisplay)
  4070. {
  4071. PNG_CONST int npasses = dp->npasses;
  4072. PNG_CONST int do_interlace = dp->do_interlace &&
  4073. dp->interlace_type == PNG_INTERLACE_ADAM7;
  4074. PNG_CONST png_uint_32 height = standard_height(pp, dp->id);
  4075. PNG_CONST png_uint_32 width = standard_width(pp, dp->id);
  4076. PNG_CONST png_store* ps = dp->ps;
  4077. int pass;
  4078. for (pass=0; pass<npasses; ++pass)
  4079. {
  4080. png_uint_32 y;
  4081. png_uint_32 wPass = PNG_PASS_COLS(width, pass);
  4082. for (y=0; y<height; ++y)
  4083. {
  4084. if (do_interlace)
  4085. {
  4086. /* wPass may be zero or this row may not be in this pass.
  4087. * png_read_row must not be called in either case.
  4088. */
  4089. if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
  4090. {
  4091. /* Read the row into a pair of temporary buffers, then do the
  4092. * merge here into the output rows.
  4093. */
  4094. png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
  4095. /* The following aids (to some extent) error detection - we can
  4096. * see where png_read_row wrote. Use opposite values in row and
  4097. * display to make this easier. Don't use 0xff (which is used in
  4098. * the image write code to fill unused bits) or 0 (which is a
  4099. * likely value to overwrite unused bits with).
  4100. */
  4101. memset(row, 0xc5, sizeof row);
  4102. memset(display, 0x5c, sizeof display);
  4103. png_read_row(pp, row, display);
  4104. if (iImage >= 0)
  4105. deinterlace_row(store_image_row(ps, pp, iImage, y), row,
  4106. dp->pixel_size, dp->w, pass);
  4107. if (iDisplay >= 0)
  4108. deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
  4109. dp->pixel_size, dp->w, pass);
  4110. }
  4111. }
  4112. else
  4113. png_read_row(pp,
  4114. iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
  4115. iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
  4116. }
  4117. }
  4118. /* And finish the read operation (only really necessary if the caller wants
  4119. * to find additional data in png_info from chunks after the last IDAT.)
  4120. */
  4121. png_read_end(pp, pi);
  4122. }
  4123. #ifdef PNG_TEXT_SUPPORTED
  4124. static void
  4125. standard_check_text(png_const_structp pp, png_const_textp tp,
  4126. png_const_charp keyword, png_const_charp text)
  4127. {
  4128. char msg[1024];
  4129. size_t pos = safecat(msg, sizeof msg, 0, "text: ");
  4130. size_t ok;
  4131. pos = safecat(msg, sizeof msg, pos, keyword);
  4132. pos = safecat(msg, sizeof msg, pos, ": ");
  4133. ok = pos;
  4134. if (tp->compression != TEXT_COMPRESSION)
  4135. {
  4136. char buf[64];
  4137. sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
  4138. tp->compression);
  4139. pos = safecat(msg, sizeof msg, pos, buf);
  4140. }
  4141. if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
  4142. {
  4143. pos = safecat(msg, sizeof msg, pos, "keyword \"");
  4144. if (tp->key != NULL)
  4145. {
  4146. pos = safecat(msg, sizeof msg, pos, tp->key);
  4147. pos = safecat(msg, sizeof msg, pos, "\", ");
  4148. }
  4149. else
  4150. pos = safecat(msg, sizeof msg, pos, "null, ");
  4151. }
  4152. if (tp->text == NULL)
  4153. pos = safecat(msg, sizeof msg, pos, "text lost, ");
  4154. else
  4155. {
  4156. if (tp->text_length != strlen(text))
  4157. {
  4158. char buf[64];
  4159. sprintf(buf, "text length changed[%lu->%lu], ",
  4160. (unsigned long)strlen(text), (unsigned long)tp->text_length);
  4161. pos = safecat(msg, sizeof msg, pos, buf);
  4162. }
  4163. if (strcmp(tp->text, text) != 0)
  4164. {
  4165. pos = safecat(msg, sizeof msg, pos, "text becomes \"");
  4166. pos = safecat(msg, sizeof msg, pos, tp->text);
  4167. pos = safecat(msg, sizeof msg, pos, "\" (was \"");
  4168. pos = safecat(msg, sizeof msg, pos, text);
  4169. pos = safecat(msg, sizeof msg, pos, "\"), ");
  4170. }
  4171. }
  4172. if (tp->itxt_length != 0)
  4173. pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
  4174. if (tp->lang != NULL)
  4175. {
  4176. pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
  4177. pos = safecat(msg, sizeof msg, pos, tp->lang);
  4178. pos = safecat(msg, sizeof msg, pos, "\", ");
  4179. }
  4180. if (tp->lang_key != NULL)
  4181. {
  4182. pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
  4183. pos = safecat(msg, sizeof msg, pos, tp->lang_key);
  4184. pos = safecat(msg, sizeof msg, pos, "\", ");
  4185. }
  4186. if (pos > ok)
  4187. {
  4188. msg[pos-2] = '\0'; /* Remove the ", " at the end */
  4189. png_error(pp, msg);
  4190. }
  4191. }
  4192. static void
  4193. standard_text_validate(standard_display *dp, png_const_structp pp,
  4194. png_infop pi, int check_end)
  4195. {
  4196. png_textp tp = NULL;
  4197. png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
  4198. if (num_text == 2 && tp != NULL)
  4199. {
  4200. standard_check_text(pp, tp, "image name", dp->ps->current->name);
  4201. /* This exists because prior to 1.5.18 the progressive reader left the
  4202. * png_struct z_stream unreset at the end of the image, so subsequent
  4203. * attempts to use it simply returns Z_STREAM_END.
  4204. */
  4205. if (check_end)
  4206. standard_check_text(pp, tp+1, "end marker", "end");
  4207. }
  4208. else
  4209. {
  4210. char msg[64];
  4211. sprintf(msg, "expected two text items, got %lu",
  4212. (unsigned long)num_text);
  4213. png_error(pp, msg);
  4214. }
  4215. }
  4216. #else
  4217. # define standard_text_validate(dp,pp,pi,check_end) ((void)0)
  4218. #endif
  4219. static void
  4220. standard_row_validate(standard_display *dp, png_const_structp pp,
  4221. int iImage, int iDisplay, png_uint_32 y)
  4222. {
  4223. int where;
  4224. png_byte std[STANDARD_ROWMAX];
  4225. /* The row must be pre-initialized to the magic number here for the size
  4226. * tests to pass:
  4227. */
  4228. memset(std, 178, sizeof std);
  4229. standard_row(pp, std, dp->id, y);
  4230. /* At the end both the 'row' and 'display' arrays should end up identical.
  4231. * In earlier passes 'row' will be partially filled in, with only the pixels
  4232. * that have been read so far, but 'display' will have those pixels
  4233. * replicated to fill the unread pixels while reading an interlaced image.
  4234. #if PNG_LIBPNG_VER < 10506
  4235. * The side effect inside the libpng sequential reader is that the 'row'
  4236. * array retains the correct values for unwritten pixels within the row
  4237. * bytes, while the 'display' array gets bits off the end of the image (in
  4238. * the last byte) trashed. Unfortunately in the progressive reader the
  4239. * row bytes are always trashed, so we always do a pixel_cmp here even though
  4240. * a memcmp of all cbRow bytes will succeed for the sequential reader.
  4241. #endif
  4242. */
  4243. if (iImage >= 0 &&
  4244. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
  4245. dp->bit_width)) != 0)
  4246. {
  4247. char msg[64];
  4248. sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
  4249. (unsigned long)y, where-1, std[where-1],
  4250. store_image_row(dp->ps, pp, iImage, y)[where-1]);
  4251. png_error(pp, msg);
  4252. }
  4253. #if PNG_LIBPNG_VER < 10506
  4254. /* In this case use pixel_cmp because we need to compare a partial
  4255. * byte at the end of the row if the row is not an exact multiple
  4256. * of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is
  4257. * changed to match!)
  4258. */
  4259. #endif
  4260. if (iDisplay >= 0 &&
  4261. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
  4262. dp->bit_width)) != 0)
  4263. {
  4264. char msg[64];
  4265. sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
  4266. (unsigned long)y, where-1, std[where-1],
  4267. store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
  4268. png_error(pp, msg);
  4269. }
  4270. }
  4271. static void
  4272. standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
  4273. int iDisplay)
  4274. {
  4275. png_uint_32 y;
  4276. if (iImage >= 0)
  4277. store_image_check(dp->ps, pp, iImage);
  4278. if (iDisplay >= 0)
  4279. store_image_check(dp->ps, pp, iDisplay);
  4280. for (y=0; y<dp->h; ++y)
  4281. standard_row_validate(dp, pp, iImage, iDisplay, y);
  4282. /* This avoids false positives if the validation code is never called! */
  4283. dp->ps->validated = 1;
  4284. }
  4285. static void PNGCBAPI
  4286. standard_end(png_structp ppIn, png_infop pi)
  4287. {
  4288. png_const_structp pp = ppIn;
  4289. standard_display *dp = voidcast(standard_display*,
  4290. png_get_progressive_ptr(pp));
  4291. UNUSED(pi)
  4292. /* Validate the image - progressive reading only produces one variant for
  4293. * interlaced images.
  4294. */
  4295. standard_text_validate(dp, pp, pi,
  4296. PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
  4297. standard_image_validate(dp, pp, 0, -1);
  4298. }
  4299. /* A single test run checking the standard image to ensure it is not damaged. */
  4300. static void
  4301. standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id,
  4302. int do_interlace, int use_update_info)
  4303. {
  4304. standard_display d;
  4305. context(psIn, fault);
  4306. /* Set up the display (stack frame) variables from the arguments to the
  4307. * function and initialize the locals that are filled in later.
  4308. */
  4309. standard_display_init(&d, psIn, id, do_interlace, use_update_info);
  4310. /* Everything is protected by a Try/Catch. The functions called also
  4311. * typically have local Try/Catch blocks.
  4312. */
  4313. Try
  4314. {
  4315. png_structp pp;
  4316. png_infop pi;
  4317. /* Get a png_struct for reading the image. This will throw an error if it
  4318. * fails, so we don't need to check the result.
  4319. */
  4320. pp = set_store_for_read(d.ps, &pi, d.id,
  4321. d.do_interlace ? (d.ps->progressive ?
  4322. "pngvalid progressive deinterlacer" :
  4323. "pngvalid sequential deinterlacer") : (d.ps->progressive ?
  4324. "progressive reader" : "sequential reader"));
  4325. /* Initialize the palette correctly from the png_store_file. */
  4326. standard_palette_init(&d);
  4327. /* Introduce the correct read function. */
  4328. if (d.ps->progressive)
  4329. {
  4330. png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
  4331. standard_end);
  4332. /* Now feed data into the reader until we reach the end: */
  4333. store_progressive_read(d.ps, pp, pi);
  4334. }
  4335. else
  4336. {
  4337. /* Note that this takes the store, not the display. */
  4338. png_set_read_fn(pp, d.ps, store_read);
  4339. /* Check the header values: */
  4340. png_read_info(pp, pi);
  4341. /* The code tests both versions of the images that the sequential
  4342. * reader can produce.
  4343. */
  4344. standard_info_imp(&d, pp, pi, 2 /*images*/);
  4345. /* Need the total bytes in the image below; we can't get to this point
  4346. * unless the PNG file values have been checked against the expected
  4347. * values.
  4348. */
  4349. {
  4350. sequential_row(&d, pp, pi, 0, 1);
  4351. /* After the last pass loop over the rows again to check that the
  4352. * image is correct.
  4353. */
  4354. if (!d.speed)
  4355. {
  4356. standard_text_validate(&d, pp, pi, 1/*check_end*/);
  4357. standard_image_validate(&d, pp, 0, 1);
  4358. }
  4359. else
  4360. d.ps->validated = 1;
  4361. }
  4362. }
  4363. /* Check for validation. */
  4364. if (!d.ps->validated)
  4365. png_error(pp, "image read failed silently");
  4366. /* Successful completion. */
  4367. }
  4368. Catch(fault)
  4369. d.ps = fault; /* make sure this hasn't been clobbered. */
  4370. /* In either case clean up the store. */
  4371. store_read_reset(d.ps);
  4372. }
  4373. static int
  4374. test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type,
  4375. int bdlo, int PNG_CONST bdhi)
  4376. {
  4377. for (; bdlo <= bdhi; ++bdlo)
  4378. {
  4379. int interlace_type;
  4380. for (interlace_type = PNG_INTERLACE_NONE;
  4381. interlace_type < INTERLACE_LAST; ++interlace_type)
  4382. {
  4383. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4384. interlace_type, 0, 0, 0), 0/*do_interlace*/, pm->use_update_info);
  4385. if (fail(pm))
  4386. return 0;
  4387. }
  4388. }
  4389. return 1; /* keep going */
  4390. }
  4391. static void
  4392. perform_standard_test(png_modifier *pm)
  4393. {
  4394. /* Test each colour type over the valid range of bit depths (expressed as
  4395. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4396. */
  4397. if (!test_standard(pm, 0, 0, READ_BDHI))
  4398. return;
  4399. if (!test_standard(pm, 2, 3, READ_BDHI))
  4400. return;
  4401. if (!test_standard(pm, 3, 0, 3))
  4402. return;
  4403. if (!test_standard(pm, 4, 3, READ_BDHI))
  4404. return;
  4405. if (!test_standard(pm, 6, 3, READ_BDHI))
  4406. return;
  4407. }
  4408. /********************************** SIZE TESTS ********************************/
  4409. static int
  4410. test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type,
  4411. int bdlo, int PNG_CONST bdhi)
  4412. {
  4413. /* Run the tests on each combination.
  4414. *
  4415. * NOTE: on my 32 bit x86 each of the following blocks takes
  4416. * a total of 3.5 seconds if done across every combo of bit depth
  4417. * width and height. This is a waste of time in practice, hence the
  4418. * hinc and winc stuff:
  4419. */
  4420. static PNG_CONST png_byte hinc[] = {1, 3, 11, 1, 5};
  4421. static PNG_CONST png_byte winc[] = {1, 9, 5, 7, 1};
  4422. for (; bdlo <= bdhi; ++bdlo)
  4423. {
  4424. png_uint_32 h, w;
  4425. for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
  4426. {
  4427. /* First test all the 'size' images against the sequential
  4428. * reader using libpng to deinterlace (where required.) This
  4429. * validates the write side of libpng. There are four possibilities
  4430. * to validate.
  4431. */
  4432. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4433. PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
  4434. pm->use_update_info);
  4435. if (fail(pm))
  4436. return 0;
  4437. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4438. PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
  4439. pm->use_update_info);
  4440. if (fail(pm))
  4441. return 0;
  4442. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  4443. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4444. PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
  4445. pm->use_update_info);
  4446. if (fail(pm))
  4447. return 0;
  4448. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4449. PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
  4450. pm->use_update_info);
  4451. if (fail(pm))
  4452. return 0;
  4453. # endif
  4454. /* Now validate the interlaced read side - do_interlace true,
  4455. * in the progressive case this does actually make a difference
  4456. * to the code used in the non-interlaced case too.
  4457. */
  4458. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4459. PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
  4460. pm->use_update_info);
  4461. if (fail(pm))
  4462. return 0;
  4463. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  4464. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4465. PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
  4466. pm->use_update_info);
  4467. if (fail(pm))
  4468. return 0;
  4469. # endif
  4470. }
  4471. }
  4472. return 1; /* keep going */
  4473. }
  4474. static void
  4475. perform_size_test(png_modifier *pm)
  4476. {
  4477. /* Test each colour type over the valid range of bit depths (expressed as
  4478. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4479. */
  4480. if (!test_size(pm, 0, 0, READ_BDHI))
  4481. return;
  4482. if (!test_size(pm, 2, 3, READ_BDHI))
  4483. return;
  4484. /* For the moment don't do the palette test - it's a waste of time when
  4485. * compared to the grayscale test.
  4486. */
  4487. #if 0
  4488. if (!test_size(pm, 3, 0, 3))
  4489. return;
  4490. #endif
  4491. if (!test_size(pm, 4, 3, READ_BDHI))
  4492. return;
  4493. if (!test_size(pm, 6, 3, READ_BDHI))
  4494. return;
  4495. }
  4496. /******************************* TRANSFORM TESTS ******************************/
  4497. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  4498. /* A set of tests to validate libpng image transforms. The possibilities here
  4499. * are legion because the transforms can be combined in a combinatorial
  4500. * fashion. To deal with this some measure of restraint is required, otherwise
  4501. * the tests would take forever.
  4502. */
  4503. typedef struct image_pixel
  4504. {
  4505. /* A local (pngvalid) representation of a PNG pixel, in all its
  4506. * various forms.
  4507. */
  4508. unsigned int red, green, blue, alpha; /* For non-palette images. */
  4509. unsigned int palette_index; /* For a palette image. */
  4510. png_byte colour_type; /* As in the spec. */
  4511. png_byte bit_depth; /* Defines bit size in row */
  4512. png_byte sample_depth; /* Scale of samples */
  4513. int have_tRNS; /* tRNS chunk may need processing */
  4514. /* For checking the code calculates double precision floating point values
  4515. * along with an error value, accumulated from the transforms. Because an
  4516. * sBIT setting allows larger error bounds (indeed, by the spec, apparently
  4517. * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
  4518. * channel is stored. This sBIT value is folded in to the stored error value
  4519. * at the end of the application of the transforms to the pixel.
  4520. */
  4521. double redf, greenf, bluef, alphaf;
  4522. double rede, greene, bluee, alphae;
  4523. png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
  4524. } image_pixel;
  4525. /* Shared utility function, see below. */
  4526. static void
  4527. image_pixel_setf(image_pixel *this, unsigned int max)
  4528. {
  4529. this->redf = this->red / (double)max;
  4530. this->greenf = this->green / (double)max;
  4531. this->bluef = this->blue / (double)max;
  4532. this->alphaf = this->alpha / (double)max;
  4533. if (this->red < max)
  4534. this->rede = this->redf * DBL_EPSILON;
  4535. else
  4536. this->rede = 0;
  4537. if (this->green < max)
  4538. this->greene = this->greenf * DBL_EPSILON;
  4539. else
  4540. this->greene = 0;
  4541. if (this->blue < max)
  4542. this->bluee = this->bluef * DBL_EPSILON;
  4543. else
  4544. this->bluee = 0;
  4545. if (this->alpha < max)
  4546. this->alphae = this->alphaf * DBL_EPSILON;
  4547. else
  4548. this->alphae = 0;
  4549. }
  4550. /* Initialize the structure for the next pixel - call this before doing any
  4551. * transforms and call it for each pixel since all the fields may need to be
  4552. * reset.
  4553. */
  4554. static void
  4555. image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
  4556. png_byte bit_depth, png_uint_32 x, store_palette palette)
  4557. {
  4558. PNG_CONST png_byte sample_depth = (png_byte)(colour_type ==
  4559. PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
  4560. PNG_CONST unsigned int max = (1U<<sample_depth)-1;
  4561. /* Initially just set everything to the same number and the alpha to opaque.
  4562. * Note that this currently assumes a simple palette where entry x has colour
  4563. * rgb(x,x,x)!
  4564. */
  4565. this->palette_index = this->red = this->green = this->blue =
  4566. sample(row, colour_type, bit_depth, x, 0);
  4567. this->alpha = max;
  4568. this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
  4569. sample_depth;
  4570. /* Then override as appropriate: */
  4571. if (colour_type == 3) /* palette */
  4572. {
  4573. /* This permits the caller to default to the sample value. */
  4574. if (palette != 0)
  4575. {
  4576. PNG_CONST unsigned int i = this->palette_index;
  4577. this->red = palette[i].red;
  4578. this->green = palette[i].green;
  4579. this->blue = palette[i].blue;
  4580. this->alpha = palette[i].alpha;
  4581. }
  4582. }
  4583. else /* not palette */
  4584. {
  4585. unsigned int i = 0;
  4586. if (colour_type & 2)
  4587. {
  4588. this->green = sample(row, colour_type, bit_depth, x, 1);
  4589. this->blue = sample(row, colour_type, bit_depth, x, 2);
  4590. i = 2;
  4591. }
  4592. if (colour_type & 4)
  4593. this->alpha = sample(row, colour_type, bit_depth, x, ++i);
  4594. }
  4595. /* Calculate the scaled values, these are simply the values divided by
  4596. * 'max' and the error is initialized to the double precision epsilon value
  4597. * from the header file.
  4598. */
  4599. image_pixel_setf(this, max);
  4600. /* Store the input information for use in the transforms - these will
  4601. * modify the information.
  4602. */
  4603. this->colour_type = colour_type;
  4604. this->bit_depth = bit_depth;
  4605. this->sample_depth = sample_depth;
  4606. this->have_tRNS = 0;
  4607. }
  4608. /* Convert a palette image to an rgb image. This necessarily converts the tRNS
  4609. * chunk at the same time, because the tRNS will be in palette form. The way
  4610. * palette validation works means that the original palette is never updated,
  4611. * instead the image_pixel value from the row contains the RGB of the
  4612. * corresponding palette entry and *this* is updated. Consequently this routine
  4613. * only needs to change the colour type information.
  4614. */
  4615. static void
  4616. image_pixel_convert_PLTE(image_pixel *this)
  4617. {
  4618. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  4619. {
  4620. if (this->have_tRNS)
  4621. {
  4622. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  4623. this->have_tRNS = 0;
  4624. }
  4625. else
  4626. this->colour_type = PNG_COLOR_TYPE_RGB;
  4627. /* The bit depth of the row changes at this point too (notice that this is
  4628. * the row format, not the sample depth, which is separate.)
  4629. */
  4630. this->bit_depth = 8;
  4631. }
  4632. }
  4633. /* Add an alpha channel; this will import the tRNS information because tRNS is
  4634. * not valid in an alpha image. The bit depth will invariably be set to at
  4635. * least 8. Palette images will be converted to alpha (using the above API).
  4636. */
  4637. static void
  4638. image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display)
  4639. {
  4640. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  4641. image_pixel_convert_PLTE(this);
  4642. if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  4643. {
  4644. if (this->colour_type == PNG_COLOR_TYPE_GRAY)
  4645. {
  4646. if (this->bit_depth < 8)
  4647. this->bit_depth = 8;
  4648. if (this->have_tRNS)
  4649. {
  4650. this->have_tRNS = 0;
  4651. /* Check the input, original, channel value here against the
  4652. * original tRNS gray chunk valie.
  4653. */
  4654. if (this->red == display->transparent.red)
  4655. this->alphaf = 0;
  4656. else
  4657. this->alphaf = 1;
  4658. }
  4659. else
  4660. this->alphaf = 1;
  4661. this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  4662. }
  4663. else if (this->colour_type == PNG_COLOR_TYPE_RGB)
  4664. {
  4665. if (this->have_tRNS)
  4666. {
  4667. this->have_tRNS = 0;
  4668. /* Again, check the exact input values, not the current transformed
  4669. * value!
  4670. */
  4671. if (this->red == display->transparent.red &&
  4672. this->green == display->transparent.green &&
  4673. this->blue == display->transparent.blue)
  4674. this->alphaf = 0;
  4675. else
  4676. this->alphaf = 1;
  4677. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  4678. }
  4679. }
  4680. /* The error in the alpha is zero and the sBIT value comes from the
  4681. * original sBIT data (actually it will always be the original bit depth).
  4682. */
  4683. this->alphae = 0;
  4684. this->alpha_sBIT = display->alpha_sBIT;
  4685. }
  4686. }
  4687. struct transform_display;
  4688. typedef struct image_transform
  4689. {
  4690. /* The name of this transform: a string. */
  4691. PNG_CONST char *name;
  4692. /* Each transform can be disabled from the command line: */
  4693. int enable;
  4694. /* The global list of transforms; read only. */
  4695. struct image_transform *PNG_CONST list;
  4696. /* The global count of the number of times this transform has been set on an
  4697. * image.
  4698. */
  4699. unsigned int global_use;
  4700. /* The local count of the number of times this transform has been set. */
  4701. unsigned int local_use;
  4702. /* The next transform in the list, each transform must call its own next
  4703. * transform after it has processed the pixel successfully.
  4704. */
  4705. PNG_CONST struct image_transform *next;
  4706. /* A single transform for the image, expressed as a series of function
  4707. * callbacks and some space for values.
  4708. *
  4709. * First a callback to add any required modifications to the png_modifier;
  4710. * this gets called just before the modifier is set up for read.
  4711. */
  4712. void (*ini)(PNG_CONST struct image_transform *this,
  4713. struct transform_display *that);
  4714. /* And a callback to set the transform on the current png_read_struct:
  4715. */
  4716. void (*set)(PNG_CONST struct image_transform *this,
  4717. struct transform_display *that, png_structp pp, png_infop pi);
  4718. /* Then a transform that takes an input pixel in one PNG format or another
  4719. * and modifies it by a pngvalid implementation of the transform (thus
  4720. * duplicating the libpng intent without, we hope, duplicating the bugs
  4721. * in the libpng implementation!) The png_structp is solely to allow error
  4722. * reporting via png_error and png_warning.
  4723. */
  4724. void (*mod)(PNG_CONST struct image_transform *this, image_pixel *that,
  4725. png_const_structp pp, PNG_CONST struct transform_display *display);
  4726. /* Add this transform to the list and return true if the transform is
  4727. * meaningful for this colour type and bit depth - if false then the
  4728. * transform should have no effect on the image so there's not a lot of
  4729. * point running it.
  4730. */
  4731. int (*add)(struct image_transform *this,
  4732. PNG_CONST struct image_transform **that, png_byte colour_type,
  4733. png_byte bit_depth);
  4734. } image_transform;
  4735. typedef struct transform_display
  4736. {
  4737. standard_display this;
  4738. /* Parameters */
  4739. png_modifier* pm;
  4740. PNG_CONST image_transform* transform_list;
  4741. /* Local variables */
  4742. png_byte output_colour_type;
  4743. png_byte output_bit_depth;
  4744. /* Modifications (not necessarily used.) */
  4745. gama_modification gama_mod;
  4746. chrm_modification chrm_mod;
  4747. srgb_modification srgb_mod;
  4748. } transform_display;
  4749. /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
  4750. static void
  4751. transform_set_encoding(transform_display *this)
  4752. {
  4753. /* Set up the png_modifier '_current' fields then use these to determine how
  4754. * to add appropriate chunks.
  4755. */
  4756. png_modifier *pm = this->pm;
  4757. modifier_set_encoding(pm);
  4758. if (modifier_color_encoding_is_set(pm))
  4759. {
  4760. if (modifier_color_encoding_is_sRGB(pm))
  4761. srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
  4762. else
  4763. {
  4764. /* Set gAMA and cHRM separately. */
  4765. gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
  4766. if (pm->current_encoding != 0)
  4767. chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
  4768. }
  4769. }
  4770. }
  4771. /* Three functions to end the list: */
  4772. static void
  4773. image_transform_ini_end(PNG_CONST image_transform *this,
  4774. transform_display *that)
  4775. {
  4776. UNUSED(this)
  4777. UNUSED(that)
  4778. }
  4779. static void
  4780. image_transform_set_end(PNG_CONST image_transform *this,
  4781. transform_display *that, png_structp pp, png_infop pi)
  4782. {
  4783. UNUSED(this)
  4784. UNUSED(that)
  4785. UNUSED(pp)
  4786. UNUSED(pi)
  4787. }
  4788. /* At the end of the list recalculate the output image pixel value from the
  4789. * double precision values set up by the preceding 'mod' calls:
  4790. */
  4791. static unsigned int
  4792. sample_scale(double sample_value, unsigned int scale)
  4793. {
  4794. sample_value = floor(sample_value * scale + .5);
  4795. /* Return NaN as 0: */
  4796. if (!(sample_value > 0))
  4797. sample_value = 0;
  4798. else if (sample_value > scale)
  4799. sample_value = scale;
  4800. return (unsigned int)sample_value;
  4801. }
  4802. static void
  4803. image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that,
  4804. png_const_structp pp, PNG_CONST transform_display *display)
  4805. {
  4806. PNG_CONST unsigned int scale = (1U<<that->sample_depth)-1;
  4807. UNUSED(this)
  4808. UNUSED(pp)
  4809. UNUSED(display)
  4810. /* At the end recalculate the digitized red green and blue values according
  4811. * to the current sample_depth of the pixel.
  4812. *
  4813. * The sample value is simply scaled to the maximum, checking for over
  4814. * and underflow (which can both happen for some image transforms,
  4815. * including simple size scaling, though libpng doesn't do that at present.
  4816. */
  4817. that->red = sample_scale(that->redf, scale);
  4818. /* The error value is increased, at the end, according to the lowest sBIT
  4819. * value seen. Common sense tells us that the intermediate integer
  4820. * representations are no more accurate than +/- 0.5 in the integral values,
  4821. * the sBIT allows the implementation to be worse than this. In addition the
  4822. * PNG specification actually permits any error within the range (-1..+1),
  4823. * but that is ignored here. Instead the final digitized value is compared,
  4824. * below to the digitized value of the error limits - this has the net effect
  4825. * of allowing (almost) +/-1 in the output value. It's difficult to see how
  4826. * any algorithm that digitizes intermediate results can be more accurate.
  4827. */
  4828. that->rede += 1./(2*((1U<<that->red_sBIT)-1));
  4829. if (that->colour_type & PNG_COLOR_MASK_COLOR)
  4830. {
  4831. that->green = sample_scale(that->greenf, scale);
  4832. that->blue = sample_scale(that->bluef, scale);
  4833. that->greene += 1./(2*((1U<<that->green_sBIT)-1));
  4834. that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
  4835. }
  4836. else
  4837. {
  4838. that->blue = that->green = that->red;
  4839. that->bluef = that->greenf = that->redf;
  4840. that->bluee = that->greene = that->rede;
  4841. }
  4842. if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
  4843. that->colour_type == PNG_COLOR_TYPE_PALETTE)
  4844. {
  4845. that->alpha = sample_scale(that->alphaf, scale);
  4846. that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
  4847. }
  4848. else
  4849. {
  4850. that->alpha = scale; /* opaque */
  4851. that->alpha = 1; /* Override this. */
  4852. that->alphae = 0; /* It's exact ;-) */
  4853. }
  4854. }
  4855. /* Static 'end' structure: */
  4856. static image_transform image_transform_end =
  4857. {
  4858. "(end)", /* name */
  4859. 1, /* enable */
  4860. 0, /* list */
  4861. 0, /* global_use */
  4862. 0, /* local_use */
  4863. 0, /* next */
  4864. image_transform_ini_end,
  4865. image_transform_set_end,
  4866. image_transform_mod_end,
  4867. 0 /* never called, I want it to crash if it is! */
  4868. };
  4869. /* Reader callbacks and implementations, where they differ from the standard
  4870. * ones.
  4871. */
  4872. static void
  4873. transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
  4874. PNG_CONST image_transform *transform_list)
  4875. {
  4876. memset(dp, 0, sizeof *dp);
  4877. /* Standard fields */
  4878. standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
  4879. pm->use_update_info);
  4880. /* Parameter fields */
  4881. dp->pm = pm;
  4882. dp->transform_list = transform_list;
  4883. /* Local variable fields */
  4884. dp->output_colour_type = 255; /* invalid */
  4885. dp->output_bit_depth = 255; /* invalid */
  4886. }
  4887. static void
  4888. transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
  4889. {
  4890. /* Reuse the standard stuff as appropriate. */
  4891. standard_info_part1(&dp->this, pp, pi);
  4892. /* Now set the list of transforms. */
  4893. dp->transform_list->set(dp->transform_list, dp, pp, pi);
  4894. /* Update the info structure for these transforms: */
  4895. {
  4896. int i = dp->this.use_update_info;
  4897. /* Always do one call, even if use_update_info is 0. */
  4898. do
  4899. png_read_update_info(pp, pi);
  4900. while (--i > 0);
  4901. }
  4902. /* And get the output information into the standard_display */
  4903. standard_info_part2(&dp->this, pp, pi, 1/*images*/);
  4904. /* Plus the extra stuff we need for the transform tests: */
  4905. dp->output_colour_type = png_get_color_type(pp, pi);
  4906. dp->output_bit_depth = png_get_bit_depth(pp, pi);
  4907. /* Validate the combination of colour type and bit depth that we are getting
  4908. * out of libpng; the semantics of something not in the PNG spec are, at
  4909. * best, unclear.
  4910. */
  4911. switch (dp->output_colour_type)
  4912. {
  4913. case PNG_COLOR_TYPE_PALETTE:
  4914. if (dp->output_bit_depth > 8) goto error;
  4915. /*FALL THROUGH*/
  4916. case PNG_COLOR_TYPE_GRAY:
  4917. if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
  4918. dp->output_bit_depth == 4)
  4919. break;
  4920. /*FALL THROUGH*/
  4921. default:
  4922. if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
  4923. break;
  4924. /*FALL THROUGH*/
  4925. error:
  4926. {
  4927. char message[128];
  4928. size_t pos;
  4929. pos = safecat(message, sizeof message, 0,
  4930. "invalid final bit depth: colour type(");
  4931. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  4932. pos = safecat(message, sizeof message, pos, ") with bit depth: ");
  4933. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  4934. png_error(pp, message);
  4935. }
  4936. }
  4937. /* Use a test pixel to check that the output agrees with what we expect -
  4938. * this avoids running the whole test if the output is unexpected.
  4939. */
  4940. {
  4941. image_pixel test_pixel;
  4942. memset(&test_pixel, 0, sizeof test_pixel);
  4943. test_pixel.colour_type = dp->this.colour_type; /* input */
  4944. test_pixel.bit_depth = dp->this.bit_depth;
  4945. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
  4946. test_pixel.sample_depth = 8;
  4947. else
  4948. test_pixel.sample_depth = test_pixel.bit_depth;
  4949. /* Don't need sBIT here, but it must be set to non-zero to avoid
  4950. * arithmetic overflows.
  4951. */
  4952. test_pixel.have_tRNS = dp->this.is_transparent;
  4953. test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
  4954. test_pixel.alpha_sBIT = test_pixel.sample_depth;
  4955. dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
  4956. if (test_pixel.colour_type != dp->output_colour_type)
  4957. {
  4958. char message[128];
  4959. size_t pos = safecat(message, sizeof message, 0, "colour type ");
  4960. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  4961. pos = safecat(message, sizeof message, pos, " expected ");
  4962. pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
  4963. png_error(pp, message);
  4964. }
  4965. if (test_pixel.bit_depth != dp->output_bit_depth)
  4966. {
  4967. char message[128];
  4968. size_t pos = safecat(message, sizeof message, 0, "bit depth ");
  4969. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  4970. pos = safecat(message, sizeof message, pos, " expected ");
  4971. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  4972. png_error(pp, message);
  4973. }
  4974. /* If both bit depth and colour type are correct check the sample depth.
  4975. * I believe these are both internal errors.
  4976. */
  4977. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
  4978. {
  4979. if (test_pixel.sample_depth != 8) /* oops - internal error! */
  4980. png_error(pp, "pngvalid: internal: palette sample depth not 8");
  4981. }
  4982. else if (test_pixel.sample_depth != dp->output_bit_depth)
  4983. {
  4984. char message[128];
  4985. size_t pos = safecat(message, sizeof message, 0,
  4986. "internal: sample depth ");
  4987. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  4988. pos = safecat(message, sizeof message, pos, " expected ");
  4989. pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
  4990. png_error(pp, message);
  4991. }
  4992. }
  4993. }
  4994. static void PNGCBAPI
  4995. transform_info(png_structp pp, png_infop pi)
  4996. {
  4997. transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
  4998. pp, pi);
  4999. }
  5000. static void
  5001. transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
  5002. unsigned int b, unsigned int a, unsigned int in_digitized, double in,
  5003. unsigned int out, png_byte sample_depth, double err, double limit,
  5004. PNG_CONST char *name, double digitization_error)
  5005. {
  5006. /* Compare the scaled, digitzed, values of our local calculation (in+-err)
  5007. * with the digitized values libpng produced; 'sample_depth' is the actual
  5008. * digitization depth of the libpng output colors (the bit depth except for
  5009. * palette images where it is always 8.) The check on 'err' is to detect
  5010. * internal errors in pngvalid itself.
  5011. */
  5012. unsigned int max = (1U<<sample_depth)-1;
  5013. double in_min = ceil((in-err)*max - digitization_error);
  5014. double in_max = floor((in+err)*max + digitization_error);
  5015. if (err > limit || !(out >= in_min && out <= in_max))
  5016. {
  5017. char message[256];
  5018. size_t pos;
  5019. pos = safecat(message, sizeof message, 0, name);
  5020. pos = safecat(message, sizeof message, pos, " output value error: rgba(");
  5021. pos = safecatn(message, sizeof message, pos, r);
  5022. pos = safecat(message, sizeof message, pos, ",");
  5023. pos = safecatn(message, sizeof message, pos, g);
  5024. pos = safecat(message, sizeof message, pos, ",");
  5025. pos = safecatn(message, sizeof message, pos, b);
  5026. pos = safecat(message, sizeof message, pos, ",");
  5027. pos = safecatn(message, sizeof message, pos, a);
  5028. pos = safecat(message, sizeof message, pos, "): ");
  5029. pos = safecatn(message, sizeof message, pos, out);
  5030. pos = safecat(message, sizeof message, pos, " expected: ");
  5031. pos = safecatn(message, sizeof message, pos, in_digitized);
  5032. pos = safecat(message, sizeof message, pos, " (");
  5033. pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
  5034. pos = safecat(message, sizeof message, pos, "..");
  5035. pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
  5036. pos = safecat(message, sizeof message, pos, ")");
  5037. png_error(pp, message);
  5038. }
  5039. }
  5040. static void
  5041. transform_image_validate(transform_display *dp, png_const_structp pp,
  5042. png_infop pi)
  5043. {
  5044. /* Constants for the loop below: */
  5045. PNG_CONST png_store* PNG_CONST ps = dp->this.ps;
  5046. PNG_CONST png_byte in_ct = dp->this.colour_type;
  5047. PNG_CONST png_byte in_bd = dp->this.bit_depth;
  5048. PNG_CONST png_uint_32 w = dp->this.w;
  5049. PNG_CONST png_uint_32 h = dp->this.h;
  5050. PNG_CONST png_byte out_ct = dp->output_colour_type;
  5051. PNG_CONST png_byte out_bd = dp->output_bit_depth;
  5052. PNG_CONST png_byte sample_depth = (png_byte)(out_ct ==
  5053. PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
  5054. PNG_CONST png_byte red_sBIT = dp->this.red_sBIT;
  5055. PNG_CONST png_byte green_sBIT = dp->this.green_sBIT;
  5056. PNG_CONST png_byte blue_sBIT = dp->this.blue_sBIT;
  5057. PNG_CONST png_byte alpha_sBIT = dp->this.alpha_sBIT;
  5058. PNG_CONST int have_tRNS = dp->this.is_transparent;
  5059. double digitization_error;
  5060. store_palette out_palette;
  5061. png_uint_32 y;
  5062. UNUSED(pi)
  5063. /* Check for row overwrite errors */
  5064. store_image_check(dp->this.ps, pp, 0);
  5065. /* Read the palette corresponding to the output if the output colour type
  5066. * indicates a palette, othewise set out_palette to garbage.
  5067. */
  5068. if (out_ct == PNG_COLOR_TYPE_PALETTE)
  5069. {
  5070. /* Validate that the palette count itself has not changed - this is not
  5071. * expected.
  5072. */
  5073. int npalette = (-1);
  5074. (void)read_palette(out_palette, &npalette, pp, pi);
  5075. if (npalette != dp->this.npalette)
  5076. png_error(pp, "unexpected change in palette size");
  5077. digitization_error = .5;
  5078. }
  5079. else
  5080. {
  5081. png_byte in_sample_depth;
  5082. memset(out_palette, 0x5e, sizeof out_palette);
  5083. /* use-input-precision means assume that if the input has 8 bit (or less)
  5084. * samples and the output has 16 bit samples the calculations will be done
  5085. * with 8 bit precision, not 16.
  5086. */
  5087. if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
  5088. in_sample_depth = 8;
  5089. else
  5090. in_sample_depth = in_bd;
  5091. if (sample_depth != 16 || in_sample_depth > 8 ||
  5092. !dp->pm->calculations_use_input_precision)
  5093. digitization_error = .5;
  5094. /* Else calculations are at 8 bit precision, and the output actually
  5095. * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
  5096. */
  5097. else
  5098. digitization_error = .5 * 257;
  5099. }
  5100. for (y=0; y<h; ++y)
  5101. {
  5102. png_const_bytep PNG_CONST pRow = store_image_row(ps, pp, 0, y);
  5103. png_uint_32 x;
  5104. /* The original, standard, row pre-transforms. */
  5105. png_byte std[STANDARD_ROWMAX];
  5106. transform_row(pp, std, in_ct, in_bd, y);
  5107. /* Go through each original pixel transforming it and comparing with what
  5108. * libpng did to the same pixel.
  5109. */
  5110. for (x=0; x<w; ++x)
  5111. {
  5112. image_pixel in_pixel, out_pixel;
  5113. unsigned int r, g, b, a;
  5114. /* Find out what we think the pixel should be: */
  5115. image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette);
  5116. in_pixel.red_sBIT = red_sBIT;
  5117. in_pixel.green_sBIT = green_sBIT;
  5118. in_pixel.blue_sBIT = blue_sBIT;
  5119. in_pixel.alpha_sBIT = alpha_sBIT;
  5120. in_pixel.have_tRNS = have_tRNS;
  5121. /* For error detection, below. */
  5122. r = in_pixel.red;
  5123. g = in_pixel.green;
  5124. b = in_pixel.blue;
  5125. a = in_pixel.alpha;
  5126. dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
  5127. /* Read the output pixel and compare it to what we got, we don't
  5128. * use the error field here, so no need to update sBIT.
  5129. */
  5130. image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette);
  5131. /* We don't expect changes to the index here even if the bit depth is
  5132. * changed.
  5133. */
  5134. if (in_ct == PNG_COLOR_TYPE_PALETTE &&
  5135. out_ct == PNG_COLOR_TYPE_PALETTE)
  5136. {
  5137. if (in_pixel.palette_index != out_pixel.palette_index)
  5138. png_error(pp, "unexpected transformed palette index");
  5139. }
  5140. /* Check the colours for palette images too - in fact the palette could
  5141. * be separately verified itself in most cases.
  5142. */
  5143. if (in_pixel.red != out_pixel.red)
  5144. transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
  5145. out_pixel.red, sample_depth, in_pixel.rede,
  5146. dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
  5147. digitization_error);
  5148. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5149. in_pixel.green != out_pixel.green)
  5150. transform_range_check(pp, r, g, b, a, in_pixel.green,
  5151. in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
  5152. dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
  5153. digitization_error);
  5154. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5155. in_pixel.blue != out_pixel.blue)
  5156. transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
  5157. out_pixel.blue, sample_depth, in_pixel.bluee,
  5158. dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
  5159. digitization_error);
  5160. if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
  5161. in_pixel.alpha != out_pixel.alpha)
  5162. transform_range_check(pp, r, g, b, a, in_pixel.alpha,
  5163. in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
  5164. dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
  5165. digitization_error);
  5166. } /* pixel (x) loop */
  5167. } /* row (y) loop */
  5168. /* Record that something was actually checked to avoid a false positive. */
  5169. dp->this.ps->validated = 1;
  5170. }
  5171. static void PNGCBAPI
  5172. transform_end(png_structp ppIn, png_infop pi)
  5173. {
  5174. png_const_structp pp = ppIn;
  5175. transform_display *dp = voidcast(transform_display*,
  5176. png_get_progressive_ptr(pp));
  5177. if (!dp->this.speed)
  5178. transform_image_validate(dp, pp, pi);
  5179. else
  5180. dp->this.ps->validated = 1;
  5181. }
  5182. /* A single test run. */
  5183. static void
  5184. transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn,
  5185. PNG_CONST image_transform* transform_listIn, PNG_CONST char * volatile name)
  5186. {
  5187. transform_display d;
  5188. context(&pmIn->this, fault);
  5189. transform_display_init(&d, pmIn, idIn, transform_listIn);
  5190. Try
  5191. {
  5192. size_t pos = 0;
  5193. png_structp pp;
  5194. png_infop pi;
  5195. char full_name[256];
  5196. /* Make sure the encoding fields are correct and enter the required
  5197. * modifications.
  5198. */
  5199. transform_set_encoding(&d);
  5200. /* Add any modifications required by the transform list. */
  5201. d.transform_list->ini(d.transform_list, &d);
  5202. /* Add the color space information, if any, to the name. */
  5203. pos = safecat(full_name, sizeof full_name, pos, name);
  5204. pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
  5205. /* Get a png_struct for reading the image. */
  5206. pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
  5207. standard_palette_init(&d.this);
  5208. # if 0
  5209. /* Logging (debugging only) */
  5210. {
  5211. char buffer[256];
  5212. (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
  5213. "running test");
  5214. fprintf(stderr, "%s\n", buffer);
  5215. }
  5216. # endif
  5217. /* Introduce the correct read function. */
  5218. if (d.pm->this.progressive)
  5219. {
  5220. /* Share the row function with the standard implementation. */
  5221. png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
  5222. transform_end);
  5223. /* Now feed data into the reader until we reach the end: */
  5224. modifier_progressive_read(d.pm, pp, pi);
  5225. }
  5226. else
  5227. {
  5228. /* modifier_read expects a png_modifier* */
  5229. png_set_read_fn(pp, d.pm, modifier_read);
  5230. /* Check the header values: */
  5231. png_read_info(pp, pi);
  5232. /* Process the 'info' requirements. Only one image is generated */
  5233. transform_info_imp(&d, pp, pi);
  5234. sequential_row(&d.this, pp, pi, -1, 0);
  5235. if (!d.this.speed)
  5236. transform_image_validate(&d, pp, pi);
  5237. else
  5238. d.this.ps->validated = 1;
  5239. }
  5240. modifier_reset(d.pm);
  5241. }
  5242. Catch(fault)
  5243. {
  5244. modifier_reset(voidcast(png_modifier*,(void*)fault));
  5245. }
  5246. }
  5247. /* The transforms: */
  5248. #define ITSTRUCT(name) image_transform_##name
  5249. #define ITDATA(name) image_transform_data_##name
  5250. #define image_transform_ini image_transform_default_ini
  5251. #define IT(name)\
  5252. static image_transform ITSTRUCT(name) =\
  5253. {\
  5254. #name,\
  5255. 1, /*enable*/\
  5256. &PT, /*list*/\
  5257. 0, /*global_use*/\
  5258. 0, /*local_use*/\
  5259. 0, /*next*/\
  5260. image_transform_ini,\
  5261. image_transform_png_set_##name##_set,\
  5262. image_transform_png_set_##name##_mod,\
  5263. image_transform_png_set_##name##_add\
  5264. }
  5265. #define PT ITSTRUCT(end) /* stores the previous transform */
  5266. /* To save code: */
  5267. static void
  5268. image_transform_default_ini(PNG_CONST image_transform *this,
  5269. transform_display *that)
  5270. {
  5271. this->next->ini(this->next, that);
  5272. }
  5273. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  5274. static int
  5275. image_transform_default_add(image_transform *this,
  5276. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5277. {
  5278. UNUSED(colour_type)
  5279. UNUSED(bit_depth)
  5280. this->next = *that;
  5281. *that = this;
  5282. return 1;
  5283. }
  5284. #endif
  5285. #ifdef PNG_READ_EXPAND_SUPPORTED
  5286. /* png_set_palette_to_rgb */
  5287. static void
  5288. image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform *this,
  5289. transform_display *that, png_structp pp, png_infop pi)
  5290. {
  5291. png_set_palette_to_rgb(pp);
  5292. this->next->set(this->next, that, pp, pi);
  5293. }
  5294. static void
  5295. image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
  5296. image_pixel *that, png_const_structp pp,
  5297. PNG_CONST transform_display *display)
  5298. {
  5299. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5300. image_pixel_convert_PLTE(that);
  5301. this->next->mod(this->next, that, pp, display);
  5302. }
  5303. static int
  5304. image_transform_png_set_palette_to_rgb_add(image_transform *this,
  5305. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5306. {
  5307. UNUSED(bit_depth)
  5308. this->next = *that;
  5309. *that = this;
  5310. return colour_type == PNG_COLOR_TYPE_PALETTE;
  5311. }
  5312. IT(palette_to_rgb);
  5313. #undef PT
  5314. #define PT ITSTRUCT(palette_to_rgb)
  5315. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5316. #ifdef PNG_READ_EXPAND_SUPPORTED
  5317. /* png_set_tRNS_to_alpha */
  5318. static void
  5319. image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform *this,
  5320. transform_display *that, png_structp pp, png_infop pi)
  5321. {
  5322. png_set_tRNS_to_alpha(pp);
  5323. this->next->set(this->next, that, pp, pi);
  5324. }
  5325. static void
  5326. image_transform_png_set_tRNS_to_alpha_mod(PNG_CONST image_transform *this,
  5327. image_pixel *that, png_const_structp pp,
  5328. PNG_CONST transform_display *display)
  5329. {
  5330. /* LIBPNG BUG: this always forces palette images to RGB. */
  5331. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5332. image_pixel_convert_PLTE(that);
  5333. /* This effectively does an 'expand' only if there is some transparency to
  5334. * convert to an alpha channel.
  5335. */
  5336. if (that->have_tRNS)
  5337. image_pixel_add_alpha(that, &display->this);
  5338. /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
  5339. else
  5340. {
  5341. if (that->bit_depth < 8)
  5342. that->bit_depth =8;
  5343. if (that->sample_depth < 8)
  5344. that->sample_depth = 8;
  5345. }
  5346. this->next->mod(this->next, that, pp, display);
  5347. }
  5348. static int
  5349. image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
  5350. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5351. {
  5352. UNUSED(bit_depth)
  5353. this->next = *that;
  5354. *that = this;
  5355. /* We don't know yet whether there will be a tRNS chunk, but we know that
  5356. * this transformation should do nothing if there already is an alpha
  5357. * channel.
  5358. */
  5359. return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  5360. }
  5361. IT(tRNS_to_alpha);
  5362. #undef PT
  5363. #define PT ITSTRUCT(tRNS_to_alpha)
  5364. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5365. #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
  5366. /* png_set_gray_to_rgb */
  5367. static void
  5368. image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this,
  5369. transform_display *that, png_structp pp, png_infop pi)
  5370. {
  5371. png_set_gray_to_rgb(pp);
  5372. this->next->set(this->next, that, pp, pi);
  5373. }
  5374. static void
  5375. image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this,
  5376. image_pixel *that, png_const_structp pp,
  5377. PNG_CONST transform_display *display)
  5378. {
  5379. /* NOTE: we can actually pend the tRNS processing at this point because we
  5380. * can correctly recognize the original pixel value even though we have
  5381. * mapped the one gray channel to the three RGB ones, but in fact libpng
  5382. * doesn't do this, so we don't either.
  5383. */
  5384. if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
  5385. image_pixel_add_alpha(that, &display->this);
  5386. /* Simply expand the bit depth and alter the colour type as required. */
  5387. if (that->colour_type == PNG_COLOR_TYPE_GRAY)
  5388. {
  5389. /* RGB images have a bit depth at least equal to '8' */
  5390. if (that->bit_depth < 8)
  5391. that->sample_depth = that->bit_depth = 8;
  5392. /* And just changing the colour type works here because the green and blue
  5393. * channels are being maintained in lock-step with the red/gray:
  5394. */
  5395. that->colour_type = PNG_COLOR_TYPE_RGB;
  5396. }
  5397. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  5398. that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5399. this->next->mod(this->next, that, pp, display);
  5400. }
  5401. static int
  5402. image_transform_png_set_gray_to_rgb_add(image_transform *this,
  5403. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5404. {
  5405. UNUSED(bit_depth)
  5406. this->next = *that;
  5407. *that = this;
  5408. return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
  5409. }
  5410. IT(gray_to_rgb);
  5411. #undef PT
  5412. #define PT ITSTRUCT(gray_to_rgb)
  5413. #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
  5414. #ifdef PNG_READ_EXPAND_SUPPORTED
  5415. /* png_set_expand */
  5416. static void
  5417. image_transform_png_set_expand_set(PNG_CONST image_transform *this,
  5418. transform_display *that, png_structp pp, png_infop pi)
  5419. {
  5420. png_set_expand(pp);
  5421. this->next->set(this->next, that, pp, pi);
  5422. }
  5423. static void
  5424. image_transform_png_set_expand_mod(PNG_CONST image_transform *this,
  5425. image_pixel *that, png_const_structp pp,
  5426. PNG_CONST transform_display *display)
  5427. {
  5428. /* The general expand case depends on what the colour type is: */
  5429. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5430. image_pixel_convert_PLTE(that);
  5431. else if (that->bit_depth < 8) /* grayscale */
  5432. that->sample_depth = that->bit_depth = 8;
  5433. if (that->have_tRNS)
  5434. image_pixel_add_alpha(that, &display->this);
  5435. this->next->mod(this->next, that, pp, display);
  5436. }
  5437. static int
  5438. image_transform_png_set_expand_add(image_transform *this,
  5439. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5440. {
  5441. UNUSED(bit_depth)
  5442. this->next = *that;
  5443. *that = this;
  5444. /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
  5445. * depth is at least 8 already.
  5446. */
  5447. return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  5448. }
  5449. IT(expand);
  5450. #undef PT
  5451. #define PT ITSTRUCT(expand)
  5452. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5453. #ifdef PNG_READ_EXPAND_SUPPORTED
  5454. /* png_set_expand_gray_1_2_4_to_8
  5455. * LIBPNG BUG: this just does an 'expand'
  5456. */
  5457. static void
  5458. image_transform_png_set_expand_gray_1_2_4_to_8_set(
  5459. PNG_CONST image_transform *this, transform_display *that, png_structp pp,
  5460. png_infop pi)
  5461. {
  5462. png_set_expand_gray_1_2_4_to_8(pp);
  5463. this->next->set(this->next, that, pp, pi);
  5464. }
  5465. static void
  5466. image_transform_png_set_expand_gray_1_2_4_to_8_mod(
  5467. PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp,
  5468. PNG_CONST transform_display *display)
  5469. {
  5470. image_transform_png_set_expand_mod(this, that, pp, display);
  5471. }
  5472. static int
  5473. image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
  5474. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5475. {
  5476. return image_transform_png_set_expand_add(this, that, colour_type,
  5477. bit_depth);
  5478. }
  5479. IT(expand_gray_1_2_4_to_8);
  5480. #undef PT
  5481. #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
  5482. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5483. #ifdef PNG_READ_EXPAND_16_SUPPORTED
  5484. /* png_set_expand_16 */
  5485. static void
  5486. image_transform_png_set_expand_16_set(PNG_CONST image_transform *this,
  5487. transform_display *that, png_structp pp, png_infop pi)
  5488. {
  5489. png_set_expand_16(pp);
  5490. this->next->set(this->next, that, pp, pi);
  5491. }
  5492. static void
  5493. image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this,
  5494. image_pixel *that, png_const_structp pp,
  5495. PNG_CONST transform_display *display)
  5496. {
  5497. /* Expect expand_16 to expand everything to 16 bits as a result of also
  5498. * causing 'expand' to happen.
  5499. */
  5500. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5501. image_pixel_convert_PLTE(that);
  5502. if (that->have_tRNS)
  5503. image_pixel_add_alpha(that, &display->this);
  5504. if (that->bit_depth < 16)
  5505. that->sample_depth = that->bit_depth = 16;
  5506. this->next->mod(this->next, that, pp, display);
  5507. }
  5508. static int
  5509. image_transform_png_set_expand_16_add(image_transform *this,
  5510. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5511. {
  5512. UNUSED(colour_type)
  5513. this->next = *that;
  5514. *that = this;
  5515. /* expand_16 does something unless the bit depth is already 16. */
  5516. return bit_depth < 16;
  5517. }
  5518. IT(expand_16);
  5519. #undef PT
  5520. #define PT ITSTRUCT(expand_16)
  5521. #endif /* PNG_READ_EXPAND_16_SUPPORTED */
  5522. #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
  5523. /* png_set_scale_16 */
  5524. static void
  5525. image_transform_png_set_scale_16_set(PNG_CONST image_transform *this,
  5526. transform_display *that, png_structp pp, png_infop pi)
  5527. {
  5528. png_set_scale_16(pp);
  5529. this->next->set(this->next, that, pp, pi);
  5530. }
  5531. static void
  5532. image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
  5533. image_pixel *that, png_const_structp pp,
  5534. PNG_CONST transform_display *display)
  5535. {
  5536. if (that->bit_depth == 16)
  5537. {
  5538. that->sample_depth = that->bit_depth = 8;
  5539. if (that->red_sBIT > 8) that->red_sBIT = 8;
  5540. if (that->green_sBIT > 8) that->green_sBIT = 8;
  5541. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  5542. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  5543. }
  5544. this->next->mod(this->next, that, pp, display);
  5545. }
  5546. static int
  5547. image_transform_png_set_scale_16_add(image_transform *this,
  5548. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5549. {
  5550. UNUSED(colour_type)
  5551. this->next = *that;
  5552. *that = this;
  5553. return bit_depth > 8;
  5554. }
  5555. IT(scale_16);
  5556. #undef PT
  5557. #define PT ITSTRUCT(scale_16)
  5558. #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
  5559. #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
  5560. /* png_set_strip_16 */
  5561. static void
  5562. image_transform_png_set_strip_16_set(PNG_CONST image_transform *this,
  5563. transform_display *that, png_structp pp, png_infop pi)
  5564. {
  5565. png_set_strip_16(pp);
  5566. this->next->set(this->next, that, pp, pi);
  5567. }
  5568. static void
  5569. image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
  5570. image_pixel *that, png_const_structp pp,
  5571. PNG_CONST transform_display *display)
  5572. {
  5573. if (that->bit_depth == 16)
  5574. {
  5575. that->sample_depth = that->bit_depth = 8;
  5576. if (that->red_sBIT > 8) that->red_sBIT = 8;
  5577. if (that->green_sBIT > 8) that->green_sBIT = 8;
  5578. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  5579. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  5580. /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
  5581. * configuration option is set. From 1.5.4 the flag is never set and the
  5582. * 'scale' API (above) must be used.
  5583. */
  5584. # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
  5585. # if PNG_LIBPNG_VER >= 10504
  5586. # error PNG_READ_ACCURATE_SCALE should not be set
  5587. # endif
  5588. /* The strip 16 algorithm drops the low 8 bits rather than calculating
  5589. * 1/257, so we need to adjust the permitted errors appropriately:
  5590. * Notice that this is only relevant prior to the addition of the
  5591. * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
  5592. */
  5593. {
  5594. PNG_CONST double d = (255-128.5)/65535;
  5595. that->rede += d;
  5596. that->greene += d;
  5597. that->bluee += d;
  5598. that->alphae += d;
  5599. }
  5600. # endif
  5601. }
  5602. this->next->mod(this->next, that, pp, display);
  5603. }
  5604. static int
  5605. image_transform_png_set_strip_16_add(image_transform *this,
  5606. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5607. {
  5608. UNUSED(colour_type)
  5609. this->next = *that;
  5610. *that = this;
  5611. return bit_depth > 8;
  5612. }
  5613. IT(strip_16);
  5614. #undef PT
  5615. #define PT ITSTRUCT(strip_16)
  5616. #endif /* PNG_READ_16_TO_8_SUPPORTED */
  5617. #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
  5618. /* png_set_strip_alpha */
  5619. static void
  5620. image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
  5621. transform_display *that, png_structp pp, png_infop pi)
  5622. {
  5623. png_set_strip_alpha(pp);
  5624. this->next->set(this->next, that, pp, pi);
  5625. }
  5626. static void
  5627. image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this,
  5628. image_pixel *that, png_const_structp pp,
  5629. PNG_CONST transform_display *display)
  5630. {
  5631. if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  5632. that->colour_type = PNG_COLOR_TYPE_GRAY;
  5633. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  5634. that->colour_type = PNG_COLOR_TYPE_RGB;
  5635. that->have_tRNS = 0;
  5636. that->alphaf = 1;
  5637. this->next->mod(this->next, that, pp, display);
  5638. }
  5639. static int
  5640. image_transform_png_set_strip_alpha_add(image_transform *this,
  5641. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  5642. {
  5643. UNUSED(bit_depth)
  5644. this->next = *that;
  5645. *that = this;
  5646. return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
  5647. }
  5648. IT(strip_alpha);
  5649. #undef PT
  5650. #define PT ITSTRUCT(strip_alpha)
  5651. #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
  5652. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  5653. /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
  5654. * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
  5655. * png_fixed_point green)
  5656. * png_get_rgb_to_gray_status
  5657. *
  5658. * The 'default' test here uses values known to be used inside libpng:
  5659. *
  5660. * red: 6968
  5661. * green: 23434
  5662. * blue: 2366
  5663. *
  5664. * These values are being retained for compatibility, along with the somewhat
  5665. * broken truncation calculation in the fast-and-inaccurate code path. Older
  5666. * versions of libpng will fail the accuracy tests below because they use the
  5667. * truncation algorithm everywhere.
  5668. */
  5669. #define data ITDATA(rgb_to_gray)
  5670. static struct
  5671. {
  5672. double gamma; /* File gamma to use in processing */
  5673. /* The following are the parameters for png_set_rgb_to_gray: */
  5674. # ifdef PNG_FLOATING_POINT_SUPPORTED
  5675. double red_to_set;
  5676. double green_to_set;
  5677. # else
  5678. png_fixed_point red_to_set;
  5679. png_fixed_point green_to_set;
  5680. # endif
  5681. /* The actual coefficients: */
  5682. double red_coefficient;
  5683. double green_coefficient;
  5684. double blue_coefficient;
  5685. /* Set if the coeefficients have been overridden. */
  5686. int coefficients_overridden;
  5687. } data;
  5688. #undef image_transform_ini
  5689. #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
  5690. static void
  5691. image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform *this,
  5692. transform_display *that)
  5693. {
  5694. png_modifier *pm = that->pm;
  5695. PNG_CONST color_encoding *e = pm->current_encoding;
  5696. UNUSED(this)
  5697. /* Since we check the encoding this flag must be set: */
  5698. pm->test_uses_encoding = 1;
  5699. /* If 'e' is not NULL chromaticity information is present and either a cHRM
  5700. * or an sRGB chunk will be inserted.
  5701. */
  5702. if (e != 0)
  5703. {
  5704. /* Coefficients come from the encoding, but may need to be normalized to a
  5705. * white point Y of 1.0
  5706. */
  5707. PNG_CONST double whiteY = e->red.Y + e->green.Y + e->blue.Y;
  5708. data.red_coefficient = e->red.Y;
  5709. data.green_coefficient = e->green.Y;
  5710. data.blue_coefficient = e->blue.Y;
  5711. if (whiteY != 1)
  5712. {
  5713. data.red_coefficient /= whiteY;
  5714. data.green_coefficient /= whiteY;
  5715. data.blue_coefficient /= whiteY;
  5716. }
  5717. }
  5718. else
  5719. {
  5720. /* The default (built in) coeffcients, as above: */
  5721. data.red_coefficient = 6968 / 32768.;
  5722. data.green_coefficient = 23434 / 32768.;
  5723. data.blue_coefficient = 2366 / 32768.;
  5724. }
  5725. data.gamma = pm->current_gamma;
  5726. /* If not set then the calculations assume linear encoding (implicitly): */
  5727. if (data.gamma == 0)
  5728. data.gamma = 1;
  5729. /* The arguments to png_set_rgb_to_gray can override the coefficients implied
  5730. * by the color space encoding. If doing exhaustive checks do the override
  5731. * in each case, otherwise do it randomly.
  5732. */
  5733. if (pm->test_exhaustive)
  5734. {
  5735. /* First time in coefficients_overridden is 0, the following sets it to 1,
  5736. * so repeat if it is set. If a test fails this may mean we subsequently
  5737. * skip a non-override test, ignore that.
  5738. */
  5739. data.coefficients_overridden = !data.coefficients_overridden;
  5740. pm->repeat = data.coefficients_overridden != 0;
  5741. }
  5742. else
  5743. data.coefficients_overridden = random_choice();
  5744. if (data.coefficients_overridden)
  5745. {
  5746. /* These values override the color encoding defaults, simply use random
  5747. * numbers.
  5748. */
  5749. png_uint_32 ru;
  5750. double total;
  5751. RANDOMIZE(ru);
  5752. data.green_coefficient = total = (ru & 0xffff) / 65535.;
  5753. ru >>= 16;
  5754. data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
  5755. total += data.red_coefficient;
  5756. data.blue_coefficient = 1 - total;
  5757. # ifdef PNG_FLOATING_POINT_SUPPORTED
  5758. data.red_to_set = data.red_coefficient;
  5759. data.green_to_set = data.green_coefficient;
  5760. # else
  5761. data.red_to_set = fix(data.red_coefficient);
  5762. data.green_to_set = fix(data.green_coefficient);
  5763. # endif
  5764. /* The following just changes the error messages: */
  5765. pm->encoding_ignored = 1;
  5766. }
  5767. else
  5768. {
  5769. data.red_to_set = -1;
  5770. data.green_to_set = -1;
  5771. }
  5772. /* Adjust the error limit in the png_modifier because of the larger errors
  5773. * produced in the digitization during the gamma handling.
  5774. */
  5775. if (data.gamma != 1) /* Use gamma tables */
  5776. {
  5777. if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
  5778. {
  5779. /* The computations have the form:
  5780. *
  5781. * r * rc + g * gc + b * bc
  5782. *
  5783. * Each component of which is +/-1/65535 from the gamma_to_1 table
  5784. * lookup, resulting in a base error of +/-6. The gamma_from_1
  5785. * conversion adds another +/-2 in the 16-bit case and
  5786. * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
  5787. */
  5788. that->pm->limit +=
  5789. # if PNG_MAX_GAMMA_8 < 14
  5790. pow((that->this.bit_depth == 16 ?
  5791. 8. : 6. + (1<<(15-PNG_MAX_GAMMA_8)))/65535, data.gamma);
  5792. # else
  5793. pow((that->this.bit_depth == 16 ?
  5794. 8. : 8. + (1<<(15-PNG_MAX_GAMMA_8)))/65535, data.gamma);
  5795. # endif
  5796. }
  5797. else
  5798. {
  5799. /* Rounding to 8 bits in the linear space causes massive errors which
  5800. * will trigger the error check in transform_range_check. Fix that
  5801. * here by taking the gamma encoding into account.
  5802. *
  5803. * When DIGITIZE is set because a pre-1.7 version of libpng is being
  5804. * tested allow a bigger slack.
  5805. *
  5806. * NOTE: this magic number was determined by experiment to be 1.1 (when
  5807. * using fixed point arithmetic). There's no great merit to the value
  5808. * below, however it only affects the limit used for checking for
  5809. * internal calculation errors, not the actual limit imposed by
  5810. * pngvalid on the output errors.
  5811. */
  5812. that->pm->limit +=
  5813. # if DIGITIZE
  5814. pow(1.1 /255, data.gamma);
  5815. # else
  5816. pow(1.0 /255, data.gamma);
  5817. # endif
  5818. }
  5819. }
  5820. else
  5821. {
  5822. /* With no gamma correction a large error comes from the truncation of the
  5823. * calculation in the 8 bit case, allow for that here.
  5824. */
  5825. if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
  5826. that->pm->limit += 4E-3;
  5827. }
  5828. }
  5829. static void
  5830. image_transform_png_set_rgb_to_gray_set(PNG_CONST image_transform *this,
  5831. transform_display *that, png_structp pp, png_infop pi)
  5832. {
  5833. PNG_CONST int error_action = 1; /* no error, no defines in png.h */
  5834. # ifdef PNG_FLOATING_POINT_SUPPORTED
  5835. png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
  5836. # else
  5837. png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
  5838. data.green_to_set);
  5839. # endif
  5840. # ifdef PNG_READ_cHRM_SUPPORTED
  5841. if (that->pm->current_encoding != 0)
  5842. {
  5843. /* We have an encoding so a cHRM chunk may have been set; if so then
  5844. * check that the libpng APIs give the correct (X,Y,Z) values within
  5845. * some margin of error for the round trip through the chromaticity
  5846. * form.
  5847. */
  5848. # ifdef PNG_FLOATING_POINT_SUPPORTED
  5849. # define API_function png_get_cHRM_XYZ
  5850. # define API_form "FP"
  5851. # define API_type double
  5852. # define API_cvt(x) (x)
  5853. # else
  5854. # define API_function png_get_cHRM_XYZ_fixed
  5855. # define API_form "fixed"
  5856. # define API_type png_fixed_point
  5857. # define API_cvt(x) ((double)(x)/PNG_FP_1)
  5858. # endif
  5859. API_type rX, gX, bX;
  5860. API_type rY, gY, bY;
  5861. API_type rZ, gZ, bZ;
  5862. if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
  5863. & PNG_INFO_cHRM) != 0)
  5864. {
  5865. double maxe;
  5866. PNG_CONST char *el;
  5867. color_encoding e, o;
  5868. /* Expect libpng to return a normalized result, but the original
  5869. * color space encoding may not be normalized.
  5870. */
  5871. modifier_current_encoding(that->pm, &o);
  5872. normalize_color_encoding(&o);
  5873. /* Sanity check the pngvalid code - the coefficients should match
  5874. * the normalized Y values of the encoding unless they were
  5875. * overridden.
  5876. */
  5877. if (data.red_to_set == -1 && data.green_to_set == -1 &&
  5878. (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
  5879. fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
  5880. fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
  5881. png_error(pp, "internal pngvalid cHRM coefficient error");
  5882. /* Generate a colour space encoding. */
  5883. e.gamma = o.gamma; /* not used */
  5884. e.red.X = API_cvt(rX);
  5885. e.red.Y = API_cvt(rY);
  5886. e.red.Z = API_cvt(rZ);
  5887. e.green.X = API_cvt(gX);
  5888. e.green.Y = API_cvt(gY);
  5889. e.green.Z = API_cvt(gZ);
  5890. e.blue.X = API_cvt(bX);
  5891. e.blue.Y = API_cvt(bY);
  5892. e.blue.Z = API_cvt(bZ);
  5893. /* This should match the original one from the png_modifier, within
  5894. * the range permitted by the libpng fixed point representation.
  5895. */
  5896. maxe = 0;
  5897. el = "-"; /* Set to element name with error */
  5898. # define CHECK(col,x)\
  5899. {\
  5900. double err = fabs(o.col.x - e.col.x);\
  5901. if (err > maxe)\
  5902. {\
  5903. maxe = err;\
  5904. el = #col "(" #x ")";\
  5905. }\
  5906. }
  5907. CHECK(red,X)
  5908. CHECK(red,Y)
  5909. CHECK(red,Z)
  5910. CHECK(green,X)
  5911. CHECK(green,Y)
  5912. CHECK(green,Z)
  5913. CHECK(blue,X)
  5914. CHECK(blue,Y)
  5915. CHECK(blue,Z)
  5916. /* Here in both fixed and floating cases to check the values read
  5917. * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
  5918. * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
  5919. */
  5920. if (maxe >= 1E-5)
  5921. {
  5922. size_t pos = 0;
  5923. char buffer[256];
  5924. pos = safecat(buffer, sizeof buffer, pos, API_form);
  5925. pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
  5926. pos = safecat(buffer, sizeof buffer, pos, el);
  5927. pos = safecat(buffer, sizeof buffer, pos, " error: ");
  5928. pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
  5929. pos = safecat(buffer, sizeof buffer, pos, " ");
  5930. /* Print the color space without the gamma value: */
  5931. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
  5932. pos = safecat(buffer, sizeof buffer, pos, " -> ");
  5933. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
  5934. png_error(pp, buffer);
  5935. }
  5936. }
  5937. }
  5938. # endif /* READ_cHRM */
  5939. this->next->set(this->next, that, pp, pi);
  5940. }
  5941. static void
  5942. image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform *this,
  5943. image_pixel *that, png_const_structp pp,
  5944. PNG_CONST transform_display *display)
  5945. {
  5946. if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
  5947. {
  5948. double gray, err;
  5949. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5950. image_pixel_convert_PLTE(that);
  5951. /* Image now has RGB channels... */
  5952. # if DIGITIZE
  5953. {
  5954. PNG_CONST png_modifier *pm = display->pm;
  5955. const unsigned int sample_depth = that->sample_depth;
  5956. const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
  5957. sample_depth);
  5958. const unsigned int gamma_depth = (sample_depth == 16 ? 16 :
  5959. (pm->assume_16_bit_calculations ? PNG_MAX_GAMMA_8 : sample_depth));
  5960. int isgray;
  5961. double r, g, b;
  5962. double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
  5963. /* Do this using interval arithmetic, otherwise it is too difficult to
  5964. * handle the errors correctly.
  5965. *
  5966. * To handle the gamma correction work out the upper and lower bounds
  5967. * of the digitized value. Assume rounding here - normally the values
  5968. * will be identical after this operation if there is only one
  5969. * transform, feel free to delete the png_error checks on this below in
  5970. * the future (this is just me trying to ensure it works!)
  5971. */
  5972. r = rlo = rhi = that->redf;
  5973. rlo -= that->rede;
  5974. rlo = digitize(rlo, calc_depth, 1/*round*/);
  5975. rhi += that->rede;
  5976. rhi = digitize(rhi, calc_depth, 1/*round*/);
  5977. g = glo = ghi = that->greenf;
  5978. glo -= that->greene;
  5979. glo = digitize(glo, calc_depth, 1/*round*/);
  5980. ghi += that->greene;
  5981. ghi = digitize(ghi, calc_depth, 1/*round*/);
  5982. b = blo = bhi = that->bluef;
  5983. blo -= that->bluee;
  5984. blo = digitize(blo, calc_depth, 1/*round*/);
  5985. bhi += that->greene;
  5986. bhi = digitize(bhi, calc_depth, 1/*round*/);
  5987. isgray = r==g && g==b;
  5988. if (data.gamma != 1)
  5989. {
  5990. PNG_CONST double power = 1/data.gamma;
  5991. PNG_CONST double abse = calc_depth == 16 ? .5/65535 : .5/255;
  5992. /* 'abse' is the absolute error permitted in linear calculations. It
  5993. * is used here to capture the error permitted in the handling
  5994. * (undoing) of the gamma encoding. Once again digitization occurs
  5995. * to handle the upper and lower bounds of the values. This is
  5996. * where the real errors are introduced.
  5997. */
  5998. r = pow(r, power);
  5999. rlo = digitize(pow(rlo, power)-abse, calc_depth, 1);
  6000. rhi = digitize(pow(rhi, power)+abse, calc_depth, 1);
  6001. g = pow(g, power);
  6002. glo = digitize(pow(glo, power)-abse, calc_depth, 1);
  6003. ghi = digitize(pow(ghi, power)+abse, calc_depth, 1);
  6004. b = pow(b, power);
  6005. blo = digitize(pow(blo, power)-abse, calc_depth, 1);
  6006. bhi = digitize(pow(bhi, power)+abse, calc_depth, 1);
  6007. }
  6008. /* Now calculate the actual gray values. Although the error in the
  6009. * coefficients depends on whether they were specified on the command
  6010. * line (in which case truncation to 15 bits happened) or not (rounding
  6011. * was used) the maxium error in an individual coefficient is always
  6012. * 1/32768, because even in the rounding case the requirement that
  6013. * coefficients add up to 32768 can cause a larger rounding error.
  6014. *
  6015. * The only time when rounding doesn't occur in 1.5.5 and later is when
  6016. * the non-gamma code path is used for less than 16 bit data.
  6017. */
  6018. gray = r * data.red_coefficient + g * data.green_coefficient +
  6019. b * data.blue_coefficient;
  6020. {
  6021. PNG_CONST int do_round = data.gamma != 1 || calc_depth == 16;
  6022. PNG_CONST double ce = 1. / 32768;
  6023. graylo = digitize(rlo * (data.red_coefficient-ce) +
  6024. glo * (data.green_coefficient-ce) +
  6025. blo * (data.blue_coefficient-ce), gamma_depth, do_round);
  6026. if (graylo <= 0)
  6027. graylo = 0;
  6028. grayhi = digitize(rhi * (data.red_coefficient+ce) +
  6029. ghi * (data.green_coefficient+ce) +
  6030. bhi * (data.blue_coefficient+ce), gamma_depth, do_round);
  6031. if (grayhi >= 1)
  6032. grayhi = 1;
  6033. }
  6034. /* And invert the gamma. */
  6035. if (data.gamma != 1)
  6036. {
  6037. PNG_CONST double power = data.gamma;
  6038. gray = pow(gray, power);
  6039. graylo = digitize(pow(graylo, power), sample_depth, 1);
  6040. grayhi = digitize(pow(grayhi, power), sample_depth, 1);
  6041. }
  6042. /* Now the error can be calculated.
  6043. *
  6044. * If r==g==b because there is no overall gamma correction libpng
  6045. * currently preserves the original value.
  6046. */
  6047. if (isgray)
  6048. err = (that->rede + that->greene + that->bluee)/3;
  6049. else
  6050. {
  6051. err = fabs(grayhi-gray);
  6052. if (fabs(gray - graylo) > err)
  6053. err = fabs(graylo-gray);
  6054. /* Check that this worked: */
  6055. if (err > pm->limit)
  6056. {
  6057. size_t pos = 0;
  6058. char buffer[128];
  6059. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6060. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6061. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6062. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6063. png_error(pp, buffer);
  6064. }
  6065. }
  6066. }
  6067. # else /* DIGITIZE */
  6068. {
  6069. double r = that->redf;
  6070. double re = that->rede;
  6071. double g = that->greenf;
  6072. double ge = that->greene;
  6073. double b = that->bluef;
  6074. double be = that->bluee;
  6075. /* The true gray case involves no math. */
  6076. if (r == g && r == b)
  6077. {
  6078. gray = r;
  6079. err = re;
  6080. if (err < ge) err = ge;
  6081. if (err < be) err = be;
  6082. }
  6083. else if (data.gamma == 1)
  6084. {
  6085. /* There is no need to do the conversions to and from linear space,
  6086. * so the calculation should be a lot more accurate. There is a
  6087. * built in 1/32768 error in the coefficients because they only have
  6088. * 15 bits and are adjusted to make sure they add up to 32768, so
  6089. * the result may have an additional error up to 1/32768. (Note
  6090. * that adding the 1/32768 here avoids needing to increase the
  6091. * global error limits to take this into account.)
  6092. */
  6093. gray = r * data.red_coefficient + g * data.green_coefficient +
  6094. b * data.blue_coefficient;
  6095. err = re * data.red_coefficient + ge * data.green_coefficient +
  6096. be * data.blue_coefficient + 1./32768 + gray * 5 * DBL_EPSILON;
  6097. }
  6098. else
  6099. {
  6100. /* The calculation happens in linear space, and this produces much
  6101. * wider errors in the encoded space. These are handled here by
  6102. * factoring the errors in to the calculation. There are two table
  6103. * lookups in the calculation and each introduces a quantization
  6104. * error defined by the table size.
  6105. */
  6106. PNG_CONST png_modifier *pm = display->pm;
  6107. double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
  6108. double out_qe = (that->sample_depth > 8 ? .5/65535 :
  6109. (pm->assume_16_bit_calculations ? .5/(1<<PNG_MAX_GAMMA_8) :
  6110. .5/255));
  6111. double rhi, ghi, bhi, grayhi;
  6112. double g1 = 1/data.gamma;
  6113. rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
  6114. r -= re + in_qe; if (r < 0) r = 0;
  6115. ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
  6116. g -= ge + in_qe; if (g < 0) g = 0;
  6117. bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
  6118. b -= be + in_qe; if (b < 0) b = 0;
  6119. r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
  6120. g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
  6121. b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
  6122. /* Work out the lower and upper bounds for the gray value in the
  6123. * encoded space, then work out an average and error. Remove the
  6124. * previously added input quantization error at this point.
  6125. */
  6126. gray = r * data.red_coefficient + g * data.green_coefficient +
  6127. b * data.blue_coefficient - 1./32768 - out_qe;
  6128. if (gray <= 0)
  6129. gray = 0;
  6130. else
  6131. {
  6132. gray *= (1 - 6 * DBL_EPSILON);
  6133. gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
  6134. }
  6135. grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
  6136. bhi * data.blue_coefficient + 1./32768 + out_qe;
  6137. grayhi *= (1 + 6 * DBL_EPSILON);
  6138. if (grayhi >= 1)
  6139. grayhi = 1;
  6140. else
  6141. grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
  6142. err = (grayhi - gray) / 2;
  6143. gray = (grayhi + gray) / 2;
  6144. if (err <= in_qe)
  6145. err = gray * DBL_EPSILON;
  6146. else
  6147. err -= in_qe;
  6148. /* Validate that the error is within limits (this has caused
  6149. * problems before, it's much easier to detect them here.)
  6150. */
  6151. if (err > pm->limit)
  6152. {
  6153. size_t pos = 0;
  6154. char buffer[128];
  6155. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6156. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6157. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6158. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6159. png_error(pp, buffer);
  6160. }
  6161. }
  6162. }
  6163. # endif /* !DIGITIZE */
  6164. that->bluef = that->greenf = that->redf = gray;
  6165. that->bluee = that->greene = that->rede = err;
  6166. /* The sBIT is the minium of the three colour channel sBITs. */
  6167. if (that->red_sBIT > that->green_sBIT)
  6168. that->red_sBIT = that->green_sBIT;
  6169. if (that->red_sBIT > that->blue_sBIT)
  6170. that->red_sBIT = that->blue_sBIT;
  6171. that->blue_sBIT = that->green_sBIT = that->red_sBIT;
  6172. /* And remove the colour bit in the type: */
  6173. if (that->colour_type == PNG_COLOR_TYPE_RGB)
  6174. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6175. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6176. that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  6177. }
  6178. this->next->mod(this->next, that, pp, display);
  6179. }
  6180. static int
  6181. image_transform_png_set_rgb_to_gray_add(image_transform *this,
  6182. PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
  6183. {
  6184. UNUSED(bit_depth)
  6185. this->next = *that;
  6186. *that = this;
  6187. return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
  6188. }
  6189. #undef data
  6190. IT(rgb_to_gray);
  6191. #undef PT
  6192. #define PT ITSTRUCT(rgb_to_gray)
  6193. #undef image_transform_ini
  6194. #define image_transform_ini image_transform_default_ini
  6195. #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
  6196. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  6197. /* png_set_background(png_structp, png_const_color_16p background_color,
  6198. * int background_gamma_code, int need_expand, double background_gamma)
  6199. * png_set_background_fixed(png_structp, png_const_color_16p background_color,
  6200. * int background_gamma_code, int need_expand,
  6201. * png_fixed_point background_gamma)
  6202. *
  6203. * This ignores the gamma (at present.)
  6204. */
  6205. #define data ITDATA(background)
  6206. static image_pixel data;
  6207. static void
  6208. image_transform_png_set_background_set(PNG_CONST image_transform *this,
  6209. transform_display *that, png_structp pp, png_infop pi)
  6210. {
  6211. png_byte colour_type, bit_depth;
  6212. png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
  6213. int expand;
  6214. png_color_16 back;
  6215. /* We need a background colour, because we don't know exactly what transforms
  6216. * have been set we have to supply the colour in the original file format and
  6217. * so we need to know what that is! The background colour is stored in the
  6218. * transform_display.
  6219. */
  6220. RANDOMIZE(random_bytes);
  6221. /* Read the random value, for colour type 3 the background colour is actually
  6222. * expressed as a 24bit rgb, not an index.
  6223. */
  6224. colour_type = that->this.colour_type;
  6225. if (colour_type == 3)
  6226. {
  6227. colour_type = PNG_COLOR_TYPE_RGB;
  6228. bit_depth = 8;
  6229. expand = 0; /* passing in an RGB not a pixel index */
  6230. }
  6231. else
  6232. {
  6233. bit_depth = that->this.bit_depth;
  6234. expand = 1;
  6235. }
  6236. image_pixel_init(&data, random_bytes, colour_type,
  6237. bit_depth, 0/*x*/, 0/*unused: palette*/);
  6238. /* Extract the background colour from this image_pixel, but make sure the
  6239. * unused fields of 'back' are garbage.
  6240. */
  6241. RANDOMIZE(back);
  6242. if (colour_type & PNG_COLOR_MASK_COLOR)
  6243. {
  6244. back.red = (png_uint_16)data.red;
  6245. back.green = (png_uint_16)data.green;
  6246. back.blue = (png_uint_16)data.blue;
  6247. }
  6248. else
  6249. back.gray = (png_uint_16)data.red;
  6250. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6251. png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  6252. # else
  6253. png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  6254. # endif
  6255. this->next->set(this->next, that, pp, pi);
  6256. }
  6257. static void
  6258. image_transform_png_set_background_mod(PNG_CONST image_transform *this,
  6259. image_pixel *that, png_const_structp pp,
  6260. PNG_CONST transform_display *display)
  6261. {
  6262. /* Check for tRNS first: */
  6263. if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
  6264. image_pixel_add_alpha(that, &display->this);
  6265. /* This is only necessary if the alpha value is less than 1. */
  6266. if (that->alphaf < 1)
  6267. {
  6268. /* Now we do the background calculation without any gamma correction. */
  6269. if (that->alphaf <= 0)
  6270. {
  6271. that->redf = data.redf;
  6272. that->greenf = data.greenf;
  6273. that->bluef = data.bluef;
  6274. that->rede = data.rede;
  6275. that->greene = data.greene;
  6276. that->bluee = data.bluee;
  6277. that->red_sBIT= data.red_sBIT;
  6278. that->green_sBIT= data.green_sBIT;
  6279. that->blue_sBIT= data.blue_sBIT;
  6280. }
  6281. else /* 0 < alpha < 1 */
  6282. {
  6283. double alf = 1 - that->alphaf;
  6284. that->redf = that->redf * that->alphaf + data.redf * alf;
  6285. that->rede = that->rede * that->alphaf + data.rede * alf +
  6286. DBL_EPSILON;
  6287. that->greenf = that->greenf * that->alphaf + data.greenf * alf;
  6288. that->greene = that->greene * that->alphaf + data.greene * alf +
  6289. DBL_EPSILON;
  6290. that->bluef = that->bluef * that->alphaf + data.bluef * alf;
  6291. that->bluee = that->bluee * that->alphaf + data.bluee * alf +
  6292. DBL_EPSILON;
  6293. }
  6294. /* Remove the alpha type and set the alpha (not in that order.) */
  6295. that->alphaf = 1;
  6296. that->alphae = 0;
  6297. if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6298. that->colour_type = PNG_COLOR_TYPE_RGB;
  6299. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6300. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6301. /* PNG_COLOR_TYPE_PALETTE is not changed */
  6302. }
  6303. this->next->mod(this->next, that, pp, display);
  6304. }
  6305. #define image_transform_png_set_background_add image_transform_default_add
  6306. #undef data
  6307. IT(background);
  6308. #undef PT
  6309. #define PT ITSTRUCT(background)
  6310. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  6311. /* This may just be 'end' if all the transforms are disabled! */
  6312. static image_transform *PNG_CONST image_transform_first = &PT;
  6313. static void
  6314. transform_enable(PNG_CONST char *name)
  6315. {
  6316. /* Everything starts out enabled, so if we see an 'enable' disabled
  6317. * everything else the first time round.
  6318. */
  6319. static int all_disabled = 0;
  6320. int found_it = 0;
  6321. image_transform *list = image_transform_first;
  6322. while (list != &image_transform_end)
  6323. {
  6324. if (strcmp(list->name, name) == 0)
  6325. {
  6326. list->enable = 1;
  6327. found_it = 1;
  6328. }
  6329. else if (!all_disabled)
  6330. list->enable = 0;
  6331. list = list->list;
  6332. }
  6333. all_disabled = 1;
  6334. if (!found_it)
  6335. {
  6336. fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
  6337. name);
  6338. exit(99);
  6339. }
  6340. }
  6341. static void
  6342. transform_disable(PNG_CONST char *name)
  6343. {
  6344. image_transform *list = image_transform_first;
  6345. while (list != &image_transform_end)
  6346. {
  6347. if (strcmp(list->name, name) == 0)
  6348. {
  6349. list->enable = 0;
  6350. return;
  6351. }
  6352. list = list->list;
  6353. }
  6354. fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
  6355. name);
  6356. exit(99);
  6357. }
  6358. static void
  6359. image_transform_reset_count(void)
  6360. {
  6361. image_transform *next = image_transform_first;
  6362. int count = 0;
  6363. while (next != &image_transform_end)
  6364. {
  6365. next->local_use = 0;
  6366. next->next = 0;
  6367. next = next->list;
  6368. ++count;
  6369. }
  6370. /* This can only happen if we every have more than 32 transforms (excluding
  6371. * the end) in the list.
  6372. */
  6373. if (count > 32) abort();
  6374. }
  6375. static int
  6376. image_transform_test_counter(png_uint_32 counter, unsigned int max)
  6377. {
  6378. /* Test the list to see if there is any point contining, given a current
  6379. * counter and a 'max' value.
  6380. */
  6381. image_transform *next = image_transform_first;
  6382. while (next != &image_transform_end)
  6383. {
  6384. /* For max 0 or 1 continue until the counter overflows: */
  6385. counter >>= 1;
  6386. /* Continue if any entry hasn't reacked the max. */
  6387. if (max > 1 && next->local_use < max)
  6388. return 1;
  6389. next = next->list;
  6390. }
  6391. return max <= 1 && counter == 0;
  6392. }
  6393. static png_uint_32
  6394. image_transform_add(PNG_CONST image_transform **this, unsigned int max,
  6395. png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
  6396. png_byte colour_type, png_byte bit_depth)
  6397. {
  6398. for (;;) /* until we manage to add something */
  6399. {
  6400. png_uint_32 mask;
  6401. image_transform *list;
  6402. /* Find the next counter value, if the counter is zero this is the start
  6403. * of the list. This routine always returns the current counter (not the
  6404. * next) so it returns 0 at the end and expects 0 at the beginning.
  6405. */
  6406. if (counter == 0) /* first time */
  6407. {
  6408. image_transform_reset_count();
  6409. if (max <= 1)
  6410. counter = 1;
  6411. else
  6412. counter = random_32();
  6413. }
  6414. else /* advance the counter */
  6415. {
  6416. switch (max)
  6417. {
  6418. case 0: ++counter; break;
  6419. case 1: counter <<= 1; break;
  6420. default: counter = random_32(); break;
  6421. }
  6422. }
  6423. /* Now add all these items, if possible */
  6424. *this = &image_transform_end;
  6425. list = image_transform_first;
  6426. mask = 1;
  6427. /* Go through the whole list adding anything that the counter selects: */
  6428. while (list != &image_transform_end)
  6429. {
  6430. if ((counter & mask) != 0 && list->enable &&
  6431. (max == 0 || list->local_use < max))
  6432. {
  6433. /* Candidate to add: */
  6434. if (list->add(list, this, colour_type, bit_depth) || max == 0)
  6435. {
  6436. /* Added, so add to the name too. */
  6437. *pos = safecat(name, sizeof_name, *pos, " +");
  6438. *pos = safecat(name, sizeof_name, *pos, list->name);
  6439. }
  6440. else
  6441. {
  6442. /* Not useful and max>0, so remove it from *this: */
  6443. *this = list->next;
  6444. list->next = 0;
  6445. /* And, since we know it isn't useful, stop it being added again
  6446. * in this run:
  6447. */
  6448. list->local_use = max;
  6449. }
  6450. }
  6451. mask <<= 1;
  6452. list = list->list;
  6453. }
  6454. /* Now if anything was added we have something to do. */
  6455. if (*this != &image_transform_end)
  6456. return counter;
  6457. /* Nothing added, but was there anything in there to add? */
  6458. if (!image_transform_test_counter(counter, max))
  6459. return 0;
  6460. }
  6461. }
  6462. #ifdef THIS_IS_THE_PROFORMA
  6463. static void
  6464. image_transform_png_set_@_set(PNG_CONST image_transform *this,
  6465. transform_display *that, png_structp pp, png_infop pi)
  6466. {
  6467. png_set_@(pp);
  6468. this->next->set(this->next, that, pp, pi);
  6469. }
  6470. static void
  6471. image_transform_png_set_@_mod(PNG_CONST image_transform *this,
  6472. image_pixel *that, png_const_structp pp,
  6473. PNG_CONST transform_display *display)
  6474. {
  6475. this->next->mod(this->next, that, pp, display);
  6476. }
  6477. static int
  6478. image_transform_png_set_@_add(image_transform *this,
  6479. PNG_CONST image_transform **that, char *name, size_t sizeof_name,
  6480. size_t *pos, png_byte colour_type, png_byte bit_depth)
  6481. {
  6482. this->next = *that;
  6483. *that = this;
  6484. *pos = safecat(name, sizeof_name, *pos, " +@");
  6485. return 1;
  6486. }
  6487. IT(@);
  6488. #endif
  6489. /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
  6490. * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
  6491. *
  6492. * Very difficult to validate this!
  6493. */
  6494. /*NOTE: TBD NYI */
  6495. /* The data layout transforms are handled by swapping our own channel data,
  6496. * necessarily these need to happen at the end of the transform list because the
  6497. * semantic of the channels changes after these are executed. Some of these,
  6498. * like set_shift and set_packing, can't be done at present because they change
  6499. * the layout of the data at the sub-sample level so sample() won't get the
  6500. * right answer.
  6501. */
  6502. /* png_set_invert_alpha */
  6503. /*NOTE: TBD NYI */
  6504. /* png_set_bgr */
  6505. /*NOTE: TBD NYI */
  6506. /* png_set_swap_alpha */
  6507. /*NOTE: TBD NYI */
  6508. /* png_set_swap */
  6509. /*NOTE: TBD NYI */
  6510. /* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); */
  6511. /*NOTE: TBD NYI */
  6512. /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
  6513. /*NOTE: TBD NYI */
  6514. /* png_set_packing */
  6515. /*NOTE: TBD NYI */
  6516. /* png_set_packswap */
  6517. /*NOTE: TBD NYI */
  6518. /* png_set_invert_mono */
  6519. /*NOTE: TBD NYI */
  6520. /* png_set_shift(png_structp, png_const_color_8p true_bits) */
  6521. /*NOTE: TBD NYI */
  6522. static void
  6523. perform_transform_test(png_modifier *pm)
  6524. {
  6525. png_byte colour_type = 0;
  6526. png_byte bit_depth = 0;
  6527. unsigned int palette_number = 0;
  6528. while (next_format(&colour_type, &bit_depth, &palette_number, 0))
  6529. {
  6530. png_uint_32 counter = 0;
  6531. size_t base_pos;
  6532. char name[64];
  6533. base_pos = safecat(name, sizeof name, 0, "transform:");
  6534. for (;;)
  6535. {
  6536. size_t pos = base_pos;
  6537. PNG_CONST image_transform *list = 0;
  6538. /* 'max' is currently hardwired to '1'; this should be settable on the
  6539. * command line.
  6540. */
  6541. counter = image_transform_add(&list, 1/*max*/, counter,
  6542. name, sizeof name, &pos, colour_type, bit_depth);
  6543. if (counter == 0)
  6544. break;
  6545. /* The command line can change this to checking interlaced images. */
  6546. do
  6547. {
  6548. pm->repeat = 0;
  6549. transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
  6550. pm->interlace_type, 0, 0, 0), list, name);
  6551. if (fail(pm))
  6552. return;
  6553. }
  6554. while (pm->repeat);
  6555. }
  6556. }
  6557. }
  6558. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  6559. /********************************* GAMMA TESTS ********************************/
  6560. #ifdef PNG_READ_GAMMA_SUPPORTED
  6561. /* Reader callbacks and implementations, where they differ from the standard
  6562. * ones.
  6563. */
  6564. typedef struct gamma_display
  6565. {
  6566. standard_display this;
  6567. /* Parameters */
  6568. png_modifier* pm;
  6569. double file_gamma;
  6570. double screen_gamma;
  6571. double background_gamma;
  6572. png_byte sbit;
  6573. int threshold_test;
  6574. int use_input_precision;
  6575. int scale16;
  6576. int expand16;
  6577. int do_background;
  6578. png_color_16 background_color;
  6579. /* Local variables */
  6580. double maxerrout;
  6581. double maxerrpc;
  6582. double maxerrabs;
  6583. } gamma_display;
  6584. #define ALPHA_MODE_OFFSET 4
  6585. static void
  6586. gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
  6587. double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
  6588. int use_input_precision, int scale16, int expand16,
  6589. int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color,
  6590. double background_gamma)
  6591. {
  6592. /* Standard fields */
  6593. standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
  6594. pm->use_update_info);
  6595. /* Parameter fields */
  6596. dp->pm = pm;
  6597. dp->file_gamma = file_gamma;
  6598. dp->screen_gamma = screen_gamma;
  6599. dp->background_gamma = background_gamma;
  6600. dp->sbit = sbit;
  6601. dp->threshold_test = threshold_test;
  6602. dp->use_input_precision = use_input_precision;
  6603. dp->scale16 = scale16;
  6604. dp->expand16 = expand16;
  6605. dp->do_background = do_background;
  6606. if (do_background && pointer_to_the_background_color != 0)
  6607. dp->background_color = *pointer_to_the_background_color;
  6608. else
  6609. memset(&dp->background_color, 0, sizeof dp->background_color);
  6610. /* Local variable fields */
  6611. dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
  6612. }
  6613. static void
  6614. gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
  6615. {
  6616. /* Reuse the standard stuff as appropriate. */
  6617. standard_info_part1(&dp->this, pp, pi);
  6618. /* If requested strip 16 to 8 bits - this is handled automagically below
  6619. * because the output bit depth is read from the library. Note that there
  6620. * are interactions with sBIT but, internally, libpng makes sbit at most
  6621. * PNG_MAX_GAMMA_8 when doing the following.
  6622. */
  6623. if (dp->scale16)
  6624. # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
  6625. png_set_scale_16(pp);
  6626. # else
  6627. /* The following works both in 1.5.4 and earlier versions: */
  6628. # ifdef PNG_READ_16_TO_8_SUPPORTED
  6629. png_set_strip_16(pp);
  6630. # else
  6631. png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
  6632. # endif
  6633. # endif
  6634. if (dp->expand16)
  6635. # ifdef PNG_READ_EXPAND_16_SUPPORTED
  6636. png_set_expand_16(pp);
  6637. # else
  6638. png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
  6639. # endif
  6640. if (dp->do_background >= ALPHA_MODE_OFFSET)
  6641. {
  6642. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6643. {
  6644. /* This tests the alpha mode handling, if supported. */
  6645. int mode = dp->do_background - ALPHA_MODE_OFFSET;
  6646. /* The gamma value is the output gamma, and is in the standard,
  6647. * non-inverted, represenation. It provides a default for the PNG file
  6648. * gamma, but since the file has a gAMA chunk this does not matter.
  6649. */
  6650. PNG_CONST double sg = dp->screen_gamma;
  6651. # ifndef PNG_FLOATING_POINT_SUPPORTED
  6652. PNG_CONST png_fixed_point g = fix(sg);
  6653. # endif
  6654. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6655. png_set_alpha_mode(pp, mode, sg);
  6656. # else
  6657. png_set_alpha_mode_fixed(pp, mode, g);
  6658. # endif
  6659. /* However, for the standard Porter-Duff algorithm the output defaults
  6660. * to be linear, so if the test requires non-linear output it must be
  6661. * corrected here.
  6662. */
  6663. if (mode == PNG_ALPHA_STANDARD && sg != 1)
  6664. {
  6665. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6666. png_set_gamma(pp, sg, dp->file_gamma);
  6667. # else
  6668. png_fixed_point f = fix(dp->file_gamma);
  6669. png_set_gamma_fixed(pp, g, f);
  6670. # endif
  6671. }
  6672. }
  6673. # else
  6674. png_error(pp, "alpha mode handling not supported");
  6675. # endif
  6676. }
  6677. else
  6678. {
  6679. /* Set up gamma processing. */
  6680. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6681. png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
  6682. # else
  6683. {
  6684. png_fixed_point s = fix(dp->screen_gamma);
  6685. png_fixed_point f = fix(dp->file_gamma);
  6686. png_set_gamma_fixed(pp, s, f);
  6687. }
  6688. # endif
  6689. if (dp->do_background)
  6690. {
  6691. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  6692. /* NOTE: this assumes the caller provided the correct background gamma!
  6693. */
  6694. PNG_CONST double bg = dp->background_gamma;
  6695. # ifndef PNG_FLOATING_POINT_SUPPORTED
  6696. PNG_CONST png_fixed_point g = fix(bg);
  6697. # endif
  6698. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6699. png_set_background(pp, &dp->background_color, dp->do_background,
  6700. 0/*need_expand*/, bg);
  6701. # else
  6702. png_set_background_fixed(pp, &dp->background_color,
  6703. dp->do_background, 0/*need_expand*/, g);
  6704. # endif
  6705. # else
  6706. png_error(pp, "png_set_background not supported");
  6707. # endif
  6708. }
  6709. }
  6710. {
  6711. int i = dp->this.use_update_info;
  6712. /* Always do one call, even if use_update_info is 0. */
  6713. do
  6714. png_read_update_info(pp, pi);
  6715. while (--i > 0);
  6716. }
  6717. /* Now we may get a different cbRow: */
  6718. standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
  6719. }
  6720. static void PNGCBAPI
  6721. gamma_info(png_structp pp, png_infop pi)
  6722. {
  6723. gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
  6724. pi);
  6725. }
  6726. /* Validate a single component value - the routine gets the input and output
  6727. * sample values as unscaled PNG component values along with a cache of all the
  6728. * information required to validate the values.
  6729. */
  6730. typedef struct validate_info
  6731. {
  6732. png_const_structp pp;
  6733. gamma_display *dp;
  6734. png_byte sbit;
  6735. int use_input_precision;
  6736. int do_background;
  6737. int scale16;
  6738. unsigned int sbit_max;
  6739. unsigned int isbit_shift;
  6740. unsigned int outmax;
  6741. double gamma_correction; /* Overall correction required. */
  6742. double file_inverse; /* Inverse of file gamma. */
  6743. double screen_gamma;
  6744. double screen_inverse; /* Inverse of screen gamma. */
  6745. double background_red; /* Linear background value, red or gray. */
  6746. double background_green;
  6747. double background_blue;
  6748. double maxabs;
  6749. double maxpc;
  6750. double maxcalc;
  6751. double maxout;
  6752. double maxout_total; /* Total including quantization error */
  6753. double outlog;
  6754. int outquant;
  6755. }
  6756. validate_info;
  6757. static void
  6758. init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
  6759. int in_depth, int out_depth)
  6760. {
  6761. PNG_CONST unsigned int outmax = (1U<<out_depth)-1;
  6762. vi->pp = pp;
  6763. vi->dp = dp;
  6764. if (dp->sbit > 0 && dp->sbit < in_depth)
  6765. {
  6766. vi->sbit = dp->sbit;
  6767. vi->isbit_shift = in_depth - dp->sbit;
  6768. }
  6769. else
  6770. {
  6771. vi->sbit = (png_byte)in_depth;
  6772. vi->isbit_shift = 0;
  6773. }
  6774. vi->sbit_max = (1U << vi->sbit)-1;
  6775. /* This mimics the libpng threshold test, '0' is used to prevent gamma
  6776. * correction in the validation test.
  6777. */
  6778. vi->screen_gamma = dp->screen_gamma;
  6779. if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
  6780. vi->screen_gamma = vi->screen_inverse = 0;
  6781. else
  6782. vi->screen_inverse = 1/vi->screen_gamma;
  6783. vi->use_input_precision = dp->use_input_precision;
  6784. vi->outmax = outmax;
  6785. vi->maxabs = abserr(dp->pm, in_depth, out_depth);
  6786. vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
  6787. vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
  6788. vi->maxout = outerr(dp->pm, in_depth, out_depth);
  6789. vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
  6790. vi->maxout_total = vi->maxout + vi->outquant * .5;
  6791. vi->outlog = outlog(dp->pm, in_depth, out_depth);
  6792. if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
  6793. (dp->this.colour_type == 3 && dp->this.is_transparent))
  6794. {
  6795. vi->do_background = dp->do_background;
  6796. if (vi->do_background != 0)
  6797. {
  6798. PNG_CONST double bg_inverse = 1/dp->background_gamma;
  6799. double r, g, b;
  6800. /* Caller must at least put the gray value into the red channel */
  6801. r = dp->background_color.red; r /= outmax;
  6802. g = dp->background_color.green; g /= outmax;
  6803. b = dp->background_color.blue; b /= outmax;
  6804. # if 0
  6805. /* libpng doesn't do this optimization, if we do pngvalid will fail.
  6806. */
  6807. if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
  6808. # endif
  6809. {
  6810. r = pow(r, bg_inverse);
  6811. g = pow(g, bg_inverse);
  6812. b = pow(b, bg_inverse);
  6813. }
  6814. vi->background_red = r;
  6815. vi->background_green = g;
  6816. vi->background_blue = b;
  6817. }
  6818. }
  6819. else
  6820. vi->do_background = 0;
  6821. if (vi->do_background == 0)
  6822. vi->background_red = vi->background_green = vi->background_blue = 0;
  6823. vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
  6824. if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
  6825. vi->gamma_correction = 0;
  6826. vi->file_inverse = 1/dp->file_gamma;
  6827. if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
  6828. vi->file_inverse = 0;
  6829. vi->scale16 = dp->scale16;
  6830. }
  6831. /* This function handles composition of a single non-alpha component. The
  6832. * argument is the input sample value, in the range 0..1, and the alpha value.
  6833. * The result is the composed, linear, input sample. If alpha is less than zero
  6834. * this is the alpha component and the function should not be called!
  6835. */
  6836. static double
  6837. gamma_component_compose(int do_background, double input_sample, double alpha,
  6838. double background, int *compose)
  6839. {
  6840. switch (do_background)
  6841. {
  6842. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  6843. case PNG_BACKGROUND_GAMMA_SCREEN:
  6844. case PNG_BACKGROUND_GAMMA_FILE:
  6845. case PNG_BACKGROUND_GAMMA_UNIQUE:
  6846. /* Standard PNG background processing. */
  6847. if (alpha < 1)
  6848. {
  6849. if (alpha > 0)
  6850. {
  6851. input_sample = input_sample * alpha + background * (1-alpha);
  6852. if (compose != NULL)
  6853. *compose = 1;
  6854. }
  6855. else
  6856. input_sample = background;
  6857. }
  6858. break;
  6859. #endif
  6860. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6861. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  6862. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  6863. /* The components are premultiplied in either case and the output is
  6864. * gamma encoded (to get standard Porter-Duff we expect the output
  6865. * gamma to be set to 1.0!)
  6866. */
  6867. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  6868. /* The optimization is that the partial-alpha entries are linear
  6869. * while the opaque pixels are gamma encoded, but this only affects the
  6870. * output encoding.
  6871. */
  6872. if (alpha < 1)
  6873. {
  6874. if (alpha > 0)
  6875. {
  6876. input_sample *= alpha;
  6877. if (compose != NULL)
  6878. *compose = 1;
  6879. }
  6880. else
  6881. input_sample = 0;
  6882. }
  6883. break;
  6884. #endif
  6885. default:
  6886. /* Standard cases where no compositing is done (so the component
  6887. * value is already correct.)
  6888. */
  6889. UNUSED(alpha)
  6890. UNUSED(background)
  6891. UNUSED(compose)
  6892. break;
  6893. }
  6894. return input_sample;
  6895. }
  6896. /* This API returns the encoded *input* component, in the range 0..1 */
  6897. static double
  6898. gamma_component_validate(PNG_CONST char *name, PNG_CONST validate_info *vi,
  6899. PNG_CONST unsigned int id, PNG_CONST unsigned int od,
  6900. PNG_CONST double alpha /* <0 for the alpha channel itself */,
  6901. PNG_CONST double background /* component background value */)
  6902. {
  6903. PNG_CONST unsigned int isbit = id >> vi->isbit_shift;
  6904. PNG_CONST unsigned int sbit_max = vi->sbit_max;
  6905. PNG_CONST unsigned int outmax = vi->outmax;
  6906. PNG_CONST int do_background = vi->do_background;
  6907. double i;
  6908. /* First check on the 'perfect' result obtained from the digitized input
  6909. * value, id, and compare this against the actual digitized result, 'od'.
  6910. * 'i' is the input result in the range 0..1:
  6911. */
  6912. i = isbit; i /= sbit_max;
  6913. /* Check for the fast route: if we don't do any background composition or if
  6914. * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
  6915. * just use the gamma_correction field to correct to the final output gamma.
  6916. */
  6917. if (alpha == 1 /* opaque pixel component */ || !do_background
  6918. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6919. || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
  6920. #endif
  6921. || (alpha < 0 /* alpha channel */
  6922. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6923. && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
  6924. #endif
  6925. ))
  6926. {
  6927. /* Then get the gamma corrected version of 'i' and compare to 'od', any
  6928. * error less than .5 is insignificant - just quantization of the output
  6929. * value to the nearest digital value (nevertheless the error is still
  6930. * recorded - it's interesting ;-)
  6931. */
  6932. double encoded_sample = i;
  6933. double encoded_error;
  6934. /* alpha less than 0 indicates the alpha channel, which is always linear
  6935. */
  6936. if (alpha >= 0 && vi->gamma_correction > 0)
  6937. encoded_sample = pow(encoded_sample, vi->gamma_correction);
  6938. encoded_sample *= outmax;
  6939. encoded_error = fabs(od-encoded_sample);
  6940. if (encoded_error > vi->dp->maxerrout)
  6941. vi->dp->maxerrout = encoded_error;
  6942. if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
  6943. return i;
  6944. }
  6945. /* The slow route - attempt to do linear calculations. */
  6946. /* There may be an error, or background processing is required, so calculate
  6947. * the actual sample values - unencoded light intensity values. Note that in
  6948. * practice these are not completely unencoded because they include a
  6949. * 'viewing correction' to decrease or (normally) increase the perceptual
  6950. * contrast of the image. There's nothing we can do about this - we don't
  6951. * know what it is - so assume the unencoded value is perceptually linear.
  6952. */
  6953. {
  6954. double input_sample = i; /* In range 0..1 */
  6955. double output, error, encoded_sample, encoded_error;
  6956. double es_lo, es_hi;
  6957. int compose = 0; /* Set to one if composition done */
  6958. int output_is_encoded; /* Set if encoded to screen gamma */
  6959. int log_max_error = 1; /* Check maximum error values */
  6960. png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
  6961. /* Convert to linear light (with the above caveat.) The alpha channel is
  6962. * already linear.
  6963. */
  6964. if (alpha >= 0)
  6965. {
  6966. int tcompose;
  6967. if (vi->file_inverse > 0)
  6968. input_sample = pow(input_sample, vi->file_inverse);
  6969. /* Handle the compose processing: */
  6970. tcompose = 0;
  6971. input_sample = gamma_component_compose(do_background, input_sample,
  6972. alpha, background, &tcompose);
  6973. if (tcompose)
  6974. compose = 1;
  6975. }
  6976. /* And similarly for the output value, but we need to check the background
  6977. * handling to linearize it correctly.
  6978. */
  6979. output = od;
  6980. output /= outmax;
  6981. output_is_encoded = vi->screen_gamma > 0;
  6982. if (alpha < 0) /* The alpha channel */
  6983. {
  6984. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6985. if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
  6986. #endif
  6987. {
  6988. /* In all other cases the output alpha channel is linear already,
  6989. * don't log errors here, they are much larger in linear data.
  6990. */
  6991. output_is_encoded = 0;
  6992. log_max_error = 0;
  6993. }
  6994. }
  6995. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  6996. else /* A component */
  6997. {
  6998. if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
  6999. alpha < 1) /* the optimized case - linear output */
  7000. {
  7001. if (alpha > 0) log_max_error = 0;
  7002. output_is_encoded = 0;
  7003. }
  7004. }
  7005. #endif
  7006. if (output_is_encoded)
  7007. output = pow(output, vi->screen_gamma);
  7008. /* Calculate (or recalculate) the encoded_sample value and repeat the
  7009. * check above (unnecessary if we took the fast route, but harmless.)
  7010. */
  7011. encoded_sample = input_sample;
  7012. if (output_is_encoded)
  7013. encoded_sample = pow(encoded_sample, vi->screen_inverse);
  7014. encoded_sample *= outmax;
  7015. encoded_error = fabs(od-encoded_sample);
  7016. /* Don't log errors in the alpha channel, or the 'optimized' case,
  7017. * neither are significant to the overall perception.
  7018. */
  7019. if (log_max_error && encoded_error > vi->dp->maxerrout)
  7020. vi->dp->maxerrout = encoded_error;
  7021. if (encoded_error < vi->maxout_total)
  7022. {
  7023. if (encoded_error < vi->outlog)
  7024. return i;
  7025. /* Test passed but error is bigger than the log limit, record why the
  7026. * test passed:
  7027. */
  7028. pass = "less than maxout:\n";
  7029. }
  7030. /* i: the original input value in the range 0..1
  7031. *
  7032. * pngvalid calculations:
  7033. * input_sample: linear result; i linearized and composed, range 0..1
  7034. * encoded_sample: encoded result; input_sample scaled to ouput bit depth
  7035. *
  7036. * libpng calculations:
  7037. * output: linear result; od scaled to 0..1 and linearized
  7038. * od: encoded result from libpng
  7039. */
  7040. /* Now we have the numbers for real errors, both absolute values as as a
  7041. * percentage of the correct value (output):
  7042. */
  7043. error = fabs(input_sample-output);
  7044. if (log_max_error && error > vi->dp->maxerrabs)
  7045. vi->dp->maxerrabs = error;
  7046. /* The following is an attempt to ignore the tendency of quantization to
  7047. * dominate the percentage errors for lower result values:
  7048. */
  7049. if (log_max_error && input_sample > .5)
  7050. {
  7051. double percentage_error = error/input_sample;
  7052. if (percentage_error > vi->dp->maxerrpc)
  7053. vi->dp->maxerrpc = percentage_error;
  7054. }
  7055. /* Now calculate the digitization limits for 'encoded_sample' using the
  7056. * 'max' values. Note that maxout is in the encoded space but maxpc and
  7057. * maxabs are in linear light space.
  7058. *
  7059. * First find the maximum error in linear light space, range 0..1:
  7060. */
  7061. {
  7062. double tmp = input_sample * vi->maxpc;
  7063. if (tmp < vi->maxabs) tmp = vi->maxabs;
  7064. /* If 'compose' is true the composition was done in linear space using
  7065. * integer arithmetic. This introduces an extra error of +/- 0.5 (at
  7066. * least) in the integer space used. 'maxcalc' records this, taking
  7067. * into account the possibility that even for 16 bit output 8 bit space
  7068. * may have been used.
  7069. */
  7070. if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
  7071. /* The 'maxout' value refers to the encoded result, to compare with
  7072. * this encode input_sample adjusted by the maximum error (tmp) above.
  7073. */
  7074. es_lo = encoded_sample - vi->maxout;
  7075. if (es_lo > 0 && input_sample-tmp > 0)
  7076. {
  7077. double low_value = input_sample-tmp;
  7078. if (output_is_encoded)
  7079. low_value = pow(low_value, vi->screen_inverse);
  7080. low_value *= outmax;
  7081. if (low_value < es_lo) es_lo = low_value;
  7082. /* Quantize this appropriately: */
  7083. es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
  7084. }
  7085. else
  7086. es_lo = 0;
  7087. es_hi = encoded_sample + vi->maxout;
  7088. if (es_hi < outmax && input_sample+tmp < 1)
  7089. {
  7090. double high_value = input_sample+tmp;
  7091. if (output_is_encoded)
  7092. high_value = pow(high_value, vi->screen_inverse);
  7093. high_value *= outmax;
  7094. if (high_value > es_hi) es_hi = high_value;
  7095. es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
  7096. }
  7097. else
  7098. es_hi = outmax;
  7099. }
  7100. /* The primary test is that the final encoded value returned by the
  7101. * library should be between the two limits (inclusive) that were
  7102. * calculated above.
  7103. */
  7104. if (od >= es_lo && od <= es_hi)
  7105. {
  7106. /* The value passes, but we may need to log the information anyway. */
  7107. if (encoded_error < vi->outlog)
  7108. return i;
  7109. if (pass == 0)
  7110. pass = "within digitization limits:\n";
  7111. }
  7112. {
  7113. /* There has been an error in processing, or we need to log this
  7114. * value.
  7115. */
  7116. double is_lo, is_hi;
  7117. /* pass is set at this point if either of the tests above would have
  7118. * passed. Don't do these additional tests here - just log the
  7119. * original [es_lo..es_hi] values.
  7120. */
  7121. if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
  7122. {
  7123. /* Ok, something is wrong - this actually happens in current libpng
  7124. * 16-to-8 processing. Assume that the input value (id, adjusted
  7125. * for sbit) can be anywhere between value-.5 and value+.5 - quite a
  7126. * large range if sbit is low.
  7127. *
  7128. * NOTE: at present because the libpng gamma table stuff has been
  7129. * changed to use a rounding algorithm to correct errors in 8-bit
  7130. * calculations the precise sbit calculation (a shift) has been
  7131. * lost. This can result in up to a +/-1 error in the presence of
  7132. * an sbit less than the bit depth.
  7133. */
  7134. # if PNG_LIBPNG_VER < 10700
  7135. # define SBIT_ERROR .5
  7136. # else
  7137. # define SBIT_ERROR 1.
  7138. # endif
  7139. double tmp = (isbit - SBIT_ERROR)/sbit_max;
  7140. if (tmp <= 0)
  7141. tmp = 0;
  7142. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  7143. tmp = pow(tmp, vi->file_inverse);
  7144. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  7145. NULL);
  7146. if (output_is_encoded && tmp > 0 && tmp < 1)
  7147. tmp = pow(tmp, vi->screen_inverse);
  7148. is_lo = ceil(outmax * tmp - vi->maxout_total);
  7149. if (is_lo < 0)
  7150. is_lo = 0;
  7151. tmp = (isbit + SBIT_ERROR)/sbit_max;
  7152. if (tmp >= 1)
  7153. tmp = 1;
  7154. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  7155. tmp = pow(tmp, vi->file_inverse);
  7156. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  7157. NULL);
  7158. if (output_is_encoded && tmp > 0 && tmp < 1)
  7159. tmp = pow(tmp, vi->screen_inverse);
  7160. is_hi = floor(outmax * tmp + vi->maxout_total);
  7161. if (is_hi > outmax)
  7162. is_hi = outmax;
  7163. if (!(od < is_lo || od > is_hi))
  7164. {
  7165. if (encoded_error < vi->outlog)
  7166. return i;
  7167. pass = "within input precision limits:\n";
  7168. }
  7169. /* One last chance. If this is an alpha channel and the 16to8
  7170. * option has been used and 'inaccurate' scaling is used then the
  7171. * bit reduction is obtained by simply using the top 8 bits of the
  7172. * value.
  7173. *
  7174. * This is only done for older libpng versions when the 'inaccurate'
  7175. * (chop) method of scaling was used.
  7176. */
  7177. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  7178. # if PNG_LIBPNG_VER < 10504
  7179. /* This may be required for other components in the future,
  7180. * but at present the presence of gamma correction effectively
  7181. * prevents the errors in the component scaling (I don't quite
  7182. * understand why, but since it's better this way I care not
  7183. * to ask, JB 20110419.)
  7184. */
  7185. if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
  7186. vi->sbit + vi->isbit_shift == 16)
  7187. {
  7188. tmp = ((id >> 8) - .5)/255;
  7189. if (tmp > 0)
  7190. {
  7191. is_lo = ceil(outmax * tmp - vi->maxout_total);
  7192. if (is_lo < 0) is_lo = 0;
  7193. }
  7194. else
  7195. is_lo = 0;
  7196. tmp = ((id >> 8) + .5)/255;
  7197. if (tmp < 1)
  7198. {
  7199. is_hi = floor(outmax * tmp + vi->maxout_total);
  7200. if (is_hi > outmax) is_hi = outmax;
  7201. }
  7202. else
  7203. is_hi = outmax;
  7204. if (!(od < is_lo || od > is_hi))
  7205. {
  7206. if (encoded_error < vi->outlog)
  7207. return i;
  7208. pass = "within 8 bit limits:\n";
  7209. }
  7210. }
  7211. # endif
  7212. # endif
  7213. }
  7214. else /* !use_input_precision */
  7215. is_lo = es_lo, is_hi = es_hi;
  7216. /* Attempt to output a meaningful error/warning message: the message
  7217. * output depends on the background/composite operation being performed
  7218. * because this changes what parameters were actually used above.
  7219. */
  7220. {
  7221. size_t pos = 0;
  7222. /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
  7223. * places. Just use outmax to work out which.
  7224. */
  7225. int precision = (outmax >= 1000 ? 6 : 3);
  7226. int use_input=1, use_background=0, do_compose=0;
  7227. char msg[256];
  7228. if (pass != 0)
  7229. pos = safecat(msg, sizeof msg, pos, "\n\t");
  7230. /* Set up the various flags, the output_is_encoded flag above
  7231. * is also used below. do_compose is just a double check.
  7232. */
  7233. switch (do_background)
  7234. {
  7235. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  7236. case PNG_BACKGROUND_GAMMA_SCREEN:
  7237. case PNG_BACKGROUND_GAMMA_FILE:
  7238. case PNG_BACKGROUND_GAMMA_UNIQUE:
  7239. use_background = (alpha >= 0 && alpha < 1);
  7240. /*FALL THROUGH*/
  7241. # endif
  7242. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7243. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  7244. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  7245. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  7246. # endif /* ALPHA_MODE_SUPPORTED */
  7247. do_compose = (alpha > 0 && alpha < 1);
  7248. use_input = (alpha != 0);
  7249. break;
  7250. default:
  7251. break;
  7252. }
  7253. /* Check the 'compose' flag */
  7254. if (compose != do_compose)
  7255. png_error(vi->pp, "internal error (compose)");
  7256. /* 'name' is the component name */
  7257. pos = safecat(msg, sizeof msg, pos, name);
  7258. pos = safecat(msg, sizeof msg, pos, "(");
  7259. pos = safecatn(msg, sizeof msg, pos, id);
  7260. if (use_input || pass != 0/*logging*/)
  7261. {
  7262. if (isbit != id)
  7263. {
  7264. /* sBIT has reduced the precision of the input: */
  7265. pos = safecat(msg, sizeof msg, pos, ", sbit(");
  7266. pos = safecatn(msg, sizeof msg, pos, vi->sbit);
  7267. pos = safecat(msg, sizeof msg, pos, "): ");
  7268. pos = safecatn(msg, sizeof msg, pos, isbit);
  7269. }
  7270. pos = safecat(msg, sizeof msg, pos, "/");
  7271. /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
  7272. pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
  7273. }
  7274. pos = safecat(msg, sizeof msg, pos, ")");
  7275. /* A component may have been multiplied (in linear space) by the
  7276. * alpha value, 'compose' says whether this is relevant.
  7277. */
  7278. if (compose || pass != 0)
  7279. {
  7280. /* If any form of composition is being done report our
  7281. * calculated linear value here (the code above doesn't record
  7282. * the input value before composition is performed, so what
  7283. * gets reported is the value after composition.)
  7284. */
  7285. if (use_input || pass != 0)
  7286. {
  7287. if (vi->file_inverse > 0)
  7288. {
  7289. pos = safecat(msg, sizeof msg, pos, "^");
  7290. pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
  7291. }
  7292. else
  7293. pos = safecat(msg, sizeof msg, pos, "[linear]");
  7294. pos = safecat(msg, sizeof msg, pos, "*(alpha)");
  7295. pos = safecatd(msg, sizeof msg, pos, alpha, precision);
  7296. }
  7297. /* Now record the *linear* background value if it was used
  7298. * (this function is not passed the original, non-linear,
  7299. * value but it is contained in the test name.)
  7300. */
  7301. if (use_background)
  7302. {
  7303. pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
  7304. pos = safecat(msg, sizeof msg, pos, "(background)");
  7305. pos = safecatd(msg, sizeof msg, pos, background, precision);
  7306. pos = safecat(msg, sizeof msg, pos, "*");
  7307. pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
  7308. }
  7309. }
  7310. /* Report the calculated value (input_sample) and the linearized
  7311. * libpng value (output) unless this is just a component gamma
  7312. * correction.
  7313. */
  7314. if (compose || alpha < 0 || pass != 0)
  7315. {
  7316. pos = safecat(msg, sizeof msg, pos,
  7317. pass != 0 ? " =\n\t" : " = ");
  7318. pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
  7319. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  7320. pos = safecatd(msg, sizeof msg, pos, output, precision);
  7321. pos = safecat(msg, sizeof msg, pos, ")");
  7322. /* Finally report the output gamma encoding, if any. */
  7323. if (output_is_encoded)
  7324. {
  7325. pos = safecat(msg, sizeof msg, pos, " ^");
  7326. pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
  7327. pos = safecat(msg, sizeof msg, pos, "(to screen) =");
  7328. }
  7329. else
  7330. pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
  7331. }
  7332. if ((!compose && alpha >= 0) || pass != 0)
  7333. {
  7334. if (pass != 0) /* logging */
  7335. pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
  7336. /* This is the non-composition case, the internal linear
  7337. * values are irrelevant (though the log below will reveal
  7338. * them.) Output a much shorter warning/error message and report
  7339. * the overall gamma correction.
  7340. */
  7341. if (vi->gamma_correction > 0)
  7342. {
  7343. pos = safecat(msg, sizeof msg, pos, " ^");
  7344. pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
  7345. pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
  7346. }
  7347. else
  7348. pos = safecat(msg, sizeof msg, pos,
  7349. " [no gamma correction] =");
  7350. if (pass != 0)
  7351. pos = safecat(msg, sizeof msg, pos, "]");
  7352. }
  7353. /* This is our calculated encoded_sample which should (but does
  7354. * not) match od:
  7355. */
  7356. pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
  7357. pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
  7358. pos = safecat(msg, sizeof msg, pos, " < ");
  7359. pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
  7360. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  7361. pos = safecatn(msg, sizeof msg, pos, od);
  7362. pos = safecat(msg, sizeof msg, pos, ")");
  7363. pos = safecat(msg, sizeof msg, pos, "/");
  7364. pos = safecatn(msg, sizeof msg, pos, outmax);
  7365. pos = safecat(msg, sizeof msg, pos, " < ");
  7366. pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
  7367. if (pass == 0) /* The error condition */
  7368. {
  7369. # ifdef PNG_WARNINGS_SUPPORTED
  7370. png_warning(vi->pp, msg);
  7371. # else
  7372. store_warning(vi->pp, msg);
  7373. # endif
  7374. }
  7375. else /* logging this value */
  7376. store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
  7377. }
  7378. }
  7379. }
  7380. return i;
  7381. }
  7382. static void
  7383. gamma_image_validate(gamma_display *dp, png_const_structp pp,
  7384. png_infop pi)
  7385. {
  7386. /* Get some constants derived from the input and output file formats: */
  7387. PNG_CONST png_store* PNG_CONST ps = dp->this.ps;
  7388. PNG_CONST png_byte in_ct = dp->this.colour_type;
  7389. PNG_CONST png_byte in_bd = dp->this.bit_depth;
  7390. PNG_CONST png_uint_32 w = dp->this.w;
  7391. PNG_CONST png_uint_32 h = dp->this.h;
  7392. PNG_CONST size_t cbRow = dp->this.cbRow;
  7393. PNG_CONST png_byte out_ct = png_get_color_type(pp, pi);
  7394. PNG_CONST png_byte out_bd = png_get_bit_depth(pp, pi);
  7395. /* There are three sources of error, firstly the quantization in the
  7396. * file encoding, determined by sbit and/or the file depth, secondly
  7397. * the output (screen) gamma and thirdly the output file encoding.
  7398. *
  7399. * Since this API receives the screen and file gamma in double
  7400. * precision it is possible to calculate an exact answer given an input
  7401. * pixel value. Therefore we assume that the *input* value is exact -
  7402. * sample/maxsample - calculate the corresponding gamma corrected
  7403. * output to the limits of double precision arithmetic and compare with
  7404. * what libpng returns.
  7405. *
  7406. * Since the library must quantize the output to 8 or 16 bits there is
  7407. * a fundamental limit on the accuracy of the output of +/-.5 - this
  7408. * quantization limit is included in addition to the other limits
  7409. * specified by the paramaters to the API. (Effectively, add .5
  7410. * everywhere.)
  7411. *
  7412. * The behavior of the 'sbit' paramter is defined by section 12.5
  7413. * (sample depth scaling) of the PNG spec. That section forces the
  7414. * decoder to assume that the PNG values have been scaled if sBIT is
  7415. * present:
  7416. *
  7417. * png-sample = floor( input-sample * (max-out/max-in) + .5);
  7418. *
  7419. * This means that only a subset of the possible PNG values should
  7420. * appear in the input. However, the spec allows the encoder to use a
  7421. * variety of approximations to the above and doesn't require any
  7422. * restriction of the values produced.
  7423. *
  7424. * Nevertheless the spec requires that the upper 'sBIT' bits of the
  7425. * value stored in a PNG file be the original sample bits.
  7426. * Consequently the code below simply scales the top sbit bits by
  7427. * (1<<sbit)-1 to obtain an original sample value.
  7428. *
  7429. * Because there is limited precision in the input it is arguable that
  7430. * an acceptable result is any valid result from input-.5 to input+.5.
  7431. * The basic tests below do not do this, however if 'use_input_precision'
  7432. * is set a subsequent test is performed above.
  7433. */
  7434. PNG_CONST unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
  7435. int processing;
  7436. png_uint_32 y;
  7437. PNG_CONST store_palette_entry *in_palette = dp->this.palette;
  7438. PNG_CONST int in_is_transparent = dp->this.is_transparent;
  7439. int out_npalette = -1;
  7440. int out_is_transparent = 0; /* Just refers to the palette case */
  7441. store_palette out_palette;
  7442. validate_info vi;
  7443. /* Check for row overwrite errors */
  7444. store_image_check(dp->this.ps, pp, 0);
  7445. /* Supply the input and output sample depths here - 8 for an indexed image,
  7446. * otherwise the bit depth.
  7447. */
  7448. init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
  7449. processing = (vi.gamma_correction > 0 && !dp->threshold_test)
  7450. || in_bd != out_bd || in_ct != out_ct || vi.do_background;
  7451. /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
  7452. * the palette there is no way of finding out, because libpng fails to
  7453. * update the palette on png_read_update_info. Indeed, libpng doesn't
  7454. * even do the required work until much later, when it doesn't have any
  7455. * info pointer. Oops. For the moment 'processing' is turned off if
  7456. * out_ct is palette.
  7457. */
  7458. if (in_ct == 3 && out_ct == 3)
  7459. processing = 0;
  7460. if (processing && out_ct == 3)
  7461. out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
  7462. for (y=0; y<h; ++y)
  7463. {
  7464. png_const_bytep pRow = store_image_row(ps, pp, 0, y);
  7465. png_byte std[STANDARD_ROWMAX];
  7466. transform_row(pp, std, in_ct, in_bd, y);
  7467. if (processing)
  7468. {
  7469. unsigned int x;
  7470. for (x=0; x<w; ++x)
  7471. {
  7472. double alpha = 1; /* serves as a flag value */
  7473. /* Record the palette index for index images. */
  7474. PNG_CONST unsigned int in_index =
  7475. in_ct == 3 ? sample(std, 3, in_bd, x, 0) : 256;
  7476. PNG_CONST unsigned int out_index =
  7477. out_ct == 3 ? sample(std, 3, out_bd, x, 0) : 256;
  7478. /* Handle input alpha - png_set_background will cause the output
  7479. * alpha to disappear so there is nothing to check.
  7480. */
  7481. if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 || (in_ct == 3 &&
  7482. in_is_transparent))
  7483. {
  7484. PNG_CONST unsigned int input_alpha = in_ct == 3 ?
  7485. dp->this.palette[in_index].alpha :
  7486. sample(std, in_ct, in_bd, x, samples_per_pixel);
  7487. unsigned int output_alpha = 65536 /* as a flag value */;
  7488. if (out_ct == 3)
  7489. {
  7490. if (out_is_transparent)
  7491. output_alpha = out_palette[out_index].alpha;
  7492. }
  7493. else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
  7494. output_alpha = sample(pRow, out_ct, out_bd, x,
  7495. samples_per_pixel);
  7496. if (output_alpha != 65536)
  7497. alpha = gamma_component_validate("alpha", &vi, input_alpha,
  7498. output_alpha, -1/*alpha*/, 0/*background*/);
  7499. else /* no alpha in output */
  7500. {
  7501. /* This is a copy of the calculation of 'i' above in order to
  7502. * have the alpha value to use in the background calculation.
  7503. */
  7504. alpha = input_alpha >> vi.isbit_shift;
  7505. alpha /= vi.sbit_max;
  7506. }
  7507. }
  7508. /* Handle grayscale or RGB components. */
  7509. if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
  7510. (void)gamma_component_validate("gray", &vi,
  7511. sample(std, in_ct, in_bd, x, 0),
  7512. sample(pRow, out_ct, out_bd, x, 0), alpha/*component*/,
  7513. vi.background_red);
  7514. else /* RGB or palette */
  7515. {
  7516. (void)gamma_component_validate("red", &vi,
  7517. in_ct == 3 ? in_palette[in_index].red :
  7518. sample(std, in_ct, in_bd, x, 0),
  7519. out_ct == 3 ? out_palette[out_index].red :
  7520. sample(pRow, out_ct, out_bd, x, 0),
  7521. alpha/*component*/, vi.background_red);
  7522. (void)gamma_component_validate("green", &vi,
  7523. in_ct == 3 ? in_palette[in_index].green :
  7524. sample(std, in_ct, in_bd, x, 1),
  7525. out_ct == 3 ? out_palette[out_index].green :
  7526. sample(pRow, out_ct, out_bd, x, 1),
  7527. alpha/*component*/, vi.background_green);
  7528. (void)gamma_component_validate("blue", &vi,
  7529. in_ct == 3 ? in_palette[in_index].blue :
  7530. sample(std, in_ct, in_bd, x, 2),
  7531. out_ct == 3 ? out_palette[out_index].blue :
  7532. sample(pRow, out_ct, out_bd, x, 2),
  7533. alpha/*component*/, vi.background_blue);
  7534. }
  7535. }
  7536. }
  7537. else if (memcmp(std, pRow, cbRow) != 0)
  7538. {
  7539. char msg[64];
  7540. /* No transform is expected on the threshold tests. */
  7541. sprintf(msg, "gamma: below threshold row %lu changed",
  7542. (unsigned long)y);
  7543. png_error(pp, msg);
  7544. }
  7545. } /* row (y) loop */
  7546. dp->this.ps->validated = 1;
  7547. }
  7548. static void PNGCBAPI
  7549. gamma_end(png_structp ppIn, png_infop pi)
  7550. {
  7551. png_const_structp pp = ppIn;
  7552. gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
  7553. if (!dp->this.speed)
  7554. gamma_image_validate(dp, pp, pi);
  7555. else
  7556. dp->this.ps->validated = 1;
  7557. }
  7558. /* A single test run checking a gamma transformation.
  7559. *
  7560. * maxabs: maximum absolute error as a fraction
  7561. * maxout: maximum output error in the output units
  7562. * maxpc: maximum percentage error (as a percentage)
  7563. */
  7564. static void
  7565. gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
  7566. PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn,
  7567. PNG_CONST int interlace_typeIn,
  7568. PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn,
  7569. PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn,
  7570. PNG_CONST char *name,
  7571. PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In,
  7572. PNG_CONST int expand16In, PNG_CONST int do_backgroundIn,
  7573. PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
  7574. {
  7575. gamma_display d;
  7576. context(&pmIn->this, fault);
  7577. gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
  7578. palette_numberIn, interlace_typeIn, 0, 0, 0),
  7579. file_gammaIn, screen_gammaIn, sbitIn,
  7580. threshold_testIn, use_input_precisionIn, scale16In,
  7581. expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
  7582. Try
  7583. {
  7584. png_structp pp;
  7585. png_infop pi;
  7586. gama_modification gama_mod;
  7587. srgb_modification srgb_mod;
  7588. sbit_modification sbit_mod;
  7589. /* For the moment don't use the png_modifier support here. */
  7590. d.pm->encoding_counter = 0;
  7591. modifier_set_encoding(d.pm); /* Just resets everything */
  7592. d.pm->current_gamma = d.file_gamma;
  7593. /* Make an appropriate modifier to set the PNG file gamma to the
  7594. * given gamma value and the sBIT chunk to the given precision.
  7595. */
  7596. d.pm->modifications = NULL;
  7597. gama_modification_init(&gama_mod, d.pm, d.file_gamma);
  7598. srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
  7599. if (d.sbit > 0)
  7600. sbit_modification_init(&sbit_mod, d.pm, d.sbit);
  7601. modification_reset(d.pm->modifications);
  7602. /* Get a png_struct for writing the image. */
  7603. pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
  7604. standard_palette_init(&d.this);
  7605. /* Introduce the correct read function. */
  7606. if (d.pm->this.progressive)
  7607. {
  7608. /* Share the row function with the standard implementation. */
  7609. png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
  7610. gamma_end);
  7611. /* Now feed data into the reader until we reach the end: */
  7612. modifier_progressive_read(d.pm, pp, pi);
  7613. }
  7614. else
  7615. {
  7616. /* modifier_read expects a png_modifier* */
  7617. png_set_read_fn(pp, d.pm, modifier_read);
  7618. /* Check the header values: */
  7619. png_read_info(pp, pi);
  7620. /* Process the 'info' requirements. Only one image is generated */
  7621. gamma_info_imp(&d, pp, pi);
  7622. sequential_row(&d.this, pp, pi, -1, 0);
  7623. if (!d.this.speed)
  7624. gamma_image_validate(&d, pp, pi);
  7625. else
  7626. d.this.ps->validated = 1;
  7627. }
  7628. modifier_reset(d.pm);
  7629. if (d.pm->log && !d.threshold_test && !d.this.speed)
  7630. fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
  7631. d.this.bit_depth, colour_types[d.this.colour_type], name,
  7632. d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
  7633. /* Log the summary values too. */
  7634. if (d.this.colour_type == 0 || d.this.colour_type == 4)
  7635. {
  7636. switch (d.this.bit_depth)
  7637. {
  7638. case 1:
  7639. break;
  7640. case 2:
  7641. if (d.maxerrout > d.pm->error_gray_2)
  7642. d.pm->error_gray_2 = d.maxerrout;
  7643. break;
  7644. case 4:
  7645. if (d.maxerrout > d.pm->error_gray_4)
  7646. d.pm->error_gray_4 = d.maxerrout;
  7647. break;
  7648. case 8:
  7649. if (d.maxerrout > d.pm->error_gray_8)
  7650. d.pm->error_gray_8 = d.maxerrout;
  7651. break;
  7652. case 16:
  7653. if (d.maxerrout > d.pm->error_gray_16)
  7654. d.pm->error_gray_16 = d.maxerrout;
  7655. break;
  7656. default:
  7657. png_error(pp, "bad bit depth (internal: 1)");
  7658. }
  7659. }
  7660. else if (d.this.colour_type == 2 || d.this.colour_type == 6)
  7661. {
  7662. switch (d.this.bit_depth)
  7663. {
  7664. case 8:
  7665. if (d.maxerrout > d.pm->error_color_8)
  7666. d.pm->error_color_8 = d.maxerrout;
  7667. break;
  7668. case 16:
  7669. if (d.maxerrout > d.pm->error_color_16)
  7670. d.pm->error_color_16 = d.maxerrout;
  7671. break;
  7672. default:
  7673. png_error(pp, "bad bit depth (internal: 2)");
  7674. }
  7675. }
  7676. else if (d.this.colour_type == 3)
  7677. {
  7678. if (d.maxerrout > d.pm->error_indexed)
  7679. d.pm->error_indexed = d.maxerrout;
  7680. }
  7681. }
  7682. Catch(fault)
  7683. modifier_reset(voidcast(png_modifier*,(void*)fault));
  7684. }
  7685. static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
  7686. png_byte bit_depth, int interlace_type, double file_gamma,
  7687. double screen_gamma)
  7688. {
  7689. size_t pos = 0;
  7690. char name[64];
  7691. pos = safecat(name, sizeof name, pos, "threshold ");
  7692. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  7693. pos = safecat(name, sizeof name, pos, "/");
  7694. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  7695. (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
  7696. file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
  7697. 0 /*no input precision*/,
  7698. 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
  7699. 0 /*no background gamma*/);
  7700. }
  7701. static void
  7702. perform_gamma_threshold_tests(png_modifier *pm)
  7703. {
  7704. png_byte colour_type = 0;
  7705. png_byte bit_depth = 0;
  7706. unsigned int palette_number = 0;
  7707. /* Don't test more than one instance of each palette - it's pointless, in
  7708. * fact this test is somewhat excessive since libpng doesn't make this
  7709. * decision based on colour type or bit depth!
  7710. */
  7711. while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
  7712. if (palette_number == 0)
  7713. {
  7714. double test_gamma = 1.0;
  7715. while (test_gamma >= .4)
  7716. {
  7717. /* There's little point testing the interlacing vs non-interlacing,
  7718. * but this can be set from the command line.
  7719. */
  7720. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  7721. test_gamma, 1/test_gamma);
  7722. test_gamma *= .95;
  7723. }
  7724. /* And a special test for sRGB */
  7725. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  7726. .45455, 2.2);
  7727. if (fail(pm))
  7728. return;
  7729. }
  7730. }
  7731. static void gamma_transform_test(png_modifier *pm,
  7732. PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth,
  7733. PNG_CONST int palette_number,
  7734. PNG_CONST int interlace_type, PNG_CONST double file_gamma,
  7735. PNG_CONST double screen_gamma, PNG_CONST png_byte sbit,
  7736. PNG_CONST int use_input_precision, PNG_CONST int scale16)
  7737. {
  7738. size_t pos = 0;
  7739. char name[64];
  7740. if (sbit != bit_depth && sbit != 0)
  7741. {
  7742. pos = safecat(name, sizeof name, pos, "sbit(");
  7743. pos = safecatn(name, sizeof name, pos, sbit);
  7744. pos = safecat(name, sizeof name, pos, ") ");
  7745. }
  7746. else
  7747. pos = safecat(name, sizeof name, pos, "gamma ");
  7748. if (scale16)
  7749. pos = safecat(name, sizeof name, pos, "16to8 ");
  7750. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  7751. pos = safecat(name, sizeof name, pos, "->");
  7752. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  7753. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  7754. file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
  7755. scale16, pm->test_gamma_expand16, 0 , 0, 0);
  7756. }
  7757. static void perform_gamma_transform_tests(png_modifier *pm)
  7758. {
  7759. png_byte colour_type = 0;
  7760. png_byte bit_depth = 0;
  7761. unsigned int palette_number = 0;
  7762. while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
  7763. {
  7764. unsigned int i, j;
  7765. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  7766. if (i != j)
  7767. {
  7768. gamma_transform_test(pm, colour_type, bit_depth, palette_number,
  7769. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
  7770. pm->use_input_precision, 0 /*do not scale16*/);
  7771. if (fail(pm))
  7772. return;
  7773. }
  7774. }
  7775. }
  7776. static void perform_gamma_sbit_tests(png_modifier *pm)
  7777. {
  7778. png_byte sbit;
  7779. /* The only interesting cases are colour and grayscale, alpha is ignored here
  7780. * for overall speed. Only bit depths where sbit is less than the bit depth
  7781. * are tested.
  7782. */
  7783. for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
  7784. {
  7785. png_byte colour_type = 0, bit_depth = 0;
  7786. unsigned int npalette = 0;
  7787. while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/))
  7788. if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
  7789. ((colour_type == 3 && sbit < 8) ||
  7790. (colour_type != 3 && sbit < bit_depth)))
  7791. {
  7792. unsigned int i;
  7793. for (i=0; i<pm->ngamma_tests; ++i)
  7794. {
  7795. unsigned int j;
  7796. for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
  7797. {
  7798. gamma_transform_test(pm, colour_type, bit_depth, npalette,
  7799. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  7800. sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
  7801. if (fail(pm))
  7802. return;
  7803. }
  7804. }
  7805. }
  7806. }
  7807. }
  7808. /* Note that this requires a 16 bit source image but produces 8 bit output, so
  7809. * we only need the 16bit write support, but the 16 bit images are only
  7810. * generated if DO_16BIT is defined.
  7811. */
  7812. #ifdef DO_16BIT
  7813. static void perform_gamma_scale16_tests(png_modifier *pm)
  7814. {
  7815. # ifndef PNG_MAX_GAMMA_8
  7816. # define PNG_MAX_GAMMA_8 11
  7817. # endif
  7818. # define SBIT_16_TO_8 PNG_MAX_GAMMA_8
  7819. /* Include the alpha cases here. Note that sbit matches the internal value
  7820. * used by the library - otherwise we will get spurious errors from the
  7821. * internal sbit style approximation.
  7822. *
  7823. * The threshold test is here because otherwise the 16 to 8 conversion will
  7824. * proceed *without* gamma correction, and the tests above will fail (but not
  7825. * by much) - this could be fixed, it only appears with the -g option.
  7826. */
  7827. unsigned int i, j;
  7828. for (i=0; i<pm->ngamma_tests; ++i)
  7829. {
  7830. for (j=0; j<pm->ngamma_tests; ++j)
  7831. {
  7832. if (i != j &&
  7833. fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
  7834. {
  7835. gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
  7836. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  7837. pm->use_input_precision_16to8, 1 /*scale16*/);
  7838. if (fail(pm))
  7839. return;
  7840. gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
  7841. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  7842. pm->use_input_precision_16to8, 1 /*scale16*/);
  7843. if (fail(pm))
  7844. return;
  7845. gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
  7846. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  7847. pm->use_input_precision_16to8, 1 /*scale16*/);
  7848. if (fail(pm))
  7849. return;
  7850. gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
  7851. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  7852. pm->use_input_precision_16to8, 1 /*scale16*/);
  7853. if (fail(pm))
  7854. return;
  7855. }
  7856. }
  7857. }
  7858. }
  7859. #endif /* 16 to 8 bit conversion */
  7860. #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
  7861. defined(PNG_READ_ALPHA_MODE_SUPPORTED)
  7862. static void gamma_composition_test(png_modifier *pm,
  7863. PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth,
  7864. PNG_CONST int palette_number,
  7865. PNG_CONST int interlace_type, PNG_CONST double file_gamma,
  7866. PNG_CONST double screen_gamma,
  7867. PNG_CONST int use_input_precision, PNG_CONST int do_background,
  7868. PNG_CONST int expand_16)
  7869. {
  7870. size_t pos = 0;
  7871. png_const_charp base;
  7872. double bg;
  7873. char name[128];
  7874. png_color_16 background;
  7875. /* Make up a name and get an appropriate background gamma value. */
  7876. switch (do_background)
  7877. {
  7878. default:
  7879. base = "";
  7880. bg = 4; /* should not be used */
  7881. break;
  7882. case PNG_BACKGROUND_GAMMA_SCREEN:
  7883. base = " bckg(Screen):";
  7884. bg = 1/screen_gamma;
  7885. break;
  7886. case PNG_BACKGROUND_GAMMA_FILE:
  7887. base = " bckg(File):";
  7888. bg = file_gamma;
  7889. break;
  7890. case PNG_BACKGROUND_GAMMA_UNIQUE:
  7891. base = " bckg(Unique):";
  7892. /* This tests the handling of a unique value, the math is such that the
  7893. * value tends to be <1, but is neither screen nor file (even if they
  7894. * match!)
  7895. */
  7896. bg = (file_gamma + screen_gamma) / 3;
  7897. break;
  7898. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7899. case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
  7900. base = " alpha(PNG)";
  7901. bg = 4; /* should not be used */
  7902. break;
  7903. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  7904. base = " alpha(Porter-Duff)";
  7905. bg = 4; /* should not be used */
  7906. break;
  7907. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  7908. base = " alpha(Optimized)";
  7909. bg = 4; /* should not be used */
  7910. break;
  7911. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  7912. base = " alpha(Broken)";
  7913. bg = 4; /* should not be used */
  7914. break;
  7915. #endif
  7916. }
  7917. /* Use random background values - the background is always presented in the
  7918. * output space (8 or 16 bit components).
  7919. */
  7920. if (expand_16 || bit_depth == 16)
  7921. {
  7922. png_uint_32 r = random_32();
  7923. background.red = (png_uint_16)r;
  7924. background.green = (png_uint_16)(r >> 16);
  7925. r = random_32();
  7926. background.blue = (png_uint_16)r;
  7927. background.gray = (png_uint_16)(r >> 16);
  7928. /* In earlier libpng versions, those where DIGITIZE is set, any background
  7929. * gamma correction in the expand16 case was done using 8-bit gamma
  7930. * correction tables, resulting in larger errors. To cope with those
  7931. * cases use a 16-bit background value which will handle this gamma
  7932. * correction.
  7933. */
  7934. # if DIGITIZE
  7935. if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
  7936. do_background == PNG_BACKGROUND_GAMMA_FILE) &&
  7937. fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
  7938. {
  7939. /* The background values will be looked up in an 8-bit table to do
  7940. * the gamma correction, so only select values which are an exact
  7941. * match for the 8-bit table entries:
  7942. */
  7943. background.red = (png_uint_16)((background.red >> 8) * 257);
  7944. background.green = (png_uint_16)((background.green >> 8) * 257);
  7945. background.blue = (png_uint_16)((background.blue >> 8) * 257);
  7946. background.gray = (png_uint_16)((background.gray >> 8) * 257);
  7947. }
  7948. # endif
  7949. }
  7950. else /* 8 bit colors */
  7951. {
  7952. png_uint_32 r = random_32();
  7953. background.red = (png_byte)r;
  7954. background.green = (png_byte)(r >> 8);
  7955. background.blue = (png_byte)(r >> 16);
  7956. background.gray = (png_byte)(r >> 24);
  7957. }
  7958. background.index = 193; /* rgb(193,193,193) to detect errors */
  7959. if (!(colour_type & PNG_COLOR_MASK_COLOR))
  7960. {
  7961. /* Grayscale input, we do not convert to RGB (TBD), so we must set the
  7962. * background to gray - else libpng seems to fail.
  7963. */
  7964. background.red = background.green = background.blue = background.gray;
  7965. }
  7966. pos = safecat(name, sizeof name, pos, "gamma ");
  7967. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  7968. pos = safecat(name, sizeof name, pos, "->");
  7969. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  7970. pos = safecat(name, sizeof name, pos, base);
  7971. if (do_background < ALPHA_MODE_OFFSET)
  7972. {
  7973. /* Include the background color and gamma in the name: */
  7974. pos = safecat(name, sizeof name, pos, "(");
  7975. /* This assumes no expand gray->rgb - the current code won't handle that!
  7976. */
  7977. if (colour_type & PNG_COLOR_MASK_COLOR)
  7978. {
  7979. pos = safecatn(name, sizeof name, pos, background.red);
  7980. pos = safecat(name, sizeof name, pos, ",");
  7981. pos = safecatn(name, sizeof name, pos, background.green);
  7982. pos = safecat(name, sizeof name, pos, ",");
  7983. pos = safecatn(name, sizeof name, pos, background.blue);
  7984. }
  7985. else
  7986. pos = safecatn(name, sizeof name, pos, background.gray);
  7987. pos = safecat(name, sizeof name, pos, ")^");
  7988. pos = safecatd(name, sizeof name, pos, bg, 3);
  7989. }
  7990. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  7991. file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
  7992. 0/*strip 16*/, expand_16, do_background, &background, bg);
  7993. }
  7994. static void
  7995. perform_gamma_composition_tests(png_modifier *pm, int do_background,
  7996. int expand_16)
  7997. {
  7998. png_byte colour_type = 0;
  7999. png_byte bit_depth = 0;
  8000. unsigned int palette_number = 0;
  8001. /* Skip the non-alpha cases - there is no setting of a transparency colour at
  8002. * present.
  8003. */
  8004. while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
  8005. if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0)
  8006. {
  8007. unsigned int i, j;
  8008. /* Don't skip the i==j case here - it's relevant. */
  8009. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  8010. {
  8011. gamma_composition_test(pm, colour_type, bit_depth, palette_number,
  8012. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  8013. pm->use_input_precision, do_background, expand_16);
  8014. if (fail(pm))
  8015. return;
  8016. }
  8017. }
  8018. }
  8019. #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
  8020. static void
  8021. init_gamma_errors(png_modifier *pm)
  8022. {
  8023. /* Use -1 to catch tests that were not actually run */
  8024. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
  8025. pm->error_color_8 = -1.;
  8026. pm->error_indexed = -1.;
  8027. pm->error_gray_16 = pm->error_color_16 = -1.;
  8028. }
  8029. static void
  8030. print_one(const char *leader, double err)
  8031. {
  8032. if (err != -1.)
  8033. printf(" %s %.5f\n", leader, err);
  8034. }
  8035. static void
  8036. summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
  8037. int indexed)
  8038. {
  8039. fflush(stderr);
  8040. if (who)
  8041. printf("\nGamma correction with %s:\n", who);
  8042. else
  8043. printf("\nBasic gamma correction:\n");
  8044. if (low_bit_depth)
  8045. {
  8046. print_one(" 2 bit gray: ", pm->error_gray_2);
  8047. print_one(" 4 bit gray: ", pm->error_gray_4);
  8048. print_one(" 8 bit gray: ", pm->error_gray_8);
  8049. print_one(" 8 bit color:", pm->error_color_8);
  8050. if (indexed)
  8051. print_one(" indexed: ", pm->error_indexed);
  8052. }
  8053. print_one("16 bit gray: ", pm->error_gray_16);
  8054. print_one("16 bit color:", pm->error_color_16);
  8055. fflush(stdout);
  8056. }
  8057. static void
  8058. perform_gamma_test(png_modifier *pm, int summary)
  8059. {
  8060. /*TODO: remove this*/
  8061. /* Save certain values for the temporary overrides below. */
  8062. unsigned int calculations_use_input_precision =
  8063. pm->calculations_use_input_precision;
  8064. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  8065. double maxout8 = pm->maxout8;
  8066. # endif
  8067. /* First some arbitrary no-transform tests: */
  8068. if (!pm->this.speed && pm->test_gamma_threshold)
  8069. {
  8070. perform_gamma_threshold_tests(pm);
  8071. if (fail(pm))
  8072. return;
  8073. }
  8074. /* Now some real transforms. */
  8075. if (pm->test_gamma_transform)
  8076. {
  8077. if (summary)
  8078. {
  8079. fflush(stderr);
  8080. printf("Gamma correction error summary\n\n");
  8081. printf("The printed value is the maximum error in the pixel values\n");
  8082. printf("calculated by the libpng gamma correction code. The error\n");
  8083. printf("is calculated as the difference between the output pixel\n");
  8084. printf("value (always an integer) and the ideal value from the\n");
  8085. printf("libpng specification (typically not an integer).\n\n");
  8086. printf("Expect this value to be less than .5 for 8 bit formats,\n");
  8087. printf("less than 1 for formats with fewer than 8 bits and a small\n");
  8088. printf("number (typically less than 5) for the 16 bit formats.\n");
  8089. printf("For performance reasons the value for 16 bit formats\n");
  8090. printf("increases when the image file includes an sBIT chunk.\n");
  8091. fflush(stdout);
  8092. }
  8093. init_gamma_errors(pm);
  8094. /*TODO: remove this. Necessary because the current libpng
  8095. * implementation works in 8 bits:
  8096. */
  8097. if (pm->test_gamma_expand16)
  8098. pm->calculations_use_input_precision = 1;
  8099. perform_gamma_transform_tests(pm);
  8100. if (!calculations_use_input_precision)
  8101. pm->calculations_use_input_precision = 0;
  8102. if (summary)
  8103. summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
  8104. if (fail(pm))
  8105. return;
  8106. }
  8107. /* The sbit tests produce much larger errors: */
  8108. if (pm->test_gamma_sbit)
  8109. {
  8110. init_gamma_errors(pm);
  8111. perform_gamma_sbit_tests(pm);
  8112. if (summary)
  8113. summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
  8114. if (fail(pm))
  8115. return;
  8116. }
  8117. #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
  8118. if (pm->test_gamma_scale16)
  8119. {
  8120. /* The 16 to 8 bit strip operations: */
  8121. init_gamma_errors(pm);
  8122. perform_gamma_scale16_tests(pm);
  8123. if (summary)
  8124. {
  8125. fflush(stderr);
  8126. printf("\nGamma correction with 16 to 8 bit reduction:\n");
  8127. printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
  8128. printf(" 16 bit color: %.5f\n", pm->error_color_16);
  8129. fflush(stdout);
  8130. }
  8131. if (fail(pm))
  8132. return;
  8133. }
  8134. #endif
  8135. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  8136. if (pm->test_gamma_background)
  8137. {
  8138. init_gamma_errors(pm);
  8139. /*TODO: remove this. Necessary because the current libpng
  8140. * implementation works in 8 bits:
  8141. */
  8142. if (pm->test_gamma_expand16)
  8143. {
  8144. pm->calculations_use_input_precision = 1;
  8145. pm->maxout8 = .499; /* because the 16 bit background is smashed */
  8146. }
  8147. perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
  8148. pm->test_gamma_expand16);
  8149. if (!calculations_use_input_precision)
  8150. pm->calculations_use_input_precision = 0;
  8151. pm->maxout8 = maxout8;
  8152. if (summary)
  8153. summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
  8154. if (fail(pm))
  8155. return;
  8156. }
  8157. #endif
  8158. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8159. if (pm->test_gamma_alpha_mode)
  8160. {
  8161. int do_background;
  8162. init_gamma_errors(pm);
  8163. /*TODO: remove this. Necessary because the current libpng
  8164. * implementation works in 8 bits:
  8165. */
  8166. if (pm->test_gamma_expand16)
  8167. pm->calculations_use_input_precision = 1;
  8168. for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
  8169. do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
  8170. ++do_background)
  8171. perform_gamma_composition_tests(pm, do_background,
  8172. pm->test_gamma_expand16);
  8173. if (!calculations_use_input_precision)
  8174. pm->calculations_use_input_precision = 0;
  8175. if (summary)
  8176. summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
  8177. if (fail(pm))
  8178. return;
  8179. }
  8180. #endif
  8181. }
  8182. #endif /* PNG_READ_GAMMA_SUPPORTED */
  8183. #endif /* PNG_READ_SUPPORTED */
  8184. /* INTERLACE MACRO VALIDATION */
  8185. /* This is copied verbatim from the specification, it is simply the pass
  8186. * number in which each pixel in each 8x8 tile appears. The array must
  8187. * be indexed adam7[y][x] and notice that the pass numbers are based at
  8188. * 1, not 0 - the base libpng uses.
  8189. */
  8190. static PNG_CONST
  8191. png_byte adam7[8][8] =
  8192. {
  8193. { 1,6,4,6,2,6,4,6 },
  8194. { 7,7,7,7,7,7,7,7 },
  8195. { 5,6,5,6,5,6,5,6 },
  8196. { 7,7,7,7,7,7,7,7 },
  8197. { 3,6,4,6,3,6,4,6 },
  8198. { 7,7,7,7,7,7,7,7 },
  8199. { 5,6,5,6,5,6,5,6 },
  8200. { 7,7,7,7,7,7,7,7 }
  8201. };
  8202. /* This routine validates all the interlace support macros in png.h for
  8203. * a variety of valid PNG widths and heights. It uses a number of similarly
  8204. * named internal routines that feed off the above array.
  8205. */
  8206. static png_uint_32
  8207. png_pass_start_row(int pass)
  8208. {
  8209. int x, y;
  8210. ++pass;
  8211. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  8212. return y;
  8213. return 0xf;
  8214. }
  8215. static png_uint_32
  8216. png_pass_start_col(int pass)
  8217. {
  8218. int x, y;
  8219. ++pass;
  8220. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  8221. return x;
  8222. return 0xf;
  8223. }
  8224. static int
  8225. png_pass_row_shift(int pass)
  8226. {
  8227. int x, y, base=(-1), inc=8;
  8228. ++pass;
  8229. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  8230. {
  8231. if (base == (-1))
  8232. base = y;
  8233. else if (base == y)
  8234. {}
  8235. else if (inc == y-base)
  8236. base=y;
  8237. else if (inc == 8)
  8238. inc = y-base, base=y;
  8239. else if (inc != y-base)
  8240. return 0xff; /* error - more than one 'inc' value! */
  8241. }
  8242. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  8243. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  8244. switch (inc)
  8245. {
  8246. case 2: return 1;
  8247. case 4: return 2;
  8248. case 8: return 3;
  8249. default: break;
  8250. }
  8251. /* error - unrecognized 'inc' */
  8252. return (inc << 8) + 0xfd;
  8253. }
  8254. static int
  8255. png_pass_col_shift(int pass)
  8256. {
  8257. int x, y, base=(-1), inc=8;
  8258. ++pass;
  8259. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  8260. {
  8261. if (base == (-1))
  8262. base = x;
  8263. else if (base == x)
  8264. {}
  8265. else if (inc == x-base)
  8266. base=x;
  8267. else if (inc == 8)
  8268. inc = x-base, base=x;
  8269. else if (inc != x-base)
  8270. return 0xff; /* error - more than one 'inc' value! */
  8271. }
  8272. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  8273. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  8274. switch (inc)
  8275. {
  8276. case 1: return 0; /* pass 7 has all the columns */
  8277. case 2: return 1;
  8278. case 4: return 2;
  8279. case 8: return 3;
  8280. default: break;
  8281. }
  8282. /* error - unrecognized 'inc' */
  8283. return (inc << 8) + 0xfd;
  8284. }
  8285. static png_uint_32
  8286. png_row_from_pass_row(png_uint_32 yIn, int pass)
  8287. {
  8288. /* By examination of the array: */
  8289. switch (pass)
  8290. {
  8291. case 0: return yIn * 8;
  8292. case 1: return yIn * 8;
  8293. case 2: return yIn * 8 + 4;
  8294. case 3: return yIn * 4;
  8295. case 4: return yIn * 4 + 2;
  8296. case 5: return yIn * 2;
  8297. case 6: return yIn * 2 + 1;
  8298. default: break;
  8299. }
  8300. return 0xff; /* bad pass number */
  8301. }
  8302. static png_uint_32
  8303. png_col_from_pass_col(png_uint_32 xIn, int pass)
  8304. {
  8305. /* By examination of the array: */
  8306. switch (pass)
  8307. {
  8308. case 0: return xIn * 8;
  8309. case 1: return xIn * 8 + 4;
  8310. case 2: return xIn * 4;
  8311. case 3: return xIn * 4 + 2;
  8312. case 4: return xIn * 2;
  8313. case 5: return xIn * 2 + 1;
  8314. case 6: return xIn;
  8315. default: break;
  8316. }
  8317. return 0xff; /* bad pass number */
  8318. }
  8319. static int
  8320. png_row_in_interlace_pass(png_uint_32 y, int pass)
  8321. {
  8322. /* Is row 'y' in pass 'pass'? */
  8323. int x;
  8324. y &= 7;
  8325. ++pass;
  8326. for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  8327. return 1;
  8328. return 0;
  8329. }
  8330. static int
  8331. png_col_in_interlace_pass(png_uint_32 x, int pass)
  8332. {
  8333. /* Is column 'x' in pass 'pass'? */
  8334. int y;
  8335. x &= 7;
  8336. ++pass;
  8337. for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  8338. return 1;
  8339. return 0;
  8340. }
  8341. static png_uint_32
  8342. png_pass_rows(png_uint_32 height, int pass)
  8343. {
  8344. png_uint_32 tiles = height>>3;
  8345. png_uint_32 rows = 0;
  8346. unsigned int x, y;
  8347. height &= 7;
  8348. ++pass;
  8349. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  8350. {
  8351. rows += tiles;
  8352. if (y < height) ++rows;
  8353. break; /* i.e. break the 'x', column, loop. */
  8354. }
  8355. return rows;
  8356. }
  8357. static png_uint_32
  8358. png_pass_cols(png_uint_32 width, int pass)
  8359. {
  8360. png_uint_32 tiles = width>>3;
  8361. png_uint_32 cols = 0;
  8362. unsigned int x, y;
  8363. width &= 7;
  8364. ++pass;
  8365. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  8366. {
  8367. cols += tiles;
  8368. if (x < width) ++cols;
  8369. break; /* i.e. break the 'y', row, loop. */
  8370. }
  8371. return cols;
  8372. }
  8373. static void
  8374. perform_interlace_macro_validation(void)
  8375. {
  8376. /* The macros to validate, first those that depend only on pass:
  8377. *
  8378. * PNG_PASS_START_ROW(pass)
  8379. * PNG_PASS_START_COL(pass)
  8380. * PNG_PASS_ROW_SHIFT(pass)
  8381. * PNG_PASS_COL_SHIFT(pass)
  8382. */
  8383. int pass;
  8384. for (pass=0; pass<7; ++pass)
  8385. {
  8386. png_uint_32 m, f, v;
  8387. m = PNG_PASS_START_ROW(pass);
  8388. f = png_pass_start_row(pass);
  8389. if (m != f)
  8390. {
  8391. fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
  8392. exit(99);
  8393. }
  8394. m = PNG_PASS_START_COL(pass);
  8395. f = png_pass_start_col(pass);
  8396. if (m != f)
  8397. {
  8398. fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
  8399. exit(99);
  8400. }
  8401. m = PNG_PASS_ROW_SHIFT(pass);
  8402. f = png_pass_row_shift(pass);
  8403. if (m != f)
  8404. {
  8405. fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
  8406. exit(99);
  8407. }
  8408. m = PNG_PASS_COL_SHIFT(pass);
  8409. f = png_pass_col_shift(pass);
  8410. if (m != f)
  8411. {
  8412. fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
  8413. exit(99);
  8414. }
  8415. /* Macros that depend on the image or sub-image height too:
  8416. *
  8417. * PNG_PASS_ROWS(height, pass)
  8418. * PNG_PASS_COLS(width, pass)
  8419. * PNG_ROW_FROM_PASS_ROW(yIn, pass)
  8420. * PNG_COL_FROM_PASS_COL(xIn, pass)
  8421. * PNG_ROW_IN_INTERLACE_PASS(y, pass)
  8422. * PNG_COL_IN_INTERLACE_PASS(x, pass)
  8423. */
  8424. for (v=0;;)
  8425. {
  8426. /* First the base 0 stuff: */
  8427. m = PNG_ROW_FROM_PASS_ROW(v, pass);
  8428. f = png_row_from_pass_row(v, pass);
  8429. if (m != f)
  8430. {
  8431. fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
  8432. v, pass, m, f);
  8433. exit(99);
  8434. }
  8435. m = PNG_COL_FROM_PASS_COL(v, pass);
  8436. f = png_col_from_pass_col(v, pass);
  8437. if (m != f)
  8438. {
  8439. fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
  8440. v, pass, m, f);
  8441. exit(99);
  8442. }
  8443. m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
  8444. f = png_row_in_interlace_pass(v, pass);
  8445. if (m != f)
  8446. {
  8447. fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  8448. v, pass, m, f);
  8449. exit(99);
  8450. }
  8451. m = PNG_COL_IN_INTERLACE_PASS(v, pass);
  8452. f = png_col_in_interlace_pass(v, pass);
  8453. if (m != f)
  8454. {
  8455. fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  8456. v, pass, m, f);
  8457. exit(99);
  8458. }
  8459. /* Then the base 1 stuff: */
  8460. ++v;
  8461. m = PNG_PASS_ROWS(v, pass);
  8462. f = png_pass_rows(v, pass);
  8463. if (m != f)
  8464. {
  8465. fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
  8466. v, pass, m, f);
  8467. exit(99);
  8468. }
  8469. m = PNG_PASS_COLS(v, pass);
  8470. f = png_pass_cols(v, pass);
  8471. if (m != f)
  8472. {
  8473. fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
  8474. v, pass, m, f);
  8475. exit(99);
  8476. }
  8477. /* Move to the next v - the stepping algorithm starts skipping
  8478. * values above 1024.
  8479. */
  8480. if (v > 1024)
  8481. {
  8482. if (v == PNG_UINT_31_MAX)
  8483. break;
  8484. v = (v << 1) ^ v;
  8485. if (v >= PNG_UINT_31_MAX)
  8486. v = PNG_UINT_31_MAX-1;
  8487. }
  8488. }
  8489. }
  8490. }
  8491. /* Test color encodings. These values are back-calculated from the published
  8492. * chromaticities. The values are accurate to about 14 decimal places; 15 are
  8493. * given. These values are much more accurate than the ones given in the spec,
  8494. * which typically don't exceed 4 decimal places. This allows testing of the
  8495. * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
  8496. * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
  8497. * more.)
  8498. *
  8499. * The png_modifier code assumes that encodings[0] is sRGB and treats it
  8500. * specially: do not change the first entry in this list!
  8501. */
  8502. static PNG_CONST color_encoding test_encodings[] =
  8503. {
  8504. /* sRGB: must be first in this list! */
  8505. /*gamma:*/ { 1/2.2,
  8506. /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
  8507. /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
  8508. /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
  8509. /* Kodak ProPhoto (wide gamut) */
  8510. /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
  8511. /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
  8512. /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
  8513. /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
  8514. /* Adobe RGB (1998) */
  8515. /*gamma:*/ { 1/(2+51./256),
  8516. /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
  8517. /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
  8518. /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
  8519. /* Adobe Wide Gamut RGB */
  8520. /*gamma:*/ { 1/(2+51./256),
  8521. /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
  8522. /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
  8523. /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
  8524. };
  8525. /* signal handler
  8526. *
  8527. * This attempts to trap signals and escape without crashing. It needs a
  8528. * context pointer so that it can throw an exception (call longjmp) to recover
  8529. * from the condition; this is handled by making the png_modifier used by 'main'
  8530. * into a global variable.
  8531. */
  8532. static png_modifier pm;
  8533. static void signal_handler(int signum)
  8534. {
  8535. size_t pos = 0;
  8536. char msg[64];
  8537. pos = safecat(msg, sizeof msg, pos, "caught signal: ");
  8538. switch (signum)
  8539. {
  8540. case SIGABRT:
  8541. pos = safecat(msg, sizeof msg, pos, "abort");
  8542. break;
  8543. case SIGFPE:
  8544. pos = safecat(msg, sizeof msg, pos, "floating point exception");
  8545. break;
  8546. case SIGILL:
  8547. pos = safecat(msg, sizeof msg, pos, "illegal instruction");
  8548. break;
  8549. case SIGINT:
  8550. pos = safecat(msg, sizeof msg, pos, "interrupt");
  8551. break;
  8552. case SIGSEGV:
  8553. pos = safecat(msg, sizeof msg, pos, "invalid memory access");
  8554. break;
  8555. case SIGTERM:
  8556. pos = safecat(msg, sizeof msg, pos, "termination request");
  8557. break;
  8558. default:
  8559. pos = safecat(msg, sizeof msg, pos, "unknown ");
  8560. pos = safecatn(msg, sizeof msg, pos, signum);
  8561. break;
  8562. }
  8563. store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
  8564. /* And finally throw an exception so we can keep going, unless this is
  8565. * SIGTERM in which case stop now.
  8566. */
  8567. if (signum != SIGTERM)
  8568. {
  8569. struct exception_context *the_exception_context =
  8570. &pm.this.exception_context;
  8571. Throw &pm.this;
  8572. }
  8573. else
  8574. exit(1);
  8575. }
  8576. /* main program */
  8577. int main(int argc, char **argv)
  8578. {
  8579. volatile int summary = 1; /* Print the error summary at the end */
  8580. volatile int memstats = 0; /* Print memory statistics at the end */
  8581. /* Create the given output file on success: */
  8582. PNG_CONST char *volatile touch = NULL;
  8583. /* This is an array of standard gamma values (believe it or not I've seen
  8584. * every one of these mentioned somewhere.)
  8585. *
  8586. * In the following list the most useful values are first!
  8587. */
  8588. static double
  8589. gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
  8590. /* This records the command and arguments: */
  8591. size_t cp = 0;
  8592. char command[1024];
  8593. anon_context(&pm.this);
  8594. /* Add appropriate signal handlers, just the ANSI specified ones: */
  8595. signal(SIGABRT, signal_handler);
  8596. signal(SIGFPE, signal_handler);
  8597. signal(SIGILL, signal_handler);
  8598. signal(SIGINT, signal_handler);
  8599. signal(SIGSEGV, signal_handler);
  8600. signal(SIGTERM, signal_handler);
  8601. #ifdef HAVE_FEENABLEEXCEPT
  8602. /* Only required to enable FP exceptions on platforms where they start off
  8603. * disabled; this is not necessary but if it is not done pngvalid will likely
  8604. * end up ignoring FP conditions that other platforms fault.
  8605. */
  8606. feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
  8607. #endif
  8608. modifier_init(&pm);
  8609. /* Preallocate the image buffer, because we know how big it needs to be,
  8610. * note that, for testing purposes, it is deliberately mis-aligned by tag
  8611. * bytes either side. All rows have an additional five bytes of padding for
  8612. * overwrite checking.
  8613. */
  8614. store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
  8615. /* Don't give argv[0], it's normally some horrible libtool string: */
  8616. cp = safecat(command, sizeof command, cp, "pngvalid");
  8617. /* Default to error on warning: */
  8618. pm.this.treat_warnings_as_errors = 1;
  8619. /* Default assume_16_bit_calculations appropriately; this tells the checking
  8620. * code that 16-bit arithmetic is used for 8-bit samples when it would make a
  8621. * difference.
  8622. */
  8623. pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
  8624. /* Currently 16 bit expansion happens at the end of the pipeline, so the
  8625. * calculations are done in the input bit depth not the output.
  8626. *
  8627. * TODO: fix this
  8628. */
  8629. pm.calculations_use_input_precision = 1U;
  8630. /* Store the test gammas */
  8631. pm.gammas = gammas;
  8632. pm.ngammas = ARRAY_SIZE(gammas);
  8633. pm.ngamma_tests = 0; /* default to off */
  8634. /* And the test encodings */
  8635. pm.encodings = test_encodings;
  8636. pm.nencodings = ARRAY_SIZE(test_encodings);
  8637. pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
  8638. /* The following allows results to pass if they correspond to anything in the
  8639. * transformed range [input-.5,input+.5]; this is is required because of the
  8640. * way libpng treates the 16_TO_8 flag when building the gamma tables in
  8641. * releases up to 1.6.0.
  8642. *
  8643. * TODO: review this
  8644. */
  8645. pm.use_input_precision_16to8 = 1U;
  8646. pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
  8647. /* Some default values (set the behavior for 'make check' here).
  8648. * These values simply control the maximum error permitted in the gamma
  8649. * transformations. The practial limits for human perception are described
  8650. * below (the setting for maxpc16), however for 8 bit encodings it isn't
  8651. * possible to meet the accepted capabilities of human vision - i.e. 8 bit
  8652. * images can never be good enough, regardless of encoding.
  8653. */
  8654. pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
  8655. pm.maxabs8 = .00005; /* 1/20000 */
  8656. pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
  8657. pm.maxpc8 = .499; /* I.e., .499% fractional error */
  8658. pm.maxout16 = .499; /* Error in *encoded* value */
  8659. pm.maxabs16 = .00005;/* 1/20000 */
  8660. pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
  8661. pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
  8662. /* NOTE: this is a reasonable perceptual limit. We assume that humans can
  8663. * perceive light level differences of 1% over a 100:1 range, so we need to
  8664. * maintain 1 in 10000 accuracy (in linear light space), which is what the
  8665. * following guarantees. It also allows significantly higher errors at
  8666. * higher 16 bit values, which is important for performance. The actual
  8667. * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
  8668. * this is only allowed for values >38149 by the following:
  8669. */
  8670. pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
  8671. /* Now parse the command line options. */
  8672. while (--argc >= 1)
  8673. {
  8674. int catmore = 0; /* Set if the argument has an argument. */
  8675. /* Record each argument for posterity: */
  8676. cp = safecat(command, sizeof command, cp, " ");
  8677. cp = safecat(command, sizeof command, cp, *++argv);
  8678. if (strcmp(*argv, "-v") == 0)
  8679. pm.this.verbose = 1;
  8680. else if (strcmp(*argv, "-l") == 0)
  8681. pm.log = 1;
  8682. else if (strcmp(*argv, "-q") == 0)
  8683. summary = pm.this.verbose = pm.log = 0;
  8684. else if (strcmp(*argv, "-w") == 0)
  8685. pm.this.treat_warnings_as_errors = 0;
  8686. else if (strcmp(*argv, "--speed") == 0)
  8687. pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
  8688. summary = 0;
  8689. else if (strcmp(*argv, "--memory") == 0)
  8690. memstats = 1;
  8691. else if (strcmp(*argv, "--size") == 0)
  8692. pm.test_size = 1;
  8693. else if (strcmp(*argv, "--nosize") == 0)
  8694. pm.test_size = 0;
  8695. else if (strcmp(*argv, "--standard") == 0)
  8696. pm.test_standard = 1;
  8697. else if (strcmp(*argv, "--nostandard") == 0)
  8698. pm.test_standard = 0;
  8699. else if (strcmp(*argv, "--transform") == 0)
  8700. pm.test_transform = 1;
  8701. else if (strcmp(*argv, "--notransform") == 0)
  8702. pm.test_transform = 0;
  8703. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  8704. else if (strncmp(*argv, "--transform-disable=",
  8705. sizeof "--transform-disable") == 0)
  8706. {
  8707. pm.test_transform = 1;
  8708. transform_disable(*argv + sizeof "--transform-disable");
  8709. }
  8710. else if (strncmp(*argv, "--transform-enable=",
  8711. sizeof "--transform-enable") == 0)
  8712. {
  8713. pm.test_transform = 1;
  8714. transform_enable(*argv + sizeof "--transform-enable");
  8715. }
  8716. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  8717. else if (strcmp(*argv, "--gamma") == 0)
  8718. {
  8719. /* Just do two gamma tests here (2.2 and linear) for speed: */
  8720. pm.ngamma_tests = 2U;
  8721. pm.test_gamma_threshold = 1;
  8722. pm.test_gamma_transform = 1;
  8723. pm.test_gamma_sbit = 1;
  8724. pm.test_gamma_scale16 = 1;
  8725. pm.test_gamma_background = 1;
  8726. pm.test_gamma_alpha_mode = 1;
  8727. }
  8728. else if (strcmp(*argv, "--nogamma") == 0)
  8729. pm.ngamma_tests = 0;
  8730. else if (strcmp(*argv, "--gamma-threshold") == 0)
  8731. pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
  8732. else if (strcmp(*argv, "--nogamma-threshold") == 0)
  8733. pm.test_gamma_threshold = 0;
  8734. else if (strcmp(*argv, "--gamma-transform") == 0)
  8735. pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
  8736. else if (strcmp(*argv, "--nogamma-transform") == 0)
  8737. pm.test_gamma_transform = 0;
  8738. else if (strcmp(*argv, "--gamma-sbit") == 0)
  8739. pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
  8740. else if (strcmp(*argv, "--nogamma-sbit") == 0)
  8741. pm.test_gamma_sbit = 0;
  8742. else if (strcmp(*argv, "--gamma-16-to-8") == 0)
  8743. pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
  8744. else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
  8745. pm.test_gamma_scale16 = 0;
  8746. else if (strcmp(*argv, "--gamma-background") == 0)
  8747. pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
  8748. else if (strcmp(*argv, "--nogamma-background") == 0)
  8749. pm.test_gamma_background = 0;
  8750. else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
  8751. pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
  8752. else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
  8753. pm.test_gamma_alpha_mode = 0;
  8754. else if (strcmp(*argv, "--expand16") == 0)
  8755. pm.test_gamma_expand16 = 1;
  8756. else if (strcmp(*argv, "--noexpand16") == 0)
  8757. pm.test_gamma_expand16 = 0;
  8758. else if (strcmp(*argv, "--more-gammas") == 0)
  8759. pm.ngamma_tests = 3U;
  8760. else if (strcmp(*argv, "--all-gammas") == 0)
  8761. pm.ngamma_tests = pm.ngammas;
  8762. else if (strcmp(*argv, "--progressive-read") == 0)
  8763. pm.this.progressive = 1;
  8764. else if (strcmp(*argv, "--use-update-info") == 0)
  8765. ++pm.use_update_info; /* Can call multiple times */
  8766. else if (strcmp(*argv, "--interlace") == 0)
  8767. {
  8768. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  8769. pm.interlace_type = PNG_INTERLACE_ADAM7;
  8770. # else
  8771. fprintf(stderr, "pngvalid: no write interlace support\n");
  8772. return SKIP;
  8773. # endif
  8774. }
  8775. else if (strcmp(*argv, "--use-input-precision") == 0)
  8776. pm.use_input_precision = 1U;
  8777. else if (strcmp(*argv, "--use-calculation-precision") == 0)
  8778. pm.use_input_precision = 0;
  8779. else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
  8780. pm.calculations_use_input_precision = 1U;
  8781. else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
  8782. pm.assume_16_bit_calculations = 1U;
  8783. else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
  8784. pm.calculations_use_input_precision =
  8785. pm.assume_16_bit_calculations = 0;
  8786. else if (strcmp(*argv, "--exhaustive") == 0)
  8787. pm.test_exhaustive = 1;
  8788. else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
  8789. --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
  8790. else if (argc > 1 && strcmp(*argv, "--touch") == 0)
  8791. --argc, touch = *++argv, catmore = 1;
  8792. else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
  8793. {
  8794. --argc;
  8795. if (strcmp(5+*argv, "abs8") == 0)
  8796. pm.maxabs8 = atof(*++argv);
  8797. else if (strcmp(5+*argv, "abs16") == 0)
  8798. pm.maxabs16 = atof(*++argv);
  8799. else if (strcmp(5+*argv, "calc8") == 0)
  8800. pm.maxcalc8 = atof(*++argv);
  8801. else if (strcmp(5+*argv, "calc16") == 0)
  8802. pm.maxcalc16 = atof(*++argv);
  8803. else if (strcmp(5+*argv, "out8") == 0)
  8804. pm.maxout8 = atof(*++argv);
  8805. else if (strcmp(5+*argv, "out16") == 0)
  8806. pm.maxout16 = atof(*++argv);
  8807. else if (strcmp(5+*argv, "pc8") == 0)
  8808. pm.maxpc8 = atof(*++argv);
  8809. else if (strcmp(5+*argv, "pc16") == 0)
  8810. pm.maxpc16 = atof(*++argv);
  8811. else
  8812. {
  8813. fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
  8814. exit(99);
  8815. }
  8816. catmore = 1;
  8817. }
  8818. else if (strcmp(*argv, "--log8") == 0)
  8819. --argc, pm.log8 = atof(*++argv), catmore = 1;
  8820. else if (strcmp(*argv, "--log16") == 0)
  8821. --argc, pm.log16 = atof(*++argv), catmore = 1;
  8822. #ifdef PNG_SET_OPTION_SUPPORTED
  8823. else if (strncmp(*argv, "--option=", 9) == 0)
  8824. {
  8825. /* Syntax of the argument is <option>:{on|off} */
  8826. const char *arg = 9+*argv;
  8827. unsigned char option=0, setting=0;
  8828. #ifdef PNG_ARM_NEON_API_SUPPORTED
  8829. if (strncmp(arg, "arm-neon:", 9) == 0)
  8830. option = PNG_ARM_NEON, arg += 9;
  8831. else
  8832. #endif
  8833. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  8834. if (strncmp(arg, "max-inflate-window:", 19) == 0)
  8835. option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
  8836. else
  8837. #endif
  8838. {
  8839. fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
  8840. exit(99);
  8841. }
  8842. if (strcmp(arg, "off") == 0)
  8843. setting = PNG_OPTION_OFF;
  8844. else if (strcmp(arg, "on") == 0)
  8845. setting = PNG_OPTION_ON;
  8846. else
  8847. {
  8848. fprintf(stderr,
  8849. "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
  8850. *argv, arg);
  8851. exit(99);
  8852. }
  8853. pm.this.options[pm.this.noptions].option = option;
  8854. pm.this.options[pm.this.noptions++].setting = setting;
  8855. }
  8856. #endif /* PNG_SET_OPTION_SUPPORTED */
  8857. else
  8858. {
  8859. fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
  8860. exit(99);
  8861. }
  8862. if (catmore) /* consumed an extra *argv */
  8863. {
  8864. cp = safecat(command, sizeof command, cp, " ");
  8865. cp = safecat(command, sizeof command, cp, *argv);
  8866. }
  8867. }
  8868. /* If pngvalid is run with no arguments default to a reasonable set of the
  8869. * tests.
  8870. */
  8871. if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
  8872. pm.ngamma_tests == 0)
  8873. {
  8874. /* Make this do all the tests done in the test shell scripts with the same
  8875. * parameters, where possible. The limitation is that all the progressive
  8876. * read and interlace stuff has to be done in separate runs, so only the
  8877. * basic 'standard' and 'size' tests are done.
  8878. */
  8879. pm.test_standard = 1;
  8880. pm.test_size = 1;
  8881. pm.test_transform = 1;
  8882. pm.ngamma_tests = 2U;
  8883. }
  8884. if (pm.ngamma_tests > 0 &&
  8885. pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
  8886. pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
  8887. pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
  8888. {
  8889. pm.test_gamma_threshold = 1;
  8890. pm.test_gamma_transform = 1;
  8891. pm.test_gamma_sbit = 1;
  8892. pm.test_gamma_scale16 = 1;
  8893. pm.test_gamma_background = 1;
  8894. pm.test_gamma_alpha_mode = 1;
  8895. }
  8896. else if (pm.ngamma_tests == 0)
  8897. {
  8898. /* Nothing to test so turn everything off: */
  8899. pm.test_gamma_threshold = 0;
  8900. pm.test_gamma_transform = 0;
  8901. pm.test_gamma_sbit = 0;
  8902. pm.test_gamma_scale16 = 0;
  8903. pm.test_gamma_background = 0;
  8904. pm.test_gamma_alpha_mode = 0;
  8905. }
  8906. Try
  8907. {
  8908. /* Make useful base images */
  8909. make_transform_images(&pm.this);
  8910. /* Perform the standard and gamma tests. */
  8911. if (pm.test_standard)
  8912. {
  8913. perform_interlace_macro_validation();
  8914. perform_formatting_test(&pm.this);
  8915. # ifdef PNG_READ_SUPPORTED
  8916. perform_standard_test(&pm);
  8917. # endif
  8918. perform_error_test(&pm);
  8919. }
  8920. /* Various oddly sized images: */
  8921. if (pm.test_size)
  8922. {
  8923. make_size_images(&pm.this);
  8924. # ifdef PNG_READ_SUPPORTED
  8925. perform_size_test(&pm);
  8926. # endif
  8927. }
  8928. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  8929. /* Combinatorial transforms: */
  8930. if (pm.test_transform)
  8931. perform_transform_test(&pm);
  8932. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  8933. #ifdef PNG_READ_GAMMA_SUPPORTED
  8934. if (pm.ngamma_tests > 0)
  8935. perform_gamma_test(&pm, summary);
  8936. #endif
  8937. }
  8938. Catch_anonymous
  8939. {
  8940. fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
  8941. if (!pm.this.verbose)
  8942. {
  8943. if (pm.this.error[0] != 0)
  8944. fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
  8945. fprintf(stderr, "pngvalid: run with -v to see what happened\n");
  8946. }
  8947. exit(1);
  8948. }
  8949. if (summary)
  8950. {
  8951. printf("%s: %s (%s point arithmetic)\n",
  8952. (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  8953. pm.this.nwarnings)) ? "FAIL" : "PASS",
  8954. command,
  8955. #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
  8956. "floating"
  8957. #else
  8958. "fixed"
  8959. #endif
  8960. );
  8961. }
  8962. if (memstats)
  8963. {
  8964. printf("Allocated memory statistics (in bytes):\n"
  8965. "\tread %lu maximum single, %lu peak, %lu total\n"
  8966. "\twrite %lu maximum single, %lu peak, %lu total\n",
  8967. (unsigned long)pm.this.read_memory_pool.max_max,
  8968. (unsigned long)pm.this.read_memory_pool.max_limit,
  8969. (unsigned long)pm.this.read_memory_pool.max_total,
  8970. (unsigned long)pm.this.write_memory_pool.max_max,
  8971. (unsigned long)pm.this.write_memory_pool.max_limit,
  8972. (unsigned long)pm.this.write_memory_pool.max_total);
  8973. }
  8974. /* Do this here to provoke memory corruption errors in memory not directly
  8975. * allocated by libpng - not a complete test, but better than nothing.
  8976. */
  8977. store_delete(&pm.this);
  8978. /* Error exit if there are any errors, and maybe if there are any
  8979. * warnings.
  8980. */
  8981. if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  8982. pm.this.nwarnings))
  8983. {
  8984. if (!pm.this.verbose)
  8985. fprintf(stderr, "pngvalid: %s\n", pm.this.error);
  8986. fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
  8987. pm.this.nwarnings);
  8988. exit(1);
  8989. }
  8990. /* Success case. */
  8991. if (touch != NULL)
  8992. {
  8993. FILE *fsuccess = fopen(touch, "wt");
  8994. if (fsuccess != NULL)
  8995. {
  8996. int error = 0;
  8997. fprintf(fsuccess, "PNG validation succeeded\n");
  8998. fflush(fsuccess);
  8999. error = ferror(fsuccess);
  9000. if (fclose(fsuccess) || error)
  9001. {
  9002. fprintf(stderr, "%s: write failed\n", touch);
  9003. exit(1);
  9004. }
  9005. }
  9006. else
  9007. {
  9008. fprintf(stderr, "%s: open failed\n", touch);
  9009. exit(1);
  9010. }
  9011. }
  9012. /* This is required because some very minimal configurations do not use it:
  9013. */
  9014. UNUSED(fail)
  9015. return 0;
  9016. }
  9017. #else /* write or low level APIs not supported */
  9018. int main(void)
  9019. {
  9020. fprintf(stderr,
  9021. "pngvalid: no low level write support in libpng, all tests skipped\n");
  9022. /* So the test is skipped: */
  9023. return SKIP;
  9024. }
  9025. #endif