pngstest.c 103.4 KB
Newer Older
J
John Bowler 已提交
1 2 3
/*-
 * pngstest.c
 *
4
 * Last changed in libpng 1.6.31 [July 27, 2017]
5
 * Copyright (c) 2013-2017 John Cunningham Bowler
6 7 8 9 10
 *
 * This code is released under the libpng license.
 * For conditions of distribution and use, see the disclaimer
 * and license in png.h
 *
J
John Bowler 已提交
11 12
 * Test for the PNG 'simplified' APIs.
 */
13
#define _ISOC90_SOURCE 1
J
John Bowler 已提交
14 15 16 17 18 19 20 21 22
#define MALLOC_CHECK_ 2/*glibc facility: turn on debugging*/

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <math.h>
23

24
#if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
25
#  include <config.h>
26 27
#endif

28 29 30 31 32 33 34 35 36
/* Define the following to use this test against your installed libpng, rather
 * than the one being built here:
 */
#ifdef PNG_FREESTANDING_TESTS
#  include <png.h>
#else
#  include "../../png.h"
#endif

37 38 39 40 41 42 43 44 45
/* 1.6.1 added support for the configure test harness, which uses 77 to indicate
 * a skipped test, in earlier versions we need to succeed on a skipped test, so:
 */
#if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
#  define SKIP 77
#else
#  define SKIP 0
#endif

46
#ifdef PNG_SIMPLIFIED_READ_SUPPORTED /* Else nothing can be done */
47
#include "../tools/sRGB.h"
J
John Bowler 已提交
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62
/* KNOWN ISSUES
 *
 * These defines switch on alternate algorithms for format conversions to match
 * the current libpng implementation; they are set to allow pngstest to pass
 * even though libpng is producing answers that are not as correct as they
 * should be.
 */
#define ALLOW_UNUSED_GPC 0
   /* If true include unused static GPC functions and declare an external array
    * of them to hide the fact that they are unused.  This is for development
    * use while testing the correct function to use to take into account libpng
    * misbehavior, such as using a simple power law to correct sRGB to linear.
    */

63 64 65
/* The following is to support direct compilation of this file as C++ */
#ifdef __cplusplus
#  define voidcast(type, value) static_cast<type>(value)
66 67
#  define aligncastconst(type, value) \
      static_cast<type>(static_cast<const void*>(value))
68 69
#else
#  define voidcast(type, value) (value)
70
#  define aligncastconst(type, value) ((const void*)(value))
71 72
#endif /* __cplusplus */

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
/* During parallel runs of pngstest each temporary file needs a unique name,
 * this is used to permit uniqueness using a command line argument which can be
 * up to 22 characters long.
 */
static char tmpf[23] = "TMP";

/* Generate random bytes.  This uses a boring repeatable algorithm and it
 * is implemented here so that it gives the same set of numbers on every
 * architecture.  It's a linear congruential generator (Knuth or Sedgewick
 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
 * Hill, "The Art of Electronics".
 */
static void
make_random_bytes(png_uint_32* seed, void* pv, size_t size)
{
   png_uint_32 u0 = seed[0], u1 = seed[1];
   png_bytep bytes = voidcast(png_bytep, pv);

   /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
    * bit-20.  The top 1 bit is in u1, the bottom 32 are in u0.
    */
   size_t i;
   for (i=0; i<size; ++i)
   {
      /* First generate 8 new bits then shift them in at the end. */
      png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
      u1 <<= 8;
      u1 |= u0 >> 24;
      u0 <<= 8;
      u0 |= u;
      *bytes++ = (png_byte)u;
   }

   seed[0] = u0;
   seed[1] = u1;
}

110 111 112 113 114 115 116 117 118
static png_uint_32 color_seed[2];

static void
reseed(void)
{
   color_seed[0] = 0x12345678U;
   color_seed[1] = 0x9abcdefU;
}

119 120 121 122 123 124
static void
random_color(png_colorp color)
{
   make_random_bytes(color_seed, color, sizeof *color);
}

125 126 127 128 129 130 131 132 133
/* Math support - neither Cygwin nor Visual Studio have C99 support and we need
 * a predictable rounding function, so make one here:
 */
static double
closestinteger(double x)
{
   return floor(x + .5);
}

134 135 136 137
/* Cast support: remove GCC whines. */
static png_byte
u8d(double d)
{
138
   d = closestinteger(d);
139 140 141 142 143 144
   return (png_byte)d;
}

static png_uint_16
u16d(double d)
{
145
   d = closestinteger(d);
146 147 148
   return (png_uint_16)d;
}

J
John Bowler 已提交
149
/* sRGB support: use exact calculations rounded to the nearest int, see the
150
 * fesetround() call in main().  sRGB_to_d optimizes the 8 to 16-bit conversion.
J
John Bowler 已提交
151
 */
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
static double sRGB_to_d[256];
static double g22_to_d[256];

static void
init_sRGB_to_d(void)
{
   int i;

   sRGB_to_d[0] = 0;
   for (i=1; i<255; ++i)
      sRGB_to_d[i] = linear_from_sRGB(i/255.);
   sRGB_to_d[255] = 1;

   g22_to_d[0] = 0;
   for (i=1; i<255; ++i)
      g22_to_d[i] = pow(i/255., 1/.45455);
   g22_to_d[255] = 1;
}

J
John Bowler 已提交
171 172 173
static png_byte
sRGB(double linear /*range 0.0 .. 1.0*/)
{
174
   return u8d(255 * sRGB_from_linear(linear));
J
John Bowler 已提交
175 176 177
}

static png_byte
178
isRGB(int fixed_linear)
J
John Bowler 已提交
179 180 181 182
{
   return sRGB(fixed_linear / 65535.);
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
#if 0 /* not used */
static png_byte
unpremultiply(int component, int alpha)
{
   if (alpha <= component)
      return 255; /* Arbitrary, but consistent with the libpng code */

   else if (alpha >= 65535)
      return isRGB(component);

   else
      return sRGB((double)component / alpha);
}
#endif

static png_uint_16
ilinear(int fixed_srgb)
{
   return u16d(65535 * sRGB_to_d[fixed_srgb]);
}

J
John Bowler 已提交
204
static png_uint_16
205
ilineara(int fixed_srgb, int alpha)
J
John Bowler 已提交
206
{
207 208 209 210 211 212 213 214 215 216 217 218 219 220
   return u16d((257 * alpha) * sRGB_to_d[fixed_srgb]);
}

static png_uint_16
ilinear_g22(int fixed_srgb)
{
   return u16d(65535 * g22_to_d[fixed_srgb]);
}

#if ALLOW_UNUSED_GPC
static png_uint_16
ilineara_g22(int fixed_srgb, int alpha)
{
   return u16d((257 * alpha) * g22_to_d[fixed_srgb]);
J
John Bowler 已提交
221
}
222
#endif
J
John Bowler 已提交
223

224 225 226 227 228 229 230 231 232
static double
YfromRGBint(int ir, int ig, int ib)
{
   double r = ir;
   double g = ig;
   double b = ib;
   return YfromRGB(r, g, b);
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
#if 0 /* unused */
/* The error that results from using a 2.2 power law in place of the correct
 * sRGB transform, given an 8-bit value which might be either sRGB or power-law.
 */
static int
power_law_error8(int value)
{
   if (value > 0 && value < 255)
   {
      double vd = value / 255.;
      double e = fabs(
         pow(sRGB_to_d[value], 1/2.2) - sRGB_from_linear(pow(vd, 2.2)));

      /* Always allow an extra 1 here for rounding errors */
      e = 1+floor(255 * e);
      return (int)e;
   }

   return 0;
}

static int error_in_sRGB_roundtrip = 56; /* by experiment */
static int
power_law_error16(int value)
{
   if (value > 0 && value < 65535)
   {
      /* Round trip the value through an 8-bit representation but using
       * non-matching to/from conversions.
       */
      double vd = value / 65535.;
      double e = fabs(
         pow(sRGB_from_linear(vd), 2.2) - linear_from_sRGB(pow(vd, 1/2.2)));

      /* Always allow an extra 1 here for rounding errors */
      e = error_in_sRGB_roundtrip+floor(65535 * e);
      return (int)e;
   }

   return 0;
}

static int
compare_8bit(int v1, int v2, int error_limit, int multiple_algorithms)
{
   int e = abs(v1-v2);
   int ev1, ev2;

   if (e <= error_limit)
      return 1;

   if (!multiple_algorithms)
      return 0;

   ev1 = power_law_error8(v1);
   if (e <= ev1)
      return 1;

   ev2 = power_law_error8(v2);
   if (e <= ev2)
      return 1;

   return 0;
}

static int
compare_16bit(int v1, int v2, int error_limit, int multiple_algorithms)
{
   int e = abs(v1-v2);
   int ev1, ev2;

   if (e <= error_limit)
      return 1;

   /* "multiple_algorithms" in this case means that a color-map has been
    * involved somewhere, so we can deduce that the values were forced to 8-bit
    * (like the via_linear case for 8-bit.)
    */
   if (!multiple_algorithms)
      return 0;

   ev1 = power_law_error16(v1);
   if (e <= ev1)
      return 1;

   ev2 = power_law_error16(v2);
   if (e <= ev2)
      return 1;

   return 0;
}
#endif /* unused */

326
#define USE_FILE 1       /* else memory */
J
John Bowler 已提交
327
#define USE_STDIO 2      /* else use file name */
328
#define STRICT 4         /* fail on warnings too */
J
John Bowler 已提交
329 330 331
#define VERBOSE 8
#define KEEP_TMPFILES 16 /* else delete temporary files */
#define KEEP_GOING 32
332 333
#define ACCUMULATE 64
#define FAST_WRITE 128
334
#define sRGB_16BIT 256
335 336 337
#define NO_RESEED  512   /* do not reseed on each new file */
#define GBG_ERROR 1024   /* do not ignore the gamma+background_rgb_to_gray
                          * libpng warning. */
J
John Bowler 已提交
338

339 340
static void
print_opts(png_uint_32 opts)
J
John Bowler 已提交
341
{
342
   if (opts & USE_FILE)
343 344 345
      printf(" --file");
   if (opts & USE_STDIO)
      printf(" --stdio");
346 347
   if (!(opts & STRICT))
      printf(" --nostrict");
348 349 350 351 352 353
   if (opts & VERBOSE)
      printf(" --verbose");
   if (opts & KEEP_TMPFILES)
      printf(" --preserve");
   if (opts & KEEP_GOING)
      printf(" --keep-going");
354 355 356 357
   if (opts & ACCUMULATE)
      printf(" --accumulate");
   if (!(opts & FAST_WRITE)) /* --fast is currently the default */
      printf(" --slow");
358 359
   if (opts & sRGB_16BIT)
      printf(" --sRGB-16bit");
360 361 362 363 364 365
   if (opts & NO_RESEED)
      printf(" --noreseed");
#if PNG_LIBPNG_VER < 10700 /* else on by default */
   if (opts & GBG_ERROR)
      printf(" --fault-gbg-warning");
#endif
366
}
J
John Bowler 已提交
367

368
#define FORMAT_NO_CHANGE 0x80000000 /* additional flag */
J
John Bowler 已提交
369 370 371 372

/* A name table for all the formats - defines the format of the '+' arguments to
 * pngstest.
 */
373 374
#define FORMAT_COUNT 64
#define FORMAT_MASK 0x3f
375
static const char * const format_names[FORMAT_COUNT] =
J
John Bowler 已提交
376 377 378 379 380 381 382 383 384
{
   "sRGB-gray",
   "sRGB-gray+alpha",
   "sRGB-rgb",
   "sRGB-rgb+alpha",
   "linear-gray",
   "linear-gray+alpha",
   "linear-rgb",
   "linear-rgb+alpha",
385 386 387 388 389 390 391 392 393 394

   "color-mapped-sRGB-gray",
   "color-mapped-sRGB-gray+alpha",
   "color-mapped-sRGB-rgb",
   "color-mapped-sRGB-rgb+alpha",
   "color-mapped-linear-gray",
   "color-mapped-linear-gray+alpha",
   "color-mapped-linear-rgb",
   "color-mapped-linear-rgb+alpha",

J
John Bowler 已提交
395 396 397 398 399 400 401 402
   "sRGB-gray",
   "sRGB-gray+alpha",
   "sRGB-bgr",
   "sRGB-bgr+alpha",
   "linear-gray",
   "linear-gray+alpha",
   "linear-bgr",
   "linear-bgr+alpha",
403 404 405 406 407 408 409 410 411 412

   "color-mapped-sRGB-gray",
   "color-mapped-sRGB-gray+alpha",
   "color-mapped-sRGB-bgr",
   "color-mapped-sRGB-bgr+alpha",
   "color-mapped-linear-gray",
   "color-mapped-linear-gray+alpha",
   "color-mapped-linear-bgr",
   "color-mapped-linear-bgr+alpha",

J
John Bowler 已提交
413 414 415 416 417 418 419 420
   "sRGB-gray",
   "alpha+sRGB-gray",
   "sRGB-rgb",
   "alpha+sRGB-rgb",
   "linear-gray",
   "alpha+linear-gray",
   "linear-rgb",
   "alpha+linear-rgb",
421 422 423 424 425 426 427 428 429 430

   "color-mapped-sRGB-gray",
   "color-mapped-alpha+sRGB-gray",
   "color-mapped-sRGB-rgb",
   "color-mapped-alpha+sRGB-rgb",
   "color-mapped-linear-gray",
   "color-mapped-alpha+linear-gray",
   "color-mapped-linear-rgb",
   "color-mapped-alpha+linear-rgb",

J
John Bowler 已提交
431 432 433 434 435 436 437 438
   "sRGB-gray",
   "alpha+sRGB-gray",
   "sRGB-bgr",
   "alpha+sRGB-bgr",
   "linear-gray",
   "alpha+linear-gray",
   "linear-bgr",
   "alpha+linear-bgr",
439 440 441 442 443 444 445 446 447

   "color-mapped-sRGB-gray",
   "color-mapped-alpha+sRGB-gray",
   "color-mapped-sRGB-bgr",
   "color-mapped-alpha+sRGB-bgr",
   "color-mapped-linear-gray",
   "color-mapped-alpha+linear-gray",
   "color-mapped-linear-bgr",
   "color-mapped-alpha+linear-bgr",
J
John Bowler 已提交
448 449 450 451 452 453 454
};

/* Decode an argument to a format number. */
static png_uint_32
formatof(const char *arg)
{
   char *ep;
455
   unsigned long format = strtoul(arg, &ep, 0);
J
John Bowler 已提交
456

457
   if (ep > arg && *ep == 0 && format < FORMAT_COUNT)
458
      return (png_uint_32)format;
J
John Bowler 已提交
459

460
   else for (format=0; format < FORMAT_COUNT; ++format)
J
John Bowler 已提交
461 462
   {
      if (strcmp(format_names[format], arg) == 0)
463
         return (png_uint_32)format;
J
John Bowler 已提交
464 465 466
   }

   fprintf(stderr, "pngstest: format name '%s' invalid\n", arg);
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
   return FORMAT_COUNT;
}

/* Bitset/test functions for formats */
#define FORMAT_SET_COUNT (FORMAT_COUNT / 32)
typedef struct
{
   png_uint_32 bits[FORMAT_SET_COUNT];
}
format_list;

static void format_init(format_list *pf)
{
   int i;
   for (i=0; i<FORMAT_SET_COUNT; ++i)
      pf->bits[i] = 0; /* All off */
}

#if 0 /* currently unused */
static void format_clear(format_list *pf)
{
   int i;
   for (i=0; i<FORMAT_SET_COUNT; ++i)
      pf->bits[i] = 0;
}
#endif

static int format_is_initial(format_list *pf)
{
   int i;
   for (i=0; i<FORMAT_SET_COUNT; ++i)
      if (pf->bits[i] != 0)
         return 0;

   return 1;
}

static int format_set(format_list *pf, png_uint_32 format)
{
   if (format < FORMAT_COUNT)
      return pf->bits[format >> 5] |= ((png_uint_32)1) << (format & 31);

   return 0;
}

#if 0 /* currently unused */
static int format_unset(format_list *pf, png_uint_32 format)
{
   if (format < FORMAT_COUNT)
      return pf->bits[format >> 5] &= ~((png_uint_32)1) << (format & 31);

   return 0;
}
#endif

static int format_isset(format_list *pf, png_uint_32 format)
{
   return format < FORMAT_COUNT &&
      (pf->bits[format >> 5] & (((png_uint_32)1) << (format & 31))) != 0;
}

static void format_default(format_list *pf, int redundant)
{
   if (redundant)
   {
      int i;

      /* set everything, including flags that are pointless */
      for (i=0; i<FORMAT_SET_COUNT; ++i)
         pf->bits[i] = ~(png_uint_32)0;
   }

   else
   {
      png_uint_32 f;

      for (f=0; f<FORMAT_COUNT; ++f)
      {
545 546 547 548 549 550 551 552
         /* Eliminate redundant and unsupported settings. */
#        ifdef PNG_FORMAT_BGR_SUPPORTED
            /* BGR is meaningless if no color: */
            if ((f & PNG_FORMAT_FLAG_COLOR) == 0 &&
               (f & PNG_FORMAT_FLAG_BGR) != 0)
#        else
            if ((f & 0x10U/*HACK: fixed value*/) != 0)
#        endif
553 554 555
            continue;

         /* AFIRST is meaningless if no alpha: */
556 557 558 559 560 561
#        ifdef PNG_FORMAT_AFIRST_SUPPORTED
            if ((f & PNG_FORMAT_FLAG_ALPHA) == 0 &&
               (f & PNG_FORMAT_FLAG_AFIRST) != 0)
#        else
            if ((f & 0x20U/*HACK: fixed value*/) != 0)
#        endif
562 563 564 565 566
            continue;

         format_set(pf, f);
      }
   }
567 568
}

J
John Bowler 已提交
569 570 571 572 573 574 575 576 577 578 579 580
/* THE Image STRUCTURE */
/* The super-class of a png_image, contains the decoded image plus the input
 * data necessary to re-read the file with a different format.
 */
typedef struct
{
   png_image   image;
   png_uint_32 opts;
   const char *file_name;
   int         stride_extra;
   FILE       *input_file;
   png_voidp   input_memory;
581
   size_t      input_memory_size;
J
John Bowler 已提交
582 583
   png_bytep   buffer;
   ptrdiff_t   stride;
584 585
   size_t      bufsize;
   size_t      allocsize;
J
John Bowler 已提交
586
   char        tmpfile_name[32];
587
   png_uint_16 colormap[256*4];
J
John Bowler 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
}
Image;

/* Initializer: also sets the permitted error limit for 16-bit operations. */
static void
newimage(Image *image)
{
   memset(image, 0, sizeof *image);
}

/* Reset the image to be read again - only needs to rewind the FILE* at present.
 */
static void
resetimage(Image *image)
{
   if (image->input_file != NULL)
      rewind(image->input_file);
}

/* Free the image buffer; the buffer is re-used on a re-read, this is just for
 * cleanup.
 */
static void
freebuffer(Image *image)
{
   if (image->buffer) free(image->buffer);
   image->buffer = NULL;
   image->bufsize = 0;
   image->allocsize = 0;
}

/* Delete function; cleans out all the allocated data and the temporary file in
 * the image.
 */
static void
freeimage(Image *image)
{
   freebuffer(image);
   png_image_free(&image->image);

   if (image->input_file != NULL)
   {
      fclose(image->input_file);
      image->input_file = NULL;
   }

   if (image->input_memory != NULL)
   {
      free(image->input_memory);
      image->input_memory = NULL;
      image->input_memory_size = 0;
   }

   if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
   {
643
      (void)remove(image->tmpfile_name);
J
John Bowler 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
      image->tmpfile_name[0] = 0;
   }
}

/* This is actually a re-initializer; allows an image structure to be re-used by
 * freeing everything that relates to an old image.
 */
static void initimage(Image *image, png_uint_32 opts, const char *file_name,
   int stride_extra)
{
   freeimage(image);
   memset(&image->image, 0, sizeof image->image);
   image->opts = opts;
   image->file_name = file_name;
   image->stride_extra = stride_extra;
}

/* Make sure the image buffer is big enough; allows re-use of the buffer if the
 * image is re-read.
 */
#define BUFFER_INIT8 73
static void
allocbuffer(Image *image)
{
668
   size_t size = PNG_IMAGE_BUFFER_SIZE(image->image, image->stride);
J
John Bowler 已提交
669 670 671 672

   if (size+32 > image->bufsize)
   {
      freebuffer(image);
673
      image->buffer = voidcast(png_bytep, malloc(size+32));
J
John Bowler 已提交
674 675
      if (image->buffer == NULL)
      {
676
         fflush(stdout);
J
John Bowler 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
         fprintf(stderr,
            "simpletest: out of memory allocating %lu(+32) byte buffer\n",
            (unsigned long)size);
         exit(1);
      }
      image->bufsize = size+32;
   }

   memset(image->buffer, 95, image->bufsize);
   memset(image->buffer+16, BUFFER_INIT8, size);
   image->allocsize = size;
}

/* Make sure 16 bytes match the given byte. */
static int
692
check16(png_const_bytep bp, int b)
J
John Bowler 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
{
   int i = 16;

   do
      if (*bp != b) return 1;
   while (--i);

   return 0;
}

/* Check for overwrite in the image buffer. */
static void
checkbuffer(Image *image, const char *arg)
{
   if (check16(image->buffer, 95))
   {
709
      fflush(stdout);
J
John Bowler 已提交
710 711 712 713 714 715
      fprintf(stderr, "%s: overwrite at start of image buffer\n", arg);
      exit(1);
   }

   if (check16(image->buffer+16+image->allocsize, 95))
   {
716
      fflush(stdout);
J
John Bowler 已提交
717 718 719 720 721 722 723 724 725 726 727
      fprintf(stderr, "%s: overwrite at end of image buffer\n", arg);
      exit(1);
   }
}

/* ERROR HANDLING */
/* Log a terminal error, also frees the libpng part of the image if necessary.
 */
static int
logerror(Image *image, const char *a1, const char *a2, const char *a3)
{
728
   fflush(stdout);
J
John Bowler 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
   if (image->image.warning_or_error)
      fprintf(stderr, "%s%s%s: %s\n", a1, a2, a3, image->image.message);

   else
      fprintf(stderr, "%s%s%s\n", a1, a2, a3);

   if (image->image.opaque != NULL)
   {
      fprintf(stderr, "%s: image opaque pointer non-NULL on error\n",
         image->file_name);
      png_image_free(&image->image);
   }

   return 0;
}

/* Log an error and close a file (just a utility to do both things in one
 * function call.)
 */
static int
logclose(Image *image, FILE *f, const char *name, const char *operation)
{
   int e = errno;

   fclose(f);
   return logerror(image, name, operation, strerror(e));
}

/* Make sure the png_image has been freed - validates that libpng is doing what
 * the spec says and freeing the image.
 */
static int
checkopaque(Image *image)
{
   if (image->image.opaque != NULL)
   {
      png_image_free(&image->image);
      return logerror(image, image->file_name, ": opaque not NULL", "");
   }

769 770 771 772 773 774 775 776 777
   /* Separate out the gamma+background_rgb_to_gray warning because it may
    * produce opaque component errors:
    */
   else if (image->image.warning_or_error != 0 &&
            (strcmp(image->image.message,
               "libpng does not support gamma+background+rgb_to_gray") == 0 ?
                  (image->opts & GBG_ERROR) != 0 : (image->opts & STRICT) != 0))
      return logerror(image, image->file_name, (image->opts & GBG_ERROR) != 0 ?
                      " --fault-gbg-warning" : " --strict", "");
778

J
John Bowler 已提交
779 780 781 782 783 784 785 786 787 788
   else
      return 1;
}

/* IMAGE COMPARISON/CHECKING */
/* Compare the pixels of two images, which should be the same but aren't.  The
 * images must have been checked for a size match.
 */
typedef struct
{
789 790 791 792
   /* The components, for grayscale images the gray value is in 'g' and if alpha
    * is not present 'a' is set to 255 or 65535 according to format.
    */
   int         r, g, b, a;
J
John Bowler 已提交
793 794
} Pixel;

795
typedef struct
796
{
797 798 799 800 801 802 803
   /* The background as the original sRGB 8-bit value converted to the final
    * integer format and as a double precision linear value in the range 0..1
    * for with partially transparent pixels.
    */
   int ir, ig, ib;
   double dr, dg, db; /* linear r,g,b scaled to 0..1 */
} Background;
J
John Bowler 已提交
804

805 806 807
/* Basic image formats; control the data but not the layout thereof. */
#define BASE_FORMATS\
   (PNG_FORMAT_FLAG_ALPHA|PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_LINEAR)
J
John Bowler 已提交
808

809 810 811 812 813 814 815
/* Read a Pixel from a buffer.  The code below stores the correct routine for
 * the format in a function pointer, these are the routines:
 */
static void
gp_g8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
816

817 818 819
   p->r = p->g = p->b = pp[0];
   p->a = 255;
}
J
John Bowler 已提交
820

821 822 823 824
static void
gp_ga8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
825

826 827 828
   p->r = p->g = p->b = pp[0];
   p->a = pp[1];
}
J
John Bowler 已提交
829

830
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
831 832 833 834
static void
gp_ag8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
835

836 837 838
   p->r = p->g = p->b = pp[1];
   p->a = pp[0];
}
839
#endif
J
John Bowler 已提交
840

841 842 843 844
static void
gp_rgb8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
845

846 847 848 849 850
   p->r = pp[0];
   p->g = pp[1];
   p->b = pp[2];
   p->a = 255;
}
J
John Bowler 已提交
851

852
#ifdef PNG_FORMAT_BGR_SUPPORTED
853 854 855 856
static void
gp_bgr8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
857

858 859 860 861 862
   p->r = pp[2];
   p->g = pp[1];
   p->b = pp[0];
   p->a = 255;
}
863
#endif
J
John Bowler 已提交
864

865 866 867 868
static void
gp_rgba8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
869

870 871 872 873 874
   p->r = pp[0];
   p->g = pp[1];
   p->b = pp[2];
   p->a = pp[3];
}
J
John Bowler 已提交
875

876
#ifdef PNG_FORMAT_BGR_SUPPORTED
877 878 879 880
static void
gp_bgra8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
881

882 883 884 885 886
   p->r = pp[2];
   p->g = pp[1];
   p->b = pp[0];
   p->a = pp[3];
}
887
#endif
J
John Bowler 已提交
888

889
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
890 891 892 893
static void
gp_argb8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
894

895 896 897 898 899
   p->r = pp[1];
   p->g = pp[2];
   p->b = pp[3];
   p->a = pp[0];
}
900
#endif
J
John Bowler 已提交
901

902
#if defined(PNG_FORMAT_AFIRST_SUPPORTED) && defined(PNG_FORMAT_BGR_SUPPORTED)
903 904 905 906
static void
gp_abgr8(Pixel *p, png_const_voidp pb)
{
   png_const_bytep pp = voidcast(png_const_bytep, pb);
J
John Bowler 已提交
907

908 909 910 911 912
   p->r = pp[3];
   p->g = pp[2];
   p->b = pp[1];
   p->a = pp[0];
}
913
#endif
J
John Bowler 已提交
914

915 916 917 918
static void
gp_g16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
919

920 921 922
   p->r = p->g = p->b = pp[0];
   p->a = 65535;
}
J
John Bowler 已提交
923

924 925 926 927
static void
gp_ga16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
928

929 930 931
   p->r = p->g = p->b = pp[0];
   p->a = pp[1];
}
J
John Bowler 已提交
932

933
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
934 935 936 937
static void
gp_ag16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
938

939 940 941
   p->r = p->g = p->b = pp[1];
   p->a = pp[0];
}
942
#endif
J
John Bowler 已提交
943

944 945 946 947
static void
gp_rgb16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
948

949 950 951 952
   p->r = pp[0];
   p->g = pp[1];
   p->b = pp[2];
   p->a = 65535;
953
}
954

955
#ifdef PNG_FORMAT_BGR_SUPPORTED
956 957
static void
gp_bgr16(Pixel *p, png_const_voidp pb)
958
{
959
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
960

961 962 963 964 965
   p->r = pp[2];
   p->g = pp[1];
   p->b = pp[0];
   p->a = 65535;
}
966
#endif
967

968 969 970 971
static void
gp_rgba16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
972

973 974 975 976 977
   p->r = pp[0];
   p->g = pp[1];
   p->b = pp[2];
   p->a = pp[3];
}
J
John Bowler 已提交
978

979
#ifdef PNG_FORMAT_BGR_SUPPORTED
980 981 982 983
static void
gp_bgra16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
984

985 986 987 988 989
   p->r = pp[2];
   p->g = pp[1];
   p->b = pp[0];
   p->a = pp[3];
}
990
#endif
J
John Bowler 已提交
991

992
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
993 994 995 996
static void
gp_argb16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
997

998 999 1000 1001 1002
   p->r = pp[1];
   p->g = pp[2];
   p->b = pp[3];
   p->a = pp[0];
}
1003
#endif
1004

1005
#if defined(PNG_FORMAT_AFIRST_SUPPORTED) && defined(PNG_FORMAT_BGR_SUPPORTED)
1006 1007 1008 1009
static void
gp_abgr16(Pixel *p, png_const_voidp pb)
{
   png_const_uint_16p pp = voidcast(png_const_uint_16p, pb);
J
John Bowler 已提交
1010

1011 1012 1013 1014 1015
   p->r = pp[3];
   p->g = pp[2];
   p->b = pp[1];
   p->a = pp[0];
}
1016
#endif
J
John Bowler 已提交
1017

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
/* Given a format, return the correct one of the above functions. */
static void (*
get_pixel(png_uint_32 format))(Pixel *p, png_const_voidp pb)
{
   /* The color-map flag is irrelevant here - the caller of the function
    * returned must either pass the buffer or, for a color-mapped image, the
    * correct entry in the color-map.
    */
   if (format & PNG_FORMAT_FLAG_LINEAR)
   {
      if (format & PNG_FORMAT_FLAG_COLOR)
      {
1030 1031
#        ifdef PNG_FORMAT_BGR_SUPPORTED
            if (format & PNG_FORMAT_FLAG_BGR)
1032
            {
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
               if (format & PNG_FORMAT_FLAG_ALPHA)
               {
#                 ifdef PNG_FORMAT_AFIRST_SUPPORTED
                     if (format & PNG_FORMAT_FLAG_AFIRST)
                        return gp_abgr16;

                     else
#                 endif
                     return gp_bgra16;
               }
J
John Bowler 已提交
1043

1044
               else
1045
                  return gp_bgr16;
1046
            }
1047

1048
            else
1049
#        endif
1050
         {
1051
            if (format & PNG_FORMAT_FLAG_ALPHA)
1052
            {
1053 1054 1055
#              ifdef PNG_FORMAT_AFIRST_SUPPORTED
                  if (format & PNG_FORMAT_FLAG_AFIRST)
                     return gp_argb16;
1056

1057 1058
                  else
#              endif
1059
                  return gp_rgba16;
1060
            }
1061 1062 1063

            else
               return gp_rgb16;
1064
         }
1065 1066 1067 1068 1069 1070
      }

      else
      {
         if (format & PNG_FORMAT_FLAG_ALPHA)
         {
1071 1072 1073
#           ifdef PNG_FORMAT_AFIRST_SUPPORTED
               if (format & PNG_FORMAT_FLAG_AFIRST)
                  return gp_ag16;
1074

1075 1076
               else
#           endif
1077 1078
               return gp_ga16;
         }
1079

1080 1081
         else
            return gp_g16;
1082 1083 1084
      }
   }

1085
   else
1086
   {
1087
      if (format & PNG_FORMAT_FLAG_COLOR)
1088
      {
1089 1090
#        ifdef PNG_FORMAT_BGR_SUPPORTED
            if (format & PNG_FORMAT_FLAG_BGR)
J
John Bowler 已提交
1091
            {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
               if (format & PNG_FORMAT_FLAG_ALPHA)
               {
#                 ifdef PNG_FORMAT_AFIRST_SUPPORTED
                     if (format & PNG_FORMAT_FLAG_AFIRST)
                        return gp_abgr8;

                     else
#                 endif
                     return gp_bgra8;
               }
1102 1103

               else
1104
                  return gp_bgr8;
J
John Bowler 已提交
1105 1106
            }

1107
            else
1108
#        endif
1109
         {
1110 1111
            if (format & PNG_FORMAT_FLAG_ALPHA)
            {
1112 1113 1114
#              ifdef PNG_FORMAT_AFIRST_SUPPORTED
                  if (format & PNG_FORMAT_FLAG_AFIRST)
                     return gp_argb8;
1115

1116 1117
                  else
#              endif
1118 1119 1120 1121 1122
                  return gp_rgba8;
            }

            else
               return gp_rgb8;
1123
         }
J
John Bowler 已提交
1124 1125
      }

1126
      else
1127
      {
1128
         if (format & PNG_FORMAT_FLAG_ALPHA)
1129
         {
1130 1131 1132
#           ifdef PNG_FORMAT_AFIRST_SUPPORTED
               if (format & PNG_FORMAT_FLAG_AFIRST)
                  return gp_ag8;
1133

1134 1135
               else
#           endif
1136 1137
               return gp_ga8;
         }
1138

1139 1140 1141 1142 1143
         else
            return gp_g8;
      }
   }
}
1144

U
Unknown 已提交
1145
/* Conversion between pixel formats.  The code above effectively eliminates the
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
 * component ordering changes leaving three basic changes:
 *
 * 1) Remove an alpha channel by pre-multiplication or compositing on a
 *    background color.  (Adding an alpha channel is a no-op.)
 *
 * 2) Remove color by mapping to grayscale.  (Grayscale to color is a no-op.)
 *
 * 3) Convert between 8-bit and 16-bit components.  (Both directtions are
 *    relevant.)
 *
 * This gives the following base format conversion matrix:
 *
 *   OUT:    ----- 8-bit -----    ----- 16-bit -----
 *   IN     G    GA   RGB  RGBA  G    GA   RGB  RGBA
 *  8 G     .    .    .    .     lin  lin  lin  lin
 *  8 GA    bckg .    bckc .     pre' pre  pre' pre
 *  8 RGB   g8   g8   .    .     glin glin lin  lin
 *  8 RGBA  g8b  g8   bckc .     gpr' gpre pre' pre
 * 16 G     sRGB sRGB sRGB sRGB  .    .    .    .
 * 16 GA    b16g unpg b16c unpc  A    .    A    .
 * 16 RGB   sG   sG   sRGB sRGB  g16  g16  .    .
 * 16 RGBA  gb16 sGp  cb16 sCp   g16  g16' A    .
 *
 *  8-bit to 8-bit:
 * bckg: composite on gray background
 * bckc: composite on color background
 * g8:   convert sRGB components to sRGB grayscale
 * g8b:  convert sRGB components to grayscale and composite on gray background
 *
 *  8-bit to 16-bit:
 * lin:  make sRGB components linear, alpha := 65535
 * pre:  make sRGB components linear and premultiply by alpha  (scale alpha)
 * pre': as 'pre' but alpha := 65535
 * glin: make sRGB components linear, convert to grayscale, alpha := 65535
 * gpre: make sRGB components grayscale and linear and premultiply by alpha
 * gpr': as 'gpre' but alpha := 65535
 *
 *  16-bit to 8-bit:
 * sRGB: convert linear components to sRGB, alpha := 255
 * unpg: unpremultiply gray component and convert to sRGB (scale alpha)
 * unpc: unpremultiply color components and convert to sRGB (scale alpha)
 * b16g: composite linear onto gray background and convert the result to sRGB
 * b16c: composite linear onto color background and convert the result to sRGB
 * sG:   convert linear RGB to sRGB grayscale
 * sGp:  unpremultiply RGB then convert to sRGB grayscale
 * sCp:  unpremultiply RGB then convert to sRGB
 * gb16: composite linear onto background and convert to sRGB grayscale
 *       (order doesn't matter, the composite and grayscale operations permute)
 * cb16: composite linear onto background and convert to sRGB
 *
 *  16-bit to 16-bit:
 * A:    set alpha to 65535
 * g16:  convert linear RGB to linear grayscale (alpha := 65535)
 * g16': as 'g16' but alpha is unchanged
 */
/* Simple copy: */
static void
gpc_noop(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   out->r = in->r;
   out->g = in->g;
   out->b = in->b;
   out->a = in->a;
}
1211

1212 1213 1214 1215 1216 1217 1218
#if ALLOW_UNUSED_GPC
static void
gpc_nop8(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   if (in->a == 0)
      out->r = out->g = out->b = 255;
1219

1220 1221 1222 1223 1224 1225
   else
   {
      out->r = in->r;
      out->g = in->g;
      out->b = in->b;
   }
1226

1227 1228 1229
   out->a = in->a;
}
#endif
1230

1231 1232 1233 1234 1235 1236 1237
#if ALLOW_UNUSED_GPC
static void
gpc_nop6(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   if (in->a == 0)
      out->r = out->g = out->b = 65535;
1238

1239 1240 1241 1242 1243 1244
   else
   {
      out->r = in->r;
      out->g = in->g;
      out->b = in->b;
   }
1245

1246 1247 1248
   out->a = in->a;
}
#endif
1249

1250 1251 1252 1253 1254 1255 1256
/* 8-bit to 8-bit conversions */
/* bckg: composite on gray background */
static void
gpc_bckg(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
      out->r = out->g = out->b = back->ig;
1257

1258 1259
   else if (in->a >= 255)
      out->r = out->g = out->b = in->g;
1260

1261 1262 1263
   else
   {
      double a = in->a / 255.;
1264

1265 1266
      out->r = out->g = out->b = sRGB(sRGB_to_d[in->g] * a + back->dg * (1-a));
   }
1267

1268 1269
   out->a = 255;
}
1270

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
/* bckc: composite on color background */
static void
gpc_bckc(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
   {
      out->r = back->ir;
      out->g = back->ig;
      out->b = back->ib;
   }
1281

1282 1283 1284 1285 1286 1287
   else if (in->a >= 255)
   {
      out->r = in->r;
      out->g = in->g;
      out->b = in->b;
   }
1288

1289 1290 1291
   else
   {
      double a = in->a / 255.;
1292

1293 1294 1295 1296
      out->r = sRGB(sRGB_to_d[in->r] * a + back->dr * (1-a));
      out->g = sRGB(sRGB_to_d[in->g] * a + back->dg * (1-a));
      out->b = sRGB(sRGB_to_d[in->b] * a + back->db * (1-a));
   }
1297

1298 1299
   out->a = 255;
}
1300

1301 1302 1303 1304 1305
/* g8: convert sRGB components to sRGB grayscale */
static void
gpc_g8(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
1306

1307 1308
   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = in->g;
J
John Bowler 已提交
1309

1310 1311 1312
   else
      out->r = out->g = out->b =
         sRGB(YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]));
J
John Bowler 已提交
1313

1314 1315
   out->a = in->a;
}
J
John Bowler 已提交
1316

1317 1318 1319 1320 1321 1322
/* g8b: convert sRGB components to grayscale and composite on gray background */
static void
gpc_g8b(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
      out->r = out->g = out->b = back->ig;
J
John Bowler 已提交
1323

1324 1325 1326 1327
   else if (in->a >= 255)
   {
      if (in->r == in->g && in->g == in->b)
         out->r = out->g = out->b = in->g;
1328

1329 1330 1331 1332
      else
         out->r = out->g = out->b = sRGB(YfromRGB(
            sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]));
   }
J
John Bowler 已提交
1333

1334 1335 1336
   else
   {
      double a = in->a/255.;
1337

1338 1339 1340
      out->r = out->g = out->b = sRGB(a * YfromRGB(sRGB_to_d[in->r],
         sRGB_to_d[in->g], sRGB_to_d[in->b]) + back->dg * (1-a));
   }
J
John Bowler 已提交
1341

1342 1343
   out->a = 255;
}
1344

1345 1346 1347 1348 1349 1350
/* 8-bit to 16-bit conversions */
/* lin: make sRGB components linear, alpha := 65535 */
static void
gpc_lin(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
J
John Bowler 已提交
1351

1352
   out->r = ilinear(in->r);
J
John Bowler 已提交
1353

1354 1355 1356
   if (in->g == in->r)
   {
      out->g = out->r;
J
John Bowler 已提交
1357

1358 1359
      if (in->b == in->r)
         out->b = out->r;
J
John Bowler 已提交
1360

1361 1362 1363
      else
         out->b = ilinear(in->b);
   }
J
John Bowler 已提交
1364

1365 1366 1367
   else
   {
      out->g = ilinear(in->g);
J
John Bowler 已提交
1368

1369 1370
      if (in->b == in->r)
         out->b = out->r;
1371

1372 1373 1374 1375 1376
      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilinear(in->b);
J
John Bowler 已提交
1377
   }
1378 1379

   out->a = 65535;
J
John Bowler 已提交
1380 1381
}

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
/* pre: make sRGB components linear and premultiply by alpha (scale alpha) */
static void
gpc_pre(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = ilineara(in->r, in->a);

   if (in->g == in->r)
   {
      out->g = out->r;

      if (in->b == in->r)
         out->b = out->r;

      else
         out->b = ilineara(in->b, in->a);
   }
J
John Bowler 已提交
1400

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
   else
   {
      out->g = ilineara(in->g, in->a);

      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilineara(in->b, in->a);
   }

   out->a = in->a * 257;
}

/* pre': as 'pre' but alpha := 65535 */
1419
static void
1420
gpc_preq(Pixel *out, const Pixel *in, const Background *back)
1421
{
1422 1423 1424 1425 1426
   (void)back;

   out->r = ilineara(in->r, in->a);

   if (in->g == in->r)
1427
   {
1428
      out->g = out->r;
1429

1430 1431
      if (in->b == in->r)
         out->b = out->r;
1432

1433 1434 1435
      else
         out->b = ilineara(in->b, in->a);
   }
1436

1437 1438 1439
   else
   {
      out->g = ilineara(in->g, in->a);
1440

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilineara(in->b, in->a);
   }

   out->a = 65535;
}

/* glin: make sRGB components linear, convert to grayscale, alpha := 65535 */
static void
gpc_glin(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilinear(in->g);

   else
      out->r = out->g = out->b = u16d(65535 *
         YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]));

   out->a = 65535;
}

/* gpre: make sRGB components grayscale and linear and premultiply by alpha */
static void
gpc_gpre(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilineara(in->g, in->a);

   else
      out->r = out->g = out->b = u16d(in->a * 257 *
         YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]));

   out->a = 257 * in->a;
}

/* gpr': as 'gpre' but alpha := 65535 */
static void
gpc_gprq(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilineara(in->g, in->a);

   else
      out->r = out->g = out->b = u16d(in->a * 257 *
         YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]));

   out->a = 65535;
}

/* 8-bit to 16-bit conversions for gAMA 45455 encoded values */
/* Lin: make gAMA 45455 components linear, alpha := 65535 */
static void
gpc_Lin(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = ilinear_g22(in->r);

   if (in->g == in->r)
   {
      out->g = out->r;

      if (in->b == in->r)
         out->b = out->r;

      else
         out->b = ilinear_g22(in->b);
   }

   else
   {
      out->g = ilinear_g22(in->g);

      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilinear_g22(in->b);
   }

   out->a = 65535;
}

#if ALLOW_UNUSED_GPC
/* Pre: make gAMA 45455 components linear and premultiply by alpha (scale alpha)
 */
static void
gpc_Pre(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = ilineara_g22(in->r, in->a);

   if (in->g == in->r)
   {
      out->g = out->r;

      if (in->b == in->r)
         out->b = out->r;

      else
         out->b = ilineara_g22(in->b, in->a);
   }

   else
   {
      out->g = ilineara_g22(in->g, in->a);

      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilineara_g22(in->b, in->a);
   }

   out->a = in->a * 257;
}
#endif

#if ALLOW_UNUSED_GPC
/* Pre': as 'Pre' but alpha := 65535 */
static void
gpc_Preq(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = ilineara_g22(in->r, in->a);

   if (in->g == in->r)
   {
      out->g = out->r;

      if (in->b == in->r)
         out->b = out->r;

      else
         out->b = ilineara_g22(in->b, in->a);
   }

   else
   {
      out->g = ilineara_g22(in->g, in->a);

      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = ilineara_g22(in->b, in->a);
   }

   out->a = 65535;
}
#endif

#if ALLOW_UNUSED_GPC
/* Glin: make gAMA 45455 components linear, convert to grayscale, alpha := 65535
 */
static void
gpc_Glin(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilinear_g22(in->g);

   else
      out->r = out->g = out->b = u16d(65535 *
         YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b]));

   out->a = 65535;
}
#endif

#if ALLOW_UNUSED_GPC
/* Gpre: make gAMA 45455 components grayscale and linear and premultiply by
 * alpha.
 */
static void
gpc_Gpre(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilineara_g22(in->g, in->a);

   else
      out->r = out->g = out->b = u16d(in->a * 257 *
         YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b]));

   out->a = 257 * in->a;
}
#endif

#if ALLOW_UNUSED_GPC
/* Gpr': as 'Gpre' but alpha := 65535 */
static void
gpc_Gprq(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->r == in->g && in->g == in->b)
      out->r = out->g = out->b = ilineara_g22(in->g, in->a);

   else
      out->r = out->g = out->b = u16d(in->a * 257 *
         YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b]));

   out->a = 65535;
}
#endif

/* 16-bit to 8-bit conversions */
/* sRGB: convert linear components to sRGB, alpha := 255 */
static void
gpc_sRGB(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = isRGB(in->r);

   if (in->g == in->r)
   {
      out->g = out->r;

      if (in->b == in->r)
         out->b = out->r;

      else
         out->b = isRGB(in->b);
   }

   else
   {
      out->g = isRGB(in->g);

      if (in->b == in->r)
         out->b = out->r;

      else if (in->b == in->g)
         out->b = out->g;

      else
         out->b = isRGB(in->b);
   }

   out->a = 255;
}

/* unpg: unpremultiply gray component and convert to sRGB (scale alpha) */
static void
gpc_unpg(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->a <= 128)
   {
      out->r = out->g = out->b = 255;
      out->a = 0;
   }

   else
   {
      out->r = out->g = out->b = sRGB((double)in->g / in->a);
      out->a = u8d(in->a / 257.);
   }
}

/* unpc: unpremultiply color components and convert to sRGB (scale alpha) */
static void
gpc_unpc(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->a <= 128)
   {
      out->r = out->g = out->b = 255;
      out->a = 0;
   }

   else
   {
      out->r = sRGB((double)in->r / in->a);
      out->g = sRGB((double)in->g / in->a);
      out->b = sRGB((double)in->b / in->a);
      out->a = u8d(in->a / 257.);
   }
}

/* b16g: composite linear onto gray background and convert the result to sRGB */
static void
gpc_b16g(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
      out->r = out->g = out->b = back->ig;

   else
   {
      double a = in->a/65535.;
      double a1 = 1-a;

      a /= 65535;
      out->r = out->g = out->b = sRGB(in->g * a + back->dg * a1);
   }

   out->a = 255;
}

/* b16c: composite linear onto color background and convert the result to sRGB*/
static void
gpc_b16c(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
   {
      out->r = back->ir;
      out->g = back->ig;
      out->b = back->ib;
   }

   else
   {
      double a = in->a/65535.;
      double a1 = 1-a;

      a /= 65535;
      out->r = sRGB(in->r * a + back->dr * a1);
      out->g = sRGB(in->g * a + back->dg * a1);
      out->b = sRGB(in->b * a + back->db * a1);
   }

   out->a = 255;
}

/* sG: convert linear RGB to sRGB grayscale */
static void
gpc_sG(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   out->r = out->g = out->b = sRGB(YfromRGBint(in->r, in->g, in->b)/65535);
   out->a = 255;
}

/* sGp: unpremultiply RGB then convert to sRGB grayscale */
static void
gpc_sGp(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->a <= 128)
   {
      out->r = out->g = out->b = 255;
      out->a = 0;
   }

   else
   {
      out->r = out->g = out->b = sRGB(YfromRGBint(in->r, in->g, in->b)/in->a);
      out->a = u8d(in->a / 257.);
   }
}

/* sCp: unpremultiply RGB then convert to sRGB */
static void
gpc_sCp(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;

   if (in->a <= 128)
   {
      out->r = out->g = out->b = 255;
      out->a = 0;
   }

   else
   {
      out->r = sRGB((double)in->r / in->a);
      out->g = sRGB((double)in->g / in->a);
      out->b = sRGB((double)in->b / in->a);
      out->a = u8d(in->a / 257.);
   }
}

/* gb16: composite linear onto background and convert to sRGB grayscale */
/*  (order doesn't matter, the composite and grayscale operations permute) */
static void
gpc_gb16(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
      out->r = out->g = out->b = back->ig;

   else if (in->a >= 65535)
      out->r = out->g = out->b = isRGB(in->g);

   else
   {
      double a = in->a / 65535.;
      double a1 = 1-a;

      a /= 65535;
      out->r = out->g = out->b = sRGB(in->g * a + back->dg * a1);
   }

   out->a = 255;
}

/* cb16: composite linear onto background and convert to sRGB */
static void
gpc_cb16(Pixel *out, const Pixel *in, const Background *back)
{
   if (in->a <= 0)
   {
      out->r = back->ir;
      out->g = back->ig;
      out->b = back->ib;
   }

   else if (in->a >= 65535)
   {
      out->r = isRGB(in->r);
      out->g = isRGB(in->g);
      out->b = isRGB(in->b);
   }

   else
   {
      double a = in->a / 65535.;
      double a1 = 1-a;

      a /= 65535;
      out->r = sRGB(in->r * a + back->dr * a1);
      out->g = sRGB(in->g * a + back->dg * a1);
      out->b = sRGB(in->b * a + back->db * a1);
   }

   out->a = 255;
}

/* 16-bit to 16-bit conversions */
/* A:    set alpha to 65535 */
static void
gpc_A(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   out->r = in->r;
   out->g = in->g;
   out->b = in->b;
   out->a = 65535;
}

/* g16:  convert linear RGB to linear grayscale (alpha := 65535) */
static void
gpc_g16(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   out->r = out->g = out->b = u16d(YfromRGBint(in->r, in->g, in->b));
   out->a = 65535;
}

/* g16': as 'g16' but alpha is unchanged */
static void
gpc_g16q(Pixel *out, const Pixel *in, const Background *back)
{
   (void)back;
   out->r = out->g = out->b = u16d(YfromRGBint(in->r, in->g, in->b));
   out->a = in->a;
}

#if ALLOW_UNUSED_GPC
/* Unused functions (to hide them from GCC unused function warnings) */
void (* const gpc_unused[])
   (Pixel *out, const Pixel *in, const Background *back) =
{
   gpc_Pre, gpc_Preq, gpc_Glin, gpc_Gpre, gpc_Gprq, gpc_nop8, gpc_nop6
};
#endif

/*   OUT:    ----- 8-bit -----    ----- 16-bit -----
 *   IN     G    GA   RGB  RGBA  G    GA   RGB  RGBA
 *  8 G     .    .    .    .     lin  lin  lin  lin
 *  8 GA    bckg .    bckc .     pre' pre  pre' pre
 *  8 RGB   g8   g8   .    .     glin glin lin  lin
 *  8 RGBA  g8b  g8   bckc .     gpr' gpre pre' pre
 * 16 G     sRGB sRGB sRGB sRGB  .    .    .    .
 * 16 GA    b16g unpg b16c unpc  A    .    A    .
 * 16 RGB   sG   sG   sRGB sRGB  g16  g16  .    .
 * 16 RGBA  gb16 sGp  cb16 sCp   g16  g16' A    .
 *
 * The matrix is held in an array indexed thus:
 *
 *   gpc_fn[out_format & BASE_FORMATS][in_format & BASE_FORMATS];
 */
/* This will produce a compile time error if the FORMAT_FLAG values don't
 * match the above matrix!
 */
#if PNG_FORMAT_FLAG_ALPHA == 1 && PNG_FORMAT_FLAG_COLOR == 2 &&\
   PNG_FORMAT_FLAG_LINEAR == 4
static void (* const gpc_fn[8/*in*/][8/*out*/])
   (Pixel *out, const Pixel *in, const Background *back) =
{
/*out: G-8     GA-8     RGB-8    RGBA-8    G-16     GA-16   RGB-16  RGBA-16 */
   {gpc_noop,gpc_noop,gpc_noop,gpc_noop, gpc_Lin, gpc_Lin, gpc_Lin, gpc_Lin },
   {gpc_bckg,gpc_noop,gpc_bckc,gpc_noop, gpc_preq,gpc_pre, gpc_preq,gpc_pre },
   {gpc_g8,  gpc_g8,  gpc_noop,gpc_noop, gpc_glin,gpc_glin,gpc_lin, gpc_lin },
   {gpc_g8b, gpc_g8,  gpc_bckc,gpc_noop, gpc_gprq,gpc_gpre,gpc_preq,gpc_pre },
   {gpc_sRGB,gpc_sRGB,gpc_sRGB,gpc_sRGB, gpc_noop,gpc_noop,gpc_noop,gpc_noop},
   {gpc_b16g,gpc_unpg,gpc_b16c,gpc_unpc, gpc_A,   gpc_noop,gpc_A,   gpc_noop},
   {gpc_sG,  gpc_sG,  gpc_sRGB,gpc_sRGB, gpc_g16, gpc_g16, gpc_noop,gpc_noop},
   {gpc_gb16,gpc_sGp, gpc_cb16,gpc_sCp,  gpc_g16, gpc_g16q,gpc_A,   gpc_noop}
};

/* The array is repeated for the cases where both the input and output are color
 * mapped because then different algorithms are used.
 */
static void (* const gpc_fn_colormapped[8/*in*/][8/*out*/])
   (Pixel *out, const Pixel *in, const Background *back) =
{
/*out: G-8     GA-8     RGB-8    RGBA-8    G-16     GA-16   RGB-16  RGBA-16 */
   {gpc_noop,gpc_noop,gpc_noop,gpc_noop, gpc_lin, gpc_lin, gpc_lin, gpc_lin },
   {gpc_bckg,gpc_noop,gpc_bckc,gpc_noop, gpc_preq,gpc_pre, gpc_preq,gpc_pre },
   {gpc_g8,  gpc_g8,  gpc_noop,gpc_noop, gpc_glin,gpc_glin,gpc_lin, gpc_lin },
   {gpc_g8b, gpc_g8,  gpc_bckc,gpc_noop, gpc_gprq,gpc_gpre,gpc_preq,gpc_pre },
   {gpc_sRGB,gpc_sRGB,gpc_sRGB,gpc_sRGB, gpc_noop,gpc_noop,gpc_noop,gpc_noop},
   {gpc_b16g,gpc_unpg,gpc_b16c,gpc_unpc, gpc_A,   gpc_noop,gpc_A,   gpc_noop},
   {gpc_sG,  gpc_sG,  gpc_sRGB,gpc_sRGB, gpc_g16, gpc_g16, gpc_noop,gpc_noop},
   {gpc_gb16,gpc_sGp, gpc_cb16,gpc_sCp,  gpc_g16, gpc_g16q,gpc_A,   gpc_noop}
};

/* The error arrays record the error in the same matrix; 64 entries, however
 * the different algorithms used in libpng for colormap and direct conversions
 * mean that four separate matrices are used (for each combination of
 * colormapped and direct.)
 *
 * In some cases the conversion between sRGB formats goes via a linear
 * intermediate; an sRGB to linear conversion (as above) is followed by a simple
 * linear to sRGB step with no other conversions.  This is done by a separate
 * error array from an arbitrary 'in' format to one of the four basic outputs
 * (since final output is always sRGB not colormapped).
 *
 * These arrays may be modified if the --accumulate flag is set during the run;
 * then instead of logging errors they are simply added in.
 *
 * The three entries are currently for transparent, partially transparent and
 * opaque input pixel values.  Notice that alpha should be exact in each case.
 *
 * Errors in alpha should only occur when converting from a direct format
 * to a colormapped format, when alpha is effectively smashed (so large
 * errors can occur.)  There should be no error in the '0' and 'opaque'
 * values.  The fourth entry in the array is used for the alpha error (and it
 * should always be zero for the 'via linear' case since this is never color
 * mapped.)
 *
 * Mapping to a colormap smashes the colors, it is necessary to have separate
 * values for these cases because they are much larger; it is very much
 * impossible to obtain a reasonable result, these are held in
 * gpc_error_to_colormap.
 */
#if PNG_FORMAT_FLAG_COLORMAP == 8 /* extra check also required */
2019
#  include "pngstest-errors.h" /* machine generated */
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
#endif /* COLORMAP flag check */
#endif /* flag checks */

typedef struct
{
   /* Basic pixel information: */
   Image*       in_image;   /* Input image */
   const Image* out_image;  /* Output image */

   /* 'background' is the value passed to the gpc_ routines, it may be NULL if
    * it should not be used (*this* program has an error if it crashes as a
    * result!)
    */
   Background        background_color;
   const Background* background;

   /* Precalculated values: */
   int          in_opaque;   /* Value of input alpha that is opaque */
   int          is_palette;  /* Sample values come from the palette */
L
luz.paz 已提交
2039
   int          accumulate;  /* Accumulate component errors (don't log) */
2040
   int          output_8bit; /* Output is 8-bit (else 16-bit) */
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348

   void (*in_gp)(Pixel*, png_const_voidp);
   void (*out_gp)(Pixel*, png_const_voidp);

   void (*transform)(Pixel *out, const Pixel *in, const Background *back);
      /* A function to perform the required transform */

   void (*from_linear)(Pixel *out, const Pixel *in, const Background *back);
      /* For 'via_linear' transforms the final, from linear, step, else NULL */

   png_uint_16 error[4];
      /* Three error values for transparent, partially transparent and opaque
       * input pixels (in turn).
       */

   png_uint_16 *error_ptr;
      /* Where these are stored in the static array (for 'accumulate') */
}
Transform;

/* Return a 'transform' as above for the given format conversion. */
static void
transform_from_formats(Transform *result, Image *in_image,
   const Image *out_image, png_const_colorp background, int via_linear)
{
   png_uint_32 in_format, out_format;
   png_uint_32 in_base, out_base;

   memset(result, 0, sizeof *result);

   /* Store the original images for error messages */
   result->in_image = in_image;
   result->out_image = out_image;

   in_format = in_image->image.format;
   out_format = out_image->image.format;

   if (in_format & PNG_FORMAT_FLAG_LINEAR)
      result->in_opaque = 65535;
   else
      result->in_opaque = 255;

   result->output_8bit = (out_format & PNG_FORMAT_FLAG_LINEAR) == 0;

   result->is_palette = 0; /* set by caller if required */
   result->accumulate = (in_image->opts & ACCUMULATE) != 0;

   /* The loaders (which need the ordering information) */
   result->in_gp = get_pixel(in_format);
   result->out_gp = get_pixel(out_format);

   /* Remove the ordering information: */
   in_format &= BASE_FORMATS | PNG_FORMAT_FLAG_COLORMAP;
   in_base = in_format & BASE_FORMATS;
   out_format &= BASE_FORMATS | PNG_FORMAT_FLAG_COLORMAP;
   out_base = out_format & BASE_FORMATS;

   if (via_linear)
   {
      /* Check for an error in this program: */
      if (out_format & (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLORMAP))
      {
         fprintf(stderr, "internal transform via linear error 0x%x->0x%x\n",
            in_format, out_format);
         exit(1);
      }

      result->transform = gpc_fn[in_base][out_base | PNG_FORMAT_FLAG_LINEAR];
      result->from_linear = gpc_fn[out_base | PNG_FORMAT_FLAG_LINEAR][out_base];
      result->error_ptr = gpc_error_via_linear[in_format][out_format];
   }

   else if (~in_format & out_format & PNG_FORMAT_FLAG_COLORMAP)
   {
      /* The input is not colormapped but the output is, the errors will
       * typically be large (only the grayscale-no-alpha case permits preserving
       * even 8-bit values.)
       */
      result->transform = gpc_fn[in_base][out_base];
      result->from_linear = NULL;
      result->error_ptr = gpc_error_to_colormap[in_base][out_base];
   }

   else
   {
      /* The caller handles the colormap->pixel value conversion, so the
       * transform function just gets a pixel value, however because libpng
       * currently contains a different implementation for mapping a colormap if
       * both input and output are colormapped we need different conversion
       * functions to deal with errors in the libpng implementation.
       */
      if (in_format & out_format & PNG_FORMAT_FLAG_COLORMAP)
         result->transform = gpc_fn_colormapped[in_base][out_base];
      else
         result->transform = gpc_fn[in_base][out_base];
      result->from_linear = NULL;
      result->error_ptr = gpc_error[in_format][out_format];
   }

   /* Follow the libpng simplified API rules to work out what to pass to the gpc
    * routines as a background value, if one is not required pass NULL so that
    * this program crashes in the even of a programming error.
    */
   result->background = NULL; /* default: not required */

   /* Rule 1: background only need be supplied if alpha is to be removed */
   if (in_format & ~out_format & PNG_FORMAT_FLAG_ALPHA)
   {
      /* The input value is 'NULL' to use the background and (otherwise) an sRGB
       * background color (to use a solid color).  The code above uses a fixed
       * byte value, BUFFER_INIT8, for buffer even for 16-bit output.  For
       * linear (16-bit) output the sRGB background color is ignored; the
       * composition is always on the background (so BUFFER_INIT8 * 257), except
       * that for the colormap (i.e. linear colormapped output) black is used.
       */
      result->background = &result->background_color;

      if (out_format & PNG_FORMAT_FLAG_LINEAR || via_linear)
      {
         if (out_format & PNG_FORMAT_FLAG_COLORMAP)
         {
            result->background_color.ir =
               result->background_color.ig =
               result->background_color.ib = 0;
            result->background_color.dr =
               result->background_color.dg =
               result->background_color.db = 0;
         }

         else
         {
            result->background_color.ir =
               result->background_color.ig =
               result->background_color.ib = BUFFER_INIT8 * 257;
            result->background_color.dr =
               result->background_color.dg =
               result->background_color.db = 0;
         }
      }

      else /* sRGB output */
      {
         if (background != NULL)
         {
            if (out_format & PNG_FORMAT_FLAG_COLOR)
            {
               result->background_color.ir = background->red;
               result->background_color.ig = background->green;
               result->background_color.ib = background->blue;
               /* TODO: sometimes libpng uses the power law conversion here, how
                * to handle this?
                */
               result->background_color.dr = sRGB_to_d[background->red];
               result->background_color.dg = sRGB_to_d[background->green];
               result->background_color.db = sRGB_to_d[background->blue];
            }

            else /* grayscale: libpng only looks at 'g' */
            {
               result->background_color.ir =
                  result->background_color.ig =
                  result->background_color.ib = background->green;
               /* TODO: sometimes libpng uses the power law conversion here, how
                * to handle this?
                */
               result->background_color.dr =
                  result->background_color.dg =
                  result->background_color.db = sRGB_to_d[background->green];
            }
         }

         else if ((out_format & PNG_FORMAT_FLAG_COLORMAP) == 0)
         {
            result->background_color.ir =
               result->background_color.ig =
               result->background_color.ib = BUFFER_INIT8;
            /* TODO: sometimes libpng uses the power law conversion here, how
             * to handle this?
             */
            result->background_color.dr =
               result->background_color.dg =
               result->background_color.db = sRGB_to_d[BUFFER_INIT8];
         }

         /* Else the output is colormapped and a background color must be
          * provided; if pngstest crashes then that is a bug in this program
          * (though libpng should png_error as well.)
          */
         else
            result->background = NULL;
      }
   }

   if (result->background == NULL)
   {
      result->background_color.ir =
         result->background_color.ig =
         result->background_color.ib = -1; /* not used */
      result->background_color.dr =
         result->background_color.dg =
         result->background_color.db = 1E30; /* not used */
   }


   /* Copy the error values into the Transform: */
   result->error[0] = result->error_ptr[0];
   result->error[1] = result->error_ptr[1];
   result->error[2] = result->error_ptr[2];
   result->error[3] = result->error_ptr[3];
}


/* Compare two pixels.
 *
 * OLD error values:
static int error_to_linear = 811; * by experiment *
static int error_to_linear_grayscale = 424; * by experiment *
static int error_to_sRGB = 6; * by experiment *
static int error_to_sRGB_grayscale = 17; * libpng error by calculation +
                                            2 by experiment *
static int error_in_compose = 2; * by experiment *
static int error_in_premultiply = 1;
 *
 * The following is *just* the result of a round trip from 8-bit sRGB to linear
 * then back to 8-bit sRGB when it is done by libpng.  There are two problems:
 *
 * 1) libpng currently uses a 2.2 power law with no linear segment, this results
 * in instability in the low values and even with 16-bit precision sRGB(1) ends
 * up mapping to sRGB(0) as a result of rounding in the 16-bit representation.
 * This gives an error of 1 in the handling of value 1 only.
 *
 * 2) libpng currently uses an intermediate 8-bit linear value in gamma
 * correction of 8-bit values.  This results in many more errors, the worse of
 * which is mapping sRGB(14) to sRGB(0).
 *
 * The general 'error_via_linear' is more complex because of pre-multiplication,
 * this compounds the 8-bit errors according to the alpha value of the pixel.
 * As a result 256 values are pre-calculated for error_via_linear.
 */
#if 0
static int error_in_libpng_gamma;
static int error_via_linear[256]; /* Indexed by 8-bit alpha */

static void
init_error_via_linear(void)
{
   int alpha;

   error_via_linear[0] = 255; /* transparent pixel */

   for (alpha=1; alpha<=255; ++alpha)
   {
      /* 16-bit values less than 128.5 get rounded to 8-bit 0 and so the worst
       * case error arises with 16-bit 128.5, work out what sRGB
       * (non-associated) value generates 128.5; any value less than this is
       * going to map to 0, so the worst error is floor(value).
       *
       * Note that errors are considerably higher (more than a factor of 2)
       * because libpng uses a simple power law for sRGB data at present.
       *
       * Add .1 for arithmetic errors inside libpng.
       */
      double v = floor(255*pow(.5/*(128.5 * 255 / 65535)*/ / alpha, 1/2.2)+.1);

      error_via_linear[alpha] = (int)v;
   }

   /* This is actually 14.99, but, despite the closeness to 15, 14 seems to work
    * ok in this case.
    */
   error_in_libpng_gamma = 14;
}
#endif

static void
print_pixel(char string[64], const Pixel *pixel, png_uint_32 format)
{
   switch (format & (PNG_FORMAT_FLAG_ALPHA|PNG_FORMAT_FLAG_COLOR))
   {
      case 0:
         sprintf(string, "%s(%d)", format_names[format], pixel->g);
         break;

      case PNG_FORMAT_FLAG_ALPHA:
         sprintf(string, "%s(%d,%d)", format_names[format], pixel->g,
            pixel->a);
         break;

      case PNG_FORMAT_FLAG_COLOR:
         sprintf(string, "%s(%d,%d,%d)", format_names[format],
            pixel->r, pixel->g, pixel->b);
         break;

      case PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA:
         sprintf(string, "%s(%d,%d,%d,%d)", format_names[format],
            pixel->r, pixel->g, pixel->b, pixel->a);
         break;

      default:
         sprintf(string, "invalid-format");
         break;
   }
}

static int
logpixel(const Transform *transform, png_uint_32 x, png_uint_32 y,
   const Pixel *in, const Pixel *calc, const Pixel *out, const char *reason)
{
2349 2350
   png_uint_32 in_format = transform->in_image->image.format;
   png_uint_32 out_format = transform->out_image->image.format;
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548

   png_uint_32 back_format = out_format & ~PNG_FORMAT_FLAG_ALPHA;
   const char *via_linear = "";

   char pixel_in[64], pixel_calc[64], pixel_out[64], pixel_loc[64];
   char background_info[100];

   print_pixel(pixel_in, in, in_format);
   print_pixel(pixel_calc, calc, out_format);
   print_pixel(pixel_out, out, out_format);

   if (transform->is_palette)
      sprintf(pixel_loc, "palette: %lu", (unsigned long)y);
   else
      sprintf(pixel_loc, "%lu,%lu", (unsigned long)x, (unsigned long)y);

   if (transform->from_linear != NULL)
   {
      via_linear = " (via linear)";
      /* And as a result the *read* format which did any background processing
       * was itself linear, so the background color information is also
       * linear.
       */
      back_format |= PNG_FORMAT_FLAG_LINEAR;
   }

   if (transform->background != NULL)
   {
      Pixel back;
      char pixel_back[64];

      back.r = transform->background->ir;
      back.g = transform->background->ig;
      back.b = transform->background->ib;
      back.a = -1; /* not used */

      print_pixel(pixel_back, &back, back_format);
      sprintf(background_info, " on background %s", pixel_back);
   }

   else
      background_info[0] = 0;

   if (transform->in_image->file_name != transform->out_image->file_name)
   {
      char error_buffer[512];
      sprintf(error_buffer,
         "(%s) %s error%s:\n %s%s ->\n       %s\n  not: %s.\n"
         "Use --preserve and examine: ", pixel_loc, reason, via_linear,
         pixel_in, background_info, pixel_out, pixel_calc);
      return logerror(transform->in_image, transform->in_image->file_name,
         error_buffer, transform->out_image->file_name);
   }

   else
   {
      char error_buffer[512];
      sprintf(error_buffer,
         "(%s) %s error%s:\n %s%s ->\n       %s\n  not: %s.\n"
         " The error happened when reading the original file with this format.",
         pixel_loc, reason, via_linear, pixel_in, background_info, pixel_out,
         pixel_calc);
      return logerror(transform->in_image, transform->in_image->file_name,
         error_buffer, "");
   }
}

static int
cmppixel(Transform *transform, png_const_voidp in, png_const_voidp out,
   png_uint_32 x, png_uint_32 y/*or palette index*/)
{
   int maxerr;
   png_const_charp errmsg;
   Pixel pixel_in, pixel_calc, pixel_out;

   transform->in_gp(&pixel_in, in);

   if (transform->from_linear == NULL)
      transform->transform(&pixel_calc, &pixel_in, transform->background);

   else
   {
      transform->transform(&pixel_out, &pixel_in, transform->background);
      transform->from_linear(&pixel_calc, &pixel_out, NULL);
   }

   transform->out_gp(&pixel_out, out);

   /* Eliminate the case where the input and output values match exactly. */
   if (pixel_calc.a == pixel_out.a && pixel_calc.r == pixel_out.r &&
      pixel_calc.g == pixel_out.g && pixel_calc.b == pixel_out.b)
      return 1;

   /* Eliminate the case where the output pixel is transparent and the output
    * is 8-bit - any component values are valid.  Don't check the input alpha
    * here to also skip the 16-bit small alpha cases.
    */
   if (transform->output_8bit && pixel_calc.a == 0 && pixel_out.a == 0)
      return 1;

   /* Check for alpha errors first; an alpha error can damage the components too
    * so avoid spurious checks on components if one is found.
    */
   errmsg = NULL;
   {
      int err_a = abs(pixel_calc.a-pixel_out.a);

      if (err_a > transform->error[3])
      {
         /* If accumulating check the components too */
         if (transform->accumulate)
            transform->error[3] = (png_uint_16)err_a;

         else
            errmsg = "alpha";
      }
   }

   /* Now if *either* of the output alphas are 0 but alpha is within tolerance
    * eliminate the 8-bit component comparison.
    */
   if (errmsg == NULL && transform->output_8bit &&
      (pixel_calc.a == 0 || pixel_out.a == 0))
      return 1;

   if (errmsg == NULL) /* else just signal an alpha error */
   {
      int err_r = abs(pixel_calc.r - pixel_out.r);
      int err_g = abs(pixel_calc.g - pixel_out.g);
      int err_b = abs(pixel_calc.b - pixel_out.b);
      int limit;

      if ((err_r | err_g | err_b) == 0)
         return 1; /* exact match */

      /* Mismatch on a component, check the input alpha */
      if (pixel_in.a >= transform->in_opaque)
      {
         errmsg = "opaque component";
         limit = 2; /* opaque */
      }

      else if (pixel_in.a > 0)
      {
         errmsg = "alpha component";
         limit = 1; /* partially transparent */
      }

      else
      {
         errmsg = "transparent component (background)";
         limit = 0; /* transparent */
      }

      maxerr = err_r;
      if (maxerr < err_g) maxerr = err_g;
      if (maxerr < err_b) maxerr = err_b;

      if (maxerr <= transform->error[limit])
         return 1; /* within the error limits */

      /* Handle a component mis-match; log it, just return an error code, or
       * accumulate it.
       */
      if (transform->accumulate)
      {
         transform->error[limit] = (png_uint_16)maxerr;
         return 1; /* to cause the caller to keep going */
      }
   }

   /* Failure to match and not accumulating, so the error must be logged. */
   return logpixel(transform, x, y, &pixel_in, &pixel_calc, &pixel_out, errmsg);
}

static png_byte
component_loc(png_byte loc[4], png_uint_32 format)
{
   /* Given a format return the number of channels and the location of
    * each channel.
    *
    * The mask 'loc' contains the component offset of the channels in the
    * following order.  Note that if 'format' is grayscale the entries 1-3 must
    * all contain the location of the gray channel.
    *
    * 0: alpha
    * 1: red or gray
    * 2: green or gray
    * 3: blue or gray
    */
   png_byte channels;

   if (format & PNG_FORMAT_FLAG_COLOR)
   {
      channels = 3;

      loc[2] = 1;

2549 2550 2551 2552 2553 2554
#     ifdef PNG_FORMAT_BGR_SUPPORTED
         if (format & PNG_FORMAT_FLAG_BGR)
         {
            loc[1] = 2;
            loc[3] = 0;
         }
2555

2556 2557
         else
#     endif
2558 2559 2560 2561 2562
      {
         loc[1] = 0;
         loc[3] = 2;
      }
   }
2563

2564 2565 2566 2567 2568
   else
   {
      channels = 1;
      loc[1] = loc[2] = loc[3] = 0;
   }
2569

2570 2571
   if (format & PNG_FORMAT_FLAG_ALPHA)
   {
2572 2573 2574 2575 2576 2577 2578 2579
#     ifdef PNG_FORMAT_AFIRST_SUPPORTED
         if (format & PNG_FORMAT_FLAG_AFIRST)
         {
            loc[0] = 0;
            ++loc[1];
            ++loc[2];
            ++loc[3];
         }
2580

2581 2582
         else
#     endif
2583
         loc[0] = channels;
2584

2585
      ++channels;
2586
   }
2587

2588 2589
   else
      loc[0] = 4; /* not present */
2590

2591
   return channels;
J
John Bowler 已提交
2592 2593 2594 2595 2596 2597
}

/* Compare two images, the original 'a', which was written out then read back in
 * to * give image 'b'.  The formats may have been changed.
 */
static int
2598 2599
compare_two_images(Image *a, Image *b, int via_linear,
   png_const_colorp background)
J
John Bowler 已提交
2600 2601 2602 2603 2604
{
   ptrdiff_t stridea = a->stride;
   ptrdiff_t strideb = b->stride;
   png_const_bytep rowa = a->buffer+16;
   png_const_bytep rowb = b->buffer+16;
2605 2606 2607 2608 2609 2610
   png_uint_32 width = a->image.width;
   png_uint_32 height = a->image.height;
   png_uint_32 formata = a->image.format;
   png_uint_32 formatb = b->image.format;
   unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata);
   unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb);
2611 2612 2613 2614
   int alpha_added, alpha_removed;
   int bchannels;
   png_uint_32 y;
   Transform tr;
2615
   int btoa[4]={0,0,0,0};
J
John Bowler 已提交
2616 2617 2618 2619 2620 2621

   /* This should never happen: */
   if (width != b->image.width || height != b->image.height)
      return logerror(a, a->file_name, ": width x height changed: ",
         b->file_name);

2622 2623 2624
   /* Set up the background and the transform */
   transform_from_formats(&tr, a, b, background, via_linear);

J
John Bowler 已提交
2625
   /* Find the first row and inter-row space. */
2626 2627 2628
   if (!(formata & PNG_FORMAT_FLAG_COLORMAP) &&
      (formata & PNG_FORMAT_FLAG_LINEAR))
      stridea *= 2;
J
John Bowler 已提交
2629

2630 2631 2632
   if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) &&
      (formatb & PNG_FORMAT_FLAG_LINEAR))
      strideb *= 2;
J
John Bowler 已提交
2633 2634 2635 2636

   if (stridea < 0) rowa += (height-1) * (-stridea);
   if (strideb < 0) rowb += (height-1) * (-strideb);

2637 2638 2639 2640
   /* First shortcut the two colormap case by comparing the image data; if it
    * matches then we expect the colormaps to match, although this is not
    * absolutely necessary for an image match.  If the colormaps fail to match
    * then there is a problem in libpng.
2641
    */
2642
   if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP)
2643
   {
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
      /* Only check colormap entries that actually exist; */
      png_const_bytep ppa, ppb;
      int match;
      png_byte in_use[256], amax = 0, bmax = 0;

      memset(in_use, 0, sizeof in_use);

      ppa = rowa;
      ppb = rowb;

      /* Do this the slow way to accumulate the 'in_use' flags, don't break out
       * of the loop until the end; this validates the color-mapped data to
       * ensure all pixels are valid color-map indexes.
       */
      for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb)
      {
         png_uint_32 x;
J
John Bowler 已提交
2661

2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
         for (x=0; x<width; ++x)
         {
            png_byte bval = ppb[x];
            png_byte aval = ppa[x];

            if (bval > bmax)
               bmax = bval;

            if (bval != aval)
               match = 0;

            in_use[aval] = 1;
            if (aval > amax)
               amax = aval;
         }
      }
J
John Bowler 已提交
2678

2679 2680
      /* If the buffers match then the colormaps must too. */
      if (match)
2681
      {
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
         /* Do the color-maps match, entry by entry?  Only check the 'in_use'
          * entries.  An error here should be logged as a color-map error.
          */
         png_const_bytep a_cmap = (png_const_bytep)a->colormap;
         png_const_bytep b_cmap = (png_const_bytep)b->colormap;
         int result = 1; /* match by default */

         /* This is used in logpixel to get the error message correct. */
         tr.is_palette = 1;

         for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample)
            if (in_use[y])
2694
         {
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
            /* The colormap entries should be valid, but because libpng doesn't
             * do any checking at present the original image may contain invalid
             * pixel values.  These cause an error here (at present) unless
             * accumulating errors in which case the program just ignores them.
             */
            if (y >= a->image.colormap_entries)
            {
               if ((a->opts & ACCUMULATE) == 0)
               {
                  char pindex[9];
                  sprintf(pindex, "%lu[%lu]", (unsigned long)y,
                     (unsigned long)a->image.colormap_entries);
                  logerror(a, a->file_name, ": bad pixel index: ", pindex);
               }
               result = 0;
            }
2711

2712
            else if (y >= b->image.colormap_entries)
2713
            {
2714
               if ((b->opts & ACCUMULATE) == 0)
2715 2716 2717 2718 2719 2720 2721
                  {
                  char pindex[9];
                  sprintf(pindex, "%lu[%lu]", (unsigned long)y,
                     (unsigned long)b->image.colormap_entries);
                  logerror(b, b->file_name, ": bad pixel index: ", pindex);
                  }
               result = 0;
2722
            }
2723

2724 2725 2726
            /* All the mismatches are logged here; there can only be 256! */
            else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y))
               result = 0;
2727 2728
         }

L
luz.paz 已提交
2729
         /* If requested, copy the error values back from the Transform. */
2730
         if (a->opts & ACCUMULATE)
2731
         {
2732 2733 2734 2735 2736
            tr.error_ptr[0] = tr.error[0];
            tr.error_ptr[1] = tr.error[1];
            tr.error_ptr[2] = tr.error[2];
            tr.error_ptr[3] = tr.error[3];
            result = 1; /* force a continue */
2737
         }
2738

2739
         return result;
2740
      }
2741

2742 2743 2744 2745 2746
      /* else the image buffers don't match pixel-wise so compare sample values
       * instead, but first validate that the pixel indexes are in range (but
       * only if not accumulating, when the error is ignored.)
       */
      else if ((a->opts & ACCUMULATE) == 0)
2747
      {
2748 2749 2750 2751 2752
#        ifdef __GNUC__
#           define BYTE_CHARS 20 /* 2^32: GCC sprintf warning */
#        else
#           define BYTE_CHARS 3 /* 2^8: real maximum value */
#        endif
2753 2754 2755 2756
         /* Check the original image first,
          * TODO: deal with input images with bad pixel values?
          */
         if (amax >= a->image.colormap_entries)
2757
         {
2758 2759 2760
            char pindex[3+2*BYTE_CHARS];
            sprintf(pindex, "%d[%u]", amax,
               (png_byte)/*SAFE*/a->image.colormap_entries);
2761
            return logerror(a, a->file_name, ": bad pixel index: ", pindex);
2762 2763
         }

2764 2765
         else if (bmax >= b->image.colormap_entries)
         {
2766 2767 2768
            char pindex[3+2*BYTE_CHARS];
            sprintf(pindex, "%d[%u]", bmax,
               (png_byte)/*SAFE*/b->image.colormap_entries);
2769 2770
            return logerror(b, b->file_name, ": bad pixel index: ", pindex);
         }
2771
      }
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
   }

   /* We can directly compare pixel values without the need to use the read
    * or transform support (i.e. a memory compare) if:
    *
    * 1) The bit depth has not changed.
    * 2) RGB to grayscale has not been done (the reverse is ok; we just compare
    *    the three RGB values to the original grayscale.)
    * 3) An alpha channel has not been removed from an 8-bit format, or the
    *    8-bit alpha value of the pixel was 255 (opaque).
    *
    * If an alpha channel has been *added* then it must have the relevant opaque
    * value (255 or 65535).
    *
    * The fist two the tests (in the order given above) (using the boolean
    * equivalence !a && !b == !(a || b))
    */
   if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) |
      (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR)))
   {
      /* Was an alpha channel changed? */
2793
      png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA;
2794 2795 2796 2797 2798 2799 2800 2801

      /* Was an alpha channel removed?  (The third test.)  If so the direct
       * comparison is only possible if the input alpha is opaque.
       */
      alpha_removed = (formata & alpha_changed) != 0;

      /* Was an alpha channel added? */
      alpha_added = (formatb & alpha_changed) != 0;
J
John Bowler 已提交
2802

2803 2804 2805 2806 2807
      /* The channels may have been moved between input and output, this finds
       * out how, recording the result in the btoa array, which says where in
       * 'a' to find each channel of 'b'.  If alpha was added then btoa[alpha]
       * ends up as 4 (and is not used.)
       */
2808
      {
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
         int i;
         png_byte aloc[4];
         png_byte bloc[4];

         /* The following are used only if the formats match, except that
          * 'bchannels' is a flag for matching formats.  btoa[x] says, for each
          * channel in b, where to find the corresponding value in a, for the
          * bchannels.  achannels may be different for a gray to rgb transform
          * (a will be 1 or 2, b will be 3 or 4 channels.)
          */
         (void)component_loc(aloc, formata);
         bchannels = component_loc(bloc, formatb);

         /* Hence the btoa array. */
         for (i=0; i<4; ++i) if (bloc[i] < 4)
            btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */

         if (alpha_added)
            alpha_added = bloc[0]; /* location of alpha channel in image b */
2828

2829 2830 2831 2832 2833
         else
            alpha_added = 4; /* Won't match an image b channel */

         if (alpha_removed)
            alpha_removed = aloc[0]; /* location of alpha channel in image a */
2834

2835 2836
         else
            alpha_removed = 4;
2837
      }
2838
   }
2839

2840 2841 2842 2843 2844 2845 2846 2847
   else
   {
      /* Direct compare is not possible, cancel out all the corresponding local
       * variables.
       */
      bchannels = 0;
      alpha_removed = alpha_added = 4;
      btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */
2848
   }
2849

2850
   for (y=0; y<height; ++y, rowa += stridea, rowb += strideb)
2851
   {
2852 2853 2854 2855
      png_const_bytep ppa, ppb;
      png_uint_32 x;

      for (x=0, ppa=rowa, ppb=rowb; x<width; ++x)
2856
      {
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
         png_const_bytep psa, psb;

         if (formata & PNG_FORMAT_FLAG_COLORMAP)
            psa = (png_const_bytep)a->colormap + a_sample * *ppa++;
         else
            psa = ppa, ppa += a_sample;

         if (formatb & PNG_FORMAT_FLAG_COLORMAP)
            psb = (png_const_bytep)b->colormap + b_sample * *ppb++;
         else
            psb = ppb, ppb += b_sample;

         /* Do the fast test if possible. */
         if (bchannels)
         {
            /* Check each 'b' channel against either the corresponding 'a'
             * channel or the opaque alpha value, as appropriate.  If
             * alpha_removed value is set (not 4) then also do this only if the
             * 'a' alpha channel (alpha_removed) is opaque; only relevant for
             * the 8-bit case.
             */
            if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */
2879
            {
2880 2881
               png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa);
               png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb);
2882

2883
               switch (bchannels)
2884 2885
               {
                  case 4:
2886
                     if (pua[btoa[3]] != pub[3]) break;
2887
                     /* FALLTHROUGH */
2888
                  case 3:
2889
                     if (pua[btoa[2]] != pub[2]) break;
2890
                     /* FALLTHROUGH */
2891
                  case 2:
2892
                     if (pua[btoa[1]] != pub[1]) break;
2893
                     /* FALLTHROUGH */
2894
                  case 1:
2895 2896 2897
                     if (pua[btoa[0]] != pub[0]) break;
                     if (alpha_added != 4 && pub[alpha_added] != 65535) break;
                     continue; /* x loop */
2898
                  default:
2899
                     break; /* impossible */
2900
               }
2901 2902
            }

2903
            else if (alpha_removed == 4 || psa[alpha_removed] == 255)
2904
            {
2905 2906 2907 2908
               switch (bchannels)
               {
                  case 4:
                     if (psa[btoa[3]] != psb[3]) break;
2909
                     /* FALLTHROUGH */
2910 2911
                  case 3:
                     if (psa[btoa[2]] != psb[2]) break;
2912
                     /* FALLTHROUGH */
2913 2914
                  case 2:
                     if (psa[btoa[1]] != psb[1]) break;
2915
                     /* FALLTHROUGH */
2916 2917 2918 2919 2920 2921 2922
                  case 1:
                     if (psa[btoa[0]] != psb[0]) break;
                     if (alpha_added != 4 && psb[alpha_added] != 255) break;
                     continue; /* x loop */
                  default:
                     break; /* impossible */
               }
2923
            }
J
John Bowler 已提交
2924 2925
         }

2926 2927 2928 2929 2930
         /* If we get to here the fast match failed; do the slow match for this
          * pixel.
          */
         if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0)
            return 0; /* error case */
J
John Bowler 已提交
2931
      }
2932
   }
J
John Bowler 已提交
2933

L
luz.paz 已提交
2934
   /* If requested, copy the error values back from the Transform. */
2935 2936 2937 2938 2939 2940
   if (a->opts & ACCUMULATE)
   {
      tr.error_ptr[0] = tr.error[0];
      tr.error_ptr[1] = tr.error[1];
      tr.error_ptr[2] = tr.error[2];
      tr.error_ptr[3] = tr.error[3];
J
John Bowler 已提交
2941 2942
   }

2943
   return 1;
J
John Bowler 已提交
2944 2945 2946 2947 2948 2949
}

/* Read the file; how the read gets done depends on which of input_file and
 * input_memory have been set.
 */
static int
2950
read_file(Image *image, png_uint_32 format, png_const_colorp background)
J
John Bowler 已提交
2951
{
2952 2953 2954
   memset(&image->image, 0, sizeof image->image);
   image->image.version = PNG_IMAGE_VERSION;

J
John Bowler 已提交
2955 2956 2957 2958 2959 2960 2961
   if (image->input_memory != NULL)
   {
      if (!png_image_begin_read_from_memory(&image->image, image->input_memory,
         image->input_memory_size))
         return logerror(image, "memory init: ", image->file_name, "");
   }

2962 2963 2964 2965 2966 2967
#  ifdef PNG_STDIO_SUPPORTED
      else if (image->input_file != NULL)
      {
         if (!png_image_begin_read_from_stdio(&image->image, image->input_file))
            return logerror(image, "stdio init: ", image->file_name, "");
      }
J
John Bowler 已提交
2968

2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
      else
      {
         if (!png_image_begin_read_from_file(&image->image, image->file_name))
            return logerror(image, "file init: ", image->file_name, "");
      }
#  else
      else
      {
         return logerror(image, "unsupported file/stdio init: ",
            image->file_name, "");
      }
#  endif
J
John Bowler 已提交
2981

2982 2983 2984 2985
   /* This must be set after the begin_read call: */
   if (image->opts & sRGB_16BIT)
      image->image.flags |= PNG_IMAGE_FLAG_16BIT_sRGB;

J
John Bowler 已提交
2986 2987 2988 2989 2990
   /* Have an initialized image with all the data we need plus, maybe, an
    * allocated file (myfile) or buffer (mybuffer) that need to be freed.
    */
   {
      int result;
2991
      png_uint_32 image_format;
2992

2993
      /* Print both original and output formats. */
2994 2995
      image_format = image->image.format;

J
John Bowler 已提交
2996
      if (image->opts & VERBOSE)
2997 2998
      {
         printf("%s %lu x %lu %s -> %s", image->file_name,
J
John Bowler 已提交
2999 3000
            (unsigned long)image->image.width,
            (unsigned long)image->image.height,
3001
            format_names[image_format & FORMAT_MASK],
J
John Bowler 已提交
3002
            (format & FORMAT_NO_CHANGE) != 0 || image->image.format == format
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
            ? "no change" : format_names[format & FORMAT_MASK]);

         if (background != NULL)
            printf(" background(%d,%d,%d)\n", background->red,
               background->green, background->blue);
         else
            printf("\n");

         fflush(stdout);
      }

      /* 'NO_CHANGE' combined with the color-map flag forces the base format
       * flags to be set on read to ensure that the original representation is
       * not lost in the pass through a colormap format.
       */
      if ((format & FORMAT_NO_CHANGE) != 0)
      {
         if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0 &&
            (image_format & PNG_FORMAT_FLAG_COLORMAP) != 0)
            format = (image_format & ~BASE_FORMATS) | (format & BASE_FORMATS);

         else
            format = image_format;
      }
3027

3028
      image->image.format = format;
3029

J
John Bowler 已提交
3030 3031 3032
      image->stride = PNG_IMAGE_ROW_STRIDE(image->image) + image->stride_extra;
      allocbuffer(image);

3033 3034
      result = png_image_finish_read(&image->image, background,
         image->buffer+16, (png_int_32)image->stride, image->colormap);
J
John Bowler 已提交
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046

      checkbuffer(image, image->file_name);

      if (result)
         return checkopaque(image);

      else
         return logerror(image, image->file_name, ": image read failed", "");
   }
}

/* Reads from a filename, which must be in image->file_name, but uses
3047 3048
 * image->opts to choose the method.  The file is always read in its native
 * format (the one the simplified API suggests).
J
John Bowler 已提交
3049 3050
 */
static int
3051
read_one_file(Image *image)
J
John Bowler 已提交
3052
{
3053
   if (!(image->opts & USE_FILE) || (image->opts & USE_STDIO))
J
John Bowler 已提交
3054 3055 3056 3057 3058 3059
   {
      /* memory or stdio. */
      FILE *f = fopen(image->file_name, "rb");

      if (f != NULL)
      {
3060
         if (image->opts & USE_FILE)
J
John Bowler 已提交
3061 3062 3063 3064 3065 3066 3067 3068
            image->input_file = f;

         else /* memory */
         {
            if (fseek(f, 0, SEEK_END) == 0)
            {
               long int cb = ftell(f);

3069
               if (cb > 0)
J
John Bowler 已提交
3070
               {
3071
#ifndef __COVERITY__
3072
                  if ((unsigned long int)cb <= (size_t)~(size_t)0)
3073
#endif
J
John Bowler 已提交
3074
                  {
3075
                     png_bytep b = voidcast(png_bytep, malloc((size_t)cb));
J
John Bowler 已提交
3076

3077
                     if (b != NULL)
J
John Bowler 已提交
3078
                     {
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
                        rewind(f);

                        if (fread(b, (size_t)cb, 1, f) == 1)
                        {
                           fclose(f);
                           image->input_memory_size = cb;
                           image->input_memory = b;
                        }

                        else
                        {
                           free(b);
                           return logclose(image, f, image->file_name,
                              ": read failed: ");
                        }
J
John Bowler 已提交
3094 3095 3096 3097
                     }

                     else
                        return logclose(image, f, image->file_name,
3098
                           ": out of memory: ");
J
John Bowler 已提交
3099 3100 3101 3102
                  }

                  else
                     return logclose(image, f, image->file_name,
3103 3104 3105 3106 3107
                        ": file too big for this architecture: ");
                     /* cb is the length of the file as a (long) and
                      * this is greater than the maximum amount of
                      * memory that can be requested from malloc.
                      */
J
John Bowler 已提交
3108 3109
               }

3110 3111 3112 3113
               else if (cb == 0)
                  return logclose(image, f, image->file_name,
                     ": zero length: ");

J
John Bowler 已提交
3114
               else
3115 3116
                  return logclose(image, f, image->file_name,
                     ": tell failed: ");
J
John Bowler 已提交
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
            }

            else
               return logclose(image, f, image->file_name, ": seek failed: ");
         }
      }

      else
         return logerror(image, image->file_name, ": open failed: ",
            strerror(errno));
   }

3129
   return read_file(image, FORMAT_NO_CHANGE, NULL);
J
John Bowler 已提交
3130 3131
}

3132
#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
J
John Bowler 已提交
3133 3134 3135
static int
write_one_file(Image *output, Image *image, int convert_to_8bit)
{
3136 3137 3138
   if (image->opts & FAST_WRITE)
      image->image.flags |= PNG_IMAGE_FLAG_FAST;

J
John Bowler 已提交
3139 3140
   if (image->opts & USE_STDIO)
   {
3141
#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
3142
#ifndef __COVERITY__
3143 3144 3145 3146
      FILE *f = tmpfile();
#else
      /* Experimental. Coverity says tmpfile() is insecure because it
       * generates predictable names.
3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
       *
       * It is possible to satisfy Coverity by using mkstemp(); however,
       * any platform supporting mkstemp() undoubtedly has a secure tmpfile()
       * implementation as well, and doesn't need the fix.  Note that
       * the fix won't work on platforms that don't support mkstemp().
       *
       * https://www.securecoding.cert.org/confluence/display/c/
       * FIO21-C.+Do+not+create+temporary+files+in+shared+directories
       * says that most historic implementations of tmpfile() provide
       * only a limited number of possible temporary file names
       * (usually 26) before file names are recycled. That article also
       * provides a secure solution that unfortunately depends upon mkstemp().
3159
       */
3160
      char tmpfile[] = "pngstest-XXXXXX";
3161 3162
      int filedes;
      FILE *f;
3163
      umask(0177);
3164
      filedes = mkstemp(tmpfile);
3165
      if (filedes < 0)
3166
        f = NULL;
3167 3168 3169 3170 3171 3172 3173 3174
      else
      {
        f = fdopen(filedes,"w+");
        /* Hide the filename immediately and ensure that the file does
         * not exist after the program ends
         */
        (void) unlink(tmpfile);
      }
3175
#endif
3176

J
John Bowler 已提交
3177 3178 3179
      if (f != NULL)
      {
         if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
3180
            image->buffer+16, (png_int_32)image->stride, image->colormap))
J
John Bowler 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
         {
            if (fflush(f) == 0)
            {
               rewind(f);
               initimage(output, image->opts, "tmpfile", image->stride_extra);
               output->input_file = f;
               if (!checkopaque(image))
                  return 0;
            }

            else
3192
               return logclose(image, f, "tmpfile", ": flush: ");
J
John Bowler 已提交
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
         }

         else
         {
            fclose(f);
            return logerror(image, "tmpfile", ": write failed", "");
         }
      }

      else
         return logerror(image, "tmpfile", ": open: ", strerror(errno));
3204 3205 3206
#else /* SIMPLIFIED_WRITE_STDIO */
      return logerror(image, "tmpfile", ": open: unsupported", "");
#endif /* SIMPLIFIED_WRITE_STDIO */
J
John Bowler 已提交
3207 3208
   }

3209
   else if (image->opts & USE_FILE)
J
John Bowler 已提交
3210
   {
3211
#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
J
John Bowler 已提交
3212 3213 3214
      static int counter = 0;
      char name[32];

3215
      sprintf(name, "%s%d.png", tmpf, ++counter);
J
John Bowler 已提交
3216 3217

      if (png_image_write_to_file(&image->image, name, convert_to_8bit,
3218
         image->buffer+16, (png_int_32)image->stride, image->colormap))
J
John Bowler 已提交
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
      {
         initimage(output, image->opts, output->tmpfile_name,
            image->stride_extra);
         /* Afterwards, or freeimage will delete it! */
         strcpy(output->tmpfile_name, name);

         if (!checkopaque(image))
            return 0;
      }

      else
         return logerror(image, name, ": write failed", "");
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
#else /* SIMPLIFIED_WRITE_STDIO */
      return logerror(image, "stdio", ": open: unsupported", "");
#endif /* SIMPLIFIED_WRITE_STDIO */
   }

   else /* use memory */
   {
      png_alloc_size_t size;

      if (png_image_write_get_memory_size(image->image, size, convert_to_8bit,
               image->buffer+16, (png_int_32)image->stride, image->colormap))
      {
3243 3244 3245
         /* This is non-fatal but ignoring it was causing serious problems in
          * the macro to be ignored:
          */
3246
         if (size > PNG_IMAGE_PNG_SIZE_MAX(image->image))
3247
            return logerror(image, "memory", ": PNG_IMAGE_SIZE_MAX wrong", "");
3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259

         initimage(output, image->opts, "memory", image->stride_extra);
         output->input_memory = malloc(size);

         if (output->input_memory != NULL)
         {
            output->input_memory_size = size;

            if (png_image_write_to_memory(&image->image, output->input_memory,
                  &output->input_memory_size, convert_to_8bit, image->buffer+16,
                  (png_int_32)image->stride, image->colormap))
            {
3260 3261
               /* This is also non-fatal but it safes safer to error out anyway:
                */
3262
               if (size != output->input_memory_size)
3263
                  return logerror(image, "memory", ": memory size wrong", "");
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
            }

            else
               return logerror(image, "memory", ": write failed", "");
         }

         else
            return logerror(image, "memory", ": out of memory", "");
      }

      else
         return logerror(image, "memory", ": get size:", "");
J
John Bowler 已提交
3276 3277 3278 3279 3280
   }

   /* 'output' has an initialized temporary image, read this back in and compare
    * this against the original: there should be no change since the original
    * format was written unmodified unless 'convert_to_8bit' was specified.
3281 3282 3283
    * However, if the original image was color-mapped, a simple read will zap
    * the linear, color and maybe alpha flags, this will cause spurious failures
    * under some circumstances.
J
John Bowler 已提交
3284
    */
3285
   if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
J
John Bowler 已提交
3286
   {
3287 3288 3289 3290 3291
      png_uint_32 original_format = image->image.format;

      if (convert_to_8bit)
         original_format &= ~PNG_FORMAT_FLAG_LINEAR;

J
John Bowler 已提交
3292
      if ((output->image.format & BASE_FORMATS) !=
3293 3294
         (original_format & BASE_FORMATS))
         return logerror(image, image->file_name, ": format changed on read: ",
J
John Bowler 已提交
3295 3296
            output->file_name);

3297
      return compare_two_images(image, output, 0/*via linear*/, NULL);
J
John Bowler 已提交
3298 3299 3300 3301 3302 3303
   }

   else
      return logerror(output, output->tmpfile_name,
         ": read of new file failed", "");
}
3304
#endif
J
John Bowler 已提交
3305 3306

static int
3307
testimage(Image *image, png_uint_32 opts, format_list *pf)
J
John Bowler 已提交
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
{
   int result;
   Image copy;

   /* Copy the original data, stealing it from 'image' */
   checkopaque(image);
   copy = *image;

   copy.opts = opts;
   copy.buffer = NULL;
   copy.bufsize = 0;
   copy.allocsize = 0;

   image->input_file = NULL;
   image->input_memory = NULL;
   image->input_memory_size = 0;
   image->tmpfile_name[0] = 0;

   {
3327
      png_uint_32 counter;
J
John Bowler 已提交
3328 3329 3330
      Image output;

      newimage(&output);
3331

J
John Bowler 已提交
3332
      result = 1;
3333 3334 3335 3336 3337 3338 3339

      /* Use the low bit of 'counter' to indicate whether or not to do alpha
       * removal with a background color or by composting onto the image; this
       * step gets skipped if it isn't relevant
       */
      for (counter=0; counter<2*FORMAT_COUNT; ++counter)
         if (format_isset(pf, counter >> 1))
J
John Bowler 已提交
3340
      {
3341
         png_uint_32 format = counter >> 1;
3342

3343 3344
         png_color background_color;
         png_colorp background = NULL;
3345

3346 3347 3348 3349 3350
         /* If there is a format change that removes the alpha channel then
          * the background is relevant.  If the output is 8-bit color-mapped
          * then a background color *must* be provided, otherwise there are
          * two tests to do - one with a color, the other with NULL.  The
          * NULL test happens second.
3351
          */
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
         if ((counter & 1) == 0)
         {
            if ((format & PNG_FORMAT_FLAG_ALPHA) == 0 &&
               (image->image.format & PNG_FORMAT_FLAG_ALPHA) != 0)
            {
               /* Alpha/transparency will be removed, the background is
                * relevant: make it a color the first time
                */
               random_color(&background_color);
               background = &background_color;

               /* BUT if the output is to a color-mapped 8-bit format then
                * the background must always be a color, so increment 'counter'
                * to skip the NULL test.
                */
               if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0 &&
                  (format & PNG_FORMAT_FLAG_LINEAR) == 0)
                  ++counter;
            }

            /* Otherwise an alpha channel is not being eliminated, just leave
             * background NULL and skip the (counter & 1) NULL test.
             */
            else
               ++counter;
         }
         /* else just use NULL for background */

         resetimage(&copy);
         copy.opts = opts; /* in case read_file needs to change it */

         result = read_file(&copy, format, background);
J
John Bowler 已提交
3384 3385 3386
         if (!result)
            break;

3387 3388
         /* Make sure the file just read matches the original file. */
         result = compare_two_images(image, &copy, 0/*via linear*/, background);
J
John Bowler 已提交
3389 3390 3391
         if (!result)
            break;

3392 3393 3394 3395 3396 3397 3398
#        ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
            /* Write the *copy* just made to a new file to make sure the write
             * side works ok.  Check the conversion to sRGB if the copy is
             * linear.
             */
            output.opts = opts;
            result = write_one_file(&output, &copy, 0/*convert to 8bit*/);
J
John Bowler 已提交
3399 3400 3401
            if (!result)
               break;

3402 3403
            /* Validate against the original too; the background is needed here
             * as well so that compare_two_images knows what color was used.
J
John Bowler 已提交
3404
             */
3405
            result = compare_two_images(image, &output, 0, background);
J
John Bowler 已提交
3406 3407
            if (!result)
               break;
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433

            if ((format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
               (format & PNG_FORMAT_FLAG_COLORMAP) == 0)
            {
               /* 'output' is linear, convert to the corresponding sRGB format.
                */
               output.opts = opts;
               result = write_one_file(&output, &copy, 1/*convert to 8bit*/);
               if (!result)
                  break;

               /* This may involve a conversion via linear; in the ideal world
                * this would round-trip correctly, but libpng 1.5.7 is not the
                * ideal world so allow a drift (error_via_linear).
                *
                * 'image' has an alpha channel but 'output' does not then there
                * will a strip-alpha-channel operation (because 'output' is
                * linear), handle this by composing on black when doing the
                * comparison.
                */
               result = compare_two_images(image, &output, 1/*via_linear*/,
                  background);
               if (!result)
                  break;
            }
#        endif /* PNG_SIMPLIFIED_WRITE_SUPPORTED */
J
John Bowler 已提交
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
      }

      freeimage(&output);
   }

   freeimage(&copy);

   return result;
}

3444 3445 3446 3447 3448 3449 3450
static int
test_one_file(const char *file_name, format_list *formats, png_uint_32 opts,
   int stride_extra, int log_pass)
{
   int result;
   Image image;

3451 3452
   if (!(opts & NO_RESEED))
      reseed(); /* ensure that the random numbers don't depend on file order */
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
   newimage(&image);
   initimage(&image, opts, file_name, stride_extra);
   result = read_one_file(&image);
   if (result)
      result = testimage(&image, opts, formats);
   freeimage(&image);

   /* Ensure that stderr is flushed into any log file */
   fflush(stderr);

   if (log_pass)
   {
      if (result)
         printf("PASS:");

      else
         printf("FAIL:");

#     ifndef PNG_SIMPLIFIED_WRITE_SUPPORTED
         printf(" (no write)");
#     endif

      print_opts(opts);
      printf(" %s\n", file_name);
      /* stdout may not be line-buffered if it is piped to a file, so: */
      fflush(stdout);
   }

   else if (!result)
      exit(1);

   return result;
}

J
John Bowler 已提交
3487
int
3488
main(int argc, char **argv)
J
John Bowler 已提交
3489
{
3490
   png_uint_32 opts = FAST_WRITE | STRICT;
3491
   format_list formats;
3492
   const char *touch = NULL;
3493
   int log_pass = 0;
3494
   int redundant = 0;
J
John Bowler 已提交
3495
   int stride_extra = 0;
3496
   int retval = 0;
J
John Bowler 已提交
3497 3498
   int c;

3499 3500 3501 3502 3503
#if PNG_LIBPNG_VER >= 10700
      /* This error should not exist in 1.7 or later: */
      opts |= GBG_ERROR;
#endif

3504 3505 3506 3507 3508
   init_sRGB_to_d();
#if 0
   init_error_via_linear();
#endif
   format_init(&formats);
3509
   reseed(); /* initialize random number seeds */
3510

J
John Bowler 已提交
3511 3512 3513 3514
   for (c=1; c<argc; ++c)
   {
      const char *arg = argv[c];

3515 3516
      if (strcmp(arg, "--log") == 0)
         log_pass = 1;
3517 3518 3519 3520 3521
      else if (strcmp(arg, "--fresh") == 0)
      {
         memset(gpc_error, 0, sizeof gpc_error);
         memset(gpc_error_via_linear, 0, sizeof gpc_error_via_linear);
      }
3522
      else if (strcmp(arg, "--file") == 0)
3523
#        ifdef PNG_STDIO_SUPPORTED
3524
            opts |= USE_FILE;
3525
#        else
3526
            return SKIP; /* skipped: no support */
3527
#        endif
J
John Bowler 已提交
3528
      else if (strcmp(arg, "--memory") == 0)
3529
         opts &= ~USE_FILE;
J
John Bowler 已提交
3530
      else if (strcmp(arg, "--stdio") == 0)
3531 3532 3533
#        ifdef PNG_STDIO_SUPPORTED
            opts |= USE_STDIO;
#        else
3534
            return SKIP; /* skipped: no support */
3535
#        endif
J
John Bowler 已提交
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
      else if (strcmp(arg, "--name") == 0)
         opts &= ~USE_STDIO;
      else if (strcmp(arg, "--verbose") == 0)
         opts |= VERBOSE;
      else if (strcmp(arg, "--quiet") == 0)
         opts &= ~VERBOSE;
      else if (strcmp(arg, "--preserve") == 0)
         opts |= KEEP_TMPFILES;
      else if (strcmp(arg, "--nopreserve") == 0)
         opts &= ~KEEP_TMPFILES;
      else if (strcmp(arg, "--keep-going") == 0)
         opts |= KEEP_GOING;
3548 3549 3550 3551 3552 3553 3554 3555
      else if (strcmp(arg, "--fast") == 0)
         opts |= FAST_WRITE;
      else if (strcmp(arg, "--slow") == 0)
         opts &= ~FAST_WRITE;
      else if (strcmp(arg, "--accumulate") == 0)
         opts |= ACCUMULATE;
      else if (strcmp(arg, "--redundant") == 0)
         redundant = 1;
J
John Bowler 已提交
3556 3557
      else if (strcmp(arg, "--stop") == 0)
         opts &= ~KEEP_GOING;
3558 3559
      else if (strcmp(arg, "--strict") == 0)
         opts |= STRICT;
3560 3561
      else if (strcmp(arg, "--nostrict") == 0)
         opts &= ~STRICT;
3562 3563 3564 3565
      else if (strcmp(arg, "--sRGB-16bit") == 0)
         opts |= sRGB_16BIT;
      else if (strcmp(arg, "--linear-16bit") == 0)
         opts &= ~sRGB_16BIT;
3566 3567 3568 3569
      else if (strcmp(arg, "--noreseed") == 0)
         opts |= NO_RESEED;
      else if (strcmp(arg, "--fault-gbg-warning") == 0)
         opts |= GBG_ERROR;
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582
      else if (strcmp(arg, "--tmpfile") == 0)
      {
         if (c+1 < argc)
         {
            if (strlen(argv[++c]) >= sizeof tmpf)
            {
               fflush(stdout);
               fprintf(stderr, "%s: %s is too long for a temp file prefix\n",
                  argv[0], argv[c]);
               exit(99);
            }

            /* Safe: checked above */
3583
            strncpy(tmpf, argv[c], sizeof (tmpf)-1);
3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
         }

         else
         {
            fflush(stdout);
            fprintf(stderr, "%s: %s requires a temporary file prefix\n",
               argv[0], arg);
            exit(99);
         }
      }
3594 3595 3596 3597 3598 3599 3600
      else if (strcmp(arg, "--touch") == 0)
      {
         if (c+1 < argc)
            touch = argv[++c];

         else
         {
3601
            fflush(stdout);
3602 3603
            fprintf(stderr, "%s: %s requires a file name argument\n",
               argv[0], arg);
3604
            exit(99);
3605 3606
         }
      }
J
John Bowler 已提交
3607 3608 3609 3610
      else if (arg[0] == '+')
      {
         png_uint_32 format = formatof(arg+1);

3611 3612
         if (format > FORMAT_COUNT)
            exit(99);
J
John Bowler 已提交
3613

3614
         format_set(&formats, format);
J
John Bowler 已提交
3615
      }
3616
      else if (arg[0] == '-' && arg[1] != 0 && (arg[1] != '0' || arg[2] != 0))
J
John Bowler 已提交
3617
      {
3618
         fflush(stdout);
J
John Bowler 已提交
3619
         fprintf(stderr, "%s: unknown option: %s\n", argv[0], arg);
3620
         exit(99);
J
John Bowler 已提交
3621 3622 3623
      }
      else
      {
3624 3625 3626 3627 3628
         if (format_is_initial(&formats))
            format_default(&formats, redundant);

         if (arg[0] == '-')
         {
3629
            int term = (arg[1] == '0' ? 0 : '\n');
3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
            unsigned int ich = 0;

            /* Loop reading files, use a static buffer to simplify this and just
             * stop if the name gets to long.
             */
            static char buffer[4096];

            do
            {
               int ch = getchar();

               /* Don't allow '\0' in file names, and terminate with '\n' or,
                * for -0, just '\0' (use -print0 to find to make this work!)
                */
               if (ch == EOF || ch == term || ch == 0)
               {
                  buffer[ich] = 0;

                  if (ich > 0 && !test_one_file(buffer, &formats, opts,
                     stride_extra, log_pass))
                     retval = 1;

                  if (ch == EOF)
                     break;

                  ich = 0;
                  --ich; /* so that the increment below sets it to 0 again */
               }

               else
                  buffer[ich] = (char)ch;
            } while (++ich < sizeof buffer);

            if (ich)
            {
               buffer[32] = 0;
               buffer[4095] = 0;
               fprintf(stderr, "%s...%s: file name too long\n", buffer,
                  buffer+(4096-32));
               exit(99);
            }
         }

         else if (!test_one_file(arg, &formats, opts, stride_extra, log_pass))
            retval = 1;
      }
   }
J
John Bowler 已提交
3677

3678 3679 3680
   if (opts & ACCUMULATE)
   {
      unsigned int in;
3681

3682 3683 3684 3685
      printf("/* contrib/libtests/pngstest-errors.h\n");
      printf(" *\n");
      printf(" * BUILT USING:" PNG_HEADER_VERSION_STRING);
      printf(" *\n");
3686 3687 3688 3689
      printf(" * This code is released under the libpng license.\n");
      printf(" * For conditions of distribution and use, see the disclaimer\n");
      printf(" * and license in png.h\n");
      printf(" *\n");
3690 3691 3692 3693 3694 3695 3696 3697 3698
      printf(" * THIS IS A MACHINE GENERATED FILE: do not edit it directly!\n");
      printf(" * Instead run:\n");
      printf(" *\n");
      printf(" *    pngstest --accumulate\n");
      printf(" *\n");
      printf(" * on as many PNG files as possible; at least PNGSuite and\n");
      printf(" * contrib/libtests/testpngs.\n");
      printf(" */\n");

3699 3700 3701 3702 3703 3704 3705
      printf("static png_uint_16 gpc_error[16/*in*/][16/*out*/][4/*a*/] =\n");
      printf("{\n");
      for (in=0; in<16; ++in)
      {
         unsigned int out;
         printf(" { /* input: %s */\n ", format_names[in]);
         for (out=0; out<16; ++out)
3706
         {
3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721
            unsigned int alpha;
            printf(" {");
            for (alpha=0; alpha<4; ++alpha)
            {
               printf(" %d", gpc_error[in][out][alpha]);
               if (alpha < 3) putchar(',');
            }
            printf(" }");
            if (out < 15)
            {
               putchar(',');
               if (out % 4 == 3) printf("\n ");
            }
         }
         printf("\n }");
3722

3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
         if (in < 15)
            putchar(',');
         else
            putchar('\n');
      }
      printf("};\n");

      printf("static png_uint_16 gpc_error_via_linear[16][4/*out*/][4] =\n");
      printf("{\n");
      for (in=0; in<16; ++in)
      {
         unsigned int out;
         printf(" { /* input: %s */\n ", format_names[in]);
         for (out=0; out<4; ++out)
         {
            unsigned int alpha;
            printf(" {");
            for (alpha=0; alpha<4; ++alpha)
3741
            {
3742 3743
               printf(" %d", gpc_error_via_linear[in][out][alpha]);
               if (alpha < 3) putchar(',');
3744
            }
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
            printf(" }");
            if (out < 3)
               putchar(',');
         }
         printf("\n }");

         if (in < 15)
            putchar(',');
         else
            putchar('\n');
      }
      printf("};\n");
3757

3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778
      printf("static png_uint_16 gpc_error_to_colormap[8/*i*/][8/*o*/][4] =\n");
      printf("{\n");
      for (in=0; in<8; ++in)
      {
         unsigned int out;
         printf(" { /* input: %s */\n ", format_names[in]);
         for (out=0; out<8; ++out)
         {
            unsigned int alpha;
            printf(" {");
            for (alpha=0; alpha<4; ++alpha)
            {
               printf(" %d", gpc_error_to_colormap[in][out][alpha]);
               if (alpha < 3) putchar(',');
            }
            printf(" }");
            if (out < 7)
            {
               putchar(',');
               if (out % 4 == 3) printf("\n ");
            }
3779
         }
3780
         printf("\n }");
3781

3782 3783 3784 3785
         if (in < 7)
            putchar(',');
         else
            putchar('\n');
3786
      }
3787
      printf("};\n");
3788
      printf("/* END MACHINE GENERATED */\n");
3789 3790
   }

3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
   if (retval == 0 && touch != NULL)
   {
      FILE *fsuccess = fopen(touch, "wt");

      if (fsuccess != NULL)
      {
         int error = 0;
         fprintf(fsuccess, "PNG simple API tests succeeded\n");
         fflush(fsuccess);
         error = ferror(fsuccess);

         if (fclose(fsuccess) || error)
         {
3804
            fflush(stdout);
3805
            fprintf(stderr, "%s: write failed\n", touch);
3806
            exit(99);
3807 3808 3809 3810 3811
         }
      }

      else
      {
3812
         fflush(stdout);
3813
         fprintf(stderr, "%s: open failed\n", touch);
3814
         exit(99);
3815 3816 3817
      }
   }

3818
   return retval;
J
John Bowler 已提交
3819
}
3820 3821 3822 3823 3824 3825

#else /* !PNG_SIMPLIFIED_READ_SUPPORTED */
int main(void)
{
   fprintf(stderr, "pngstest: no read support in libpng, test skipped\n");
   /* So the test is skipped: */
3826
   return SKIP;
3827 3828
}
#endif /* PNG_SIMPLIFIED_READ_SUPPORTED */