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