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