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