1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* pngread.c - read a PNG file
  26  *
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file and, per its terms, should not be removed:
  31  *
  32  * Last changed in libpng 1.6.26 [October 20, 2016]
  33  * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
  34  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  35  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  36  *
  37  * This code is released under the libpng license.
  38  * For conditions of distribution and use, see the disclaimer
  39  * and license in png.h
  40  *
  41  * This file contains routines that an application calls directly to
  42  * read a PNG file or stream.
  43  */
  44 
  45 #include "pngpriv.h"
  46 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
  47 #  include <errno.h>
  48 #endif
  49 
  50 #ifdef PNG_READ_SUPPORTED
  51 
  52 /* Create a PNG structure for reading, and allocate any memory needed. */
  53 PNG_FUNCTION(png_structp,PNGAPI
  54 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
  55     png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
  56 {
  57 #ifndef PNG_USER_MEM_SUPPORTED
  58    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
  59         error_fn, warn_fn, NULL, NULL, NULL);
  60 #else
  61    return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  62         warn_fn, NULL, NULL, NULL);
  63 }
  64 
  65 /* Alternate create PNG structure for reading, and allocate any memory
  66  * needed.
  67  */
  68 PNG_FUNCTION(png_structp,PNGAPI
  69 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
  70     png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  71     png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
  72 {
  73    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
  74        error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
  75 #endif /* USER_MEM */
  76 
  77    if (png_ptr != NULL)
  78    {
  79       png_ptr->mode = PNG_IS_READ_STRUCT;
  80 
  81       /* Added in libpng-1.6.0; this can be used to detect a read structure if
  82        * required (it will be zero in a write structure.)
  83        */
  84 #     ifdef PNG_SEQUENTIAL_READ_SUPPORTED
  85          png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
  86 #     endif
  87 
  88 #     ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
  89          png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
  90 
  91          /* In stable builds only warn if an application error can be completely
  92           * handled.
  93           */
  94 #        if PNG_RELEASE_BUILD
  95             png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
  96 #        endif
  97 #     endif
  98 
  99       /* TODO: delay this, it can be done in png_init_io (if the app doesn't
 100        * do it itself) avoiding setting the default function if it is not
 101        * required.
 102        */
 103       png_set_read_fn(png_ptr, NULL, NULL);
 104    }
 105 
 106    return png_ptr;
 107 }
 108 
 109 
 110 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 111 /* Read the information before the actual image data.  This has been
 112  * changed in v0.90 to allow reading a file that already has the magic
 113  * bytes read from the stream.  You can tell libpng how many bytes have
 114  * been read from the beginning of the stream (up to the maximum of 8)
 115  * via png_set_sig_bytes(), and we will only check the remaining bytes
 116  * here.  The application can then have access to the signature bytes we
 117  * read if it is determined that this isn't a valid PNG file.
 118  */
 119 void PNGAPI
 120 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
 121 {
 122 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 123    int keep;
 124 #endif
 125 
 126    png_debug(1, "in png_read_info");
 127 
 128    if (png_ptr == NULL || info_ptr == NULL)
 129       return;
 130 
 131    /* Read and check the PNG file signature. */
 132    png_read_sig(png_ptr, info_ptr);
 133 
 134    for (;;)
 135    {
 136       png_uint_32 length = png_read_chunk_header(png_ptr);
 137       png_uint_32 chunk_name = png_ptr->chunk_name;
 138 
 139       /* IDAT logic needs to happen here to simplify getting the two flags
 140        * right.
 141        */
 142       if (chunk_name == png_IDAT)
 143       {
 144          if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
 145             png_chunk_error(png_ptr, "Missing IHDR before IDAT");
 146 
 147          else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
 148              (png_ptr->mode & PNG_HAVE_PLTE) == 0)
 149             png_chunk_error(png_ptr, "Missing PLTE before IDAT");
 150 
 151          else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
 152             png_chunk_benign_error(png_ptr, "Too many IDATs found");
 153 
 154          png_ptr->mode |= PNG_HAVE_IDAT;
 155       }
 156 
 157       else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
 158       {
 159          png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
 160          png_ptr->mode |= PNG_AFTER_IDAT;
 161       }
 162 
 163       /* This should be a binary subdivision search or a hash for
 164        * matching the chunk name rather than a linear search.
 165        */
 166       if (chunk_name == png_IHDR)
 167          png_handle_IHDR(png_ptr, info_ptr, length);
 168 
 169       else if (chunk_name == png_IEND)
 170          png_handle_IEND(png_ptr, info_ptr, length);
 171 
 172 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 173       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
 174       {
 175          png_handle_unknown(png_ptr, info_ptr, length, keep);
 176 
 177          if (chunk_name == png_PLTE)
 178             png_ptr->mode |= PNG_HAVE_PLTE;
 179 
 180          else if (chunk_name == png_IDAT)
 181          {
 182             png_ptr->idat_size = 0; /* It has been consumed */
 183             break;
 184          }
 185       }
 186 #endif
 187       else if (chunk_name == png_PLTE)
 188          png_handle_PLTE(png_ptr, info_ptr, length);
 189 
 190       else if (chunk_name == png_IDAT)
 191       {
 192          png_ptr->idat_size = length;
 193          break;
 194       }
 195 
 196 #ifdef PNG_READ_bKGD_SUPPORTED
 197       else if (chunk_name == png_bKGD)
 198          png_handle_bKGD(png_ptr, info_ptr, length);
 199 #endif
 200 
 201 #ifdef PNG_READ_cHRM_SUPPORTED
 202       else if (chunk_name == png_cHRM)
 203          png_handle_cHRM(png_ptr, info_ptr, length);
 204 #endif
 205 
 206 #ifdef PNG_READ_gAMA_SUPPORTED
 207       else if (chunk_name == png_gAMA)
 208          png_handle_gAMA(png_ptr, info_ptr, length);
 209 #endif
 210 
 211 #ifdef PNG_READ_hIST_SUPPORTED
 212       else if (chunk_name == png_hIST)
 213          png_handle_hIST(png_ptr, info_ptr, length);
 214 #endif
 215 
 216 #ifdef PNG_READ_oFFs_SUPPORTED
 217       else if (chunk_name == png_oFFs)
 218          png_handle_oFFs(png_ptr, info_ptr, length);
 219 #endif
 220 
 221 #ifdef PNG_READ_pCAL_SUPPORTED
 222       else if (chunk_name == png_pCAL)
 223          png_handle_pCAL(png_ptr, info_ptr, length);
 224 #endif
 225 
 226 #ifdef PNG_READ_sCAL_SUPPORTED
 227       else if (chunk_name == png_sCAL)
 228          png_handle_sCAL(png_ptr, info_ptr, length);
 229 #endif
 230 
 231 #ifdef PNG_READ_pHYs_SUPPORTED
 232       else if (chunk_name == png_pHYs)
 233          png_handle_pHYs(png_ptr, info_ptr, length);
 234 #endif
 235 
 236 #ifdef PNG_READ_sBIT_SUPPORTED
 237       else if (chunk_name == png_sBIT)
 238          png_handle_sBIT(png_ptr, info_ptr, length);
 239 #endif
 240 
 241 #ifdef PNG_READ_sRGB_SUPPORTED
 242       else if (chunk_name == png_sRGB)
 243          png_handle_sRGB(png_ptr, info_ptr, length);
 244 #endif
 245 
 246 #ifdef PNG_READ_iCCP_SUPPORTED
 247       else if (chunk_name == png_iCCP)
 248          png_handle_iCCP(png_ptr, info_ptr, length);
 249 #endif
 250 
 251 #ifdef PNG_READ_sPLT_SUPPORTED
 252       else if (chunk_name == png_sPLT)
 253          png_handle_sPLT(png_ptr, info_ptr, length);
 254 #endif
 255 
 256 #ifdef PNG_READ_tEXt_SUPPORTED
 257       else if (chunk_name == png_tEXt)
 258          png_handle_tEXt(png_ptr, info_ptr, length);
 259 #endif
 260 
 261 #ifdef PNG_READ_tIME_SUPPORTED
 262       else if (chunk_name == png_tIME)
 263          png_handle_tIME(png_ptr, info_ptr, length);
 264 #endif
 265 
 266 #ifdef PNG_READ_tRNS_SUPPORTED
 267       else if (chunk_name == png_tRNS)
 268          png_handle_tRNS(png_ptr, info_ptr, length);
 269 #endif
 270 
 271 #ifdef PNG_READ_zTXt_SUPPORTED
 272       else if (chunk_name == png_zTXt)
 273          png_handle_zTXt(png_ptr, info_ptr, length);
 274 #endif
 275 
 276 #ifdef PNG_READ_iTXt_SUPPORTED
 277       else if (chunk_name == png_iTXt)
 278          png_handle_iTXt(png_ptr, info_ptr, length);
 279 #endif
 280 
 281       else
 282          png_handle_unknown(png_ptr, info_ptr, length,
 283              PNG_HANDLE_CHUNK_AS_DEFAULT);
 284    }
 285 }
 286 #endif /* SEQUENTIAL_READ */
 287 
 288 /* Optional call to update the users info_ptr structure */
 289 void PNGAPI
 290 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
 291 {
 292    png_debug(1, "in png_read_update_info");
 293 
 294    if (png_ptr != NULL)
 295    {
 296       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
 297       {
 298          png_read_start_row(png_ptr);
 299 
 300 #        ifdef PNG_READ_TRANSFORMS_SUPPORTED
 301             png_read_transform_info(png_ptr, info_ptr);
 302 #        else
 303             PNG_UNUSED(info_ptr)
 304 #        endif
 305       }
 306 
 307       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
 308       else
 309          png_app_error(png_ptr,
 310              "png_read_update_info/png_start_read_image: duplicate call");
 311    }
 312 }
 313 
 314 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 315 /* Initialize palette, background, etc, after transformations
 316  * are set, but before any reading takes place.  This allows
 317  * the user to obtain a gamma-corrected palette, for example.
 318  * If the user doesn't call this, we will do it ourselves.
 319  */
 320 void PNGAPI
 321 png_start_read_image(png_structrp png_ptr)
 322 {
 323    png_debug(1, "in png_start_read_image");
 324 
 325    if (png_ptr != NULL)
 326    {
 327       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
 328          png_read_start_row(png_ptr);
 329 
 330       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
 331       else
 332          png_app_error(png_ptr,
 333              "png_start_read_image/png_read_update_info: duplicate call");
 334    }
 335 }
 336 #endif /* SEQUENTIAL_READ */
 337 
 338 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 339 #ifdef PNG_MNG_FEATURES_SUPPORTED
 340 /* Undoes intrapixel differencing,
 341  * NOTE: this is apparently only supported in the 'sequential' reader.
 342  */
 343 static void
 344 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
 345 {
 346    png_debug(1, "in png_do_read_intrapixel");
 347 
 348    if (
 349        (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
 350    {
 351       int bytes_per_pixel;
 352       png_uint_32 row_width = row_info->width;
 353 
 354       if (row_info->bit_depth == 8)
 355       {
 356          png_bytep rp;
 357          png_uint_32 i;
 358 
 359          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 360             bytes_per_pixel = 3;
 361 
 362          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 363             bytes_per_pixel = 4;
 364 
 365          else
 366             return;
 367 
 368          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
 369          {
 370             *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
 371             *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
 372          }
 373       }
 374       else if (row_info->bit_depth == 16)
 375       {
 376          png_bytep rp;
 377          png_uint_32 i;
 378 
 379          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 380             bytes_per_pixel = 6;
 381 
 382          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 383             bytes_per_pixel = 8;
 384 
 385          else
 386             return;
 387 
 388          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
 389          {
 390             png_uint_32 s0   = (png_uint_32)(*(rp    ) << 8) | *(rp + 1);
 391             png_uint_32 s1   = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
 392             png_uint_32 s2   = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
 393             png_uint_32 red  = (s0 + s1 + 65536) & 0xffff;
 394             png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
 395             *(rp    ) = (png_byte)((red >> 8) & 0xff);
 396             *(rp + 1) = (png_byte)(red & 0xff);
 397             *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
 398             *(rp + 5) = (png_byte)(blue & 0xff);
 399          }
 400       }
 401    }
 402 }
 403 #endif /* MNG_FEATURES */
 404 
 405 void PNGAPI
 406 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
 407 {
 408    png_row_info row_info;
 409 
 410    if (png_ptr == NULL)
 411       return;
 412 
 413    png_debug2(1, "in png_read_row (row %lu, pass %d)",
 414        (unsigned long)png_ptr->row_number, png_ptr->pass);
 415 
 416    /* png_read_start_row sets the information (in particular iwidth) for this
 417     * interlace pass.
 418     */
 419    if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
 420       png_read_start_row(png_ptr);
 421 
 422    /* 1.5.6: row_info moved out of png_struct to a local here. */
 423    row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
 424    row_info.color_type = png_ptr->color_type;
 425    row_info.bit_depth = png_ptr->bit_depth;
 426    row_info.channels = png_ptr->channels;
 427    row_info.pixel_depth = png_ptr->pixel_depth;
 428    row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
 429 
 430 #ifdef PNG_WARNINGS_SUPPORTED
 431    if (png_ptr->row_number == 0 && png_ptr->pass == 0)
 432    {
 433    /* Check for transforms that have been set but were defined out */
 434 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
 435    if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
 436       png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
 437 #endif
 438 
 439 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
 440    if ((png_ptr->transformations & PNG_FILLER) != 0)
 441       png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
 442 #endif
 443 
 444 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
 445     !defined(PNG_READ_PACKSWAP_SUPPORTED)
 446    if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
 447       png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
 448 #endif
 449 
 450 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
 451    if ((png_ptr->transformations & PNG_PACK) != 0)
 452       png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
 453 #endif
 454 
 455 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
 456    if ((png_ptr->transformations & PNG_SHIFT) != 0)
 457       png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
 458 #endif
 459 
 460 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
 461    if ((png_ptr->transformations & PNG_BGR) != 0)
 462       png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
 463 #endif
 464 
 465 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
 466    if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
 467       png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
 468 #endif
 469    }
 470 #endif /* WARNINGS */
 471 
 472 #ifdef PNG_READ_INTERLACING_SUPPORTED
 473    /* If interlaced and we do not need a new row, combine row and return.
 474     * Notice that the pixels we have from previous rows have been transformed
 475     * already; we can only combine like with like (transformed or
 476     * untransformed) and, because of the libpng API for interlaced images, this
 477     * means we must transform before de-interlacing.
 478     */
 479    if (png_ptr->interlaced != 0 &&
 480        (png_ptr->transformations & PNG_INTERLACE) != 0)
 481    {
 482       switch (png_ptr->pass)
 483       {
 484          case 0:
 485             if (png_ptr->row_number & 0x07)
 486             {
 487                if (dsp_row != NULL)
 488                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 489                png_read_finish_row(png_ptr);
 490                return;
 491             }
 492             break;
 493 
 494          case 1:
 495             if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
 496             {
 497                if (dsp_row != NULL)
 498                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 499 
 500                png_read_finish_row(png_ptr);
 501                return;
 502             }
 503             break;
 504 
 505          case 2:
 506             if ((png_ptr->row_number & 0x07) != 4)
 507             {
 508                if (dsp_row != NULL && (png_ptr->row_number & 4))
 509                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 510 
 511                png_read_finish_row(png_ptr);
 512                return;
 513             }
 514             break;
 515 
 516          case 3:
 517             if ((png_ptr->row_number & 3) || png_ptr->width < 3)
 518             {
 519                if (dsp_row != NULL)
 520                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 521 
 522                png_read_finish_row(png_ptr);
 523                return;
 524             }
 525             break;
 526 
 527          case 4:
 528             if ((png_ptr->row_number & 3) != 2)
 529             {
 530                if (dsp_row != NULL && (png_ptr->row_number & 2))
 531                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 532 
 533                png_read_finish_row(png_ptr);
 534                return;
 535             }
 536             break;
 537 
 538          case 5:
 539             if ((png_ptr->row_number & 1) || png_ptr->width < 2)
 540             {
 541                if (dsp_row != NULL)
 542                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
 543 
 544                png_read_finish_row(png_ptr);
 545                return;
 546             }
 547             break;
 548 
 549          default:
 550          case 6:
 551             if ((png_ptr->row_number & 1) == 0)
 552             {
 553                png_read_finish_row(png_ptr);
 554                return;
 555             }
 556             break;
 557       }
 558    }
 559 #endif
 560 
 561    if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
 562       png_error(png_ptr, "Invalid attempt to read row data");
 563 
 564    /* Fill the row with IDAT data: */
 565    png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
 566 
 567    if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
 568    {
 569       if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
 570          png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
 571              png_ptr->prev_row + 1, png_ptr->row_buf[0]);
 572       else
 573          png_error(png_ptr, "bad adaptive filter value");
 574    }
 575 
 576    /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
 577     * 1.5.6, while the buffer really is this big in current versions of libpng
 578     * it may not be in the future, so this was changed just to copy the
 579     * interlaced count:
 580     */
 581    memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
 582 
 583 #ifdef PNG_MNG_FEATURES_SUPPORTED
 584    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
 585        (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
 586    {
 587       /* Intrapixel differencing */
 588       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
 589    }
 590 #endif
 591 
 592 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
 593    if (png_ptr->transformations)
 594       png_do_read_transformations(png_ptr, &row_info);
 595 #endif
 596 
 597    /* The transformed pixel depth should match the depth now in row_info. */
 598    if (png_ptr->transformed_pixel_depth == 0)
 599    {
 600       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
 601       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
 602          png_error(png_ptr, "sequential row overflow");
 603    }
 604 
 605    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
 606       png_error(png_ptr, "internal sequential row size calculation error");
 607 
 608 #ifdef PNG_READ_INTERLACING_SUPPORTED
 609    /* Expand interlaced rows to full size */
 610    if (png_ptr->interlaced != 0 &&
 611       (png_ptr->transformations & PNG_INTERLACE) != 0)
 612    {
 613       if (png_ptr->pass < 6)
 614          png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
 615              png_ptr->transformations);
 616 
 617       if (dsp_row != NULL)
 618          png_combine_row(png_ptr, dsp_row, 1/*display*/);
 619 
 620       if (row != NULL)
 621          png_combine_row(png_ptr, row, 0/*row*/);
 622    }
 623 
 624    else
 625 #endif
 626    {
 627       if (row != NULL)
 628          png_combine_row(png_ptr, row, -1/*ignored*/);
 629 
 630       if (dsp_row != NULL)
 631          png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
 632    }
 633    png_read_finish_row(png_ptr);
 634 
 635    if (png_ptr->read_row_fn != NULL)
 636       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
 637 
 638 }
 639 #endif /* SEQUENTIAL_READ */
 640 
 641 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 642 /* Read one or more rows of image data.  If the image is interlaced,
 643  * and png_set_interlace_handling() has been called, the rows need to
 644  * contain the contents of the rows from the previous pass.  If the
 645  * image has alpha or transparency, and png_handle_alpha()[*] has been
 646  * called, the rows contents must be initialized to the contents of the
 647  * screen.
 648  *
 649  * "row" holds the actual image, and pixels are placed in it
 650  * as they arrive.  If the image is displayed after each pass, it will
 651  * appear to "sparkle" in.  "display_row" can be used to display a
 652  * "chunky" progressive image, with finer detail added as it becomes
 653  * available.  If you do not want this "chunky" display, you may pass
 654  * NULL for display_row.  If you do not want the sparkle display, and
 655  * you have not called png_handle_alpha(), you may pass NULL for rows.
 656  * If you have called png_handle_alpha(), and the image has either an
 657  * alpha channel or a transparency chunk, you must provide a buffer for
 658  * rows.  In this case, you do not have to provide a display_row buffer
 659  * also, but you may.  If the image is not interlaced, or if you have
 660  * not called png_set_interlace_handling(), the display_row buffer will
 661  * be ignored, so pass NULL to it.
 662  *
 663  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
 664  */
 665 
 666 void PNGAPI
 667 png_read_rows(png_structrp png_ptr, png_bytepp row,
 668     png_bytepp display_row, png_uint_32 num_rows)
 669 {
 670    png_uint_32 i;
 671    png_bytepp rp;
 672    png_bytepp dp;
 673 
 674    png_debug(1, "in png_read_rows");
 675 
 676    if (png_ptr == NULL)
 677       return;
 678 
 679    rp = row;
 680    dp = display_row;
 681    if (rp != NULL && dp != NULL)
 682       for (i = 0; i < num_rows; i++)
 683       {
 684          png_bytep rptr = *rp++;
 685          png_bytep dptr = *dp++;
 686 
 687          png_read_row(png_ptr, rptr, dptr);
 688       }
 689 
 690    else if (rp != NULL)
 691       for (i = 0; i < num_rows; i++)
 692       {
 693          png_bytep rptr = *rp;
 694          png_read_row(png_ptr, rptr, NULL);
 695          rp++;
 696       }
 697 
 698    else if (dp != NULL)
 699       for (i = 0; i < num_rows; i++)
 700       {
 701          png_bytep dptr = *dp;
 702          png_read_row(png_ptr, NULL, dptr);
 703          dp++;
 704       }
 705 }
 706 #endif /* SEQUENTIAL_READ */
 707 
 708 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 709 /* Read the entire image.  If the image has an alpha channel or a tRNS
 710  * chunk, and you have called png_handle_alpha()[*], you will need to
 711  * initialize the image to the current image that PNG will be overlaying.
 712  * We set the num_rows again here, in case it was incorrectly set in
 713  * png_read_start_row() by a call to png_read_update_info() or
 714  * png_start_read_image() if png_set_interlace_handling() wasn't called
 715  * prior to either of these functions like it should have been.  You can
 716  * only call this function once.  If you desire to have an image for
 717  * each pass of a interlaced image, use png_read_rows() instead.
 718  *
 719  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
 720  */
 721 void PNGAPI
 722 png_read_image(png_structrp png_ptr, png_bytepp image)
 723 {
 724    png_uint_32 i, image_height;
 725    int pass, j;
 726    png_bytepp rp;
 727 
 728    png_debug(1, "in png_read_image");
 729 
 730    if (png_ptr == NULL)
 731       return;
 732 
 733 #ifdef PNG_READ_INTERLACING_SUPPORTED
 734    if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
 735    {
 736       pass = png_set_interlace_handling(png_ptr);
 737       /* And make sure transforms are initialized. */
 738       png_start_read_image(png_ptr);
 739    }
 740    else
 741    {
 742       if (png_ptr->interlaced != 0 &&
 743           (png_ptr->transformations & PNG_INTERLACE) == 0)
 744       {
 745          /* Caller called png_start_read_image or png_read_update_info without
 746           * first turning on the PNG_INTERLACE transform.  We can fix this here,
 747           * but the caller should do it!
 748           */
 749          png_warning(png_ptr, "Interlace handling should be turned on when "
 750              "using png_read_image");
 751          /* Make sure this is set correctly */
 752          png_ptr->num_rows = png_ptr->height;
 753       }
 754 
 755       /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
 756        * the above error case.
 757        */
 758       pass = png_set_interlace_handling(png_ptr);
 759    }
 760 #else
 761    if (png_ptr->interlaced)
 762       png_error(png_ptr,
 763           "Cannot read interlaced image -- interlace handler disabled");
 764 
 765    pass = 1;
 766 #endif
 767 
 768    image_height=png_ptr->height;
 769 
 770    for (j = 0; j < pass; j++)
 771    {
 772       rp = image;
 773       for (i = 0; i < image_height; i++)
 774       {
 775          png_read_row(png_ptr, *rp, NULL);
 776          rp++;
 777       }
 778    }
 779 }
 780 #endif /* SEQUENTIAL_READ */
 781 
 782 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 783 /* Read the end of the PNG file.  Will not read past the end of the
 784  * file, will verify the end is accurate, and will read any comments
 785  * or time information at the end of the file, if info is not NULL.
 786  */
 787 void PNGAPI
 788 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
 789 {
 790 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 791    int keep;
 792 #endif
 793 
 794    png_debug(1, "in png_read_end");
 795 
 796    if (png_ptr == NULL)
 797       return;
 798 
 799    /* If png_read_end is called in the middle of reading the rows there may
 800     * still be pending IDAT data and an owned zstream.  Deal with this here.
 801     */
 802 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 803    if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
 804 #endif
 805       png_read_finish_IDAT(png_ptr);
 806 
 807 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
 808    /* Report invalid palette index; added at libng-1.5.10 */
 809    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
 810        png_ptr->num_palette_max > png_ptr->num_palette)
 811       png_benign_error(png_ptr, "Read palette index exceeding num_palette");
 812 #endif
 813 
 814    do
 815    {
 816       png_uint_32 length = png_read_chunk_header(png_ptr);
 817       png_uint_32 chunk_name = png_ptr->chunk_name;
 818 
 819       if (chunk_name != png_IDAT)
 820          png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
 821 
 822       if (chunk_name == png_IEND)
 823          png_handle_IEND(png_ptr, info_ptr, length);
 824 
 825       else if (chunk_name == png_IHDR)
 826          png_handle_IHDR(png_ptr, info_ptr, length);
 827 
 828       else if (info_ptr == NULL)
 829          png_crc_finish(png_ptr, length);
 830 
 831 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 832       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
 833       {
 834          if (chunk_name == png_IDAT)
 835          {
 836             if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
 837                 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
 838                png_benign_error(png_ptr, ".Too many IDATs found");
 839          }
 840          png_handle_unknown(png_ptr, info_ptr, length, keep);
 841          if (chunk_name == png_PLTE)
 842             png_ptr->mode |= PNG_HAVE_PLTE;
 843       }
 844 #endif
 845 
 846       else if (chunk_name == png_IDAT)
 847       {
 848          /* Zero length IDATs are legal after the last IDAT has been
 849           * read, but not after other chunks have been read.  1.6 does not
 850           * always read all the deflate data; specifically it cannot be relied
 851           * upon to read the Adler32 at the end.  If it doesn't ignore IDAT
 852           * chunks which are longer than zero as well:
 853           */
 854          if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
 855              || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
 856             png_benign_error(png_ptr, "..Too many IDATs found");
 857 
 858          png_crc_finish(png_ptr, length);
 859       }
 860       else if (chunk_name == png_PLTE)
 861          png_handle_PLTE(png_ptr, info_ptr, length);
 862 
 863 #ifdef PNG_READ_bKGD_SUPPORTED
 864       else if (chunk_name == png_bKGD)
 865          png_handle_bKGD(png_ptr, info_ptr, length);
 866 #endif
 867 
 868 #ifdef PNG_READ_cHRM_SUPPORTED
 869       else if (chunk_name == png_cHRM)
 870          png_handle_cHRM(png_ptr, info_ptr, length);
 871 #endif
 872 
 873 #ifdef PNG_READ_gAMA_SUPPORTED
 874       else if (chunk_name == png_gAMA)
 875          png_handle_gAMA(png_ptr, info_ptr, length);
 876 #endif
 877 
 878 #ifdef PNG_READ_hIST_SUPPORTED
 879       else if (chunk_name == png_hIST)
 880          png_handle_hIST(png_ptr, info_ptr, length);
 881 #endif
 882 
 883 #ifdef PNG_READ_oFFs_SUPPORTED
 884       else if (chunk_name == png_oFFs)
 885          png_handle_oFFs(png_ptr, info_ptr, length);
 886 #endif
 887 
 888 #ifdef PNG_READ_pCAL_SUPPORTED
 889       else if (chunk_name == png_pCAL)
 890          png_handle_pCAL(png_ptr, info_ptr, length);
 891 #endif
 892 
 893 #ifdef PNG_READ_sCAL_SUPPORTED
 894       else if (chunk_name == png_sCAL)
 895          png_handle_sCAL(png_ptr, info_ptr, length);
 896 #endif
 897 
 898 #ifdef PNG_READ_pHYs_SUPPORTED
 899       else if (chunk_name == png_pHYs)
 900          png_handle_pHYs(png_ptr, info_ptr, length);
 901 #endif
 902 
 903 #ifdef PNG_READ_sBIT_SUPPORTED
 904       else if (chunk_name == png_sBIT)
 905          png_handle_sBIT(png_ptr, info_ptr, length);
 906 #endif
 907 
 908 #ifdef PNG_READ_sRGB_SUPPORTED
 909       else if (chunk_name == png_sRGB)
 910          png_handle_sRGB(png_ptr, info_ptr, length);
 911 #endif
 912 
 913 #ifdef PNG_READ_iCCP_SUPPORTED
 914       else if (chunk_name == png_iCCP)
 915          png_handle_iCCP(png_ptr, info_ptr, length);
 916 #endif
 917 
 918 #ifdef PNG_READ_sPLT_SUPPORTED
 919       else if (chunk_name == png_sPLT)
 920          png_handle_sPLT(png_ptr, info_ptr, length);
 921 #endif
 922 
 923 #ifdef PNG_READ_tEXt_SUPPORTED
 924       else if (chunk_name == png_tEXt)
 925          png_handle_tEXt(png_ptr, info_ptr, length);
 926 #endif
 927 
 928 #ifdef PNG_READ_tIME_SUPPORTED
 929       else if (chunk_name == png_tIME)
 930          png_handle_tIME(png_ptr, info_ptr, length);
 931 #endif
 932 
 933 #ifdef PNG_READ_tRNS_SUPPORTED
 934       else if (chunk_name == png_tRNS)
 935          png_handle_tRNS(png_ptr, info_ptr, length);
 936 #endif
 937 
 938 #ifdef PNG_READ_zTXt_SUPPORTED
 939       else if (chunk_name == png_zTXt)
 940          png_handle_zTXt(png_ptr, info_ptr, length);
 941 #endif
 942 
 943 #ifdef PNG_READ_iTXt_SUPPORTED
 944       else if (chunk_name == png_iTXt)
 945          png_handle_iTXt(png_ptr, info_ptr, length);
 946 #endif
 947 
 948       else
 949          png_handle_unknown(png_ptr, info_ptr, length,
 950              PNG_HANDLE_CHUNK_AS_DEFAULT);
 951    } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
 952 }
 953 #endif /* SEQUENTIAL_READ */
 954 
 955 /* Free all memory used in the read struct */
 956 static void
 957 png_read_destroy(png_structrp png_ptr)
 958 {
 959    png_debug(1, "in png_read_destroy");
 960 
 961 #ifdef PNG_READ_GAMMA_SUPPORTED
 962    png_destroy_gamma_table(png_ptr);
 963 #endif
 964 
 965    png_free(png_ptr, png_ptr->big_row_buf);
 966    png_ptr->big_row_buf = NULL;
 967    png_free(png_ptr, png_ptr->big_prev_row);
 968    png_ptr->big_prev_row = NULL;
 969    png_free(png_ptr, png_ptr->read_buffer);
 970    png_ptr->read_buffer = NULL;
 971 
 972 #ifdef PNG_READ_QUANTIZE_SUPPORTED
 973    png_free(png_ptr, png_ptr->palette_lookup);
 974    png_ptr->palette_lookup = NULL;
 975    png_free(png_ptr, png_ptr->quantize_index);
 976    png_ptr->quantize_index = NULL;
 977 #endif
 978 
 979    if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
 980    {
 981       png_zfree(png_ptr, png_ptr->palette);
 982       png_ptr->palette = NULL;
 983    }
 984    png_ptr->free_me &= ~PNG_FREE_PLTE;
 985 
 986 #if defined(PNG_tRNS_SUPPORTED) || \
 987     defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 988    if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
 989    {
 990       png_free(png_ptr, png_ptr->trans_alpha);
 991       png_ptr->trans_alpha = NULL;
 992    }
 993    png_ptr->free_me &= ~PNG_FREE_TRNS;
 994 #endif
 995 
 996    inflateEnd(&png_ptr->zstream);
 997 
 998 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 999    png_free(png_ptr, png_ptr->save_buffer);
1000    png_ptr->save_buffer = NULL;
1001 #endif
1002 
1003 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
1004    defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
1005    png_free(png_ptr, png_ptr->unknown_chunk.data);
1006    png_ptr->unknown_chunk.data = NULL;
1007 #endif
1008 
1009 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
1010    png_free(png_ptr, png_ptr->chunk_list);
1011    png_ptr->chunk_list = NULL;
1012 #endif
1013 
1014    /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
1015     * callbacks are still set at this point.  They are required to complete the
1016     * destruction of the png_struct itself.
1017     */
1018 }
1019 
1020 /* Free all memory used by the read */
1021 void PNGAPI
1022 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
1023     png_infopp end_info_ptr_ptr)
1024 {
1025    png_structrp png_ptr = NULL;
1026 
1027    png_debug(1, "in png_destroy_read_struct");
1028 
1029    if (png_ptr_ptr != NULL)
1030       png_ptr = *png_ptr_ptr;
1031 
1032    if (png_ptr == NULL)
1033       return;
1034 
1035    /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1036     * behavior.  Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1037     * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1038     */
1039    png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1040    png_destroy_info_struct(png_ptr, info_ptr_ptr);
1041 
1042    *png_ptr_ptr = NULL;
1043    png_read_destroy(png_ptr);
1044    png_destroy_png_struct(png_ptr);
1045 }
1046 
1047 void PNGAPI
1048 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1049 {
1050    if (png_ptr == NULL)
1051       return;
1052 
1053    png_ptr->read_row_fn = read_row_fn;
1054 }
1055 
1056 
1057 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1058 #ifdef PNG_INFO_IMAGE_SUPPORTED
1059 void PNGAPI
1060 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1061     int transforms, voidp params)
1062 {
1063    if (png_ptr == NULL || info_ptr == NULL)
1064       return;
1065 
1066    /* png_read_info() gives us all of the information from the
1067     * PNG file before the first IDAT (image data chunk).
1068     */
1069    png_read_info(png_ptr, info_ptr);
1070    if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1071       png_error(png_ptr, "Image is too high to process with png_read_png()");
1072 
1073    /* -------------- image transformations start here ------------------- */
1074    /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1075     * is not implemented.  This will only happen in de-configured (non-default)
1076     * libpng builds.  The results can be unexpected - png_read_png may return
1077     * short or mal-formed rows because the transform is skipped.
1078     */
1079 
1080    /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1081     */
1082    if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1083       /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1084        * did in earlier versions, while "scale_16" is now more accurate.
1085        */
1086 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1087       png_set_scale_16(png_ptr);
1088 #else
1089       png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1090 #endif
1091 
1092    /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1093     * latter by doing SCALE first.  This is ok and allows apps not to check for
1094     * which is supported to get the right answer.
1095     */
1096    if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1097 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1098       png_set_strip_16(png_ptr);
1099 #else
1100       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1101 #endif
1102 
1103    /* Strip alpha bytes from the input data without combining with
1104     * the background (not recommended).
1105     */
1106    if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1107 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1108       png_set_strip_alpha(png_ptr);
1109 #else
1110       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1111 #endif
1112 
1113    /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1114     * byte into separate bytes (useful for paletted and grayscale images).
1115     */
1116    if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1117 #ifdef PNG_READ_PACK_SUPPORTED
1118       png_set_packing(png_ptr);
1119 #else
1120       png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1121 #endif
1122 
1123    /* Change the order of packed pixels to least significant bit first
1124     * (not useful if you are using png_set_packing).
1125     */
1126    if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1127 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1128       png_set_packswap(png_ptr);
1129 #else
1130       png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1131 #endif
1132 
1133    /* Expand paletted colors into true RGB triplets
1134     * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1135     * Expand paletted or RGB images with transparency to full alpha
1136     * channels so the data will be available as RGBA quartets.
1137     */
1138    if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1139 #ifdef PNG_READ_EXPAND_SUPPORTED
1140       png_set_expand(png_ptr);
1141 #else
1142       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1143 #endif
1144 
1145    /* We don't handle background color or gamma transformation or quantizing.
1146     */
1147 
1148    /* Invert monochrome files to have 0 as white and 1 as black
1149     */
1150    if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1151 #ifdef PNG_READ_INVERT_SUPPORTED
1152       png_set_invert_mono(png_ptr);
1153 #else
1154       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1155 #endif
1156 
1157    /* If you want to shift the pixel values from the range [0,255] or
1158     * [0,65535] to the original [0,7] or [0,31], or whatever range the
1159     * colors were originally in:
1160     */
1161    if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1162 #ifdef PNG_READ_SHIFT_SUPPORTED
1163       if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1164          png_set_shift(png_ptr, &info_ptr->sig_bit);
1165 #else
1166       png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1167 #endif
1168 
1169    /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1170    if ((transforms & PNG_TRANSFORM_BGR) != 0)
1171 #ifdef PNG_READ_BGR_SUPPORTED
1172       png_set_bgr(png_ptr);
1173 #else
1174       png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1175 #endif
1176 
1177    /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1178    if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1179 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1180       png_set_swap_alpha(png_ptr);
1181 #else
1182       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1183 #endif
1184 
1185    /* Swap bytes of 16-bit files to least significant byte first */
1186    if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1187 #ifdef PNG_READ_SWAP_SUPPORTED
1188       png_set_swap(png_ptr);
1189 #else
1190       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1191 #endif
1192 
1193 /* Added at libpng-1.2.41 */
1194    /* Invert the alpha channel from opacity to transparency */
1195    if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1196 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1197       png_set_invert_alpha(png_ptr);
1198 #else
1199       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1200 #endif
1201 
1202 /* Added at libpng-1.2.41 */
1203    /* Expand grayscale image to RGB */
1204    if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1205 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1206       png_set_gray_to_rgb(png_ptr);
1207 #else
1208       png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1209 #endif
1210 
1211 /* Added at libpng-1.5.4 */
1212    if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1213 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1214       png_set_expand_16(png_ptr);
1215 #else
1216       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1217 #endif
1218 
1219    /* We don't handle adding filler bytes */
1220 
1221    /* We use png_read_image and rely on that for interlace handling, but we also
1222     * call png_read_update_info therefore must turn on interlace handling now:
1223     */
1224    (void)png_set_interlace_handling(png_ptr);
1225 
1226    /* Optional call to gamma correct and add the background to the palette
1227     * and update info structure.  REQUIRED if you are expecting libpng to
1228     * update the palette for you (i.e., you selected such a transform above).
1229     */
1230    png_read_update_info(png_ptr, info_ptr);
1231 
1232    /* -------------- image transformations end here ------------------- */
1233 
1234    png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1235    if (info_ptr->row_pointers == NULL)
1236    {
1237       png_uint_32 iptr;
1238 
1239       info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1240           info_ptr->height * (sizeof (png_bytep))));
1241 
1242       for (iptr=0; iptr<info_ptr->height; iptr++)
1243          info_ptr->row_pointers[iptr] = NULL;
1244 
1245       info_ptr->free_me |= PNG_FREE_ROWS;
1246 
1247       for (iptr = 0; iptr < info_ptr->height; iptr++)
1248          info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1249              png_malloc(png_ptr, info_ptr->rowbytes));
1250    }
1251 
1252    png_read_image(png_ptr, info_ptr->row_pointers);
1253    info_ptr->valid |= PNG_INFO_IDAT;
1254 
1255    /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1256    png_read_end(png_ptr, info_ptr);
1257 
1258    PNG_UNUSED(params)
1259 }
1260 #endif /* INFO_IMAGE */
1261 #endif /* SEQUENTIAL_READ */
1262 
1263 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1264 /* SIMPLIFIED READ
1265  *
1266  * This code currently relies on the sequential reader, though it could easily
1267  * be made to work with the progressive one.
1268  */
1269 /* Arguments to png_image_finish_read: */
1270 
1271 /* Encoding of PNG data (used by the color-map code) */
1272 #  define P_NOTSET  0 /* File encoding not yet known */
1273 #  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
1274 #  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1275 #  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
1276 #  define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1277 
1278 /* Color-map processing: after libpng has run on the PNG image further
1279  * processing may be needed to convert the data to color-map indices.
1280  */
1281 #define PNG_CMAP_NONE      0
1282 #define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
1283 #define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
1284 #define PNG_CMAP_RGB       3 /* Process RGB data */
1285 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1286 
1287 /* The following document where the background is for each processing case. */
1288 #define PNG_CMAP_NONE_BACKGROUND      256
1289 #define PNG_CMAP_GA_BACKGROUND        231
1290 #define PNG_CMAP_TRANS_BACKGROUND     254
1291 #define PNG_CMAP_RGB_BACKGROUND       256
1292 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1293 
1294 typedef struct
1295 {
1296    /* Arguments: */
1297    png_imagep image;
1298    png_voidp  buffer;
1299    png_int_32 row_stride;
1300    png_voidp  colormap;
1301    png_const_colorp background;
1302    /* Local variables: */
1303    png_voidp       local_row;
1304    png_voidp       first_row;
1305    ptrdiff_t       row_bytes;           /* step between rows */
1306    int             file_encoding;       /* E_ values above */
1307    png_fixed_point gamma_to_linear;     /* For P_FILE, reciprocal of gamma */
1308    int             colormap_processing; /* PNG_CMAP_ values above */
1309 } png_image_read_control;
1310 
1311 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1312  * called, so setting up the jmp_buf is not required.  This means that anything
1313  * called from here must *not* call png_malloc - it has to call png_malloc_warn
1314  * instead so that control is returned safely back to this routine.
1315  */
1316 static int
1317 png_image_read_init(png_imagep image)
1318 {
1319    if (image->opaque == NULL)
1320    {
1321       png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1322           png_safe_error, png_safe_warning);
1323 
1324       /* And set the rest of the structure to NULL to ensure that the various
1325        * fields are consistent.
1326        */
1327       memset(image, 0, (sizeof *image));
1328       image->version = PNG_IMAGE_VERSION;
1329 
1330       if (png_ptr != NULL)
1331       {
1332          png_infop info_ptr = png_create_info_struct(png_ptr);
1333 
1334          if (info_ptr != NULL)
1335          {
1336             png_controlp control = png_voidcast(png_controlp,
1337                 png_malloc_warn(png_ptr, (sizeof *control)));
1338 
1339             if (control != NULL)
1340             {
1341                memset(control, 0, (sizeof *control));
1342 
1343                control->png_ptr = png_ptr;
1344                control->info_ptr = info_ptr;
1345                control->for_write = 0;
1346 
1347                image->opaque = control;
1348                return 1;
1349             }
1350 
1351             /* Error clean up */
1352             png_destroy_info_struct(png_ptr, &info_ptr);
1353          }
1354 
1355          png_destroy_read_struct(&png_ptr, NULL, NULL);
1356       }
1357 
1358       return png_image_error(image, "png_image_read: out of memory");
1359    }
1360 
1361    return png_image_error(image, "png_image_read: opaque pointer not NULL");
1362 }
1363 
1364 /* Utility to find the base format of a PNG file from a png_struct. */
1365 static png_uint_32
1366 png_image_format(png_structrp png_ptr)
1367 {
1368    png_uint_32 format = 0;
1369 
1370    if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1371       format |= PNG_FORMAT_FLAG_COLOR;
1372 
1373    if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1374       format |= PNG_FORMAT_FLAG_ALPHA;
1375 
1376    /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1377     * sets the png_struct fields; that's all we are interested in here.  The
1378     * precise interaction with an app call to png_set_tRNS and PNG file reading
1379     * is unclear.
1380     */
1381    else if (png_ptr->num_trans > 0)
1382       format |= PNG_FORMAT_FLAG_ALPHA;
1383 
1384    if (png_ptr->bit_depth == 16)
1385       format |= PNG_FORMAT_FLAG_LINEAR;
1386 
1387    if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1388       format |= PNG_FORMAT_FLAG_COLORMAP;
1389 
1390    return format;
1391 }
1392 
1393 /* Is the given gamma significantly different from sRGB?  The test is the same
1394  * one used in pngrtran.c when deciding whether to do gamma correction.  The
1395  * arithmetic optimizes the division by using the fact that the inverse of the
1396  * file sRGB gamma is 2.2
1397  */
1398 static int
1399 png_gamma_not_sRGB(png_fixed_point g)
1400 {
1401    if (g < PNG_FP_1)
1402    {
1403       /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1404       if (g == 0)
1405          return 0;
1406 
1407       return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1408    }
1409 
1410    return 1;
1411 }
1412 
1413 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1414  * header and fill in all the information.  This is executed in a safe context,
1415  * unlike the init routine above.
1416  */
1417 static int
1418 png_image_read_header(png_voidp argument)
1419 {
1420    png_imagep image = png_voidcast(png_imagep, argument);
1421    png_structrp png_ptr = image->opaque->png_ptr;
1422    png_inforp info_ptr = image->opaque->info_ptr;
1423 
1424 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1425    png_set_benign_errors(png_ptr, 1/*warn*/);
1426 #endif
1427    png_read_info(png_ptr, info_ptr);
1428 
1429    /* Do this the fast way; just read directly out of png_struct. */
1430    image->width = png_ptr->width;
1431    image->height = png_ptr->height;
1432 
1433    {
1434       png_uint_32 format = png_image_format(png_ptr);
1435 
1436       image->format = format;
1437 
1438 #ifdef PNG_COLORSPACE_SUPPORTED
1439       /* Does the colorspace match sRGB?  If there is no color endpoint
1440        * (colorant) information assume yes, otherwise require the
1441        * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set.  If the
1442        * colorspace has been determined to be invalid ignore it.
1443        */
1444       if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1445          & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1446             PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1447          image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1448 #endif
1449    }
1450 
1451    /* We need the maximum number of entries regardless of the format the
1452     * application sets here.
1453     */
1454    {
1455       png_uint_32 cmap_entries;
1456 
1457       switch (png_ptr->color_type)
1458       {
1459          case PNG_COLOR_TYPE_GRAY:
1460             cmap_entries = 1U << png_ptr->bit_depth;
1461             break;
1462 
1463          case PNG_COLOR_TYPE_PALETTE:
1464             cmap_entries = (png_uint_32)png_ptr->num_palette;
1465             break;
1466 
1467          default:
1468             cmap_entries = 256;
1469             break;
1470       }
1471 
1472       if (cmap_entries > 256)
1473          cmap_entries = 256;
1474 
1475       image->colormap_entries = cmap_entries;
1476    }
1477 
1478    return 1;
1479 }
1480 
1481 #ifdef PNG_STDIO_SUPPORTED
1482 int PNGAPI
1483 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1484 {
1485    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1486    {
1487       if (file != NULL)
1488       {
1489          if (png_image_read_init(image) != 0)
1490          {
1491             /* This is slightly evil, but png_init_io doesn't do anything other
1492              * than this and we haven't changed the standard IO functions so
1493              * this saves a 'safe' function.
1494              */
1495             image->opaque->png_ptr->io_ptr = file;
1496             return png_safe_execute(image, png_image_read_header, image);
1497          }
1498       }
1499 
1500       else
1501          return png_image_error(image,
1502              "png_image_begin_read_from_stdio: invalid argument");
1503    }
1504 
1505    else if (image != NULL)
1506       return png_image_error(image,
1507           "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1508 
1509    return 0;
1510 }
1511 
1512 int PNGAPI
1513 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1514 {
1515    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1516    {
1517       if (file_name != NULL)
1518       {
1519          FILE *fp = fopen(file_name, "rb");
1520 
1521          if (fp != NULL)
1522          {
1523             if (png_image_read_init(image) != 0)
1524             {
1525                image->opaque->png_ptr->io_ptr = fp;
1526                image->opaque->owned_file = 1;
1527                return png_safe_execute(image, png_image_read_header, image);
1528             }
1529 
1530             /* Clean up: just the opened file. */
1531             (void)fclose(fp);
1532          }
1533 
1534          else
1535             return png_image_error(image, strerror(errno));
1536       }
1537 
1538       else
1539          return png_image_error(image,
1540              "png_image_begin_read_from_file: invalid argument");
1541    }
1542 
1543    else if (image != NULL)
1544       return png_image_error(image,
1545           "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1546 
1547    return 0;
1548 }
1549 #endif /* STDIO */
1550 
1551 static void PNGCBAPI
1552 png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
1553 {
1554    if (png_ptr != NULL)
1555    {
1556       png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1557       if (image != NULL)
1558       {
1559          png_controlp cp = image->opaque;
1560          if (cp != NULL)
1561          {
1562             png_const_bytep memory = cp->memory;
1563             png_size_t size = cp->size;
1564 
1565             if (memory != NULL && size >= need)
1566             {
1567                memcpy(out, memory, need);
1568                cp->memory = memory + need;
1569                cp->size = size - need;
1570                return;
1571             }
1572 
1573             png_error(png_ptr, "read beyond end of data");
1574          }
1575       }
1576 
1577       png_error(png_ptr, "invalid memory read");
1578    }
1579 }
1580 
1581 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1582     png_const_voidp memory, png_size_t size)
1583 {
1584    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1585    {
1586       if (memory != NULL && size > 0)
1587       {
1588          if (png_image_read_init(image) != 0)
1589          {
1590             /* Now set the IO functions to read from the memory buffer and
1591              * store it into io_ptr.  Again do this in-place to avoid calling a
1592              * libpng function that requires error handling.
1593              */
1594             image->opaque->memory = png_voidcast(png_const_bytep, memory);
1595             image->opaque->size = size;
1596             image->opaque->png_ptr->io_ptr = image;
1597             image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1598 
1599             return png_safe_execute(image, png_image_read_header, image);
1600          }
1601       }
1602 
1603       else
1604          return png_image_error(image,
1605              "png_image_begin_read_from_memory: invalid argument");
1606    }
1607 
1608    else if (image != NULL)
1609       return png_image_error(image,
1610           "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1611 
1612    return 0;
1613 }
1614 
1615 /* Utility function to skip chunks that are not used by the simplified image
1616  * read functions and an appropriate macro to call it.
1617  */
1618 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1619 static void
1620 png_image_skip_unused_chunks(png_structrp png_ptr)
1621 {
1622    /* Prepare the reader to ignore all recognized chunks whose data will not
1623     * be used, i.e., all chunks recognized by libpng except for those
1624     * involved in basic image reading:
1625     *
1626     *    IHDR, PLTE, IDAT, IEND
1627     *
1628     * Or image data handling:
1629     *
1630     *    tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1631     *
1632     * This provides a small performance improvement and eliminates any
1633     * potential vulnerability to security problems in the unused chunks.
1634     *
1635     * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1636     * too.  This allows the simplified API to be compiled without iCCP support,
1637     * however if the support is there the chunk is still checked to detect
1638     * errors (which are unfortunately quite common.)
1639     */
1640    {
1641          static PNG_CONST png_byte chunks_to_process[] = {
1642             98,  75,  71,  68, '\0',  /* bKGD */
1643             99,  72,  82,  77, '\0',  /* cHRM */
1644            103,  65,  77,  65, '\0',  /* gAMA */
1645 #        ifdef PNG_READ_iCCP_SUPPORTED
1646            105,  67,  67,  80, '\0',  /* iCCP */
1647 #        endif
1648            115,  66,  73,  84, '\0',  /* sBIT */
1649            115,  82,  71,  66, '\0',  /* sRGB */
1650            };
1651 
1652        /* Ignore unknown chunks and all other chunks except for the
1653         * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1654         */
1655        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1656            NULL, -1);
1657 
1658        /* But do not ignore image data handling chunks */
1659        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1660            chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1661    }
1662 }
1663 
1664 #  define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1665 #else
1666 #  define PNG_SKIP_CHUNKS(p) ((void)0)
1667 #endif /* HANDLE_AS_UNKNOWN */
1668 
1669 /* The following macro gives the exact rounded answer for all values in the
1670  * range 0..255 (it actually divides by 51.2, but the rounding still generates
1671  * the correct numbers 0..5
1672  */
1673 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1674 
1675 /* Utility functions to make particular color-maps */
1676 static void
1677 set_file_encoding(png_image_read_control *display)
1678 {
1679    png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1680    if (png_gamma_significant(g) != 0)
1681    {
1682       if (png_gamma_not_sRGB(g) != 0)
1683       {
1684          display->file_encoding = P_FILE;
1685          display->gamma_to_linear = png_reciprocal(g);
1686       }
1687 
1688       else
1689          display->file_encoding = P_sRGB;
1690    }
1691 
1692    else
1693       display->file_encoding = P_LINEAR8;
1694 }
1695 
1696 static unsigned int
1697 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1698 {
1699    if (encoding == P_FILE) /* double check */
1700       encoding = display->file_encoding;
1701 
1702    if (encoding == P_NOTSET) /* must be the file encoding */
1703    {
1704       set_file_encoding(display);
1705       encoding = display->file_encoding;
1706    }
1707 
1708    switch (encoding)
1709    {
1710       case P_FILE:
1711          value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1712          break;
1713 
1714       case P_sRGB:
1715          value = png_sRGB_table[value];
1716          break;
1717 
1718       case P_LINEAR:
1719          break;
1720 
1721       case P_LINEAR8:
1722          value *= 257;
1723          break;
1724 
1725 #ifdef __GNUC__
1726       default:
1727          png_error(display->image->opaque->png_ptr,
1728              "unexpected encoding (internal error)");
1729 #endif
1730    }
1731 
1732    return value;
1733 }
1734 
1735 static png_uint_32
1736 png_colormap_compose(png_image_read_control *display,
1737     png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1738     png_uint_32 background, int encoding)
1739 {
1740    /* The file value is composed on the background, the background has the given
1741     * encoding and so does the result, the file is encoded with P_FILE and the
1742     * file and alpha are 8-bit values.  The (output) encoding will always be
1743     * P_LINEAR or P_sRGB.
1744     */
1745    png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1746    png_uint_32 b = decode_gamma(display, background, encoding);
1747 
1748    /* The alpha is always an 8-bit value (it comes from the palette), the value
1749     * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1750     */
1751    f = f * alpha + b * (255-alpha);
1752 
1753    if (encoding == P_LINEAR)
1754    {
1755       /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1756        * accurate, it divides by 255.00000005937181414556, with no overflow.)
1757        */
1758       f *= 257; /* Now scaled by 65535 */
1759       f += f >> 16;
1760       f = (f+32768) >> 16;
1761    }
1762 
1763    else /* P_sRGB */
1764       f = PNG_sRGB_FROM_LINEAR(f);
1765 
1766    return f;
1767 }
1768 
1769 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1770  * be 8-bit.
1771  */
1772 static void
1773 png_create_colormap_entry(png_image_read_control *display,
1774     png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1775     png_uint_32 alpha, int encoding)
1776 {
1777    png_imagep image = display->image;
1778    const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1779        P_LINEAR : P_sRGB;
1780    const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1781        (red != green || green != blue);
1782 
1783    if (ip > 255)
1784       png_error(image->opaque->png_ptr, "color-map index out of range");
1785 
1786    /* Update the cache with whether the file gamma is significantly different
1787     * from sRGB.
1788     */
1789    if (encoding == P_FILE)
1790    {
1791       if (display->file_encoding == P_NOTSET)
1792          set_file_encoding(display);
1793 
1794       /* Note that the cached value may be P_FILE too, but if it is then the
1795        * gamma_to_linear member has been set.
1796        */
1797       encoding = display->file_encoding;
1798    }
1799 
1800    if (encoding == P_FILE)
1801    {
1802       png_fixed_point g = display->gamma_to_linear;
1803 
1804       red = png_gamma_16bit_correct(red*257, g);
1805       green = png_gamma_16bit_correct(green*257, g);
1806       blue = png_gamma_16bit_correct(blue*257, g);
1807 
1808       if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1809       {
1810          alpha *= 257;
1811          encoding = P_LINEAR;
1812       }
1813 
1814       else
1815       {
1816          red = PNG_sRGB_FROM_LINEAR(red * 255);
1817          green = PNG_sRGB_FROM_LINEAR(green * 255);
1818          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1819          encoding = P_sRGB;
1820       }
1821    }
1822 
1823    else if (encoding == P_LINEAR8)
1824    {
1825       /* This encoding occurs quite frequently in test cases because PngSuite
1826        * includes a gAMA 1.0 chunk with most images.
1827        */
1828       red *= 257;
1829       green *= 257;
1830       blue *= 257;
1831       alpha *= 257;
1832       encoding = P_LINEAR;
1833    }
1834 
1835    else if (encoding == P_sRGB &&
1836        (convert_to_Y  != 0 || output_encoding == P_LINEAR))
1837    {
1838       /* The values are 8-bit sRGB values, but must be converted to 16-bit
1839        * linear.
1840        */
1841       red = png_sRGB_table[red];
1842       green = png_sRGB_table[green];
1843       blue = png_sRGB_table[blue];
1844       alpha *= 257;
1845       encoding = P_LINEAR;
1846    }
1847 
1848    /* This is set if the color isn't gray but the output is. */
1849    if (encoding == P_LINEAR)
1850    {
1851       if (convert_to_Y != 0)
1852       {
1853          /* NOTE: these values are copied from png_do_rgb_to_gray */
1854          png_uint_32 y = (png_uint_32)6968 * red  + (png_uint_32)23434 * green +
1855             (png_uint_32)2366 * blue;
1856 
1857          if (output_encoding == P_LINEAR)
1858             y = (y + 16384) >> 15;
1859 
1860          else
1861          {
1862             /* y is scaled by 32768, we need it scaled by 255: */
1863             y = (y + 128) >> 8;
1864             y *= 255;
1865             y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1866             alpha = PNG_DIV257(alpha);
1867             encoding = P_sRGB;
1868          }
1869 
1870          blue = red = green = y;
1871       }
1872 
1873       else if (output_encoding == P_sRGB)
1874       {
1875          red = PNG_sRGB_FROM_LINEAR(red * 255);
1876          green = PNG_sRGB_FROM_LINEAR(green * 255);
1877          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1878          alpha = PNG_DIV257(alpha);
1879          encoding = P_sRGB;
1880       }
1881    }
1882 
1883    if (encoding != output_encoding)
1884       png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1885 
1886    /* Store the value. */
1887    {
1888 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
1889          const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1890             (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1891 #     else
1892 #        define afirst 0
1893 #     endif
1894 #     ifdef PNG_FORMAT_BGR_SUPPORTED
1895          const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1896 #     else
1897 #        define bgr 0
1898 #     endif
1899 
1900       if (output_encoding == P_LINEAR)
1901       {
1902          png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1903 
1904          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1905 
1906          /* The linear 16-bit values must be pre-multiplied by the alpha channel
1907           * value, if less than 65535 (this is, effectively, composite on black
1908           * if the alpha channel is removed.)
1909           */
1910          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1911          {
1912             case 4:
1913                entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1914                /* FALL THROUGH */
1915 
1916             case 3:
1917                if (alpha < 65535)
1918                {
1919                   if (alpha > 0)
1920                   {
1921                      blue = (blue * alpha + 32767U)/65535U;
1922                      green = (green * alpha + 32767U)/65535U;
1923                      red = (red * alpha + 32767U)/65535U;
1924                   }
1925 
1926                   else
1927                      red = green = blue = 0;
1928                }
1929                entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1930                entry[afirst + 1] = (png_uint_16)green;
1931                entry[afirst + bgr] = (png_uint_16)red;
1932                break;
1933 
1934             case 2:
1935                entry[1 ^ afirst] = (png_uint_16)alpha;
1936                /* FALL THROUGH */
1937 
1938             case 1:
1939                if (alpha < 65535)
1940                {
1941                   if (alpha > 0)
1942                      green = (green * alpha + 32767U)/65535U;
1943 
1944                   else
1945                      green = 0;
1946                }
1947                entry[afirst] = (png_uint_16)green;
1948                break;
1949 
1950             default:
1951                break;
1952          }
1953       }
1954 
1955       else /* output encoding is P_sRGB */
1956       {
1957          png_bytep entry = png_voidcast(png_bytep, display->colormap);
1958 
1959          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1960 
1961          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1962          {
1963             case 4:
1964                entry[afirst ? 0 : 3] = (png_byte)alpha;
1965             case 3:
1966                entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1967                entry[afirst + 1] = (png_byte)green;
1968                entry[afirst + bgr] = (png_byte)red;
1969                break;
1970 
1971             case 2:
1972                entry[1 ^ afirst] = (png_byte)alpha;
1973             case 1:
1974                entry[afirst] = (png_byte)green;
1975                break;
1976 
1977             default:
1978                break;
1979          }
1980       }
1981 
1982 #     ifdef afirst
1983 #        undef afirst
1984 #     endif
1985 #     ifdef bgr
1986 #        undef bgr
1987 #     endif
1988    }
1989 }
1990 
1991 static int
1992 make_gray_file_colormap(png_image_read_control *display)
1993 {
1994    unsigned int i;
1995 
1996    for (i=0; i<256; ++i)
1997       png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1998 
1999    return (int)i;
2000 }
2001 
2002 static int
2003 make_gray_colormap(png_image_read_control *display)
2004 {
2005    unsigned int i;
2006 
2007    for (i=0; i<256; ++i)
2008       png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
2009 
2010    return (int)i;
2011 }
2012 #define PNG_GRAY_COLORMAP_ENTRIES 256
2013 
2014 static int
2015 make_ga_colormap(png_image_read_control *display)
2016 {
2017    unsigned int i, a;
2018 
2019    /* Alpha is retained, the output will be a color-map with entries
2020     * selected by six levels of alpha.  One transparent entry, 6 gray
2021     * levels for all the intermediate alpha values, leaving 230 entries
2022     * for the opaque grays.  The color-map entries are the six values
2023     * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
2024     * relevant entry.
2025     *
2026     * if (alpha > 229) // opaque
2027     * {
2028     *    // The 231 entries are selected to make the math below work:
2029     *    base = 0;
2030     *    entry = (231 * gray + 128) >> 8;
2031     * }
2032     * else if (alpha < 26) // transparent
2033     * {
2034     *    base = 231;
2035     *    entry = 0;
2036     * }
2037     * else // partially opaque
2038     * {
2039     *    base = 226 + 6 * PNG_DIV51(alpha);
2040     *    entry = PNG_DIV51(gray);
2041     * }
2042     */
2043    i = 0;
2044    while (i < 231)
2045    {
2046       unsigned int gray = (i * 256 + 115) / 231;
2047       png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2048    }
2049 
2050    /* 255 is used here for the component values for consistency with the code
2051     * that undoes premultiplication in pngwrite.c.
2052     */
2053    png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2054 
2055    for (a=1; a<5; ++a)
2056    {
2057       unsigned int g;
2058 
2059       for (g=0; g<6; ++g)
2060          png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2061              P_sRGB);
2062    }
2063 
2064    return (int)i;
2065 }
2066 
2067 #define PNG_GA_COLORMAP_ENTRIES 256
2068 
2069 static int
2070 make_rgb_colormap(png_image_read_control *display)
2071 {
2072    unsigned int i, r;
2073 
2074    /* Build a 6x6x6 opaque RGB cube */
2075    for (i=r=0; r<6; ++r)
2076    {
2077       unsigned int g;
2078 
2079       for (g=0; g<6; ++g)
2080       {
2081          unsigned int b;
2082 
2083          for (b=0; b<6; ++b)
2084             png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2085                 P_sRGB);
2086       }
2087    }
2088 
2089    return (int)i;
2090 }
2091 
2092 #define PNG_RGB_COLORMAP_ENTRIES 216
2093 
2094 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2095 #define PNG_RGB_INDEX(r,g,b) \
2096    ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2097 
2098 static int
2099 png_image_read_colormap(png_voidp argument)
2100 {
2101    png_image_read_control *display =
2102       png_voidcast(png_image_read_control*, argument);
2103    const png_imagep image = display->image;
2104 
2105    const png_structrp png_ptr = image->opaque->png_ptr;
2106    const png_uint_32 output_format = image->format;
2107    const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2108       P_LINEAR : P_sRGB;
2109 
2110    unsigned int cmap_entries;
2111    unsigned int output_processing;        /* Output processing option */
2112    unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2113 
2114    /* Background information; the background color and the index of this color
2115     * in the color-map if it exists (else 256).
2116     */
2117    unsigned int background_index = 256;
2118    png_uint_32 back_r, back_g, back_b;
2119 
2120    /* Flags to accumulate things that need to be done to the input. */
2121    int expand_tRNS = 0;
2122 
2123    /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2124     * very difficult to do, the results look awful, and it is difficult to see
2125     * what possible use it is because the application can't control the
2126     * color-map.
2127     */
2128    if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2129          png_ptr->num_trans > 0) /* alpha in input */ &&
2130       ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2131    {
2132       if (output_encoding == P_LINEAR) /* compose on black */
2133          back_b = back_g = back_r = 0;
2134 
2135       else if (display->background == NULL /* no way to remove it */)
2136          png_error(png_ptr,
2137              "background color must be supplied to remove alpha/transparency");
2138 
2139       /* Get a copy of the background color (this avoids repeating the checks
2140        * below.)  The encoding is 8-bit sRGB or 16-bit linear, depending on the
2141        * output format.
2142        */
2143       else
2144       {
2145          back_g = display->background->green;
2146          if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2147          {
2148             back_r = display->background->red;
2149             back_b = display->background->blue;
2150          }
2151          else
2152             back_b = back_r = back_g;
2153       }
2154    }
2155 
2156    else if (output_encoding == P_LINEAR)
2157       back_b = back_r = back_g = 65535;
2158 
2159    else
2160       back_b = back_r = back_g = 255;
2161 
2162    /* Default the input file gamma if required - this is necessary because
2163     * libpng assumes that if no gamma information is present the data is in the
2164     * output format, but the simplified API deduces the gamma from the input
2165     * format.
2166     */
2167    if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2168    {
2169       /* Do this directly, not using the png_colorspace functions, to ensure
2170        * that it happens even if the colorspace is invalid (though probably if
2171        * it is the setting will be ignored)  Note that the same thing can be
2172        * achieved at the application interface with png_set_gAMA.
2173        */
2174       if (png_ptr->bit_depth == 16 &&
2175          (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2176          png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2177 
2178       else
2179          png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2180 
2181       png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2182    }
2183 
2184    /* Decide what to do based on the PNG color type of the input data.  The
2185     * utility function png_create_colormap_entry deals with most aspects of the
2186     * output transformations; this code works out how to produce bytes of
2187     * color-map entries from the original format.
2188     */
2189    switch (png_ptr->color_type)
2190    {
2191       case PNG_COLOR_TYPE_GRAY:
2192          if (png_ptr->bit_depth <= 8)
2193          {
2194             /* There at most 256 colors in the output, regardless of
2195              * transparency.
2196              */
2197             unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2198 
2199             cmap_entries = 1U << png_ptr->bit_depth;
2200             if (cmap_entries > image->colormap_entries)
2201                png_error(png_ptr, "gray[8] color-map: too few entries");
2202 
2203             step = 255 / (cmap_entries - 1);
2204             output_processing = PNG_CMAP_NONE;
2205 
2206             /* If there is a tRNS chunk then this either selects a transparent
2207              * value or, if the output has no alpha, the background color.
2208              */
2209             if (png_ptr->num_trans > 0)
2210             {
2211                trans = png_ptr->trans_color.gray;
2212 
2213                if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2214                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2215             }
2216 
2217             /* png_create_colormap_entry just takes an RGBA and writes the
2218              * corresponding color-map entry using the format from 'image',
2219              * including the required conversion to sRGB or linear as
2220              * appropriate.  The input values are always either sRGB (if the
2221              * gamma correction flag is 0) or 0..255 scaled file encoded values
2222              * (if the function must gamma correct them).
2223              */
2224             for (i=val=0; i<cmap_entries; ++i, val += step)
2225             {
2226                /* 'i' is a file value.  While this will result in duplicated
2227                 * entries for 8-bit non-sRGB encoded files it is necessary to
2228                 * have non-gamma corrected values to do tRNS handling.
2229                 */
2230                if (i != trans)
2231                   png_create_colormap_entry(display, i, val, val, val, 255,
2232                       P_FILE/*8-bit with file gamma*/);
2233 
2234                /* Else this entry is transparent.  The colors don't matter if
2235                 * there is an alpha channel (back_alpha == 0), but it does no
2236                 * harm to pass them in; the values are not set above so this
2237                 * passes in white.
2238                 *
2239                 * NOTE: this preserves the full precision of the application
2240                 * supplied background color when it is used.
2241                 */
2242                else
2243                   png_create_colormap_entry(display, i, back_r, back_g, back_b,
2244                       back_alpha, output_encoding);
2245             }
2246 
2247             /* We need libpng to preserve the original encoding. */
2248             data_encoding = P_FILE;
2249 
2250             /* The rows from libpng, while technically gray values, are now also
2251              * color-map indices; however, they may need to be expanded to 1
2252              * byte per pixel.  This is what png_set_packing does (i.e., it
2253              * unpacks the bit values into bytes.)
2254              */
2255             if (png_ptr->bit_depth < 8)
2256                png_set_packing(png_ptr);
2257          }
2258 
2259          else /* bit depth is 16 */
2260          {
2261             /* The 16-bit input values can be converted directly to 8-bit gamma
2262              * encoded values; however, if a tRNS chunk is present 257 color-map
2263              * entries are required.  This means that the extra entry requires
2264              * special processing; add an alpha channel, sacrifice gray level
2265              * 254 and convert transparent (alpha==0) entries to that.
2266              *
2267              * Use libpng to chop the data to 8 bits.  Convert it to sRGB at the
2268              * same time to minimize quality loss.  If a tRNS chunk is present
2269              * this means libpng must handle it too; otherwise it is impossible
2270              * to do the exact match on the 16-bit value.
2271              *
2272              * If the output has no alpha channel *and* the background color is
2273              * gray then it is possible to let libpng handle the substitution by
2274              * ensuring that the corresponding gray level matches the background
2275              * color exactly.
2276              */
2277             data_encoding = P_sRGB;
2278 
2279             if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2280                png_error(png_ptr, "gray[16] color-map: too few entries");
2281 
2282             cmap_entries = (unsigned int)make_gray_colormap(display);
2283 
2284             if (png_ptr->num_trans > 0)
2285             {
2286                unsigned int back_alpha;
2287 
2288                if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2289                   back_alpha = 0;
2290 
2291                else
2292                {
2293                   if (back_r == back_g && back_g == back_b)
2294                   {
2295                      /* Background is gray; no special processing will be
2296                       * required.
2297                       */
2298                      png_color_16 c;
2299                      png_uint_32 gray = back_g;
2300 
2301                      if (output_encoding == P_LINEAR)
2302                      {
2303                         gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2304 
2305                         /* And make sure the corresponding palette entry
2306                          * matches.
2307                          */
2308                         png_create_colormap_entry(display, gray, back_g, back_g,
2309                             back_g, 65535, P_LINEAR);
2310                      }
2311 
2312                      /* The background passed to libpng, however, must be the
2313                       * sRGB value.
2314                       */
2315                      c.index = 0; /*unused*/
2316                      c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2317 
2318                      /* NOTE: does this work without expanding tRNS to alpha?
2319                       * It should be the color->gray case below apparently
2320                       * doesn't.
2321                       */
2322                      png_set_background_fixed(png_ptr, &c,
2323                          PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2324                          0/*gamma: not used*/);
2325 
2326                      output_processing = PNG_CMAP_NONE;
2327                      break;
2328                   }
2329 #ifdef __COVERITY__
2330                  /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2331                   * here.
2332                   */
2333                   back_alpha = 255;
2334 #else
2335                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2336 #endif
2337                }
2338 
2339                /* output_processing means that the libpng-processed row will be
2340                 * 8-bit GA and it has to be processing to single byte color-map
2341                 * values.  Entry 254 is replaced by either a completely
2342                 * transparent entry or by the background color at full
2343                 * precision (and the background color is not a simple gray
2344                 * level in this case.)
2345                 */
2346                expand_tRNS = 1;
2347                output_processing = PNG_CMAP_TRANS;
2348                background_index = 254;
2349 
2350                /* And set (overwrite) color-map entry 254 to the actual
2351                 * background color at full precision.
2352                 */
2353                png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2354                    back_alpha, output_encoding);
2355             }
2356 
2357             else
2358                output_processing = PNG_CMAP_NONE;
2359          }
2360          break;
2361 
2362       case PNG_COLOR_TYPE_GRAY_ALPHA:
2363          /* 8-bit or 16-bit PNG with two channels - gray and alpha.  A minimum
2364           * of 65536 combinations.  If, however, the alpha channel is to be
2365           * removed there are only 256 possibilities if the background is gray.
2366           * (Otherwise there is a subset of the 65536 possibilities defined by
2367           * the triangle between black, white and the background color.)
2368           *
2369           * Reduce 16-bit files to 8-bit and sRGB encode the result.  No need to
2370           * worry about tRNS matching - tRNS is ignored if there is an alpha
2371           * channel.
2372           */
2373          data_encoding = P_sRGB;
2374 
2375          if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2376          {
2377             if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2378                png_error(png_ptr, "gray+alpha color-map: too few entries");
2379 
2380             cmap_entries = (unsigned int)make_ga_colormap(display);
2381 
2382             background_index = PNG_CMAP_GA_BACKGROUND;
2383             output_processing = PNG_CMAP_GA;
2384          }
2385 
2386          else /* alpha is removed */
2387          {
2388             /* Alpha must be removed as the PNG data is processed when the
2389              * background is a color because the G and A channels are
2390              * independent and the vector addition (non-parallel vectors) is a
2391              * 2-D problem.
2392              *
2393              * This can be reduced to the same algorithm as above by making a
2394              * colormap containing gray levels (for the opaque grays), a
2395              * background entry (for a transparent pixel) and a set of four six
2396              * level color values, one set for each intermediate alpha value.
2397              * See the comments in make_ga_colormap for how this works in the
2398              * per-pixel processing.
2399              *
2400              * If the background is gray, however, we only need a 256 entry gray
2401              * level color map.  It is sufficient to make the entry generated
2402              * for the background color be exactly the color specified.
2403              */
2404             if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2405                (back_r == back_g && back_g == back_b))
2406             {
2407                /* Background is gray; no special processing will be required. */
2408                png_color_16 c;
2409                png_uint_32 gray = back_g;
2410 
2411                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2412                   png_error(png_ptr, "gray-alpha color-map: too few entries");
2413 
2414                cmap_entries = (unsigned int)make_gray_colormap(display);
2415 
2416                if (output_encoding == P_LINEAR)
2417                {
2418                   gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2419 
2420                   /* And make sure the corresponding palette entry matches. */
2421                   png_create_colormap_entry(display, gray, back_g, back_g,
2422                       back_g, 65535, P_LINEAR);
2423                }
2424 
2425                /* The background passed to libpng, however, must be the sRGB
2426                 * value.
2427                 */
2428                c.index = 0; /*unused*/
2429                c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2430 
2431                png_set_background_fixed(png_ptr, &c,
2432                    PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2433                    0/*gamma: not used*/);
2434 
2435                output_processing = PNG_CMAP_NONE;
2436             }
2437 
2438             else
2439             {
2440                png_uint_32 i, a;
2441 
2442                /* This is the same as png_make_ga_colormap, above, except that
2443                 * the entries are all opaque.
2444                 */
2445                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2446                   png_error(png_ptr, "ga-alpha color-map: too few entries");
2447 
2448                i = 0;
2449                while (i < 231)
2450                {
2451                   png_uint_32 gray = (i * 256 + 115) / 231;
2452                   png_create_colormap_entry(display, i++, gray, gray, gray,
2453                       255, P_sRGB);
2454                }
2455 
2456                /* NOTE: this preserves the full precision of the application
2457                 * background color.
2458                 */
2459                background_index = i;
2460                png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2461 #ifdef __COVERITY__
2462                    /* Coverity claims that output_encoding
2463                     * cannot be 2 (P_LINEAR) here.
2464                     */ 255U,
2465 #else
2466                     output_encoding == P_LINEAR ? 65535U : 255U,
2467 #endif
2468                     output_encoding);
2469 
2470                /* For non-opaque input composite on the sRGB background - this
2471                 * requires inverting the encoding for each component.  The input
2472                 * is still converted to the sRGB encoding because this is a
2473                 * reasonable approximate to the logarithmic curve of human
2474                 * visual sensitivity, at least over the narrow range which PNG
2475                 * represents.  Consequently 'G' is always sRGB encoded, while
2476                 * 'A' is linear.  We need the linear background colors.
2477                 */
2478                if (output_encoding == P_sRGB) /* else already linear */
2479                {
2480                   /* This may produce a value not exactly matching the
2481                    * background, but that's ok because these numbers are only
2482                    * used when alpha != 0
2483                    */
2484                   back_r = png_sRGB_table[back_r];
2485                   back_g = png_sRGB_table[back_g];
2486                   back_b = png_sRGB_table[back_b];
2487                }
2488 
2489                for (a=1; a<5; ++a)
2490                {
2491                   unsigned int g;
2492 
2493                   /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2494                    * by an 8-bit alpha value (0..255).
2495                    */
2496                   png_uint_32 alpha = 51 * a;
2497                   png_uint_32 back_rx = (255-alpha) * back_r;
2498                   png_uint_32 back_gx = (255-alpha) * back_g;
2499                   png_uint_32 back_bx = (255-alpha) * back_b;
2500 
2501                   for (g=0; g<6; ++g)
2502                   {
2503                      png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2504 
2505                      png_create_colormap_entry(display, i++,
2506                          PNG_sRGB_FROM_LINEAR(gray + back_rx),
2507                          PNG_sRGB_FROM_LINEAR(gray + back_gx),
2508                          PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2509                   }
2510                }
2511 
2512                cmap_entries = i;
2513                output_processing = PNG_CMAP_GA;
2514             }
2515          }
2516          break;
2517 
2518       case PNG_COLOR_TYPE_RGB:
2519       case PNG_COLOR_TYPE_RGB_ALPHA:
2520          /* Exclude the case where the output is gray; we can always handle this
2521           * with the cases above.
2522           */
2523          if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2524          {
2525             /* The color-map will be grayscale, so we may as well convert the
2526              * input RGB values to a simple grayscale and use the grayscale
2527              * code above.
2528              *
2529              * NOTE: calling this apparently damages the recognition of the
2530              * transparent color in background color handling; call
2531              * png_set_tRNS_to_alpha before png_set_background_fixed.
2532              */
2533             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2534                 -1);
2535             data_encoding = P_sRGB;
2536 
2537             /* The output will now be one or two 8-bit gray or gray+alpha
2538              * channels.  The more complex case arises when the input has alpha.
2539              */
2540             if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2541                png_ptr->num_trans > 0) &&
2542                (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2543             {
2544                /* Both input and output have an alpha channel, so no background
2545                 * processing is required; just map the GA bytes to the right
2546                 * color-map entry.
2547                 */
2548                expand_tRNS = 1;
2549 
2550                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2551                   png_error(png_ptr, "rgb[ga] color-map: too few entries");
2552 
2553                cmap_entries = (unsigned int)make_ga_colormap(display);
2554                background_index = PNG_CMAP_GA_BACKGROUND;
2555                output_processing = PNG_CMAP_GA;
2556             }
2557 
2558             else
2559             {
2560                /* Either the input or the output has no alpha channel, so there
2561                 * will be no non-opaque pixels in the color-map; it will just be
2562                 * grayscale.
2563                 */
2564                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2565                   png_error(png_ptr, "rgb[gray] color-map: too few entries");
2566 
2567                /* Ideally this code would use libpng to do the gamma correction,
2568                 * but if an input alpha channel is to be removed we will hit the
2569                 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2570                 * correction bug).  Fix this by dropping the gamma correction in
2571                 * this case and doing it in the palette; this will result in
2572                 * duplicate palette entries, but that's better than the
2573                 * alternative of double gamma correction.
2574                 */
2575                if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2576                   png_ptr->num_trans > 0) &&
2577                   png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2578                {
2579                   cmap_entries = (unsigned int)make_gray_file_colormap(display);
2580                   data_encoding = P_FILE;
2581                }
2582 
2583                else
2584                   cmap_entries = (unsigned int)make_gray_colormap(display);
2585 
2586                /* But if the input has alpha or transparency it must be removed
2587                 */
2588                if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2589                   png_ptr->num_trans > 0)
2590                {
2591                   png_color_16 c;
2592                   png_uint_32 gray = back_g;
2593 
2594                   /* We need to ensure that the application background exists in
2595                    * the colormap and that completely transparent pixels map to
2596                    * it.  Achieve this simply by ensuring that the entry
2597                    * selected for the background really is the background color.
2598                    */
2599                   if (data_encoding == P_FILE) /* from the fixup above */
2600                   {
2601                      /* The app supplied a gray which is in output_encoding, we
2602                       * need to convert it to a value of the input (P_FILE)
2603                       * encoding then set this palette entry to the required
2604                       * output encoding.
2605                       */
2606                      if (output_encoding == P_sRGB)
2607                         gray = png_sRGB_table[gray]; /* now P_LINEAR */
2608 
2609                      gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2610                          png_ptr->colorspace.gamma)); /* now P_FILE */
2611 
2612                      /* And make sure the corresponding palette entry contains
2613                       * exactly the required sRGB value.
2614                       */
2615                      png_create_colormap_entry(display, gray, back_g, back_g,
2616                          back_g, 0/*unused*/, output_encoding);
2617                   }
2618 
2619                   else if (output_encoding == P_LINEAR)
2620                   {
2621                      gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2622 
2623                      /* And make sure the corresponding palette entry matches.
2624                       */
2625                      png_create_colormap_entry(display, gray, back_g, back_g,
2626                         back_g, 0/*unused*/, P_LINEAR);
2627                   }
2628 
2629                   /* The background passed to libpng, however, must be the
2630                    * output (normally sRGB) value.
2631                    */
2632                   c.index = 0; /*unused*/
2633                   c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2634 
2635                   /* NOTE: the following is apparently a bug in libpng. Without
2636                    * it the transparent color recognition in
2637                    * png_set_background_fixed seems to go wrong.
2638                    */
2639                   expand_tRNS = 1;
2640                   png_set_background_fixed(png_ptr, &c,
2641                       PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2642                       0/*gamma: not used*/);
2643                }
2644 
2645                output_processing = PNG_CMAP_NONE;
2646             }
2647          }
2648 
2649          else /* output is color */
2650          {
2651             /* We could use png_quantize here so long as there is no transparent
2652              * color or alpha; png_quantize ignores alpha.  Easier overall just
2653              * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2654              * Consequently we always want libpng to produce sRGB data.
2655              */
2656             data_encoding = P_sRGB;
2657 
2658             /* Is there any transparency or alpha? */
2659             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2660                png_ptr->num_trans > 0)
2661             {
2662                /* Is there alpha in the output too?  If so all four channels are
2663                 * processed into a special RGB cube with alpha support.
2664                 */
2665                if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2666                {
2667                   png_uint_32 r;
2668 
2669                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2670                      png_error(png_ptr, "rgb+alpha color-map: too few entries");
2671 
2672                   cmap_entries = (unsigned int)make_rgb_colormap(display);
2673 
2674                   /* Add a transparent entry. */
2675                   png_create_colormap_entry(display, cmap_entries, 255, 255,
2676                       255, 0, P_sRGB);
2677 
2678                   /* This is stored as the background index for the processing
2679                    * algorithm.
2680                    */
2681                   background_index = cmap_entries++;
2682 
2683                   /* Add 27 r,g,b entries each with alpha 0.5. */
2684                   for (r=0; r<256; r = (r << 1) | 0x7f)
2685                   {
2686                      png_uint_32 g;
2687 
2688                      for (g=0; g<256; g = (g << 1) | 0x7f)
2689                      {
2690                         png_uint_32 b;
2691 
2692                         /* This generates components with the values 0, 127 and
2693                          * 255
2694                          */
2695                         for (b=0; b<256; b = (b << 1) | 0x7f)
2696                            png_create_colormap_entry(display, cmap_entries++,
2697                                r, g, b, 128, P_sRGB);
2698                      }
2699                   }
2700 
2701                   expand_tRNS = 1;
2702                   output_processing = PNG_CMAP_RGB_ALPHA;
2703                }
2704 
2705                else
2706                {
2707                   /* Alpha/transparency must be removed.  The background must
2708                    * exist in the color map (achieved by setting adding it after
2709                    * the 666 color-map).  If the standard processing code will
2710                    * pick up this entry automatically that's all that is
2711                    * required; libpng can be called to do the background
2712                    * processing.
2713                    */
2714                   unsigned int sample_size =
2715                      PNG_IMAGE_SAMPLE_SIZE(output_format);
2716                   png_uint_32 r, g, b; /* sRGB background */
2717 
2718                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2719                      png_error(png_ptr, "rgb-alpha color-map: too few entries");
2720 
2721                   cmap_entries = (unsigned int)make_rgb_colormap(display);
2722 
2723                   png_create_colormap_entry(display, cmap_entries, back_r,
2724                       back_g, back_b, 0/*unused*/, output_encoding);
2725 
2726                   if (output_encoding == P_LINEAR)
2727                   {
2728                      r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2729                      g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2730                      b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2731                   }
2732 
2733                   else
2734                   {
2735                      r = back_r;
2736                      g = back_g;
2737                      b = back_g;
2738                   }
2739 
2740                   /* Compare the newly-created color-map entry with the one the
2741                    * PNG_CMAP_RGB algorithm will use.  If the two entries don't
2742                    * match, add the new one and set this as the background
2743                    * index.
2744                    */
2745                   if (memcmp((png_const_bytep)display->colormap +
2746                       sample_size * cmap_entries,
2747                       (png_const_bytep)display->colormap +
2748                           sample_size * PNG_RGB_INDEX(r,g,b),
2749                      sample_size) != 0)
2750                   {
2751                      /* The background color must be added. */
2752                      background_index = cmap_entries++;
2753 
2754                      /* Add 27 r,g,b entries each with created by composing with
2755                       * the background at alpha 0.5.
2756                       */
2757                      for (r=0; r<256; r = (r << 1) | 0x7f)
2758                      {
2759                         for (g=0; g<256; g = (g << 1) | 0x7f)
2760                         {
2761                            /* This generates components with the values 0, 127
2762                             * and 255
2763                             */
2764                            for (b=0; b<256; b = (b << 1) | 0x7f)
2765                               png_create_colormap_entry(display, cmap_entries++,
2766                                   png_colormap_compose(display, r, P_sRGB, 128,
2767                                       back_r, output_encoding),
2768                                   png_colormap_compose(display, g, P_sRGB, 128,
2769                                       back_g, output_encoding),
2770                                   png_colormap_compose(display, b, P_sRGB, 128,
2771                                       back_b, output_encoding),
2772                                   0/*unused*/, output_encoding);
2773                         }
2774                      }
2775 
2776                      expand_tRNS = 1;
2777                      output_processing = PNG_CMAP_RGB_ALPHA;
2778                   }
2779 
2780                   else /* background color is in the standard color-map */
2781                   {
2782                      png_color_16 c;
2783 
2784                      c.index = 0; /*unused*/
2785                      c.red = (png_uint_16)back_r;
2786                      c.gray = c.green = (png_uint_16)back_g;
2787                      c.blue = (png_uint_16)back_b;
2788 
2789                      png_set_background_fixed(png_ptr, &c,
2790                          PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2791                          0/*gamma: not used*/);
2792 
2793                      output_processing = PNG_CMAP_RGB;
2794                   }
2795                }
2796             }
2797 
2798             else /* no alpha or transparency in the input */
2799             {
2800                /* Alpha in the output is irrelevant, simply map the opaque input
2801                 * pixels to the 6x6x6 color-map.
2802                 */
2803                if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2804                   png_error(png_ptr, "rgb color-map: too few entries");
2805 
2806                cmap_entries = (unsigned int)make_rgb_colormap(display);
2807                output_processing = PNG_CMAP_RGB;
2808             }
2809          }
2810          break;
2811 
2812       case PNG_COLOR_TYPE_PALETTE:
2813          /* It's already got a color-map.  It may be necessary to eliminate the
2814           * tRNS entries though.
2815           */
2816          {
2817             unsigned int num_trans = png_ptr->num_trans;
2818             png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2819             png_const_colorp colormap = png_ptr->palette;
2820             const int do_background = trans != NULL &&
2821                (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2822             unsigned int i;
2823 
2824             /* Just in case: */
2825             if (trans == NULL)
2826                num_trans = 0;
2827 
2828             output_processing = PNG_CMAP_NONE;
2829             data_encoding = P_FILE; /* Don't change from color-map indices */
2830             cmap_entries = (unsigned int)png_ptr->num_palette;
2831             if (cmap_entries > 256)
2832                cmap_entries = 256;
2833 
2834             if (cmap_entries > (unsigned int)image->colormap_entries)
2835                png_error(png_ptr, "palette color-map: too few entries");
2836 
2837             for (i=0; i < cmap_entries; ++i)
2838             {
2839                if (do_background != 0 && i < num_trans && trans[i] < 255)
2840                {
2841                   if (trans[i] == 0)
2842                      png_create_colormap_entry(display, i, back_r, back_g,
2843                          back_b, 0, output_encoding);
2844 
2845                   else
2846                   {
2847                      /* Must compose the PNG file color in the color-map entry
2848                       * on the sRGB color in 'back'.
2849                       */
2850                      png_create_colormap_entry(display, i,
2851                          png_colormap_compose(display, colormap[i].red,
2852                              P_FILE, trans[i], back_r, output_encoding),
2853                          png_colormap_compose(display, colormap[i].green,
2854                              P_FILE, trans[i], back_g, output_encoding),
2855                          png_colormap_compose(display, colormap[i].blue,
2856                              P_FILE, trans[i], back_b, output_encoding),
2857                          output_encoding == P_LINEAR ? trans[i] * 257U :
2858                              trans[i],
2859                          output_encoding);
2860                   }
2861                }
2862 
2863                else
2864                   png_create_colormap_entry(display, i, colormap[i].red,
2865                       colormap[i].green, colormap[i].blue,
2866                       i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2867             }
2868 
2869             /* The PNG data may have indices packed in fewer than 8 bits, it
2870              * must be expanded if so.
2871              */
2872             if (png_ptr->bit_depth < 8)
2873                png_set_packing(png_ptr);
2874          }
2875          break;
2876 
2877       default:
2878          png_error(png_ptr, "invalid PNG color type");
2879          /*NOT REACHED*/
2880    }
2881 
2882    /* Now deal with the output processing */
2883    if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2884        (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2885       png_set_tRNS_to_alpha(png_ptr);
2886 
2887    switch (data_encoding)
2888    {
2889       case P_sRGB:
2890          /* Change to 8-bit sRGB */
2891          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2892          /* FALL THROUGH */
2893 
2894       case P_FILE:
2895          if (png_ptr->bit_depth > 8)
2896             png_set_scale_16(png_ptr);
2897          break;
2898 
2899 #ifdef __GNUC__
2900       default:
2901          png_error(png_ptr, "bad data option (internal error)");
2902 #endif
2903    }
2904 
2905    if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2906       png_error(png_ptr, "color map overflow (BAD internal error)");
2907 
2908    image->colormap_entries = cmap_entries;
2909 
2910    /* Double check using the recorded background index */
2911    switch (output_processing)
2912    {
2913       case PNG_CMAP_NONE:
2914          if (background_index != PNG_CMAP_NONE_BACKGROUND)
2915             goto bad_background;
2916          break;
2917 
2918       case PNG_CMAP_GA:
2919          if (background_index != PNG_CMAP_GA_BACKGROUND)
2920             goto bad_background;
2921          break;
2922 
2923       case PNG_CMAP_TRANS:
2924          if (background_index >= cmap_entries ||
2925             background_index != PNG_CMAP_TRANS_BACKGROUND)
2926             goto bad_background;
2927          break;
2928 
2929       case PNG_CMAP_RGB:
2930          if (background_index != PNG_CMAP_RGB_BACKGROUND)
2931             goto bad_background;
2932          break;
2933 
2934       case PNG_CMAP_RGB_ALPHA:
2935          if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2936             goto bad_background;
2937          break;
2938 
2939       default:
2940          png_error(png_ptr, "bad processing option (internal error)");
2941 
2942       bad_background:
2943          png_error(png_ptr, "bad background index (internal error)");
2944    }
2945 
2946    display->colormap_processing = (int)output_processing;
2947 
2948    return 1/*ok*/;
2949 }
2950 
2951 /* The final part of the color-map read called from png_image_finish_read. */
2952 static int
2953 png_image_read_and_map(png_voidp argument)
2954 {
2955    png_image_read_control *display = png_voidcast(png_image_read_control*,
2956        argument);
2957    png_imagep image = display->image;
2958    png_structrp png_ptr = image->opaque->png_ptr;
2959    int passes;
2960 
2961    /* Called when the libpng data must be transformed into the color-mapped
2962     * form.  There is a local row buffer in display->local and this routine must
2963     * do the interlace handling.
2964     */
2965    switch (png_ptr->interlaced)
2966    {
2967       case PNG_INTERLACE_NONE:
2968          passes = 1;
2969          break;
2970 
2971       case PNG_INTERLACE_ADAM7:
2972          passes = PNG_INTERLACE_ADAM7_PASSES;
2973          break;
2974 
2975       default:
2976          png_error(png_ptr, "unknown interlace type");
2977    }
2978 
2979    {
2980       png_uint_32  height = image->height;
2981       png_uint_32  width = image->width;
2982       int          proc = display->colormap_processing;
2983       png_bytep    first_row = png_voidcast(png_bytep, display->first_row);
2984       ptrdiff_t    step_row = display->row_bytes;
2985       int pass;
2986 
2987       for (pass = 0; pass < passes; ++pass)
2988       {
2989          unsigned int     startx, stepx, stepy;
2990          png_uint_32      y;
2991 
2992          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2993          {
2994             /* The row may be empty for a short image: */
2995             if (PNG_PASS_COLS(width, pass) == 0)
2996                continue;
2997 
2998             startx = PNG_PASS_START_COL(pass);
2999             stepx = PNG_PASS_COL_OFFSET(pass);
3000             y = PNG_PASS_START_ROW(pass);
3001             stepy = PNG_PASS_ROW_OFFSET(pass);
3002          }
3003 
3004          else
3005          {
3006             y = 0;
3007             startx = 0;
3008             stepx = stepy = 1;
3009          }
3010 
3011          for (; y<height; y += stepy)
3012          {
3013             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3014             png_bytep outrow = first_row + y * step_row;
3015             png_const_bytep end_row = outrow + width;
3016 
3017             /* Read read the libpng data into the temporary buffer. */
3018             png_read_row(png_ptr, inrow, NULL);
3019 
3020             /* Now process the row according to the processing option, note
3021              * that the caller verifies that the format of the libpng output
3022              * data is as required.
3023              */
3024             outrow += startx;
3025             switch (proc)
3026             {
3027                case PNG_CMAP_GA:
3028                   for (; outrow < end_row; outrow += stepx)
3029                   {
3030                      /* The data is always in the PNG order */
3031                      unsigned int gray = *inrow++;
3032                      unsigned int alpha = *inrow++;
3033                      unsigned int entry;
3034 
3035                      /* NOTE: this code is copied as a comment in
3036                       * make_ga_colormap above.  Please update the
3037                       * comment if you change this code!
3038                       */
3039                      if (alpha > 229) /* opaque */
3040                      {
3041                         entry = (231 * gray + 128) >> 8;
3042                      }
3043                      else if (alpha < 26) /* transparent */
3044                      {
3045                         entry = 231;
3046                      }
3047                      else /* partially opaque */
3048                      {
3049                         entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3050                      }
3051 
3052                      *outrow = (png_byte)entry;
3053                   }
3054                   break;
3055 
3056                case PNG_CMAP_TRANS:
3057                   for (; outrow < end_row; outrow += stepx)
3058                   {
3059                      png_byte gray = *inrow++;
3060                      png_byte alpha = *inrow++;
3061 
3062                      if (alpha == 0)
3063                         *outrow = PNG_CMAP_TRANS_BACKGROUND;
3064 
3065                      else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3066                         *outrow = gray;
3067 
3068                      else
3069                         *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3070                   }
3071                   break;
3072 
3073                case PNG_CMAP_RGB:
3074                   for (; outrow < end_row; outrow += stepx)
3075                   {
3076                      *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3077                      inrow += 3;
3078                   }
3079                   break;
3080 
3081                case PNG_CMAP_RGB_ALPHA:
3082                   for (; outrow < end_row; outrow += stepx)
3083                   {
3084                      unsigned int alpha = inrow[3];
3085 
3086                      /* Because the alpha entries only hold alpha==0.5 values
3087                       * split the processing at alpha==0.25 (64) and 0.75
3088                       * (196).
3089                       */
3090 
3091                      if (alpha >= 196)
3092                         *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3093                             inrow[2]);
3094 
3095                      else if (alpha < 64)
3096                         *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3097 
3098                      else
3099                      {
3100                         /* Likewise there are three entries for each of r, g
3101                          * and b.  We could select the entry by popcount on
3102                          * the top two bits on those architectures that
3103                          * support it, this is what the code below does,
3104                          * crudely.
3105                          */
3106                         unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3107 
3108                         /* Here are how the values map:
3109                          *
3110                          * 0x00 .. 0x3f -> 0
3111                          * 0x40 .. 0xbf -> 1
3112                          * 0xc0 .. 0xff -> 2
3113                          *
3114                          * So, as above with the explicit alpha checks, the
3115                          * breakpoints are at 64 and 196.
3116                          */
3117                         if (inrow[0] & 0x80) back_i += 9; /* red */
3118                         if (inrow[0] & 0x40) back_i += 9;
3119                         if (inrow[0] & 0x80) back_i += 3; /* green */
3120                         if (inrow[0] & 0x40) back_i += 3;
3121                         if (inrow[0] & 0x80) back_i += 1; /* blue */
3122                         if (inrow[0] & 0x40) back_i += 1;
3123 
3124                         *outrow = (png_byte)back_i;
3125                      }
3126 
3127                      inrow += 4;
3128                   }
3129                   break;
3130 
3131                default:
3132                   break;
3133             }
3134          }
3135       }
3136    }
3137 
3138    return 1;
3139 }
3140 
3141 static int
3142 png_image_read_colormapped(png_voidp argument)
3143 {
3144    png_image_read_control *display = png_voidcast(png_image_read_control*,
3145        argument);
3146    png_imagep image = display->image;
3147    png_controlp control = image->opaque;
3148    png_structrp png_ptr = control->png_ptr;
3149    png_inforp info_ptr = control->info_ptr;
3150 
3151    int passes = 0; /* As a flag */
3152 
3153    PNG_SKIP_CHUNKS(png_ptr);
3154 
3155    /* Update the 'info' structure and make sure the result is as required; first
3156     * make sure to turn on the interlace handling if it will be required
3157     * (because it can't be turned on *after* the call to png_read_update_info!)
3158     */
3159    if (display->colormap_processing == PNG_CMAP_NONE)
3160       passes = png_set_interlace_handling(png_ptr);
3161 
3162    png_read_update_info(png_ptr, info_ptr);
3163 
3164    /* The expected output can be deduced from the colormap_processing option. */
3165    switch (display->colormap_processing)
3166    {
3167       case PNG_CMAP_NONE:
3168          /* Output must be one channel and one byte per pixel, the output
3169           * encoding can be anything.
3170           */
3171          if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3172             info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3173             info_ptr->bit_depth == 8)
3174             break;
3175 
3176          goto bad_output;
3177 
3178       case PNG_CMAP_TRANS:
3179       case PNG_CMAP_GA:
3180          /* Output must be two channels and the 'G' one must be sRGB, the latter
3181           * can be checked with an exact number because it should have been set
3182           * to this number above!
3183           */
3184          if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3185             info_ptr->bit_depth == 8 &&
3186             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3187             image->colormap_entries == 256)
3188             break;
3189 
3190          goto bad_output;
3191 
3192       case PNG_CMAP_RGB:
3193          /* Output must be 8-bit sRGB encoded RGB */
3194          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3195             info_ptr->bit_depth == 8 &&
3196             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3197             image->colormap_entries == 216)
3198             break;
3199 
3200          goto bad_output;
3201 
3202       case PNG_CMAP_RGB_ALPHA:
3203          /* Output must be 8-bit sRGB encoded RGBA */
3204          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3205             info_ptr->bit_depth == 8 &&
3206             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3207             image->colormap_entries == 244 /* 216 + 1 + 27 */)
3208             break;
3209 
3210          /* goto bad_output; */
3211          /* FALL THROUGH */
3212 
3213       default:
3214       bad_output:
3215          png_error(png_ptr, "bad color-map processing (internal error)");
3216    }
3217 
3218    /* Now read the rows.  Do this here if it is possible to read directly into
3219     * the output buffer, otherwise allocate a local row buffer of the maximum
3220     * size libpng requires and call the relevant processing routine safely.
3221     */
3222    {
3223       png_voidp first_row = display->buffer;
3224       ptrdiff_t row_bytes = display->row_stride;
3225 
3226       /* The following expression is designed to work correctly whether it gives
3227        * a signed or an unsigned result.
3228        */
3229       if (row_bytes < 0)
3230       {
3231          char *ptr = png_voidcast(char*, first_row);
3232          ptr += (image->height-1) * (-row_bytes);
3233          first_row = png_voidcast(png_voidp, ptr);
3234       }
3235 
3236       display->first_row = first_row;
3237       display->row_bytes = row_bytes;
3238    }
3239 
3240    if (passes == 0)
3241    {
3242       int result;
3243       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3244 
3245       display->local_row = row;
3246       result = png_safe_execute(image, png_image_read_and_map, display);
3247       display->local_row = NULL;
3248       png_free(png_ptr, row);
3249 
3250       return result;
3251    }
3252 
3253    else
3254    {
3255       png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3256 
3257       while (--passes >= 0)
3258       {
3259          png_uint_32      y = image->height;
3260          png_bytep        row = png_voidcast(png_bytep, display->first_row);
3261 
3262          for (; y > 0; --y)
3263          {
3264             png_read_row(png_ptr, row, NULL);
3265             row += row_bytes;
3266          }
3267       }
3268 
3269       return 1;
3270    }
3271 }
3272 
3273 /* Just the row reading part of png_image_read. */
3274 static int
3275 png_image_read_composite(png_voidp argument)
3276 {
3277    png_image_read_control *display = png_voidcast(png_image_read_control*,
3278        argument);
3279    png_imagep image = display->image;
3280    png_structrp png_ptr = image->opaque->png_ptr;
3281    int passes;
3282 
3283    switch (png_ptr->interlaced)
3284    {
3285       case PNG_INTERLACE_NONE:
3286          passes = 1;
3287          break;
3288 
3289       case PNG_INTERLACE_ADAM7:
3290          passes = PNG_INTERLACE_ADAM7_PASSES;
3291          break;
3292 
3293       default:
3294          png_error(png_ptr, "unknown interlace type");
3295    }
3296 
3297    {
3298       png_uint_32  height = image->height;
3299       png_uint_32  width = image->width;
3300       ptrdiff_t    step_row = display->row_bytes;
3301       unsigned int channels =
3302           (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3303       int pass;
3304 
3305       for (pass = 0; pass < passes; ++pass)
3306       {
3307          unsigned int     startx, stepx, stepy;
3308          png_uint_32      y;
3309 
3310          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3311          {
3312             /* The row may be empty for a short image: */
3313             if (PNG_PASS_COLS(width, pass) == 0)
3314                continue;
3315 
3316             startx = PNG_PASS_START_COL(pass) * channels;
3317             stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3318             y = PNG_PASS_START_ROW(pass);
3319             stepy = PNG_PASS_ROW_OFFSET(pass);
3320          }
3321 
3322          else
3323          {
3324             y = 0;
3325             startx = 0;
3326             stepx = channels;
3327             stepy = 1;
3328          }
3329 
3330          for (; y<height; y += stepy)
3331          {
3332             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3333             png_bytep outrow;
3334             png_const_bytep end_row;
3335 
3336             /* Read the row, which is packed: */
3337             png_read_row(png_ptr, inrow, NULL);
3338 
3339             outrow = png_voidcast(png_bytep, display->first_row);
3340             outrow += y * step_row;
3341             end_row = outrow + width * channels;
3342 
3343             /* Now do the composition on each pixel in this row. */
3344             outrow += startx;
3345             for (; outrow < end_row; outrow += stepx)
3346             {
3347                png_byte alpha = inrow[channels];
3348 
3349                if (alpha > 0) /* else no change to the output */
3350                {
3351                   unsigned int c;
3352 
3353                   for (c=0; c<channels; ++c)
3354                   {
3355                      png_uint_32 component = inrow[c];
3356 
3357                      if (alpha < 255) /* else just use component */
3358                      {
3359                         /* This is PNG_OPTIMIZED_ALPHA, the component value
3360                          * is a linear 8-bit value.  Combine this with the
3361                          * current outrow[c] value which is sRGB encoded.
3362                          * Arithmetic here is 16-bits to preserve the output
3363                          * values correctly.
3364                          */
3365                         component *= 257*255; /* =65535 */
3366                         component += (255-alpha)*png_sRGB_table[outrow[c]];
3367 
3368                         /* So 'component' is scaled by 255*65535 and is
3369                          * therefore appropriate for the sRGB to linear
3370                          * conversion table.
3371                          */
3372                         component = PNG_sRGB_FROM_LINEAR(component);
3373                      }
3374 
3375                      outrow[c] = (png_byte)component;
3376                   }
3377                }
3378 
3379                inrow += channels+1; /* components and alpha channel */
3380             }
3381          }
3382       }
3383    }
3384 
3385    return 1;
3386 }
3387 
3388 /* The do_local_background case; called when all the following transforms are to
3389  * be done:
3390  *
3391  * PNG_RGB_TO_GRAY
3392  * PNG_COMPOSITE
3393  * PNG_GAMMA
3394  *
3395  * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3396  * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3397  * correction.  The fix-up is to prevent the PNG_COMPOSITE operation from
3398  * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3399  * row and handles the removal or pre-multiplication of the alpha channel.
3400  */
3401 static int
3402 png_image_read_background(png_voidp argument)
3403 {
3404    png_image_read_control *display = png_voidcast(png_image_read_control*,
3405        argument);
3406    png_imagep image = display->image;
3407    png_structrp png_ptr = image->opaque->png_ptr;
3408    png_inforp info_ptr = image->opaque->info_ptr;
3409    png_uint_32 height = image->height;
3410    png_uint_32 width = image->width;
3411    int pass, passes;
3412 
3413    /* Double check the convoluted logic below.  We expect to get here with
3414     * libpng doing rgb to gray and gamma correction but background processing
3415     * left to the png_image_read_background function.  The rows libpng produce
3416     * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3417     */
3418    if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3419       png_error(png_ptr, "lost rgb to gray");
3420 
3421    if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3422       png_error(png_ptr, "unexpected compose");
3423 
3424    if (png_get_channels(png_ptr, info_ptr) != 2)
3425       png_error(png_ptr, "lost/gained channels");
3426 
3427    /* Expect the 8-bit case to always remove the alpha channel */
3428    if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3429       (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3430       png_error(png_ptr, "unexpected 8-bit transformation");
3431 
3432    switch (png_ptr->interlaced)
3433    {
3434       case PNG_INTERLACE_NONE:
3435          passes = 1;
3436          break;
3437 
3438       case PNG_INTERLACE_ADAM7:
3439          passes = PNG_INTERLACE_ADAM7_PASSES;
3440          break;
3441 
3442       default:
3443          png_error(png_ptr, "unknown interlace type");
3444    }
3445 
3446    /* Use direct access to info_ptr here because otherwise the simplified API
3447     * would require PNG_EASY_ACCESS_SUPPORTED (just for this.)  Note this is
3448     * checking the value after libpng expansions, not the original value in the
3449     * PNG.
3450     */
3451    switch (info_ptr->bit_depth)
3452    {
3453       case 8:
3454          /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3455           * to be removed by composing on a background: either the row if
3456           * display->background is NULL or display->background->green if not.
3457           * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3458           */
3459          {
3460             png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3461             ptrdiff_t step_row = display->row_bytes;
3462 
3463             for (pass = 0; pass < passes; ++pass)
3464             {
3465                png_bytep row = png_voidcast(png_bytep, display->first_row);
3466                unsigned int     startx, stepx, stepy;
3467                png_uint_32      y;
3468 
3469                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3470                {
3471                   /* The row may be empty for a short image: */
3472                   if (PNG_PASS_COLS(width, pass) == 0)
3473                      continue;
3474 
3475                   startx = PNG_PASS_START_COL(pass);
3476                   stepx = PNG_PASS_COL_OFFSET(pass);
3477                   y = PNG_PASS_START_ROW(pass);
3478                   stepy = PNG_PASS_ROW_OFFSET(pass);
3479                }
3480 
3481                else
3482                {
3483                   y = 0;
3484                   startx = 0;
3485                   stepx = stepy = 1;
3486                }
3487 
3488                if (display->background == NULL)
3489                {
3490                   for (; y<height; y += stepy)
3491                   {
3492                      png_bytep inrow = png_voidcast(png_bytep,
3493                          display->local_row);
3494                      png_bytep outrow = first_row + y * step_row;
3495                      png_const_bytep end_row = outrow + width;
3496 
3497                      /* Read the row, which is packed: */
3498                      png_read_row(png_ptr, inrow, NULL);
3499 
3500                      /* Now do the composition on each pixel in this row. */
3501                      outrow += startx;
3502                      for (; outrow < end_row; outrow += stepx)
3503                      {
3504                         png_byte alpha = inrow[1];
3505 
3506                         if (alpha > 0) /* else no change to the output */
3507                         {
3508                            png_uint_32 component = inrow[0];
3509 
3510                            if (alpha < 255) /* else just use component */
3511                            {
3512                               /* Since PNG_OPTIMIZED_ALPHA was not set it is
3513                                * necessary to invert the sRGB transfer
3514                                * function and multiply the alpha out.
3515                                */
3516                               component = png_sRGB_table[component] * alpha;
3517                               component += png_sRGB_table[outrow[0]] *
3518                                  (255-alpha);
3519                               component = PNG_sRGB_FROM_LINEAR(component);
3520                            }
3521 
3522                            outrow[0] = (png_byte)component;
3523                         }
3524 
3525                         inrow += 2; /* gray and alpha channel */
3526                      }
3527                   }
3528                }
3529 
3530                else /* constant background value */
3531                {
3532                   png_byte background8 = display->background->green;
3533                   png_uint_16 background = png_sRGB_table[background8];
3534 
3535                   for (; y<height; y += stepy)
3536                   {
3537                      png_bytep inrow = png_voidcast(png_bytep,
3538                          display->local_row);
3539                      png_bytep outrow = first_row + y * step_row;
3540                      png_const_bytep end_row = outrow + width;
3541 
3542                      /* Read the row, which is packed: */
3543                      png_read_row(png_ptr, inrow, NULL);
3544 
3545                      /* Now do the composition on each pixel in this row. */
3546                      outrow += startx;
3547                      for (; outrow < end_row; outrow += stepx)
3548                      {
3549                         png_byte alpha = inrow[1];
3550 
3551                         if (alpha > 0) /* else use background */
3552                         {
3553                            png_uint_32 component = inrow[0];
3554 
3555                            if (alpha < 255) /* else just use component */
3556                            {
3557                               component = png_sRGB_table[component] * alpha;
3558                               component += background * (255-alpha);
3559                               component = PNG_sRGB_FROM_LINEAR(component);
3560                            }
3561 
3562                            outrow[0] = (png_byte)component;
3563                         }
3564 
3565                         else
3566                            outrow[0] = background8;
3567 
3568                         inrow += 2; /* gray and alpha channel */
3569                      }
3570 
3571                      row += display->row_bytes;
3572                   }
3573                }
3574             }
3575          }
3576          break;
3577 
3578       case 16:
3579          /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3580           * still be done and, maybe, the alpha channel removed.  This code also
3581           * handles the alpha-first option.
3582           */
3583          {
3584             png_uint_16p first_row = png_voidcast(png_uint_16p,
3585                 display->first_row);
3586             /* The division by two is safe because the caller passed in a
3587              * stride which was multiplied by 2 (below) to get row_bytes.
3588              */
3589             ptrdiff_t    step_row = display->row_bytes / 2;
3590             unsigned int preserve_alpha = (image->format &
3591                 PNG_FORMAT_FLAG_ALPHA) != 0;
3592             unsigned int outchannels = 1U+preserve_alpha;
3593             int swap_alpha = 0;
3594 
3595 #           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3596                if (preserve_alpha != 0 &&
3597                    (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3598                   swap_alpha = 1;
3599 #           endif
3600 
3601             for (pass = 0; pass < passes; ++pass)
3602             {
3603                unsigned int     startx, stepx, stepy;
3604                png_uint_32      y;
3605 
3606                /* The 'x' start and step are adjusted to output components here.
3607                 */
3608                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3609                {
3610                   /* The row may be empty for a short image: */
3611                   if (PNG_PASS_COLS(width, pass) == 0)
3612                      continue;
3613 
3614                   startx = PNG_PASS_START_COL(pass) * outchannels;
3615                   stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3616                   y = PNG_PASS_START_ROW(pass);
3617                   stepy = PNG_PASS_ROW_OFFSET(pass);
3618                }
3619 
3620                else
3621                {
3622                   y = 0;
3623                   startx = 0;
3624                   stepx = outchannels;
3625                   stepy = 1;
3626                }
3627 
3628                for (; y<height; y += stepy)
3629                {
3630                   png_const_uint_16p inrow;
3631                   png_uint_16p outrow = first_row + y*step_row;
3632                   png_uint_16p end_row = outrow + width * outchannels;
3633 
3634                   /* Read the row, which is packed: */
3635                   png_read_row(png_ptr, png_voidcast(png_bytep,
3636                       display->local_row), NULL);
3637                   inrow = png_voidcast(png_const_uint_16p, display->local_row);
3638 
3639                   /* Now do the pre-multiplication on each pixel in this row.
3640                    */
3641                   outrow += startx;
3642                   for (; outrow < end_row; outrow += stepx)
3643                   {
3644                      png_uint_32 component = inrow[0];
3645                      png_uint_16 alpha = inrow[1];
3646 
3647                      if (alpha > 0) /* else 0 */
3648                      {
3649                         if (alpha < 65535) /* else just use component */
3650                         {
3651                            component *= alpha;
3652                            component += 32767;
3653                            component /= 65535;
3654                         }
3655                      }
3656 
3657                      else
3658                         component = 0;
3659 
3660                      outrow[swap_alpha] = (png_uint_16)component;
3661                      if (preserve_alpha != 0)
3662                         outrow[1 ^ swap_alpha] = alpha;
3663 
3664                      inrow += 2; /* components and alpha channel */
3665                   }
3666                }
3667             }
3668          }
3669          break;
3670 
3671 #ifdef __GNUC__
3672       default:
3673          png_error(png_ptr, "unexpected bit depth");
3674 #endif
3675    }
3676 
3677    return 1;
3678 }
3679 
3680 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3681 static int
3682 png_image_read_direct(png_voidp argument)
3683 {
3684    png_image_read_control *display = png_voidcast(png_image_read_control*,
3685        argument);
3686    png_imagep image = display->image;
3687    png_structrp png_ptr = image->opaque->png_ptr;
3688    png_inforp info_ptr = image->opaque->info_ptr;
3689 
3690    png_uint_32 format = image->format;
3691    int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3692    int do_local_compose = 0;
3693    int do_local_background = 0; /* to avoid double gamma correction bug */
3694    int passes = 0;
3695 
3696    /* Add transforms to ensure the correct output format is produced then check
3697     * that the required implementation support is there.  Always expand; always
3698     * need 8 bits minimum, no palette and expanded tRNS.
3699     */
3700    png_set_expand(png_ptr);
3701 
3702    /* Now check the format to see if it was modified. */
3703    {
3704       png_uint_32 base_format = png_image_format(png_ptr) &
3705          ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3706       png_uint_32 change = format ^ base_format;
3707       png_fixed_point output_gamma;
3708       int mode; /* alpha mode */
3709 
3710       /* Do this first so that we have a record if rgb to gray is happening. */
3711       if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3712       {
3713          /* gray<->color transformation required. */
3714          if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3715             png_set_gray_to_rgb(png_ptr);
3716 
3717          else
3718          {
3719             /* libpng can't do both rgb to gray and
3720              * background/pre-multiplication if there is also significant gamma
3721              * correction, because both operations require linear colors and
3722              * the code only supports one transform doing the gamma correction.
3723              * Handle this by doing the pre-multiplication or background
3724              * operation in this code, if necessary.
3725              *
3726              * TODO: fix this by rewriting pngrtran.c (!)
3727              *
3728              * For the moment (given that fixing this in pngrtran.c is an
3729              * enormous change) 'do_local_background' is used to indicate that
3730              * the problem exists.
3731              */
3732             if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3733                do_local_background = 1/*maybe*/;
3734 
3735             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3736                 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3737          }
3738 
3739          change &= ~PNG_FORMAT_FLAG_COLOR;
3740       }
3741 
3742       /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3743        */
3744       {
3745          png_fixed_point input_gamma_default;
3746 
3747          if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3748              (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3749             input_gamma_default = PNG_GAMMA_LINEAR;
3750          else
3751             input_gamma_default = PNG_DEFAULT_sRGB;
3752 
3753          /* Call png_set_alpha_mode to set the default for the input gamma; the
3754           * output gamma is set by a second call below.
3755           */
3756          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3757       }
3758 
3759       if (linear != 0)
3760       {
3761          /* If there *is* an alpha channel in the input it must be multiplied
3762           * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3763           */
3764          if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3765             mode = PNG_ALPHA_STANDARD; /* associated alpha */
3766 
3767          else
3768             mode = PNG_ALPHA_PNG;
3769 
3770          output_gamma = PNG_GAMMA_LINEAR;
3771       }
3772 
3773       else
3774       {
3775          mode = PNG_ALPHA_PNG;
3776          output_gamma = PNG_DEFAULT_sRGB;
3777       }
3778 
3779       /* If 'do_local_background' is set check for the presence of gamma
3780        * correction; this is part of the work-round for the libpng bug
3781        * described above.
3782        *
3783        * TODO: fix libpng and remove this.
3784        */
3785       if (do_local_background != 0)
3786       {
3787          png_fixed_point gtest;
3788 
3789          /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3790           * gamma correction, the screen gamma hasn't been set on png_struct
3791           * yet; it's set below.  png_struct::gamma, however, is set to the
3792           * final value.
3793           */
3794          if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma,
3795              PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
3796             do_local_background = 0;
3797 
3798          else if (mode == PNG_ALPHA_STANDARD)
3799          {
3800             do_local_background = 2/*required*/;
3801             mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3802          }
3803 
3804          /* else leave as 1 for the checks below */
3805       }
3806 
3807       /* If the bit-depth changes then handle that here. */
3808       if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3809       {
3810          if (linear != 0 /*16-bit output*/)
3811             png_set_expand_16(png_ptr);
3812 
3813          else /* 8-bit output */
3814             png_set_scale_16(png_ptr);
3815 
3816          change &= ~PNG_FORMAT_FLAG_LINEAR;
3817       }
3818 
3819       /* Now the background/alpha channel changes. */
3820       if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3821       {
3822          /* Removing an alpha channel requires composition for the 8-bit
3823           * formats; for the 16-bit it is already done, above, by the
3824           * pre-multiplication and the channel just needs to be stripped.
3825           */
3826          if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3827          {
3828             /* If RGB->gray is happening the alpha channel must be left and the
3829              * operation completed locally.
3830              *
3831              * TODO: fix libpng and remove this.
3832              */
3833             if (do_local_background != 0)
3834                do_local_background = 2/*required*/;
3835 
3836             /* 16-bit output: just remove the channel */
3837             else if (linear != 0) /* compose on black (well, pre-multiply) */
3838                png_set_strip_alpha(png_ptr);
3839 
3840             /* 8-bit output: do an appropriate compose */
3841             else if (display->background != NULL)
3842             {
3843                png_color_16 c;
3844 
3845                c.index = 0; /*unused*/
3846                c.red = display->background->red;
3847                c.green = display->background->green;
3848                c.blue = display->background->blue;
3849                c.gray = display->background->green;
3850 
3851                /* This is always an 8-bit sRGB value, using the 'green' channel
3852                 * for gray is much better than calculating the luminance here;
3853                 * we can get off-by-one errors in that calculation relative to
3854                 * the app expectations and that will show up in transparent
3855                 * pixels.
3856                 */
3857                png_set_background_fixed(png_ptr, &c,
3858                    PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3859                    0/*gamma: not used*/);
3860             }
3861 
3862             else /* compose on row: implemented below. */
3863             {
3864                do_local_compose = 1;
3865                /* This leaves the alpha channel in the output, so it has to be
3866                 * removed by the code below.  Set the encoding to the 'OPTIMIZE'
3867                 * one so the code only has to hack on the pixels that require
3868                 * composition.
3869                 */
3870                mode = PNG_ALPHA_OPTIMIZED;
3871             }
3872          }
3873 
3874          else /* output needs an alpha channel */
3875          {
3876             /* This is tricky because it happens before the swap operation has
3877              * been accomplished; however, the swap does *not* swap the added
3878              * alpha channel (weird API), so it must be added in the correct
3879              * place.
3880              */
3881             png_uint_32 filler; /* opaque filler */
3882             int where;
3883 
3884             if (linear != 0)
3885                filler = 65535;
3886 
3887             else
3888                filler = 255;
3889 
3890 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
3891             if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3892             {
3893                where = PNG_FILLER_BEFORE;
3894                change &= ~PNG_FORMAT_FLAG_AFIRST;
3895             }
3896 
3897             else
3898 #endif
3899             where = PNG_FILLER_AFTER;
3900 
3901             png_set_add_alpha(png_ptr, filler, where);
3902          }
3903 
3904          /* This stops the (irrelevant) call to swap_alpha below. */
3905          change &= ~PNG_FORMAT_FLAG_ALPHA;
3906       }
3907 
3908       /* Now set the alpha mode correctly; this is always done, even if there is
3909        * no alpha channel in either the input or the output because it correctly
3910        * sets the output gamma.
3911        */
3912       png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3913 
3914 #     ifdef PNG_FORMAT_BGR_SUPPORTED
3915          if ((change & PNG_FORMAT_FLAG_BGR) != 0)
3916          {
3917             /* Check only the output format; PNG is never BGR; don't do this if
3918              * the output is gray, but fix up the 'format' value in that case.
3919              */
3920             if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3921                png_set_bgr(png_ptr);
3922 
3923             else
3924                format &= ~PNG_FORMAT_FLAG_BGR;
3925 
3926             change &= ~PNG_FORMAT_FLAG_BGR;
3927          }
3928 #     endif
3929 
3930 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
3931          if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
3932          {
3933             /* Only relevant if there is an alpha channel - it's particularly
3934              * important to handle this correctly because do_local_compose may
3935              * be set above and then libpng will keep the alpha channel for this
3936              * code to remove.
3937              */
3938             if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
3939             {
3940                /* Disable this if doing a local background,
3941                 * TODO: remove this when local background is no longer required.
3942                 */
3943                if (do_local_background != 2)
3944                   png_set_swap_alpha(png_ptr);
3945             }
3946 
3947             else
3948                format &= ~PNG_FORMAT_FLAG_AFIRST;
3949 
3950             change &= ~PNG_FORMAT_FLAG_AFIRST;
3951          }
3952 #     endif
3953 
3954       /* If the *output* is 16-bit then we need to check for a byte-swap on this
3955        * architecture.
3956        */
3957       if (linear != 0)
3958       {
3959          PNG_CONST png_uint_16 le = 0x0001;
3960 
3961          if ((*(png_const_bytep) & le) != 0)
3962             png_set_swap(png_ptr);
3963       }
3964 
3965       /* If change is not now 0 some transformation is missing - error out. */
3966       if (change != 0)
3967          png_error(png_ptr, "png_read_image: unsupported transformation");
3968    }
3969 
3970    PNG_SKIP_CHUNKS(png_ptr);
3971 
3972    /* Update the 'info' structure and make sure the result is as required; first
3973     * make sure to turn on the interlace handling if it will be required
3974     * (because it can't be turned on *after* the call to png_read_update_info!)
3975     *
3976     * TODO: remove the do_local_background fixup below.
3977     */
3978    if (do_local_compose == 0 && do_local_background != 2)
3979       passes = png_set_interlace_handling(png_ptr);
3980 
3981    png_read_update_info(png_ptr, info_ptr);
3982 
3983    {
3984       png_uint_32 info_format = 0;
3985 
3986       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3987          info_format |= PNG_FORMAT_FLAG_COLOR;
3988 
3989       if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
3990       {
3991          /* do_local_compose removes this channel below. */
3992          if (do_local_compose == 0)
3993          {
3994             /* do_local_background does the same if required. */
3995             if (do_local_background != 2 ||
3996                (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3997                info_format |= PNG_FORMAT_FLAG_ALPHA;
3998          }
3999       }
4000 
4001       else if (do_local_compose != 0) /* internal error */
4002          png_error(png_ptr, "png_image_read: alpha channel lost");
4003 
4004       if (info_ptr->bit_depth == 16)
4005          info_format |= PNG_FORMAT_FLAG_LINEAR;
4006 
4007 #ifdef PNG_FORMAT_BGR_SUPPORTED
4008       if ((png_ptr->transformations & PNG_BGR) != 0)
4009          info_format |= PNG_FORMAT_FLAG_BGR;
4010 #endif
4011 
4012 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4013          if (do_local_background == 2)
4014          {
4015             if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4016                info_format |= PNG_FORMAT_FLAG_AFIRST;
4017          }
4018 
4019          if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
4020             ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
4021             (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
4022          {
4023             if (do_local_background == 2)
4024                png_error(png_ptr, "unexpected alpha swap transformation");
4025 
4026             info_format |= PNG_FORMAT_FLAG_AFIRST;
4027          }
4028 #     endif
4029 
4030       /* This is actually an internal error. */
4031       if (info_format != format)
4032          png_error(png_ptr, "png_read_image: invalid transformations");
4033    }
4034 
4035    /* Now read the rows.  If do_local_compose is set then it is necessary to use
4036     * a local row buffer.  The output will be GA, RGBA or BGRA and must be
4037     * converted to G, RGB or BGR as appropriate.  The 'local_row' member of the
4038     * display acts as a flag.
4039     */
4040    {
4041       png_voidp first_row = display->buffer;
4042       ptrdiff_t row_bytes = display->row_stride;
4043 
4044       if (linear != 0)
4045          row_bytes *= 2;
4046 
4047       /* The following expression is designed to work correctly whether it gives
4048        * a signed or an unsigned result.
4049        */
4050       if (row_bytes < 0)
4051       {
4052          char *ptr = png_voidcast(char*, first_row);
4053          ptr += (image->height-1) * (-row_bytes);
4054          first_row = png_voidcast(png_voidp, ptr);
4055       }
4056 
4057       display->first_row = first_row;
4058       display->row_bytes = row_bytes;
4059    }
4060 
4061    if (do_local_compose != 0)
4062    {
4063       int result;
4064       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4065 
4066       display->local_row = row;
4067       result = png_safe_execute(image, png_image_read_composite, display);
4068       display->local_row = NULL;
4069       png_free(png_ptr, row);
4070 
4071       return result;
4072    }
4073 
4074    else if (do_local_background == 2)
4075    {
4076       int result;
4077       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4078 
4079       display->local_row = row;
4080       result = png_safe_execute(image, png_image_read_background, display);
4081       display->local_row = NULL;
4082       png_free(png_ptr, row);
4083 
4084       return result;
4085    }
4086 
4087    else
4088    {
4089       png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4090 
4091       while (--passes >= 0)
4092       {
4093          png_uint_32      y = image->height;
4094          png_bytep        row = png_voidcast(png_bytep, display->first_row);
4095 
4096          for (; y > 0; --y)
4097          {
4098             png_read_row(png_ptr, row, NULL);
4099             row += row_bytes;
4100          }
4101       }
4102 
4103       return 1;
4104    }
4105 }
4106 
4107 int PNGAPI
4108 png_image_finish_read(png_imagep image, png_const_colorp background,
4109     void *buffer, png_int_32 row_stride, void *colormap)
4110 {
4111    if (image != NULL && image->version == PNG_IMAGE_VERSION)
4112    {
4113       /* Check for row_stride overflow.  This check is not performed on the
4114        * original PNG format because it may not occur in the output PNG format
4115        * and libpng deals with the issues of reading the original.
4116        */
4117       const unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4118 
4119       /* The following checks just the 'row_stride' calculation to ensure it
4120        * fits in a signed 32-bit value.  Because channels/components can be
4121        * either 1 or 2 bytes in size the length of a row can still overflow 32
4122        * bits; this is just to verify that the 'row_stride' argument can be
4123        * represented.
4124        */
4125       if (image->width <= 0x7fffffffU/channels) /* no overflow */
4126       {
4127          png_uint_32 check;
4128          const png_uint_32 png_row_stride = image->width * channels;
4129 
4130          if (row_stride == 0)
4131             row_stride = (png_int_32)/*SAFE*/png_row_stride;
4132 
4133          if (row_stride < 0)
4134             check = (png_uint_32)(-row_stride);
4135 
4136          else
4137             check = (png_uint_32)row_stride;
4138 
4139          /* This verifies 'check', the absolute value of the actual stride
4140           * passed in and detects overflow in the application calculation (i.e.
4141           * if the app did actually pass in a non-zero 'row_stride'.
4142           */
4143          if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4144          {
4145             /* Now check for overflow of the image buffer calculation; this
4146              * limits the whole image size to 32 bits for API compatibility with
4147              * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4148              *
4149              * The PNG_IMAGE_BUFFER_SIZE macro is:
4150              *
4151              *    (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4152              *
4153              * And the component size is always 1 or 2, so make sure that the
4154              * number of *bytes* that the application is saying are available
4155              * does actually fit into a 32-bit number.
4156              *
4157              * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4158              * will be changed to use png_alloc_size_t; bigger images can be
4159              * accomodated on 64-bit systems.
4160              */
4161             if (image->height <=
4162                 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4163             {
4164                if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4165                   (image->colormap_entries > 0 && colormap != NULL))
4166                {
4167                   int result;
4168                   png_image_read_control display;
4169 
4170                   memset(&display, 0, (sizeof display));
4171                   display.image = image;
4172                   display.buffer = buffer;
4173                   display.row_stride = row_stride;
4174                   display.colormap = colormap;
4175                   display.background = background;
4176                   display.local_row = NULL;
4177 
4178                   /* Choose the correct 'end' routine; for the color-map case
4179                    * all the setup has already been done.
4180                    */
4181                   if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4182                      result =
4183                          png_safe_execute(image,
4184                              png_image_read_colormap, &display) &&
4185                              png_safe_execute(image,
4186                              png_image_read_colormapped, &display);
4187 
4188                   else
4189                      result =
4190                         png_safe_execute(image,
4191                             png_image_read_direct, &display);
4192 
4193                   png_image_free(image);
4194                   return result;
4195                }
4196 
4197                else
4198                   return png_image_error(image,
4199                       "png_image_finish_read[color-map]: no color-map");
4200             }
4201 
4202             else
4203                return png_image_error(image,
4204                    "png_image_finish_read: image too large");
4205          }
4206 
4207          else
4208             return png_image_error(image,
4209                 "png_image_finish_read: invalid argument");
4210       }
4211 
4212       else
4213          return png_image_error(image,
4214              "png_image_finish_read: row_stride too large");
4215    }
4216 
4217    else if (image != NULL)
4218       return png_image_error(image,
4219           "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4220 
4221    return 0;
4222 }
4223 
4224 #endif /* SIMPLIFIED_READ */
4225 #endif /* READ */