pngstest.c 73.9 KB
Newer Older
J
John Bowler 已提交
1 2 3
/*-
 * pngstest.c
 *
4
 * Copyright (c) 2012 John Cunningham Bowler
5
 *
6
 * Last changed in libpng 1.6.0 [(PENDING RELEASE)]
7 8 9 10 11
 *
 * 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 已提交
12 13
 * Test for the PNG 'simplified' APIs.
 */
14
#define _ISOC90_SOURCE 1
J
John Bowler 已提交
15 16 17 18 19 20 21 22 23
#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>
24

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

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
J
John Bowler 已提交
37

38
#include "../tools/sRGB.h"
J
John Bowler 已提交
39

40 41 42 43 44 45 46
/* The following is to support direct compilation of this file as C++ */
#ifdef __cplusplus
#  define voidcast(type, value) static_cast<type>(value)
#else
#  define voidcast(type, value) (value)
#endif /* __cplusplus */

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/* 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;
}

static void
random_color(png_colorp color)
{
   static png_uint_32 color_seed[2] = { 0x12345678, 0x9abcdef };
   make_random_bytes(color_seed, color, sizeof *color);
}

85 86 87 88 89 90 91 92 93
/* 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);
}

94 95 96 97
/* Cast support: remove GCC whines. */
static png_byte
u8d(double d)
{
98
   d = closestinteger(d);
99 100 101 102 103 104
   return (png_byte)d;
}

static png_uint_16
u16d(double d)
{
105
   d = closestinteger(d);
106 107 108
   return (png_uint_16)d;
}

J
John Bowler 已提交
109 110 111 112 113 114
/* sRGB support: use exact calculations rounded to the nearest int, see the
 * fesetround() call in main().
 */
static png_byte
sRGB(double linear /*range 0.0 .. 1.0*/)
{
115
   return u8d(255 * sRGB_from_linear(linear));
J
John Bowler 已提交
116 117 118
}

static png_byte
119
isRGB(int fixed_linear)
J
John Bowler 已提交
120 121 122 123 124
{
   return sRGB(fixed_linear / 65535.);
}

static png_uint_16
125
ilineara(int fixed_srgb, int alpha)
J
John Bowler 已提交
126
{
127
   return u16d((257 * alpha) * linear_from_sRGB(fixed_srgb / 255.));
J
John Bowler 已提交
128 129
}

130 131 132 133 134 135 136 137 138
static double
YfromRGBint(int ir, int ig, int ib)
{
   double r = ir;
   double g = ig;
   double b = ib;
   return YfromRGB(r, g, b);
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/* 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(linear_from_sRGB(vd), 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 convertions.
       */
      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;
}

J
John Bowler 已提交
230 231
#define READ_FILE 1      /* else memory */
#define USE_STDIO 2      /* else use file name */
232
/* 4: unused */
J
John Bowler 已提交
233 234 235 236
#define VERBOSE 8
#define KEEP_TMPFILES 16 /* else delete temporary files */
#define KEEP_GOING 32

237 238
static void
print_opts(png_uint_32 opts)
J
John Bowler 已提交
239
{
240 241 242 243 244 245 246 247 248 249 250
   if (opts & READ_FILE)
      printf(" --file");
   if (opts & USE_STDIO)
      printf(" --stdio");
   if (opts & VERBOSE)
      printf(" --verbose");
   if (opts & KEEP_TMPFILES)
      printf(" --preserve");
   if (opts & KEEP_GOING)
      printf(" --keep-going");
}
J
John Bowler 已提交
251

252
#define FORMAT_NO_CHANGE 0x80000000 /* additional flag */
J
John Bowler 已提交
253 254 255 256

/* A name table for all the formats - defines the format of the '+' arguments to
 * pngstest.
 */
257
#define FORMAT_COUNT 64
258
#define FORMAT_MASK 0x3f
259
static PNG_CONST char * PNG_CONST format_names[FORMAT_COUNT] =
J
John Bowler 已提交
260 261 262 263 264 265 266 267 268
{
   "sRGB-gray",
   "sRGB-gray+alpha",
   "sRGB-rgb",
   "sRGB-rgb+alpha",
   "linear-gray",
   "linear-gray+alpha",
   "linear-rgb",
   "linear-rgb+alpha",
269 270 271 272 273 274 275 276 277 278

   "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 已提交
279 280 281 282 283 284 285 286
   "sRGB-gray",
   "sRGB-gray+alpha",
   "sRGB-bgr",
   "sRGB-bgr+alpha",
   "linear-gray",
   "linear-gray+alpha",
   "linear-bgr",
   "linear-bgr+alpha",
287 288 289 290 291 292 293 294 295 296

   "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 已提交
297 298 299 300 301 302 303 304
   "sRGB-gray",
   "alpha+sRGB-gray",
   "sRGB-rgb",
   "alpha+sRGB-rgb",
   "linear-gray",
   "alpha+linear-gray",
   "linear-rgb",
   "alpha+linear-rgb",
305 306 307 308 309 310 311 312 313 314

   "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 已提交
315 316 317 318 319 320 321 322
   "sRGB-gray",
   "alpha+sRGB-gray",
   "sRGB-bgr",
   "alpha+sRGB-bgr",
   "linear-gray",
   "alpha+linear-gray",
   "linear-bgr",
   "alpha+linear-bgr",
323 324 325 326 327 328 329 330 331

   "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 已提交
332 333 334 335 336 337 338
};

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

341
   if (ep > arg && *ep == 0 && format < FORMAT_COUNT)
342
      return (png_uint_32)format;
J
John Bowler 已提交
343

344
   else for (format=0; format < FORMAT_COUNT; ++format)
J
John Bowler 已提交
345 346
   {
      if (strcmp(format_names[format], arg) == 0)
347
         return (png_uint_32)format;
J
John Bowler 已提交
348 349 350
   }

   fprintf(stderr, "pngstest: format name '%s' invalid\n", arg);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
   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)
366
      pf->bits[i] = 0; /* All off */
367 368
}

369
#if 0 /* currently unused */
370 371 372 373 374 375
static void format_clear(format_list *pf)
{
   int i;
   for (i=0; i<FORMAT_SET_COUNT; ++i)
      pf->bits[i] = 0;
}
376
#endif
377 378 379 380 381

static int format_is_initial(format_list *pf)
{
   int i;
   for (i=0; i<FORMAT_SET_COUNT; ++i)
382
      if (pf->bits[i] != 0)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
         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;
J
John Bowler 已提交
410 411
}

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
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)
      {
         /* Eliminate redundant settings. */
         /* BGR is meaningless if no color: */
         if ((f & PNG_FORMAT_FLAG_COLOR) == 0 && (f & PNG_FORMAT_FLAG_BGR) != 0)
            continue;

         /* AFIRST is meaningless if no alpha: */
         if ((f & PNG_FORMAT_FLAG_ALPHA) == 0 &&
            (f & PNG_FORMAT_FLAG_AFIRST) != 0)
            continue;

         format_set(pf, f);
      }
   }
}

J
John Bowler 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
/* 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;
   png_size_t  input_memory_size;
   png_bytep   buffer;
   ptrdiff_t   stride;
   png_size_t  bufsize;
   png_size_t  allocsize;
461
   /* png_color   background; */
J
John Bowler 已提交
462
   char        tmpfile_name[32];
463
   png_uint_16 colormap[256*4];
J
John Bowler 已提交
464 465 466 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 545 546 547 548
}
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)
   {
      remove(image->tmpfile_name);
      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)
{
   png_size_t size = PNG_IMAGE_BUFFER_SIZE(image->image, image->stride);

   if (size+32 > image->bufsize)
   {
      freebuffer(image);
549
      image->buffer = voidcast(png_bytep, malloc(size+32));
J
John Bowler 已提交
550 551
      if (image->buffer == NULL)
      {
552
         fflush(stdout);
J
John Bowler 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
         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
568
check16(png_const_bytep bp, int b)
J
John Bowler 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
{
   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))
   {
585
      fflush(stdout);
J
John Bowler 已提交
586 587 588 589 590 591
      fprintf(stderr, "%s: overwrite at start of image buffer\n", arg);
      exit(1);
   }

   if (check16(image->buffer+16+image->allocsize, 95))
   {
592
      fflush(stdout);
J
John Bowler 已提交
593 594 595 596 597 598 599 600 601 602 603
      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)
{
604
   fflush(stdout);
J
John Bowler 已提交
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 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
   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", "");
   }

   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
{
   png_uint_32 format;
   png_uint_16 r16, g16, b16, y16, a16;
   png_byte    r8, g8, b8, y8, a8;
} Pixel;

/* This is not particularly fast, but it works.  The input has pixels stored
 * either as pre-multiplied linear 16-bit or as sRGB encoded non-pre-multiplied
662
 * 8-bit values.  The routine reads either and does exact conversion to the
J
John Bowler 已提交
663 664 665 666 667 668
 * other format.
 *
 * Grayscale values are mapped r==g==b=y.  Non-alpha images have alpha
 * 65535/255.  Color images have a correctly calculated Y value using the sRGB Y
 * calculation.
 *
669 670
 * Colors are looked up in the color map if required.
 *
J
John Bowler 已提交
671 672 673 674 675 676 677 678 679
 * The API returns false if an error is detected; this can only be if the alpha
 * value is less than the component in the linear case.
 */
static int 
get_pixel(Image *image, Pixel *pixel, png_const_bytep pp)
{
   png_uint_32 format = image->image.format;
   int result = 1;

680
   if (format & PNG_FORMAT_FLAG_COLORMAP)
681
      pp = (png_bytep)image->colormap + PNG_IMAGE_SAMPLE_SIZE(format) * *pp;
682

683
   pixel->format = format;
J
John Bowler 已提交
684 685 686 687 688

   /* Initialize the alpha values for opaque: */
   pixel->a8 = 255;
   pixel->a16 = 65535;

689
   switch (PNG_IMAGE_SAMPLE_COMPONENT_SIZE(format))
J
John Bowler 已提交
690 691
   {
      default:
692
         fflush(stdout);
693 694
         fprintf(stderr, "pngstest: impossible sample component size: %lu\n",
            (unsigned long)PNG_IMAGE_SAMPLE_COMPONENT_SIZE(format));
J
John Bowler 已提交
695 696 697 698
         exit(1);

      case sizeof (png_uint_16):
         {
699
            png_const_uint_16p up = (png_const_uint_16p)pp;
J
John Bowler 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
               pixel->a16 = *up++;

            if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
            {
               if ((format & PNG_FORMAT_FLAG_BGR) != 0)
               {
                  pixel->b16 = *up++;
                  pixel->g16 = *up++;
                  pixel->r16 = *up++;
               }

               else
               {
                  pixel->r16 = *up++;
                  pixel->g16 = *up++;
                  pixel->b16 = *up++;
               }

               /* Because the 'Y' calculation is linear the pre-multiplication
                * of the r16,g16,b16 values can be ignored.
                */
724 725
               pixel->y16 = u16d(YfromRGBint(pixel->r16, pixel->g16,
                  pixel->b16));
J
John Bowler 已提交
726 727 728 729 730 731 732 733 734 735 736 737
            }

            else
               pixel->r16 = pixel->g16 = pixel->b16 = pixel->y16 = *up++;

            if ((format & PNG_FORMAT_FLAG_AFIRST) == 0 &&
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
               pixel->a16 = *up++;

            /* 'a1' is 1/65535 * 1/alpha, for alpha in the range 0..1 */
            if (pixel->a16 == 0)
            {
738 739 740
               if (pixel->r16 > 0 || pixel->g16 > 0 || pixel->b16 > 0)
                  result = 0;

J
John Bowler 已提交
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 769
               pixel->r8 = pixel->g8 = pixel->b8 = pixel->y8 = 255;
               pixel->a8 = 0;
            }

            else
            {
               double a1 = 1. / pixel->a16;

               if (pixel->a16 < pixel->r16)
                  result = 0, pixel->r8 = 255;
               else
                  pixel->r8 = sRGB(pixel->r16 * a1);

               if (pixel->a16 < pixel->g16)
                  result = 0, pixel->g8 = 255;
               else
                  pixel->g8 = sRGB(pixel->g16 * a1);

               if (pixel->a16 < pixel->b16)
                  result = 0, pixel->b8 = 255;
               else
                  pixel->b8 = sRGB(pixel->b16 * a1);

               if (pixel->a16 < pixel->y16)
                  result = 0, pixel->y8 = 255;
               else
                  pixel->y8 = sRGB(pixel->y16 * a1);

               /* The 8-bit alpha value is just a16/257. */
770
               pixel->a8 = u8d(pixel->a16 / 257.);
J
John Bowler 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
            }
         }
         break;

      case sizeof (png_byte):
         {
            double y;

            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
               pixel->a8 = *pp++;

            if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
            {
               if ((format & PNG_FORMAT_FLAG_BGR) != 0)
               {
                  pixel->b8 = *pp++;
                  pixel->g8 = *pp++;
                  pixel->r8 = *pp++;
               }

               else
               {
                  pixel->r8 = *pp++;
                  pixel->g8 = *pp++;
                  pixel->b8 = *pp++;
               }

               /* The y8 value requires convert to linear, convert to &, convert
                * to sRGB:
                */
               y = YfromRGB(linear_from_sRGB(pixel->r8/255.),
                  linear_from_sRGB(pixel->g8/255.),
                  linear_from_sRGB(pixel->b8/255.));

               pixel->y8 = sRGB(y);
            }

            else
            {
               pixel->r8 = pixel->g8 = pixel->b8 = pixel->y8 = *pp++;
               y = linear_from_sRGB(pixel->y8/255.);
            }

            if ((format & PNG_FORMAT_FLAG_AFIRST) == 0 &&
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
               pixel->a8 = *pp++;

            pixel->r16 = ilineara(pixel->r8, pixel->a8);
            pixel->g16 = ilineara(pixel->g8, pixel->a8);
            pixel->b16 = ilineara(pixel->b8, pixel->a8);
822 823
            pixel->y16 = u16d((257 * pixel->a8) * y);
            pixel->a16 = (png_uint_16)(pixel->a8 * 257);
J
John Bowler 已提交
824 825 826 827 828 829 830 831 832 833 834
         }
         break;
   }

   return result;
}

/* Two pixels are equal if the value of the left equals the value of the right
 * as defined by the format of the right, or if it is close enough given the
 * permitted error limits.  If the formats match the values should (exactly!)
 *
835
 * If the right pixel has no alpha channel but the left does, it was removed
J
John Bowler 已提交
836 837 838 839 840 841 842
 * somehow.  For an 8-bit *output* removal uses the background color if given
 * else the default (the value filled in to the row buffer by allocbuffer()
 * above.)
 *
 * The result of this function is NULL if the pixels match else a reason why
 * they don't match.
 *
843
 * Error values below are inflated because some of the conversions are done
J
John Bowler 已提交
844 845 846 847
 * inside libpng using a simple power law transform of .45455 and others are
 * done in the simplified API code using the correct sRGB tables.  This needs
 * to be made consistent.
 */
848 849 850 851 852 853 854
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 = 11; /* by experiment */
static int error_in_compose = 0;
static int error_via_linear = 14; /* by experiment */
static int error_in_premultiply = 1;
J
John Bowler 已提交
855 856

static const char *
857 858
cmppixel(Pixel *a, Pixel *b, const png_color *background, int via_linear,
   int multiple_algorithms)
J
John Bowler 已提交
859
{
860
   int error_limit = 0;
J
John Bowler 已提交
861 862 863 864 865 866

   if (b->format & PNG_FORMAT_FLAG_LINEAR)
   {
      /* If the input was non-opaque then use the pre-multiplication error
       * limit.
       */
867 868
      if ((a->format & PNG_FORMAT_FLAG_ALPHA) && a->a16 < 65535 &&
         error_limit < error_in_premultiply)
J
John Bowler 已提交
869 870 871 872
         error_limit = error_in_premultiply;

      if (b->format & PNG_FORMAT_FLAG_ALPHA)
      {
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
         if ((b->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
            (a->format & PNG_FORMAT_FLAG_COLORMAP) != 0 ||
            (a->format & PNG_FORMAT_FLAG_ALPHA) == 0)
         {
            /* Expect an exact match. */
            if (b->a16 != a->a16)
               return "linear alpha mismatch";
         }

         else
         {
            /* Transform from non-color-mapped format with alpha to color-map
             * with alpha.  Most alphs is lost.
             */
            if (b->format & PNG_FORMAT_FLAG_COLOR)
            {
               /* Color; three levels of alpha (only!) */
               if (abs(b->a16 - a->a16) > 16384)
                  return "linear color-mapped color alpha mismatch";
            }

            else
            {
               /* Grayscale (GA palette), 6 levels of alpha. */
               if (abs(b->a16 - a->a16) > 6554)
                  return "linear color-mapped gray alpha mismatch";
            }

            /* If the alpha ends up as zero skip any check on the color
             * components.
             */
            if (b->a16 == 0 && b->y16 == 0)
               return NULL;
         }
J
John Bowler 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
      }

      else if (a->format & PNG_FORMAT_FLAG_ALPHA)
      {
         /* An alpha channel has been removed, the destination is linear so the
          * removal algorithm is just the premultiplication - compose on black -
          * and the 16-bit colors are correct already.
          */
      }

      if (b->format & PNG_FORMAT_FLAG_COLOR)
      {
         const char *err = "linear color mismatch";

         /* Check for an exact match. */
         if (a->r16 == b->r16 && a->g16 == b->g16 && a->b16 == b->b16)
            return NULL;

         /* Not an exact match; allow drift only if the input is 8-bit */
         if (!(a->format & PNG_FORMAT_FLAG_LINEAR))
         {
            if (error_limit < error_to_linear)
            {
               error_limit = error_to_linear;
931
               err = "sRGB to linear conversion error";
J
John Bowler 已提交
932 933 934
            }
         }

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
         /* Well, ok, if the file is color-mapped the color-mapping probably
          * used colors spaced at 51 in sRGB space, so there is massive drift to
          * be allowed here.
          */
         if (b->format & PNG_FORMAT_FLAG_COLORMAP)
         {
            /* If the input (a) was detectably grayscale then just permit the
             * grayscale errors; we require libpng to at least do this.
             */
            if ((a->format & PNG_FORMAT_FLAG_COLOR) == 0)
            {
               png_byte v = isRGB(a->y16);

               if (b->r8 == v && b->g8 == v && b->b8 == v)
                  return NULL;

               if ((a->format & PNG_FORMAT_FLAG_ALPHA) != 0 &&
                  (b->format & PNG_FORMAT_FLAG_ALPHA) == 0) /* alpha removed */
               {
                  /* Alpha was removed by compose-on-black; fix up the pixel a
                   * '8-bit' values to match.
                   */
                  a->r8 = isRGB(a->r16);
                  a->g8 = isRGB(a->g16);
                  a->b8 = isRGB(a->b16);
                  a->y8 = isRGB(a->y16);

                  if (b->y8 == 255 && a->y8 == 254)
                     return NULL; /* transparency hacked 254->255 */

                  else if (b->y8 == 254 && a->a8 != 0)
                     return "possible error in transparency hack (color)";
               }

               if ((b->format & PNG_FORMAT_FLAG_ALPHA) != 0)
               {
                  /* GA color-map; limited accuracy for opaque pixels, +/- 26
                   * accuracy for partially transparent ones.
                   */
                  if (error_limit < 1)
                     error_limit = 1;

                  if (a->a8 > 0 && a->a8 < 255)
                  {
                     if (error_limit < 26)
                        error_limit = 26;
                  }
               }
            }

            else /* input is not detectably grayscale */
            {
               /* The input was forced into an sRGB 666 color-map; error +/-26,
                * guess the error limit from the actual input values.
                */
               int red = (isRGB(a->r16)+25)/51;
               int green = (isRGB(a->g16)+25)/51;
               int blue = (isRGB(a->b16)+25)/51;

               if ((red-1)*51 <= b->r8 && (red+1)*51 >= b->r8 &&
                  (green-1)*51 <= b->g8 && (green+1)*51 >= b->g8 &&
                  (blue-1)*51 <= b->b8 && (blue+1)*51 >= b->b8)
                  return NULL;

               return "666 color-map error";
            }

            /* Now compare the 8-bit values, not the 16-bit ones. */
            if (compare_8bit(a->r8, b->r8, error_limit, multiple_algorithms) &&
               compare_8bit(a->g8, b->g8, error_limit, multiple_algorithms) &&
               compare_8bit(a->b8, b->b8, error_limit, multiple_algorithms))
               return NULL;

            return "linear color-map color mismatch";
         }

         else if (compare_16bit(a->r16, b->r16, error_limit,
               multiple_algorithms) &&
            compare_16bit(a->g16, b->g16, error_limit, multiple_algorithms) &&
            compare_16bit(a->b16, b->b16, error_limit, multiple_algorithms))
J
John Bowler 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
            return NULL;

         return err;
      }

      else /* b is grayscale */
      {
         const char *err = "linear gray mismatch";

         /* Check for an exact match. */
1025
         if (a->y16 == b->y16 && a->a16 == b->a16)
J
John Bowler 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
            return NULL;

         /* Not an exact match; allow drift only if the input is 8-bit or if it
          * has been converted from color.
          */
         if (!(a->format & PNG_FORMAT_FLAG_LINEAR))
         {
            /* Converted to linear, check for that drift. */
            if (error_limit < error_to_linear)
            {
               error_limit = error_to_linear;
1037
               err = "8-bit gray to linear conversion error";
J
John Bowler 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
            }

            if (abs(a->y16-b->y16) <= error_to_linear)
               return NULL;

         }

         if (a->format & PNG_FORMAT_FLAG_COLOR)
         {
            /* Converted to grayscale, allow drift */
            if (error_limit < error_to_linear_grayscale)
            {
               error_limit = error_to_linear_grayscale;
1051
               err = "color to linear gray conversion error";
J
John Bowler 已提交
1052 1053 1054
            }
         }

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
         if (b->format & PNG_FORMAT_FLAG_COLORMAP)
         {
            /* Forced into a colormap, since the format is a grayscale one we
             * can calculate the permitted error from the sRGB bucket the value
             * should fall into.
             */
            png_byte v = a->y8;

            if (b->y8 == v && a->a8 == b->a8)
               return NULL;

            if ((a->format & PNG_FORMAT_FLAG_ALPHA) != 0 &&
               (b->format & PNG_FORMAT_FLAG_ALPHA) == 0) /* alpha removed */
            {
               /* Alpha was removed by compose-on-black; fix up the pixel a
                * '8-bit' values to match.
                */
               a->r8 = isRGB(a->r16);
               a->g8 = isRGB(a->g16);
               a->b8 = isRGB(a->b16);
               a->y8 = isRGB(a->y16);

               if (b->y8 == 255 && a->y8 == 254)
                  return NULL; /* transparency hacked 254->255 */

               else if (b->y8 == 254 && a->a8 != 0)
                  return "possible error in transparency hack (gray)";
            }

            if ((b->format & PNG_FORMAT_FLAG_ALPHA) != 0)
            {
               /* GA color-map; limited accuracy for opaque pixels, +/- 26
                * accuracy for partially transparent ones.
                */
               if (error_limit < 1)
                  error_limit = 1;

               if (a->a8 > 0 && a->a8 < 255)
               {
                  if (error_limit < 26)
                     error_limit = 26;
               }
            }

            /* And compare the 8-bit values, not the 16-bit ones. */
            if (compare_8bit(a->y8, b->y8, error_limit, multiple_algorithms))
               return NULL;

            return "linear color-map gray mismatch";
         }

         else if (compare_16bit(a->y16, b->y16, error_limit,
            multiple_algorithms))
J
John Bowler 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
            return NULL;

         return err;
      }
   }

   else /* RHS is 8-bit */
   {
      const char *err;

      /* For 8-bit to 8-bit use 'error_via_linear'; this handles the cases where
1119
       * the original image is compared with the output of another conversion:
J
John Bowler 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
       * see where the parameter is set to non-zero below.
       */
      if (!(a->format & PNG_FORMAT_FLAG_LINEAR) && via_linear)
         error_limit = error_via_linear;

      if (b->format & PNG_FORMAT_FLAG_COLOR)
         err = "8-bit color mismatch";
      
      else
         err = "8-bit gray mismatch";

      /* If the original data had an alpha channel and was not pre-multiplied
       * pre-multiplication may lose precision in non-opaque pixel values.  If
       * the output is linear the premultiplied 16-bit values will be used, but
       * if 'via_linear' is set an intermediate 16-bit pre-multiplied form has
       * been used and this must be taken into account here.
       */
      if (via_linear && (a->format & PNG_FORMAT_FLAG_ALPHA) &&
         !(a->format & PNG_FORMAT_FLAG_LINEAR) &&
         a->a16 < 65535)
      {
         if (a->a16 > 0)
         {
            /* First calculate the rounded 16-bit component values, (r,g,b) or y
             * as appropriate, then back-calculate the 8-bit values for
             * comparison below.
             */
            if (a->format & PNG_FORMAT_FLAG_COLOR)
            {
1149 1150 1151
               double r = closestinteger((65535. * a->r16) / a->a16)/65535;
               double g = closestinteger((65535. * a->g16) / a->a16)/65535;
               double blue = closestinteger((65535. * a->b16) / a->a16)/65535;
J
John Bowler 已提交
1152

1153 1154 1155
               a->r16 = u16d(r * a->a16);
               a->g16 = u16d(g * a->a16);
               a->b16 = u16d(blue * a->a16);
1156
               a->y16 = u16d(YfromRGBint(a->r16, a->g16, a->b16));
J
John Bowler 已提交
1157

1158 1159 1160 1161
               a->r8 = u8d(r * 255);
               a->g8 = u8d(g * 255);
               a->b8 = u8d(blue * 255);
               a->y8 = u8d(255 * YfromRGB(r, g, blue));
J
John Bowler 已提交
1162 1163 1164 1165
            }

            else
            {
1166
               double y = closestinteger((65535. * a->y16) / a->a16)/65535.;
J
John Bowler 已提交
1167

1168 1169
               a->b16 = a->g16 = a->r16 = a->y16 = u16d(y * a->a16);
               a->b8 = a->g8 = a->r8 = a->y8 = u8d(255 * y);
J
John Bowler 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
            }
         }

         else
         {
            a->r16 = a->g16 = a->b16 = a->y16 = 0;
            a->r8 = a->g8 = a->b8 = a->y8 = 255;
         }
      }


      if (b->format & PNG_FORMAT_FLAG_ALPHA)
      {
         /* Expect an exact match on the 8 bit value. */
         if (b->a8 != a->a8)
            return "8-bit alpha mismatch";

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
         /* If the input was not color-mapped but the output is transparent
          * pixels will have been forced to just one palette entry, with the
          * value 255,255,255,0.
          */
         if ((a->format & PNG_FORMAT_FLAG_COLORMAP) == 0 &&
            (b->format & PNG_FORMAT_FLAG_COLORMAP) != 0 &&
             (a->format & PNG_FORMAT_FLAG_ALPHA) != 0 &&
             a->a16 == 0)
         {
            if (b->format & PNG_FORMAT_FLAG_COLOR)
            {
               if (b->r8 == 255 && b->g8 == 255 && b->b8 == 255 && b->a8 == 0)
                  return NULL;

               return "bad RGB color-map transparent entry";
            }

            else if (b->y8 == 255 && b->a8 == 0)
               return NULL;

            return "bad gray color-map transparent entry";
         }

J
John Bowler 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
         /* If the *input* was linear+alpha as well libpng will have converted
          * the non-premultiplied format directly to the sRGB non-premultiplied
          * format and the precision loss on an intermediate pre-multiplied
          * format will have been avoided.  In this case we will get spurious
          * values in the non-opaque pixels.
          */
         if (!via_linear && (a->format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
            (a->format & PNG_FORMAT_FLAG_ALPHA) != 0 &&
            a->a16 < 65535)
         {
            /* We don't know the original values (libpng has already removed
             * them) but we can make sure they are in range here by doing a
             * comparison on the pre-multiplied values instead.
             */
            if (a->a16 > 0)
            {
               if (b->format & PNG_FORMAT_FLAG_COLOR)
               {
                  double r, g, blue;

                  r = (255. * b->r16)/b->a16;
1231
                  b->r8 = u8d(r);
J
John Bowler 已提交
1232 1233

                  g = (255. * b->g16)/b->a16;
1234
                  b->g8 = u8d(g);
J
John Bowler 已提交
1235 1236

                  blue = (255. * b->b16)/b->a16;
1237
                  b->b8 = u8d(blue);
J
John Bowler 已提交
1238

1239
                  b->y8 = u8d(YfromRGB(r, g, blue));
J
John Bowler 已提交
1240 1241 1242 1243 1244
               }

               else
               {
                  b->r8 = b->g8 = b->b8 = b->y8 =
1245
                     u8d((255. * b->y16)/b->a16);
J
John Bowler 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
               }
            }

            else
               b->r8 = b->g8 = b->b8 = b->y8 = 255;
         }
      }

      else if (a->format & PNG_FORMAT_FLAG_ALPHA)
      {
1256
         png_uint_32 alpha;
J
John Bowler 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

         /* An alpha channel has been removed; the background will have been
          * composed in.  Adjust the 'a' pixel to represent this by doing the
          * correct compose.  Set the error limit, above, to an appropriate
          * value for the compose operation.
          */
         if (error_limit < error_in_compose)
            error_limit = error_in_compose;

         alpha = 65535 - a->a16; /* for the background */

         if (b->format & PNG_FORMAT_FLAG_COLOR) /* background is rgb */
         {
            err = "8-bit color compose error";

            if (via_linear)
            {
               /* The 16-bit values are already correct (being pre-multiplied),
                * just recalculate the 8-bit values.
                */
               a->r8 = isRGB(a->r16);
               a->g8 = isRGB(a->g16);
               a->b8 = isRGB(a->b16);
               a->y8 = isRGB(a->y16);

               /* There should be no libpng error in this (ideally) */
               error_limit = 0;
            }

            else if (background == NULL)
            {
               double add = alpha * linear_from_sRGB(BUFFER_INIT8/255.);
1289
               double r, g, blue, y;
J
John Bowler 已提交
1290 1291

               r = a->r16 + add;
1292
               a->r16 = u16d(r);
J
John Bowler 已提交
1293 1294 1295
               a->r8 = sRGB(r/65535);

               g = a->g16 + add;
1296
               a->g16 = u16d(g);
J
John Bowler 已提交
1297 1298
               a->g8 = sRGB(g/65535);

1299 1300 1301
               blue = a->b16 + add;
               a->b16 = u16d(blue);
               a->b8 = sRGB(blue/65535);
J
John Bowler 已提交
1302

1303 1304
               y = YfromRGB(r, g, blue);
               a->y16 = u16d(y);
J
John Bowler 已提交
1305 1306 1307 1308 1309
               a->y8 = sRGB(y/65535);
            }

            else
            {
1310
               double r, g, blue, y;
J
John Bowler 已提交
1311 1312

               r = a->r16 + alpha * linear_from_sRGB(background->red/255.);
1313
               a->r16 = u16d(r);
J
John Bowler 已提交
1314 1315 1316
               a->r8 = sRGB(r/65535);

               g = a->g16 + alpha * linear_from_sRGB(background->green/255.);
1317
               a->g16 = u16d(g);
J
John Bowler 已提交
1318 1319
               a->g8 = sRGB(g/65535);

1320 1321 1322
               blue = a->b16 + alpha * linear_from_sRGB(background->blue/255.);
               a->b16 = u16d(blue);
               a->b8 = sRGB(blue/65535);
J
John Bowler 已提交
1323

1324 1325
               y = YfromRGB(r, g, blue);
               a->y16 = u16d(y * 65535);
J
John Bowler 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
               a->y8 = sRGB(y);
            }
         }

         else /* background is gray */
         {
            err = "8-bit gray compose error";

            if (via_linear)
            {
               a->r8 = a->g8 = a->b8 = a->y8 = isRGB(a->y16);
               error_limit = 0;
            }

            else
            {
               /* When the output is gray the background comes from just the
                * green channel.
                */
               double y = a->y16 + alpha * linear_from_sRGB(
                  (background == NULL ? BUFFER_INIT8 : background->green)/255.);

1348
               a->r16 = a->g16 = a->b16 = a->y16 = u16d(y);
J
John Bowler 已提交
1349 1350 1351
               a->r8 = a->g8 = a->b8 = a->y8 = sRGB(y/65535);
            }
         }
1352 1353 1354 1355 1356

         /* NOTE: the alpha channel is the original one, so logpixel will show
          * the original alpha but the composed color channels.  This gives
          * linear values that are apparently wrong on error, but is useful.
          */
J
John Bowler 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365
      }

      if (b->format & PNG_FORMAT_FLAG_COLOR)
      {

         /* Check for an exact match. */
         if (a->r8 == b->r8 && a->g8 == b->g8 && a->b8 == b->b8)
            return NULL;

1366
         /* Check for linear to 8-bit conversion. */
J
John Bowler 已提交
1367 1368 1369 1370
         if (a->format & PNG_FORMAT_FLAG_LINEAR)
         {
            if (error_limit < error_to_sRGB)
            {
1371
               err = "linear to sRGB conversion error";
J
John Bowler 已提交
1372 1373 1374 1375
               error_limit = error_to_sRGB;
            }
         }

1376 1377 1378 1379 1380 1381 1382 1383 1384
         /* Check for color-map trashing. */
         if (b->format & PNG_FORMAT_FLAG_COLORMAP)
         {
            /* The data has been forced into an RGB666 colormap.  Unless the
             * original was detectably grayscale or color-mapped (we expect
             * color maps to be preserved.)
             */
            if ((a->format & PNG_FORMAT_FLAG_COLOR) == 0)
            {
1385
               /* grayscale input, currently generates no additional errors */
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
            }

            else if ((a->format & PNG_FORMAT_FLAG_COLORMAP) == 0)
            {
               /* color-map input */
               if (error_limit < 26)
                  error_limit = 26;
            }

            else
            {
               /* Color-map to color-map: expect no errors. */
            }
         }

         if (compare_8bit(a->r8, b->r8, error_limit, multiple_algorithms) &&
            compare_8bit(a->g8, b->g8, error_limit, multiple_algorithms) &&
            compare_8bit(a->b8, b->b8, error_limit, multiple_algorithms))
J
John Bowler 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            return NULL;

         return err;
      }

      else /* b is grayscale */
      {
         /* Check for an exact match. */
         if (a->y8 == b->y8)
            return NULL;

         /* Not an exact match; allow drift only if the input is linear or if it
          * has been converted from color.
          */
         if (a->format & PNG_FORMAT_FLAG_LINEAR)
         {
            /* Converted to linear, check for that drift. */
            if (error_limit < error_to_sRGB)
            {
               error_limit = error_to_sRGB;
1424
               err = "linear to 8-bit gray conversion error";
J
John Bowler 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433
            }
         }

         if (a->format & PNG_FORMAT_FLAG_COLOR)
         {
            /* Converted to grayscale, allow drift */
            if (error_limit < error_to_sRGB_grayscale)
            {
               error_limit = error_to_sRGB_grayscale;
1434
               err = "color to 8-bit gray conversion error";
J
John Bowler 已提交
1435 1436 1437
            }
         }

1438
         if (compare_8bit(a->y8, b->y8, error_limit, multiple_algorithms))
J
John Bowler 已提交
1439 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
            return NULL;

         return err;
      }
   }
}

/* 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)

static void
print_pixel(char string[64], Pixel *pixel)
{
   switch (pixel->format & BASE_FORMATS)
   {
      case 0: /* 8-bit, one channel */
         sprintf(string, "%s(%d)", format_names[pixel->format], pixel->y8);
         break;

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

      case PNG_FORMAT_FLAG_COLOR:
         sprintf(string, "%s(%d,%d,%d)", format_names[pixel->format],
            pixel->r8, pixel->g8, pixel->b8);
         break;

      case PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA:
         sprintf(string, "%s(%d,%d,%d,%d)", format_names[pixel->format],
            pixel->r8, pixel->g8, pixel->b8, pixel->a8);
         break;

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

      case PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_ALPHA:
         sprintf(string, "%s(%d,%d)", format_names[pixel->format], pixel->y16,
            pixel->a16);
         break;

      case PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR:
         sprintf(string, "%s(%d,%d,%d)", format_names[pixel->format],
            pixel->r16, pixel->g16, pixel->b16);
         break;

      case PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA:
         sprintf(string, "%s(%d,%d,%d,%d)", format_names[pixel->format],
            pixel->r16, pixel->g16, pixel->b16, pixel->a16);
         break;
1492 1493 1494 1495

      default:
         sprintf(string, "invalid-format");
         break;
J
John Bowler 已提交
1496 1497 1498 1499
   }
}

static int
1500 1501
logpixel(Image *original, Image *copy, png_uint_32 x, png_uint_32 y, Pixel *a,
   Pixel *b, const char *reason)
J
John Bowler 已提交
1502 1503 1504 1505 1506
{
   char pixel_a[64], pixel_b[64];

   print_pixel(pixel_a, a);
   print_pixel(pixel_b, b);
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
   if (original->file_name != copy->file_name)
   {
      char error_buffer[256];
      sprintf(error_buffer,
         "(%lu,%lu) %s:\n\t%s ->\n\t\t%s\n\tUse --preserve and examine: ",
         (unsigned long)x, (unsigned long)y, reason, pixel_a, pixel_b);
      return logerror(original, original->file_name, error_buffer,
         copy->file_name);
   }

   else
   {
      char error_buffer[256];
      sprintf(error_buffer,
         "(%lu,%lu) %s:\n\t%s ->\n\t\t%s.\n"
         "\tThe error happened when reading the original file with this format",
         (unsigned long)x, (unsigned long)y, reason, pixel_a, pixel_b);
      return logerror(original, original->file_name, error_buffer, "");
   }
}

static int
badpixel(Image *ia, png_uint_32 x, png_uint_32 y, Pixel *pa, const char *reason)
{
   char pixel_a[64];
   char error_buffer[128];

   print_pixel(pixel_a, pa);
   sprintf(error_buffer, "(%lu,%lu) %s: ", (unsigned long)x, (unsigned long)y,
      reason);
   return logerror(ia, ia->file_name, error_buffer, pixel_a);
J
John Bowler 已提交
1538 1539 1540 1541 1542 1543
}

/* 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
1544 1545
compare_two_images(Image *a, Image *b, int via_linear,
   png_const_colorp background)
J
John Bowler 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554
{
   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;
   ptrdiff_t stridea = a->stride;
   ptrdiff_t strideb = b->stride;
   png_const_bytep rowa = a->buffer+16;
   png_const_bytep rowb = b->buffer+16;
1555
   png_byte channels;
1556 1557
   int fast_track = 0;
   int two_algorithms = ((formata ^ formatb) & PNG_FORMAT_FLAG_COLORMAP) != 0;
J
John Bowler 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
   int result = 1;
   unsigned int check_alpha = 0; /* must be zero or one */
   png_byte swap_mask[4];
   png_uint_32 x, y;
   png_const_bytep ppa, ppb;

   /* 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);

   /* Find the first row and inter-row space. */
1570 1571 1572
   if (!(formata & PNG_FORMAT_FLAG_COLORMAP) &&
      (formata & PNG_FORMAT_FLAG_LINEAR))
      stridea *= 2;
J
John Bowler 已提交
1573

1574 1575 1576
   if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) &&
      (formatb & PNG_FORMAT_FLAG_LINEAR))
      strideb *= 2;
J
John Bowler 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

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

   /* The following are used only if the formats match, except that 'channels'
    * is a flag for matching formats.
    */
   channels = 0;
   swap_mask[3] = swap_mask[2] = swap_mask[1] = swap_mask[0] = 0;

   /* Set up the masks if no base format change, or if the format change was
1588 1589
    * just to add an alpha channel (note that this ignores whether or not the
    * image is color-mapped.)
J
John Bowler 已提交
1590
    */
1591 1592
   if (((formata & BASE_FORMATS) == (formatb & BASE_FORMATS)) ||
      ((formata | PNG_FORMAT_FLAG_ALPHA) & BASE_FORMATS) ==
J
John Bowler 已提交
1593 1594
         (formatb & BASE_FORMATS))
   {
1595 1596
      png_byte astart = 0; /* index of first component */
      png_byte bstart = 0;
J
John Bowler 已提交
1597 1598

      /* Set to the actual number of channels in 'a' */
1599 1600 1601 1602
      if (formata & PNG_FORMAT_FLAG_COLOR)
         channels = 3U;
      else
         channels = 1U;
J
John Bowler 已提交
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

      if (formata & PNG_FORMAT_FLAG_ALPHA)
      {
         /* Both formats have an alpha channel */
         if (formata & PNG_FORMAT_FLAG_AFIRST)
         {
            astart = 1;

            if (formatb & PNG_FORMAT_FLAG_AFIRST)
            {
               bstart = 1;
               swap_mask[0] = 0;
            }

            else
               swap_mask[0] = channels; /* 'b' alpha is at end */
         }

         else if (formatb & PNG_FORMAT_FLAG_AFIRST)
         {
            /* 'a' alpha is at end, 'b' is at start (0) */
            bstart = 1;
            swap_mask[channels] = 0;
         }

         else
            swap_mask[channels] = channels;

         ++channels;
      }

      else if (formatb & PNG_FORMAT_FLAG_ALPHA)
      {
         /* Only 'b' has an alpha channel */
         check_alpha = 1;
         if (formatb & PNG_FORMAT_FLAG_AFIRST)
         {
            bstart = 1;
            /* Put the location of the alpha channel in swap_mask[3], since it
             * cannot be used if 'a' does not have an alpha channel.
             */
            swap_mask[3] = 0;
         }

         else
            swap_mask[3] = channels;
      }

      if (formata & PNG_FORMAT_FLAG_COLOR)
      {
         unsigned int swap = 0;

         /* Colors match, but are they swapped? */
         if ((formata ^ formatb) & PNG_FORMAT_FLAG_BGR) /* Swapped. */
            swap = 2;

1659 1660 1661
         swap_mask[astart+0] = (png_byte)(bstart+(0^swap));
         swap_mask[astart+1] = (png_byte)(bstart+1);
         swap_mask[astart+2] = (png_byte)(bstart+(2^swap));
J
John Bowler 已提交
1662 1663 1664 1665
      }

      else /* grayscale: 1 channel */
         swap_mask[astart] = bstart;
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

      /* Now work out if the fast-track match is possible - the byte
       * representations need to be equivalent (apart from the addition of an
       * opaque alpha channel) but allow indirection via a color-map
       */
      {
         png_uint_32 f = (formata & formatb);

         if (formata & PNG_FORMAT_FLAG_COLORMAP)
            fast_track += 4; /* image a color-mapped */

         if (formatb & PNG_FORMAT_FLAG_COLORMAP)
            fast_track += 8; /* image b color-mapped */

         if (fast_track == 12)
         {
            /* Do the color-maps match, entry by entry?   Always do this the
             * slow way unless the maps are identical, the number of entries
             * must match.
             */
            unsigned int entries = a->image.colormap_entries;

            if (entries == b->image.colormap_entries)
            {
               unsigned int entry = 0;

               while (entry < entries)
               {
                  Pixel pixel_a, pixel_b;
                  png_byte p = (png_byte)entry;

                  if (!get_pixel(a, &pixel_a, &p))
                     return badpixel(a, entry, 0, &pixel_a,
                        "bad palette entry value");

                  if (!get_pixel(b, &pixel_b, &p))
                     return badpixel(b, entry, 0, &pixel_b,
                        "bad palette entry value");

                  if (cmppixel(&pixel_a, &pixel_b, background, via_linear,
                     0/*multiple_algorithms*/) != NULL)
                     break;

                  ++entry;
               }

               /* both sides color-mapped, color-maps match */
               if (entry == entries)
                  fast_track += 1;

               /* else color-map entries are mismatched so compare pixel by
                * pixel.
                */
            }
         }

         else if (f & PNG_FORMAT_FLAG_LINEAR)
            fast_track += 2; /* linear */

         else if (!((formata | formatb) & PNG_FORMAT_FLAG_LINEAR))
            fast_track += 3; /* sRGB */
      }
J
John Bowler 已提交
1728 1729 1730 1731 1732 1733 1734
   }

   ppa = rowa;
   ppb = rowb;
   for (x=y=0; y<height;)
   {
      /* Do the fast test if possible. */
1735
      switch (fast_track)
J
John Bowler 已提交
1736
      {
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
         case 8+4+1: /* both sides color-mapped and color-maps match */
            while (x < width)
            {
               if (ppa[0] != ppb[0])
                  break;

               /* This pixel matches, advance to the next. */
               ++ppa;
               ++ppb;
               ++x;
            }
            break;

         case 2: /* both sides double byte, neither color-mapped */
J
John Bowler 已提交
1751
            {
1752 1753
               png_const_uint_16p lppa = (png_const_uint_16p)ppa;
               png_const_uint_16p lppb = (png_const_uint_16p)ppb;
J
John Bowler 已提交
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

               while (x < width) switch (channels)
               {
                  case 4:
                     if (lppa[3] != lppb[swap_mask[3]])
                        goto linear_mismatch;
                  case 3:
                     if (lppa[2] != lppb[swap_mask[2]])
                        goto linear_mismatch;
                  case 2:
                     if (lppa[1] != lppb[swap_mask[1]])
                        goto linear_mismatch;
                  case 1:
                     if (lppa[0] != lppb[swap_mask[0]])
                        goto linear_mismatch;

                     /* The pixels apparently match, but if an alpha channel has
                      * been added (in b) it must be 65535 too.
                      */
                     if (check_alpha && 65535 != lppb[swap_mask[3]])
                        goto linear_mismatch;

                     /* This pixel matches, advance to the next. */
                     lppa += channels;
                     lppb += channels + check_alpha;
                     ++x;
1780
                  default:
1781
                     goto linear_mismatch;
J
John Bowler 已提交
1782 1783 1784
               }

            linear_mismatch:
1785 1786
               ppa = (png_const_bytep)lppa;
               ppb = (png_const_bytep)lppb;
J
John Bowler 已提交
1787 1788 1789
            }
            break;

1790 1791 1792 1793 1794 1795
         case 4+2: /* both sides double byte, imagea is color-mapped */
            {
               png_const_uint_16p lppb = (png_const_uint_16p)ppb;

               while (x < width)
               {
1796
                  png_const_uint_16p lppa = a->colormap + channels * *ppa;
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

                  switch (channels)
                  {
                     case 4:
                        if (lppa[3] != lppb[swap_mask[3]])
                           goto linear_colormapa_mismatch;
                     case 3:
                        if (lppa[2] != lppb[swap_mask[2]])
                           goto linear_colormapa_mismatch;
                     case 2:
                        if (lppa[1] != lppb[swap_mask[1]])
                           goto linear_colormapa_mismatch;
                     case 1:
                        if (lppa[0] != lppb[swap_mask[0]])
                           goto linear_colormapa_mismatch;

                        /* The pixels apparently match, but if an alpha channel
                         * has been added (in b) it must be 65535 too.
                         */
                        if (check_alpha && 65535 != lppb[swap_mask[3]])
                           goto linear_colormapa_mismatch;

                        /* This pixel matches, advance to the next. */
                        ppa += 1;
                        lppb += channels + check_alpha;
                        ++x;
                     default:
                        goto linear_colormapa_mismatch;
                  }
               }

            linear_colormapa_mismatch:
               ppb = (png_const_bytep)lppb;
            }
            break;

         case 8+2: /* both sides double byte, imageb color-mapped */
            {
               png_const_uint_16p lppa = (png_const_uint_16p)ppa;

               while (x < width)
               {
1839
                  png_const_uint_16p lppb = b->colormap + channels * *ppb;
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

                  switch (channels)
                  {
                     case 4:
                        if (lppa[3] != lppb[swap_mask[3]])
                           goto linear_colormapb_mismatch;
                     case 3:
                        if (lppa[2] != lppb[swap_mask[2]])
                           goto linear_colormapb_mismatch;
                     case 2:
                        if (lppa[1] != lppb[swap_mask[1]])
                           goto linear_colormapb_mismatch;
                     case 1:
                        if (lppa[0] != lppb[swap_mask[0]])
                           goto linear_colormapb_mismatch;

                        /* The pixels apparently match, but if an alpha channel
                         * has been added (in b) it must be 65535 too.
                         */
                        if (check_alpha && 65535 != lppb[swap_mask[3]])
                           goto linear_colormapb_mismatch;

                        /* This pixel matches, advance to the next. */
                        lppa += channels;
                        ppb += 1;
                        ++x;
                     default:
                        goto linear_colormapb_mismatch;
                  }
               }

            linear_colormapb_mismatch:
               ppa = (png_const_bytep)lppa;
            }
            break;

         case 3: /* both sides sRGB, neither color-mapped */
J
John Bowler 已提交
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
            while (x < width) switch (channels)
            {
               case 4:
                  if (ppa[3] != ppb[swap_mask[3]])
                     goto sRGB_mismatch;
               case 3:
                  if (ppa[2] != ppb[swap_mask[2]])
                     goto sRGB_mismatch;
               case 2:
                  if (ppa[1] != ppb[swap_mask[1]])
                     goto sRGB_mismatch;
               case 1:
                  if (ppa[0] != ppb[swap_mask[0]])
                     goto sRGB_mismatch;

                  /* The pixels apparently match, but if an alpha channel has
1893
                   * been added (in b) it must be 1.0 too.
J
John Bowler 已提交
1894
                   */
1895
                  if (check_alpha && 255 != ppb[swap_mask[3]])
J
John Bowler 已提交
1896 1897 1898 1899 1900 1901
                     goto sRGB_mismatch;

                  /* This pixel matches, advance to the next. */
                  ppa += channels;
                  ppb += channels + check_alpha;
                  ++x;
1902
               default:
1903
                  goto sRGB_mismatch;
J
John Bowler 已提交
1904 1905 1906 1907 1908
            }

         sRGB_mismatch:
            break;

1909
         case 4+3: /* both sides sRGB, imagea color-mapped */
1910
            while (x < width)
1911
            {
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
               png_const_bytep colormap_a = (png_const_bytep)a->colormap;
               
               switch (channels)
               {
                  case 4:
                     if (colormap_a[ppa[3]] != ppb[swap_mask[3]])
                        goto sRGB_colormapa_mismatch;
                  case 3:
                     if (colormap_a[ppa[2]] != ppb[swap_mask[2]])
                        goto sRGB_colormapa_mismatch;
                  case 2:
                     if (colormap_a[ppa[1]] != ppb[swap_mask[1]])
                        goto sRGB_colormapa_mismatch;
                  case 1:
                     if (colormap_a[ppa[0]] != ppb[swap_mask[0]])
                        goto sRGB_mismatch;
1928

1929 1930 1931 1932 1933
                     /* The pixels apparently match, but if an alpha channel has
                      * been added (in b) it must be 1.0 too.
                      */
                     if (check_alpha && 255 != ppb[swap_mask[3]])
                        goto sRGB_colormapa_mismatch;
1934

1935 1936 1937 1938 1939 1940 1941
                     /* This pixel matches, advance to the next. */
                     ppa += 1;
                     ppb += channels + check_alpha;
                     ++x;
                  default:
                     goto sRGB_colormapa_mismatch;
               }
1942 1943 1944 1945 1946 1947
            }

         sRGB_colormapa_mismatch:
            break;

         case 8+3: /* both sides sRGB, imageb color-mapped */
1948
            while (x < width)
1949
            {
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
               png_const_bytep colormap_b = (png_const_bytep)b->colormap;
               
               switch (channels)
               {
                  case 4:
                     if (ppa[3] != colormap_b[ppb[swap_mask[3]]])
                        goto sRGB_colormapb_mismatch;
                  case 3:
                     if (ppa[2] != colormap_b[ppb[swap_mask[2]]])
                        goto sRGB_colormapb_mismatch;
                  case 2:
                     if (ppa[1] != colormap_b[ppb[swap_mask[1]]])
                        goto sRGB_colormapb_mismatch;
                  case 1:
                     if (ppa[0] != colormap_b[ppb[swap_mask[0]]])
                        goto sRGB_colormapb_mismatch;
1966

1967 1968 1969 1970 1971
                     /* The pixels apparently match, but if an alpha channel has
                      * been added (in b) it must be 1.0 too.
                      */
                     if (check_alpha && 255 != colormap_b[ppb[swap_mask[3]]])
                        goto sRGB_colormapb_mismatch;
1972

1973 1974 1975 1976 1977 1978 1979
                     /* This pixel matches, advance to the next. */
                     ppa += channels;
                     ppb += 1;
                     ++x;
                  default:
                     goto sRGB_colormapb_mismatch;
               }
1980 1981 1982 1983 1984
            }

         sRGB_colormapb_mismatch:
            break;

J
John Bowler 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
         default: /* formats do not match */
            break;
      }

      /* If at the end of the row advance to the next row, if not at the end
       * compare the pixels the slow way.
       */
      if (x < width)
      {
         Pixel pixel_a, pixel_b;
         const char *mismatch;

1997 1998 1999 2000 2001 2002 2003 2004
         if (!get_pixel(a, &pixel_a, ppa))
            return badpixel(a, x, y, &pixel_a, "bad pixel value");

         if (!get_pixel(b, &pixel_b, ppb))
            return badpixel(b, x, y, &pixel_b, "bad pixel value");

         mismatch = cmppixel(&pixel_a, &pixel_b, background, via_linear,
            two_algorithms);
J
John Bowler 已提交
2005 2006 2007

         if (mismatch != NULL)
         {
2008
            (void)logpixel(a, b, x, y, &pixel_a, &pixel_b, mismatch);
J
John Bowler 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

            if ((a->opts & KEEP_GOING) == 0)
               return 0;

            result = 0;
         }

         ++x;
      }

      if (x >= width)
      {
         x = 0;
         ++y;
         rowa += stridea;
         rowb += strideb;
         ppa = rowa;
         ppb = rowb;
      }
   }

   return result;
}

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

J
John Bowler 已提交
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
   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, "");
   }

   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, "");
   }

   else
   {
      if (!png_image_begin_read_from_file(&image->image, image->file_name))
         return logerror(image, "file init: ", image->file_name, "");
   }

   /* 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;
2066
      png_uint_32 image_format;
J
John Bowler 已提交
2067 2068

      /* Print both original and output formats. */
2069 2070
      image_format = image->image.format;

J
John Bowler 已提交
2071
      if (image->opts & VERBOSE)
2072 2073
      {
         printf("%s %lu x %lu %s -> %s", image->file_name,
J
John Bowler 已提交
2074 2075
            (unsigned long)image->image.width,
            (unsigned long)image->image.height,
2076
            format_names[image_format & FORMAT_MASK],
J
John Bowler 已提交
2077
            (format & FORMAT_NO_CHANGE) != 0 || image->image.format == format
2078
            ? "no change" : format_names[format & FORMAT_MASK]);
J
John Bowler 已提交
2079

2080 2081 2082 2083 2084 2085 2086 2087 2088
         if (background != NULL)
            printf(" background(%d,%d,%d)\n", background->red,
               background->green, background->blue);
         else
            printf("\n");

         fflush(stdout);
      }

2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
      /* '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;
      }

      image->image.format = format;

J
John Bowler 已提交
2105 2106 2107
      image->stride = PNG_IMAGE_ROW_STRIDE(image->image) + image->stride_extra;
      allocbuffer(image);

2108
      result = png_image_finish_read(&image->image, background,
2109
         image->buffer+16, (png_int_32)image->stride, image->colormap);
J
John Bowler 已提交
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

      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
2122 2123
 * image->opts to choose the method.  The file is always read in its native
 * format (the one the simplified API suggests).
J
John Bowler 已提交
2124 2125
 */
static int
2126
read_one_file(Image *image)
J
John Bowler 已提交
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
{
   if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO))
   {
      /* memory or stdio. */
      FILE *f = fopen(image->file_name, "rb");

      if (f != NULL)
      {
         if (image->opts & READ_FILE)
            image->input_file = f;

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

2144
               if (cb >= 0 && (unsigned long int)cb < (size_t)~(size_t)0)
J
John Bowler 已提交
2145
               {
2146
                  png_bytep b = voidcast(png_bytep, malloc((size_t)cb));
J
John Bowler 已提交
2147 2148 2149 2150 2151

                  if (b != NULL)
                  {
                     rewind(f);

2152
                     if (fread(b, (size_t)cb, 1, f) == 1)
J
John Bowler 已提交
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
                     {
                        fclose(f);
                        image->input_memory_size = cb;
                        image->input_memory = b;
                     }

                     else
                     {
                        free(b);
                        return logclose(image, f, image->file_name,
                           ": read failed");
                     }
                  }

                  else
                     return logclose(image, f, image->file_name,
                        ": out of memory");
               }

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

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

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

2186
   return read_file(image, FORMAT_NO_CHANGE, NULL);
J
John Bowler 已提交
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
}

static int
write_one_file(Image *output, Image *image, int convert_to_8bit)
{
   if (image->opts & USE_STDIO)
   {
      FILE *f = tmpfile();

      if (f != NULL)
      {
         if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
2199
            image->buffer+16, (png_int_32)image->stride, image->colormap))
J
John Bowler 已提交
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
         {
            if (fflush(f) == 0)
            {
               rewind(f);
               initimage(output, image->opts, "tmpfile", image->stride_extra);
               output->input_file = f;
               if (!checkopaque(image))
                  return 0;
            }

            else
               return logclose(image, f, "tmpfile", ": flush");
         }

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

      else
         return logerror(image, "tmpfile", ": open: ", strerror(errno));
   }

   else
   {
      static int counter = 0;
      char name[32];

2230
      sprintf(name, "TMP%d.png", ++counter);
J
John Bowler 已提交
2231 2232

      if (png_image_write_to_file(&image->image, name, convert_to_8bit,
2233
         image->buffer+16, (png_int_32)image->stride, image->colormap))
J
John Bowler 已提交
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
      {
         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", "");
   }

   /* '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.
2251 2252 2253
    * 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 已提交
2254
    */
2255
   if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
J
John Bowler 已提交
2256
   {
2257 2258 2259 2260 2261
      png_uint_32 original_format = image->image.format;

      if (convert_to_8bit)
         original_format &= ~PNG_FORMAT_FLAG_LINEAR;

J
John Bowler 已提交
2262
      if ((output->image.format & BASE_FORMATS) !=
2263 2264
         (original_format & BASE_FORMATS))
         return logerror(image, image->file_name, ": format changed on read: ",
J
John Bowler 已提交
2265 2266
            output->file_name);

2267
      return compare_two_images(image, output, 0/*via linear*/, NULL);
J
John Bowler 已提交
2268 2269 2270 2271 2272 2273 2274 2275
   }

   else
      return logerror(output, output->tmpfile_name,
         ": read of new file failed", "");
}

static int
2276
testimage(Image *image, png_uint_32 opts, format_list *pf)
J
John Bowler 已提交
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
{
   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;

   {
2296
      png_uint_32 counter;
J
John Bowler 已提交
2297 2298 2299 2300 2301
      Image output;

      newimage(&output);
      
      result = 1;
2302 2303 2304 2305 2306 2307 2308

      /* 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 已提交
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 2349
         png_uint_32 format = counter >> 1;

         png_color background_color;
         png_colorp background = NULL;

         /* 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.
          */
         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 */


J
John Bowler 已提交
2350
         resetimage(&copy);
2351 2352 2353
         copy.opts = opts; /* in case read_file needs to change it */

         result = read_file(&copy, format, background);
J
John Bowler 已提交
2354 2355 2356 2357
         if (!result)
            break;

         /* Make sure the file just read matches the original file. */
2358
         result = compare_two_images(image, &copy, 0/*via linear*/, background);
J
John Bowler 已提交
2359 2360 2361 2362
         if (!result)
            break;

         /* Write the *copy* just made to a new file to make sure the write side
2363
          * works ok.  Check the conversion to sRGB if the copy is linear.
J
John Bowler 已提交
2364
          */
2365
         output.opts = opts;
J
John Bowler 已提交
2366 2367 2368 2369
         result = write_one_file(&output, &copy, 0/*convert to 8bit*/);
         if (!result)
            break;

2370 2371 2372 2373
         /* Validate against the original too; the background is needed here
          * as well so that compare_two_images knows what color was used.
          */
         result = compare_two_images(image, &output, 0, background);
J
John Bowler 已提交
2374 2375 2376
         if (!result)
            break;

2377 2378
         if ((format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
            (format & PNG_FORMAT_FLAG_COLORMAP) == 0)
J
John Bowler 已提交
2379 2380
         {
            /* 'output' is linear, convert to the corresponding sRGB format. */
2381
            output.opts = opts;
J
John Bowler 已提交
2382 2383 2384 2385
            result = write_one_file(&output, &copy, 1/*convert to 8bit*/);
            if (!result)
               break;

2386
            /* This may involve a conversion via linear; in the ideal world this
J
John Bowler 已提交
2387 2388 2389 2390 2391 2392 2393 2394
             * 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.
             */
2395 2396
            result = compare_two_images(image, &output, 1/*via_linear*/,
               background);
J
John Bowler 已提交
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
            if (!result)
               break;
         }
      }

      freeimage(&output);
   }

   freeimage(&copy);

   return result;
}

int
2411
main(int argc, char **argv)
J
John Bowler 已提交
2412 2413
{
   png_uint_32 opts = 0;
2414
   format_list formats;
2415
   const char *touch = NULL;
2416
   int log_pass = 0;
2417
   int redundant = 0;
J
John Bowler 已提交
2418
   int stride_extra = 0;
2419
   int retval = 0;
J
John Bowler 已提交
2420 2421
   int c;

2422 2423
   format_init(&formats);

J
John Bowler 已提交
2424 2425 2426 2427
   for (c=1; c<argc; ++c)
   {
      const char *arg = argv[c];

2428 2429 2430
      if (strcmp(arg, "--log") == 0)
         log_pass = 1;
      else if (strcmp(arg, "--file") == 0)
J
John Bowler 已提交
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
         opts |= READ_FILE;
      else if (strcmp(arg, "--memory") == 0)
         opts &= ~READ_FILE;
      else if (strcmp(arg, "--stdio") == 0)
         opts |= USE_STDIO;
      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;
2448 2449
      else if (strcmp(arg, "--redundant") == 0)
         redundant = 1;
J
John Bowler 已提交
2450 2451
      else if (strcmp(arg, "--stop") == 0)
         opts &= ~KEEP_GOING;
2452 2453 2454 2455 2456 2457 2458
      else if (strcmp(arg, "--touch") == 0)
      {
         if (c+1 < argc)
            touch = argv[++c];

         else
         {
2459
            fflush(stdout);
2460 2461 2462 2463 2464
            fprintf(stderr, "%s: %s requires a file name argument\n",
               argv[0], arg);
            exit(1);
         }
      }
J
John Bowler 已提交
2465 2466 2467 2468
      else if (arg[0] == '+')
      {
         png_uint_32 format = formatof(arg+1);

2469
         if (format > FORMAT_COUNT)
J
John Bowler 已提交
2470 2471
            exit(1);

2472
         format_set(&formats, format);
J
John Bowler 已提交
2473 2474 2475
      }
      else if (arg[0] == '-')
      {
2476
         fflush(stdout);
J
John Bowler 已提交
2477 2478 2479 2480 2481 2482 2483 2484
         fprintf(stderr, "%s: unknown option: %s\n", argv[0], arg);
         exit(1);
      }
      else
      {
         int result;
         Image image;

2485 2486 2487
         if (format_is_initial(&formats))
            format_default(&formats, redundant);

J
John Bowler 已提交
2488 2489
         newimage(&image);
         initimage(&image, opts, arg, stride_extra);
2490
         result = read_one_file(&image);
J
John Bowler 已提交
2491
         if (result)
2492
            result = testimage(&image, opts, &formats);
J
John Bowler 已提交
2493 2494
         freeimage(&image);

2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
         if (log_pass)
         {
            if (result)
               printf("PASS:");

            else
            {
               printf("FAIL:");
               retval = 1;
            }

            print_opts(opts);
            printf(" %s\n", arg);
         }

         else if (!result)
J
John Bowler 已提交
2511 2512 2513 2514
            exit(1);
      }
   }

2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
   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)
         {
2528
            fflush(stdout);
2529 2530 2531 2532 2533 2534 2535
            fprintf(stderr, "%s: write failed\n", touch);
            exit(1);
         }
      }

      else
      {
2536
         fflush(stdout);
2537 2538 2539 2540 2541
         fprintf(stderr, "%s: open failed\n", touch);
         exit(1);
      }
   }

2542
   return retval;
J
John Bowler 已提交
2543
}