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