media/libpng/pngread.c

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     2 /* pngread.c - read a PNG file
     3  *
     4  * Last changed in libpng 1.6.10 [March 6, 2014]
     5  * Copyright (c) 1998-2014 Glenn Randers-Pehrson
     6  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
     7  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
     8  *
     9  * This code is released under the libpng license.
    10  * For conditions of distribution and use, see the disclaimer
    11  * and license in png.h
    12  *
    13  * This file contains routines that an application calls directly to
    14  * read a PNG file or stream.
    15  */
    17 #include "pngpriv.h"
    18 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
    19 #  include <errno.h>
    20 #endif
    22 #ifdef PNG_READ_SUPPORTED
    24 /* Create a PNG structure for reading, and allocate any memory needed. */
    25 PNG_FUNCTION(png_structp,PNGAPI
    26 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
    27     png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
    28 {
    29 #ifndef PNG_USER_MEM_SUPPORTED
    30    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
    31       error_fn, warn_fn, NULL, NULL, NULL);
    32 #else
    33    return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
    34        warn_fn, NULL, NULL, NULL);
    35 }
    37 /* Alternate create PNG structure for reading, and allocate any memory
    38  * needed.
    39  */
    40 PNG_FUNCTION(png_structp,PNGAPI
    41 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
    42     png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
    43     png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
    44 {
    45    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
    46       error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
    47 #endif /* PNG_USER_MEM_SUPPORTED */
    49    if (png_ptr != NULL)
    50    {
    51       png_ptr->mode = PNG_IS_READ_STRUCT;
    53       /* Added in libpng-1.6.0; this can be used to detect a read structure if
    54        * required (it will be zero in a write structure.)
    55        */
    56 #     ifdef PNG_SEQUENTIAL_READ_SUPPORTED
    57          png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
    58 #     endif
    60 #     ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
    61          png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
    63          /* In stable builds only warn if an application error can be completely
    64           * handled.
    65           */
    66 #        if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
    67             png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
    68 #        endif
    69 #     endif
    71       /* TODO: delay this, it can be done in png_init_io (if the app doesn't
    72        * do it itself) avoiding setting the default function if it is not
    73        * required.
    74        */
    75       png_set_read_fn(png_ptr, NULL, NULL);
    76    }
    78    return png_ptr;
    79 }
    82 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
    83 /* Read the information before the actual image data.  This has been
    84  * changed in v0.90 to allow reading a file that already has the magic
    85  * bytes read from the stream.  You can tell libpng how many bytes have
    86  * been read from the beginning of the stream (up to the maximum of 8)
    87  * via png_set_sig_bytes(), and we will only check the remaining bytes
    88  * here.  The application can then have access to the signature bytes we
    89  * read if it is determined that this isn't a valid PNG file.
    90  */
    91 void PNGAPI
    92 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
    93 {
    94 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
    95    int keep;
    96 #endif
    98    png_debug(1, "in png_read_info");
   100    if (png_ptr == NULL || info_ptr == NULL)
   101       return;
   103    /* Read and check the PNG file signature. */
   104    png_read_sig(png_ptr, info_ptr);
   106    for (;;)
   107    {
   108       png_uint_32 length = png_read_chunk_header(png_ptr);
   109       png_uint_32 chunk_name = png_ptr->chunk_name;
   111       /* IDAT logic needs to happen here to simplify getting the two flags
   112        * right.
   113        */
   114       if (chunk_name == png_IDAT)
   115       {
   116          if (!(png_ptr->mode & PNG_HAVE_IHDR))
   117             png_chunk_error(png_ptr, "Missing IHDR before IDAT");
   119          else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
   120              !(png_ptr->mode & PNG_HAVE_PLTE))
   121             png_chunk_error(png_ptr, "Missing PLTE before IDAT");
   123          else if (png_ptr->mode & PNG_AFTER_IDAT)
   124             png_chunk_benign_error(png_ptr, "Too many IDATs found");
   126          png_ptr->mode |= PNG_HAVE_IDAT;
   127       }
   129       else if (png_ptr->mode & PNG_HAVE_IDAT)
   130          png_ptr->mode |= PNG_AFTER_IDAT;
   132       /* This should be a binary subdivision search or a hash for
   133        * matching the chunk name rather than a linear search.
   134        */
   135       if (chunk_name == png_IHDR)
   136          png_handle_IHDR(png_ptr, info_ptr, length);
   138       else if (chunk_name == png_IEND)
   139          png_handle_IEND(png_ptr, info_ptr, length);
   141 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
   142       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
   143       {
   144          png_handle_unknown(png_ptr, info_ptr, length, keep);
   146          if (chunk_name == png_PLTE)
   147             png_ptr->mode |= PNG_HAVE_PLTE;
   149          else if (chunk_name == png_IDAT)
   150          {
   151             png_ptr->idat_size = 0; /* It has been consumed */
   152             break;
   153          }
   154       }
   155 #endif
   156       else if (chunk_name == png_PLTE)
   157          png_handle_PLTE(png_ptr, info_ptr, length);
   159       else if (chunk_name == png_IDAT)
   160       {
   161 #ifdef PNG_READ_APNG_SUPPORTED
   162          png_have_info(png_ptr, info_ptr);
   163 #endif
   164          png_ptr->idat_size = length;
   165          break;
   166       }
   168 #ifdef PNG_READ_bKGD_SUPPORTED
   169       else if (chunk_name == png_bKGD)
   170          png_handle_bKGD(png_ptr, info_ptr, length);
   171 #endif
   173 #ifdef PNG_READ_cHRM_SUPPORTED
   174       else if (chunk_name == png_cHRM)
   175          png_handle_cHRM(png_ptr, info_ptr, length);
   176 #endif
   178 #ifdef PNG_READ_gAMA_SUPPORTED
   179       else if (chunk_name == png_gAMA)
   180          png_handle_gAMA(png_ptr, info_ptr, length);
   181 #endif
   183 #ifdef PNG_READ_hIST_SUPPORTED
   184       else if (chunk_name == png_hIST)
   185          png_handle_hIST(png_ptr, info_ptr, length);
   186 #endif
   188 #ifdef PNG_READ_oFFs_SUPPORTED
   189       else if (chunk_name == png_oFFs)
   190          png_handle_oFFs(png_ptr, info_ptr, length);
   191 #endif
   193 #ifdef PNG_READ_pCAL_SUPPORTED
   194       else if (chunk_name == png_pCAL)
   195          png_handle_pCAL(png_ptr, info_ptr, length);
   196 #endif
   198 #ifdef PNG_READ_sCAL_SUPPORTED
   199       else if (chunk_name == png_sCAL)
   200          png_handle_sCAL(png_ptr, info_ptr, length);
   201 #endif
   203 #ifdef PNG_READ_pHYs_SUPPORTED
   204       else if (chunk_name == png_pHYs)
   205          png_handle_pHYs(png_ptr, info_ptr, length);
   206 #endif
   208 #ifdef PNG_READ_sBIT_SUPPORTED
   209       else if (chunk_name == png_sBIT)
   210          png_handle_sBIT(png_ptr, info_ptr, length);
   211 #endif
   213 #ifdef PNG_READ_sRGB_SUPPORTED
   214       else if (chunk_name == png_sRGB)
   215          png_handle_sRGB(png_ptr, info_ptr, length);
   216 #endif
   218 #ifdef PNG_READ_iCCP_SUPPORTED
   219       else if (chunk_name == png_iCCP)
   220          png_handle_iCCP(png_ptr, info_ptr, length);
   221 #endif
   223 #ifdef PNG_READ_sPLT_SUPPORTED
   224       else if (chunk_name == png_sPLT)
   225          png_handle_sPLT(png_ptr, info_ptr, length);
   226 #endif
   228 #ifdef PNG_READ_tEXt_SUPPORTED
   229       else if (chunk_name == png_tEXt)
   230          png_handle_tEXt(png_ptr, info_ptr, length);
   231 #endif
   233 #ifdef PNG_READ_tIME_SUPPORTED
   234       else if (chunk_name == png_tIME)
   235          png_handle_tIME(png_ptr, info_ptr, length);
   236 #endif
   238 #ifdef PNG_READ_tRNS_SUPPORTED
   239       else if (chunk_name == png_tRNS)
   240          png_handle_tRNS(png_ptr, info_ptr, length);
   241 #endif
   243 #ifdef PNG_READ_zTXt_SUPPORTED
   244       else if (chunk_name == png_zTXt)
   245          png_handle_zTXt(png_ptr, info_ptr, length);
   246 #endif
   248 #ifdef PNG_READ_iTXt_SUPPORTED
   249       else if (chunk_name == png_iTXt)
   250          png_handle_iTXt(png_ptr, info_ptr, length);
   251 #endif
   253 #ifdef PNG_READ_APNG_SUPPORTED
   254       else if (chunk_name == png_acTL)
   255          png_handle_acTL(png_ptr, info_ptr, length);
   257       else if (chunk_name == png_fcTL)
   258          png_handle_fcTL(png_ptr, info_ptr, length);
   260       else if (chunk_name == png_fdAT)
   261          png_handle_fdAT(png_ptr, info_ptr, length);
   262 #endif
   264       else
   265          png_handle_unknown(png_ptr, info_ptr, length,
   266             PNG_HANDLE_CHUNK_AS_DEFAULT);
   267    }
   268 }
   269 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   271 #ifdef PNG_READ_APNG_SUPPORTED
   272 void PNGAPI
   273 png_read_frame_head(png_structp png_ptr, png_infop info_ptr)
   274 {
   275     png_byte have_chunk_after_DAT; /* after IDAT or after fdAT */
   277     png_debug(0, "Reading frame head");
   279     if (!(png_ptr->mode & PNG_HAVE_acTL))
   280         png_error(png_ptr, "attempt to png_read_frame_head() but "
   281                            "no acTL present");
   283     /* do nothing for the main IDAT */
   284     if (png_ptr->num_frames_read == 0)
   285         return;
   287     png_read_reset(png_ptr);
   288     png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
   289     png_ptr->mode &= ~PNG_HAVE_fcTL;
   291     have_chunk_after_DAT = 0;
   292     for (;;)
   293     {
   294         png_uint_32 length = png_read_chunk_header(png_ptr);
   296         if (png_ptr->chunk_name == png_IDAT)
   297         {
   298             /* discard trailing IDATs for the first frame */
   299             if (have_chunk_after_DAT || png_ptr->num_frames_read > 1)
   300                 png_error(png_ptr, "png_read_frame_head(): out of place IDAT");
   301             png_crc_finish(png_ptr, length);
   302         }
   304         else if (png_ptr->chunk_name == png_fcTL)
   305         {
   306             png_handle_fcTL(png_ptr, info_ptr, length);
   307             have_chunk_after_DAT = 1;
   308         }
   310         else if (png_ptr->chunk_name == png_fdAT)
   311         {
   312             png_ensure_sequence_number(png_ptr, length);
   314             /* discard trailing fdATs for frames other than the first */
   315             if (!have_chunk_after_DAT && png_ptr->num_frames_read > 1)
   316                 png_crc_finish(png_ptr, length - 4);
   317             else if(png_ptr->mode & PNG_HAVE_fcTL)
   318             {
   319                 png_ptr->idat_size = length - 4;
   320                 png_ptr->mode |= PNG_HAVE_IDAT;
   322                 break;
   323             }
   324             else
   325                 png_error(png_ptr, "png_read_frame_head(): out of place fdAT");
   326         }
   327         else
   328         {
   329             png_warning(png_ptr, "Skipped (ignored) a chunk "
   330                                  "between APNG chunks");
   331             png_crc_finish(png_ptr, length);
   332         }
   333     }
   334 }
   335 #endif /* PNG_READ_APNG_SUPPORTED */
   337 /* Optional call to update the users info_ptr structure */
   338 void PNGAPI
   339 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
   340 {
   341    png_debug(1, "in png_read_update_info");
   343    if (png_ptr != NULL)
   344    {
   345       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
   346       {
   347          png_read_start_row(png_ptr);
   349 #        ifdef PNG_READ_TRANSFORMS_SUPPORTED
   350             png_read_transform_info(png_ptr, info_ptr);
   351 #        else
   352             PNG_UNUSED(info_ptr)
   353 #        endif
   354       }
   356       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
   357       else
   358          png_app_error(png_ptr,
   359             "png_read_update_info/png_start_read_image: duplicate call");
   360    }
   361 }
   363 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   364 /* Initialize palette, background, etc, after transformations
   365  * are set, but before any reading takes place.  This allows
   366  * the user to obtain a gamma-corrected palette, for example.
   367  * If the user doesn't call this, we will do it ourselves.
   368  */
   369 void PNGAPI
   370 png_start_read_image(png_structrp png_ptr)
   371 {
   372    png_debug(1, "in png_start_read_image");
   374    if (png_ptr != NULL)
   375    {
   376       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
   377          png_read_start_row(png_ptr);
   379       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
   380       else
   381          png_app_error(png_ptr,
   382             "png_start_read_image/png_read_update_info: duplicate call");
   383    }
   384 }
   385 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   387 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   388 #ifdef PNG_MNG_FEATURES_SUPPORTED
   389 /* Undoes intrapixel differencing,
   390  * NOTE: this is apparently only supported in the 'sequential' reader.
   391  */
   392 static void
   393 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
   394 {
   395    png_debug(1, "in png_do_read_intrapixel");
   397    if (
   398        (row_info->color_type & PNG_COLOR_MASK_COLOR))
   399    {
   400       int bytes_per_pixel;
   401       png_uint_32 row_width = row_info->width;
   403       if (row_info->bit_depth == 8)
   404       {
   405          png_bytep rp;
   406          png_uint_32 i;
   408          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
   409             bytes_per_pixel = 3;
   411          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
   412             bytes_per_pixel = 4;
   414          else
   415             return;
   417          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
   418          {
   419             *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
   420             *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
   421          }
   422       }
   423       else if (row_info->bit_depth == 16)
   424       {
   425          png_bytep rp;
   426          png_uint_32 i;
   428          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
   429             bytes_per_pixel = 6;
   431          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
   432             bytes_per_pixel = 8;
   434          else
   435             return;
   437          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
   438          {
   439             png_uint_32 s0   = (*(rp    ) << 8) | *(rp + 1);
   440             png_uint_32 s1   = (*(rp + 2) << 8) | *(rp + 3);
   441             png_uint_32 s2   = (*(rp + 4) << 8) | *(rp + 5);
   442             png_uint_32 red  = (s0 + s1 + 65536) & 0xffff;
   443             png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
   444             *(rp    ) = (png_byte)((red >> 8) & 0xff);
   445             *(rp + 1) = (png_byte)(red & 0xff);
   446             *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
   447             *(rp + 5) = (png_byte)(blue & 0xff);
   448          }
   449       }
   450    }
   451 }
   452 #endif /* PNG_MNG_FEATURES_SUPPORTED */
   454 void PNGAPI
   455 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
   456 {
   457    png_row_info row_info;
   459    if (png_ptr == NULL)
   460       return;
   462    png_debug2(1, "in png_read_row (row %lu, pass %d)",
   463        (unsigned long)png_ptr->row_number, png_ptr->pass);
   465    /* png_read_start_row sets the information (in particular iwidth) for this
   466     * interlace pass.
   467     */
   468    if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
   469       png_read_start_row(png_ptr);
   471    /* 1.5.6: row_info moved out of png_struct to a local here. */
   472    row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
   473    row_info.color_type = png_ptr->color_type;
   474    row_info.bit_depth = png_ptr->bit_depth;
   475    row_info.channels = png_ptr->channels;
   476    row_info.pixel_depth = png_ptr->pixel_depth;
   477    row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
   479    if (png_ptr->row_number == 0 && png_ptr->pass == 0)
   480    {
   481    /* Check for transforms that have been set but were defined out */
   482 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
   483    if (png_ptr->transformations & PNG_INVERT_MONO)
   484       png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
   485 #endif
   487 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
   488    if (png_ptr->transformations & PNG_FILLER)
   489       png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
   490 #endif
   492 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
   493     !defined(PNG_READ_PACKSWAP_SUPPORTED)
   494    if (png_ptr->transformations & PNG_PACKSWAP)
   495       png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
   496 #endif
   498 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
   499    if (png_ptr->transformations & PNG_PACK)
   500       png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
   501 #endif
   503 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
   504    if (png_ptr->transformations & PNG_SHIFT)
   505       png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
   506 #endif
   508 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
   509    if (png_ptr->transformations & PNG_BGR)
   510       png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
   511 #endif
   513 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
   514    if (png_ptr->transformations & PNG_SWAP_BYTES)
   515       png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
   516 #endif
   517    }
   519 #ifdef PNG_READ_INTERLACING_SUPPORTED
   520    /* If interlaced and we do not need a new row, combine row and return.
   521     * Notice that the pixels we have from previous rows have been transformed
   522     * already; we can only combine like with like (transformed or
   523     * untransformed) and, because of the libpng API for interlaced images, this
   524     * means we must transform before de-interlacing.
   525     */
   526    if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
   527    {
   528       switch (png_ptr->pass)
   529       {
   530          case 0:
   531             if (png_ptr->row_number & 0x07)
   532             {
   533                if (dsp_row != NULL)
   534                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   535                png_read_finish_row(png_ptr);
   536                return;
   537             }
   538             break;
   540          case 1:
   541             if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
   542             {
   543                if (dsp_row != NULL)
   544                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   546                png_read_finish_row(png_ptr);
   547                return;
   548             }
   549             break;
   551          case 2:
   552             if ((png_ptr->row_number & 0x07) != 4)
   553             {
   554                if (dsp_row != NULL && (png_ptr->row_number & 4))
   555                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   557                png_read_finish_row(png_ptr);
   558                return;
   559             }
   560             break;
   562          case 3:
   563             if ((png_ptr->row_number & 3) || png_ptr->width < 3)
   564             {
   565                if (dsp_row != NULL)
   566                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   568                png_read_finish_row(png_ptr);
   569                return;
   570             }
   571             break;
   573          case 4:
   574             if ((png_ptr->row_number & 3) != 2)
   575             {
   576                if (dsp_row != NULL && (png_ptr->row_number & 2))
   577                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   579                png_read_finish_row(png_ptr);
   580                return;
   581             }
   582             break;
   584          case 5:
   585             if ((png_ptr->row_number & 1) || png_ptr->width < 2)
   586             {
   587                if (dsp_row != NULL)
   588                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
   590                png_read_finish_row(png_ptr);
   591                return;
   592             }
   593             break;
   595          default:
   596          case 6:
   597             if (!(png_ptr->row_number & 1))
   598             {
   599                png_read_finish_row(png_ptr);
   600                return;
   601             }
   602             break;
   603       }
   604    }
   605 #endif
   607    if (!(png_ptr->mode & PNG_HAVE_IDAT))
   608       png_error(png_ptr, "Invalid attempt to read row data");
   610    /* Fill the row with IDAT data: */
   611    png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
   613    if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
   614    {
   615       if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
   616          png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
   617             png_ptr->prev_row + 1, png_ptr->row_buf[0]);
   618       else
   619          png_error(png_ptr, "bad adaptive filter value");
   620    }
   622    /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
   623     * 1.5.6, while the buffer really is this big in current versions of libpng
   624     * it may not be in the future, so this was changed just to copy the
   625     * interlaced count:
   626     */
   627    memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
   629 #ifdef PNG_MNG_FEATURES_SUPPORTED
   630    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
   631        (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
   632    {
   633       /* Intrapixel differencing */
   634       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
   635    }
   636 #endif
   638 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
   639    if (png_ptr->transformations)
   640       png_do_read_transformations(png_ptr, &row_info);
   641 #endif
   643    /* The transformed pixel depth should match the depth now in row_info. */
   644    if (png_ptr->transformed_pixel_depth == 0)
   645    {
   646       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
   647       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
   648          png_error(png_ptr, "sequential row overflow");
   649    }
   651    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
   652       png_error(png_ptr, "internal sequential row size calculation error");
   654 #ifdef PNG_READ_INTERLACING_SUPPORTED
   655    /* Blow up interlaced rows to full size */
   656    if (png_ptr->interlaced &&
   657       (png_ptr->transformations & PNG_INTERLACE))
   658    {
   659       if (png_ptr->pass < 6)
   660          png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
   661             png_ptr->transformations);
   663       if (dsp_row != NULL)
   664          png_combine_row(png_ptr, dsp_row, 1/*display*/);
   666       if (row != NULL)
   667          png_combine_row(png_ptr, row, 0/*row*/);
   668    }
   670    else
   671 #endif
   672    {
   673       if (row != NULL)
   674          png_combine_row(png_ptr, row, -1/*ignored*/);
   676       if (dsp_row != NULL)
   677          png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
   678    }
   679    png_read_finish_row(png_ptr);
   681    if (png_ptr->read_row_fn != NULL)
   682       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
   684 }
   685 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   687 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   688 /* Read one or more rows of image data.  If the image is interlaced,
   689  * and png_set_interlace_handling() has been called, the rows need to
   690  * contain the contents of the rows from the previous pass.  If the
   691  * image has alpha or transparency, and png_handle_alpha()[*] has been
   692  * called, the rows contents must be initialized to the contents of the
   693  * screen.
   694  *
   695  * "row" holds the actual image, and pixels are placed in it
   696  * as they arrive.  If the image is displayed after each pass, it will
   697  * appear to "sparkle" in.  "display_row" can be used to display a
   698  * "chunky" progressive image, with finer detail added as it becomes
   699  * available.  If you do not want this "chunky" display, you may pass
   700  * NULL for display_row.  If you do not want the sparkle display, and
   701  * you have not called png_handle_alpha(), you may pass NULL for rows.
   702  * If you have called png_handle_alpha(), and the image has either an
   703  * alpha channel or a transparency chunk, you must provide a buffer for
   704  * rows.  In this case, you do not have to provide a display_row buffer
   705  * also, but you may.  If the image is not interlaced, or if you have
   706  * not called png_set_interlace_handling(), the display_row buffer will
   707  * be ignored, so pass NULL to it.
   708  *
   709  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
   710  */
   712 void PNGAPI
   713 png_read_rows(png_structrp png_ptr, png_bytepp row,
   714     png_bytepp display_row, png_uint_32 num_rows)
   715 {
   716    png_uint_32 i;
   717    png_bytepp rp;
   718    png_bytepp dp;
   720    png_debug(1, "in png_read_rows");
   722    if (png_ptr == NULL)
   723       return;
   725    rp = row;
   726    dp = display_row;
   727    if (rp != NULL && dp != NULL)
   728       for (i = 0; i < num_rows; i++)
   729       {
   730          png_bytep rptr = *rp++;
   731          png_bytep dptr = *dp++;
   733          png_read_row(png_ptr, rptr, dptr);
   734       }
   736    else if (rp != NULL)
   737       for (i = 0; i < num_rows; i++)
   738       {
   739          png_bytep rptr = *rp;
   740          png_read_row(png_ptr, rptr, NULL);
   741          rp++;
   742       }
   744    else if (dp != NULL)
   745       for (i = 0; i < num_rows; i++)
   746       {
   747          png_bytep dptr = *dp;
   748          png_read_row(png_ptr, NULL, dptr);
   749          dp++;
   750       }
   751 }
   752 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   754 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   755 /* Read the entire image.  If the image has an alpha channel or a tRNS
   756  * chunk, and you have called png_handle_alpha()[*], you will need to
   757  * initialize the image to the current image that PNG will be overlaying.
   758  * We set the num_rows again here, in case it was incorrectly set in
   759  * png_read_start_row() by a call to png_read_update_info() or
   760  * png_start_read_image() if png_set_interlace_handling() wasn't called
   761  * prior to either of these functions like it should have been.  You can
   762  * only call this function once.  If you desire to have an image for
   763  * each pass of a interlaced image, use png_read_rows() instead.
   764  *
   765  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
   766  */
   767 void PNGAPI
   768 png_read_image(png_structrp png_ptr, png_bytepp image)
   769 {
   770    png_uint_32 i, image_height;
   771    int pass, j;
   772    png_bytepp rp;
   774    png_debug(1, "in png_read_image");
   776    if (png_ptr == NULL)
   777       return;
   779 #ifdef PNG_READ_INTERLACING_SUPPORTED
   780    if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
   781    {
   782       pass = png_set_interlace_handling(png_ptr);
   783       /* And make sure transforms are initialized. */
   784       png_start_read_image(png_ptr);
   785    }
   786    else
   787    {
   788       if (png_ptr->interlaced && !(png_ptr->transformations & PNG_INTERLACE))
   789       {
   790          /* Caller called png_start_read_image or png_read_update_info without
   791           * first turning on the PNG_INTERLACE transform.  We can fix this here,
   792           * but the caller should do it!
   793           */
   794          png_warning(png_ptr, "Interlace handling should be turned on when "
   795             "using png_read_image");
   796          /* Make sure this is set correctly */
   797          png_ptr->num_rows = png_ptr->height;
   798       }
   800       /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
   801        * the above error case.
   802        */
   803       pass = png_set_interlace_handling(png_ptr);
   804    }
   805 #else
   806    if (png_ptr->interlaced)
   807       png_error(png_ptr,
   808           "Cannot read interlaced image -- interlace handler disabled");
   810    pass = 1;
   811 #endif
   813    image_height=png_ptr->height;
   815    for (j = 0; j < pass; j++)
   816    {
   817       rp = image;
   818       for (i = 0; i < image_height; i++)
   819       {
   820          png_read_row(png_ptr, *rp, NULL);
   821          rp++;
   822       }
   823    }
   824 }
   825 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   827 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   828 /* Read the end of the PNG file.  Will not read past the end of the
   829  * file, will verify the end is accurate, and will read any comments
   830  * or time information at the end of the file, if info is not NULL.
   831  */
   832 void PNGAPI
   833 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
   834 {
   835 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
   836    int keep;
   837 #endif
   839    png_debug(1, "in png_read_end");
   841    if (png_ptr == NULL)
   842       return;
   844    /* If png_read_end is called in the middle of reading the rows there may
   845     * still be pending IDAT data and an owned zstream.  Deal with this here.
   846     */
   847 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
   848    if (!png_chunk_unknown_handling(png_ptr, png_IDAT))
   849 #endif
   850       png_read_finish_IDAT(png_ptr);
   852 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
   853    /* Report invalid palette index; added at libng-1.5.10 */
   854    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
   855       png_ptr->num_palette_max > png_ptr->num_palette)
   856      png_benign_error(png_ptr, "Read palette index exceeding num_palette");
   857 #endif
   859    do
   860    {
   861       png_uint_32 length = png_read_chunk_header(png_ptr);
   862       png_uint_32 chunk_name = png_ptr->chunk_name;
   864       if (chunk_name == png_IEND)
   865          png_handle_IEND(png_ptr, info_ptr, length);
   867       else if (chunk_name == png_IHDR)
   868          png_handle_IHDR(png_ptr, info_ptr, length);
   870       else if (info_ptr == NULL)
   871          png_crc_finish(png_ptr, length);
   873 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
   874       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
   875       {
   876          if (chunk_name == png_IDAT)
   877          {
   878             if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
   879                png_benign_error(png_ptr, "Too many IDATs found");
   880          }
   881          png_handle_unknown(png_ptr, info_ptr, length, keep);
   882          if (chunk_name == png_PLTE)
   883             png_ptr->mode |= PNG_HAVE_PLTE;
   884       }
   885 #endif
   887       else if (chunk_name == png_IDAT)
   888       {
   889          /* Zero length IDATs are legal after the last IDAT has been
   890           * read, but not after other chunks have been read.
   891           */
   892          if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
   893             png_benign_error(png_ptr, "Too many IDATs found");
   895          png_crc_finish(png_ptr, length);
   896       }
   897       else if (chunk_name == png_PLTE)
   898          png_handle_PLTE(png_ptr, info_ptr, length);
   900 #ifdef PNG_READ_bKGD_SUPPORTED
   901       else if (chunk_name == png_bKGD)
   902          png_handle_bKGD(png_ptr, info_ptr, length);
   903 #endif
   905 #ifdef PNG_READ_cHRM_SUPPORTED
   906       else if (chunk_name == png_cHRM)
   907          png_handle_cHRM(png_ptr, info_ptr, length);
   908 #endif
   910 #ifdef PNG_READ_gAMA_SUPPORTED
   911       else if (chunk_name == png_gAMA)
   912          png_handle_gAMA(png_ptr, info_ptr, length);
   913 #endif
   915 #ifdef PNG_READ_hIST_SUPPORTED
   916       else if (chunk_name == png_hIST)
   917          png_handle_hIST(png_ptr, info_ptr, length);
   918 #endif
   920 #ifdef PNG_READ_oFFs_SUPPORTED
   921       else if (chunk_name == png_oFFs)
   922          png_handle_oFFs(png_ptr, info_ptr, length);
   923 #endif
   925 #ifdef PNG_READ_pCAL_SUPPORTED
   926       else if (chunk_name == png_pCAL)
   927          png_handle_pCAL(png_ptr, info_ptr, length);
   928 #endif
   930 #ifdef PNG_READ_sCAL_SUPPORTED
   931       else if (chunk_name == png_sCAL)
   932          png_handle_sCAL(png_ptr, info_ptr, length);
   933 #endif
   935 #ifdef PNG_READ_pHYs_SUPPORTED
   936       else if (chunk_name == png_pHYs)
   937          png_handle_pHYs(png_ptr, info_ptr, length);
   938 #endif
   940 #ifdef PNG_READ_sBIT_SUPPORTED
   941       else if (chunk_name == png_sBIT)
   942          png_handle_sBIT(png_ptr, info_ptr, length);
   943 #endif
   945 #ifdef PNG_READ_sRGB_SUPPORTED
   946       else if (chunk_name == png_sRGB)
   947          png_handle_sRGB(png_ptr, info_ptr, length);
   948 #endif
   950 #ifdef PNG_READ_iCCP_SUPPORTED
   951       else if (chunk_name == png_iCCP)
   952          png_handle_iCCP(png_ptr, info_ptr, length);
   953 #endif
   955 #ifdef PNG_READ_sPLT_SUPPORTED
   956       else if (chunk_name == png_sPLT)
   957          png_handle_sPLT(png_ptr, info_ptr, length);
   958 #endif
   960 #ifdef PNG_READ_tEXt_SUPPORTED
   961       else if (chunk_name == png_tEXt)
   962          png_handle_tEXt(png_ptr, info_ptr, length);
   963 #endif
   965 #ifdef PNG_READ_tIME_SUPPORTED
   966       else if (chunk_name == png_tIME)
   967          png_handle_tIME(png_ptr, info_ptr, length);
   968 #endif
   970 #ifdef PNG_READ_tRNS_SUPPORTED
   971       else if (chunk_name == png_tRNS)
   972          png_handle_tRNS(png_ptr, info_ptr, length);
   973 #endif
   975 #ifdef PNG_READ_zTXt_SUPPORTED
   976       else if (chunk_name == png_zTXt)
   977          png_handle_zTXt(png_ptr, info_ptr, length);
   978 #endif
   980 #ifdef PNG_READ_iTXt_SUPPORTED
   981       else if (chunk_name == png_iTXt)
   982          png_handle_iTXt(png_ptr, info_ptr, length);
   983 #endif
   985       else
   986          png_handle_unknown(png_ptr, info_ptr, length,
   987             PNG_HANDLE_CHUNK_AS_DEFAULT);
   988    } while (!(png_ptr->mode & PNG_HAVE_IEND));
   989 }
   990 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   992 /* Free all memory used in the read struct */
   993 static void
   994 png_read_destroy(png_structrp png_ptr)
   995 {
   996    png_debug(1, "in png_read_destroy");
   998 #ifdef PNG_READ_GAMMA_SUPPORTED
   999    png_destroy_gamma_table(png_ptr);
  1000 #endif
  1002    png_free(png_ptr, png_ptr->big_row_buf);
  1003    png_free(png_ptr, png_ptr->big_prev_row);
  1004    png_free(png_ptr, png_ptr->read_buffer);
  1006 #ifdef PNG_READ_QUANTIZE_SUPPORTED
  1007    png_free(png_ptr, png_ptr->palette_lookup);
  1008    png_free(png_ptr, png_ptr->quantize_index);
  1009 #endif
  1011    if (png_ptr->free_me & PNG_FREE_PLTE)
  1012       png_zfree(png_ptr, png_ptr->palette);
  1013    png_ptr->free_me &= ~PNG_FREE_PLTE;
  1015 #if defined(PNG_tRNS_SUPPORTED) || \
  1016     defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  1017    if (png_ptr->free_me & PNG_FREE_TRNS)
  1018       png_free(png_ptr, png_ptr->trans_alpha);
  1019    png_ptr->free_me &= ~PNG_FREE_TRNS;
  1020 #endif
  1022    inflateEnd(&png_ptr->zstream);
  1024 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  1025    png_free(png_ptr, png_ptr->save_buffer);
  1026 #endif
  1028 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) &&\
  1029    defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  1030    png_free(png_ptr, png_ptr->unknown_chunk.data);
  1031 #endif
  1033 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
  1034    png_free(png_ptr, png_ptr->chunk_list);
  1035 #endif
  1037    /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
  1038     * callbacks are still set at this point.  They are required to complete the
  1039     * destruction of the png_struct itself.
  1040     */
  1043 /* Free all memory used by the read */
  1044 void PNGAPI
  1045 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  1046     png_infopp end_info_ptr_ptr)
  1048    png_structrp png_ptr = NULL;
  1050    png_debug(1, "in png_destroy_read_struct");
  1052    if (png_ptr_ptr != NULL)
  1053       png_ptr = *png_ptr_ptr;
  1055    if (png_ptr == NULL)
  1056       return;
  1058    /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
  1059     * behavior.  Prior to 1.6.0 libpng did extra 'info' destruction in this API.
  1060     * The extra was, apparently, unnecessary yet this hides memory leak bugs.
  1061     */
  1062    png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
  1063    png_destroy_info_struct(png_ptr, info_ptr_ptr);
  1065    *png_ptr_ptr = NULL;
  1066    png_read_destroy(png_ptr);
  1067    png_destroy_png_struct(png_ptr);
  1070 void PNGAPI
  1071 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
  1073    if (png_ptr == NULL)
  1074       return;
  1076    png_ptr->read_row_fn = read_row_fn;
  1080 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
  1081 #ifdef PNG_INFO_IMAGE_SUPPORTED
  1082 void PNGAPI
  1083 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
  1084                            int transforms,
  1085                            voidp params)
  1087    if (png_ptr == NULL || info_ptr == NULL)
  1088       return;
  1090    /* png_read_info() gives us all of the information from the
  1091     * PNG file before the first IDAT (image data chunk).
  1092     */
  1093    png_read_info(png_ptr, info_ptr);
  1094    if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
  1095       png_error(png_ptr, "Image is too high to process with png_read_png()");
  1097    /* -------------- image transformations start here ------------------- */
  1098    /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
  1099     * is not implemented.  This will only happen in de-configured (non-default)
  1100     * libpng builds.  The results can be unexpected - png_read_png may return
  1101     * short or mal-formed rows because the transform is skipped.
  1102     */
  1104    /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
  1105     */
  1106    if (transforms & PNG_TRANSFORM_SCALE_16)
  1107      /* Added at libpng-1.5.4. "strip_16" produces the same result that it
  1108       * did in earlier versions, while "scale_16" is now more accurate.
  1109       */
  1110 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
  1111       png_set_scale_16(png_ptr);
  1112 #else
  1113       png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
  1114 #endif
  1116    /* If both SCALE and STRIP are required pngrtran will effectively cancel the
  1117     * latter by doing SCALE first.  This is ok and allows apps not to check for
  1118     * which is supported to get the right answer.
  1119     */
  1120    if (transforms & PNG_TRANSFORM_STRIP_16)
  1121 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
  1122       png_set_strip_16(png_ptr);
  1123 #else
  1124       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
  1125 #endif
  1127    /* Strip alpha bytes from the input data without combining with
  1128     * the background (not recommended).
  1129     */
  1130    if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  1131 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
  1132       png_set_strip_alpha(png_ptr);
  1133 #else
  1134       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
  1135 #endif
  1137    /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  1138     * byte into separate bytes (useful for paletted and grayscale images).
  1139     */
  1140    if (transforms & PNG_TRANSFORM_PACKING)
  1141 #ifdef PNG_READ_PACK_SUPPORTED
  1142       png_set_packing(png_ptr);
  1143 #else
  1144       png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
  1145 #endif
  1147    /* Change the order of packed pixels to least significant bit first
  1148     * (not useful if you are using png_set_packing).
  1149     */
  1150    if (transforms & PNG_TRANSFORM_PACKSWAP)
  1151 #ifdef PNG_READ_PACKSWAP_SUPPORTED
  1152       png_set_packswap(png_ptr);
  1153 #else
  1154       png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
  1155 #endif
  1157    /* Expand paletted colors into true RGB triplets
  1158     * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  1159     * Expand paletted or RGB images with transparency to full alpha
  1160     * channels so the data will be available as RGBA quartets.
  1161     */
  1162    if (transforms & PNG_TRANSFORM_EXPAND)
  1163 #ifdef PNG_READ_EXPAND_SUPPORTED
  1164       png_set_expand(png_ptr);
  1165 #else
  1166       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
  1167 #endif
  1169    /* We don't handle background color or gamma transformation or quantizing.
  1170     */
  1172    /* Invert monochrome files to have 0 as white and 1 as black
  1173     */
  1174    if (transforms & PNG_TRANSFORM_INVERT_MONO)
  1175 #ifdef PNG_READ_INVERT_SUPPORTED
  1176       png_set_invert_mono(png_ptr);
  1177 #else
  1178       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
  1179 #endif
  1181    /* If you want to shift the pixel values from the range [0,255] or
  1182     * [0,65535] to the original [0,7] or [0,31], or whatever range the
  1183     * colors were originally in:
  1184     */
  1185    if (transforms & PNG_TRANSFORM_SHIFT)
  1186 #ifdef PNG_READ_SHIFT_SUPPORTED
  1187       if (info_ptr->valid & PNG_INFO_sBIT)
  1188          png_set_shift(png_ptr, &info_ptr->sig_bit);
  1189 #else
  1190       png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
  1191 #endif
  1193    /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
  1194    if (transforms & PNG_TRANSFORM_BGR)
  1195 #ifdef PNG_READ_BGR_SUPPORTED
  1196       png_set_bgr(png_ptr);
  1197 #else
  1198       png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
  1199 #endif
  1201    /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
  1202    if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  1203 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
  1204       png_set_swap_alpha(png_ptr);
  1205 #else
  1206       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
  1207 #endif
  1209    /* Swap bytes of 16-bit files to least significant byte first */
  1210    if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  1211 #ifdef PNG_READ_SWAP_SUPPORTED
  1212       png_set_swap(png_ptr);
  1213 #else
  1214       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
  1215 #endif
  1217 /* Added at libpng-1.2.41 */
  1218    /* Invert the alpha channel from opacity to transparency */
  1219    if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  1220 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
  1221       png_set_invert_alpha(png_ptr);
  1222 #else
  1223       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
  1224 #endif
  1226 /* Added at libpng-1.2.41 */
  1227    /* Expand grayscale image to RGB */
  1228    if (transforms & PNG_TRANSFORM_GRAY_TO_RGB)
  1229 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
  1230       png_set_gray_to_rgb(png_ptr);
  1231 #else
  1232       png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
  1233 #endif
  1235 /* Added at libpng-1.5.4 */
  1236    if (transforms & PNG_TRANSFORM_EXPAND_16)
  1237 #ifdef PNG_READ_EXPAND_16_SUPPORTED
  1238       png_set_expand_16(png_ptr);
  1239 #else
  1240       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
  1241 #endif
  1243    /* We don't handle adding filler bytes */
  1245    /* We use png_read_image and rely on that for interlace handling, but we also
  1246     * call png_read_update_info therefore must turn on interlace handling now:
  1247     */
  1248    (void)png_set_interlace_handling(png_ptr);
  1250    /* Optional call to gamma correct and add the background to the palette
  1251     * and update info structure.  REQUIRED if you are expecting libpng to
  1252     * update the palette for you (i.e., you selected such a transform above).
  1253     */
  1254    png_read_update_info(png_ptr, info_ptr);
  1256    /* -------------- image transformations end here ------------------- */
  1258    png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  1259    if (info_ptr->row_pointers == NULL)
  1261       png_uint_32 iptr;
  1263       info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
  1264           info_ptr->height * (sizeof (png_bytep))));
  1266       for (iptr=0; iptr<info_ptr->height; iptr++)
  1267          info_ptr->row_pointers[iptr] = NULL;
  1269       info_ptr->free_me |= PNG_FREE_ROWS;
  1271       for (iptr = 0; iptr < info_ptr->height; iptr++)
  1272          info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
  1273             png_malloc(png_ptr, info_ptr->rowbytes));
  1276    png_read_image(png_ptr, info_ptr->row_pointers);
  1277    info_ptr->valid |= PNG_INFO_IDAT;
  1279    /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
  1280    png_read_end(png_ptr, info_ptr);
  1282    PNG_UNUSED(params)
  1284 #endif /* PNG_INFO_IMAGE_SUPPORTED */
  1285 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
  1287 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
  1288 /* SIMPLIFIED READ
  1290  * This code currently relies on the sequential reader, though it could easily
  1291  * be made to work with the progressive one.
  1292  */
  1293 /* Arguments to png_image_finish_read: */
  1295 /* Encoding of PNG data (used by the color-map code) */
  1296 #  define P_NOTSET  0 /* File encoding not yet known */
  1297 #  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
  1298 #  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
  1299 #  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
  1300 #  define P_LINEAR8 4 /* 8-bit linear: only from a file value */
  1302 /* Color-map processing: after libpng has run on the PNG image further
  1303  * processing may be needed to conver the data to color-map indicies.
  1304  */
  1305 #define PNG_CMAP_NONE      0
  1306 #define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
  1307 #define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
  1308 #define PNG_CMAP_RGB       3 /* Process RGB data */
  1309 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
  1311 /* The following document where the background is for each processing case. */
  1312 #define PNG_CMAP_NONE_BACKGROUND      256
  1313 #define PNG_CMAP_GA_BACKGROUND        231
  1314 #define PNG_CMAP_TRANS_BACKGROUND     254
  1315 #define PNG_CMAP_RGB_BACKGROUND       256
  1316 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
  1318 typedef struct
  1320    /* Arguments: */
  1321    png_imagep image;
  1322    png_voidp  buffer;
  1323    png_int_32 row_stride;
  1324    png_voidp  colormap;
  1325    png_const_colorp background;
  1326    /* Local variables: */
  1327    png_voidp       local_row;
  1328    png_voidp       first_row;
  1329    ptrdiff_t       row_bytes;           /* step between rows */
  1330    int             file_encoding;       /* E_ values above */
  1331    png_fixed_point gamma_to_linear;     /* For P_FILE, reciprocal of gamma */
  1332    int             colormap_processing; /* PNG_CMAP_ values above */
  1333 } png_image_read_control;
  1335 /* Do all the *safe* initialization - 'safe' means that png_error won't be
  1336  * called, so setting up the jmp_buf is not required.  This means that anything
  1337  * called from here must *not* call png_malloc - it has to call png_malloc_warn
  1338  * instead so that control is returned safely back to this routine.
  1339  */
  1340 static int
  1341 png_image_read_init(png_imagep image)
  1343    if (image->opaque == NULL)
  1345       png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
  1346           png_safe_error, png_safe_warning);
  1348       /* And set the rest of the structure to NULL to ensure that the various
  1349        * fields are consistent.
  1350        */
  1351       memset(image, 0, (sizeof *image));
  1352       image->version = PNG_IMAGE_VERSION;
  1354       if (png_ptr != NULL)
  1356          png_infop info_ptr = png_create_info_struct(png_ptr);
  1358          if (info_ptr != NULL)
  1360             png_controlp control = png_voidcast(png_controlp,
  1361                png_malloc_warn(png_ptr, (sizeof *control)));
  1363             if (control != NULL)
  1365                memset(control, 0, (sizeof *control));
  1367                control->png_ptr = png_ptr;
  1368                control->info_ptr = info_ptr;
  1369                control->for_write = 0;
  1371                image->opaque = control;
  1372                return 1;
  1375             /* Error clean up */
  1376             png_destroy_info_struct(png_ptr, &info_ptr);
  1379          png_destroy_read_struct(&png_ptr, NULL, NULL);
  1382       return png_image_error(image, "png_image_read: out of memory");
  1385    return png_image_error(image, "png_image_read: opaque pointer not NULL");
  1388 /* Utility to find the base format of a PNG file from a png_struct. */
  1389 static png_uint_32
  1390 png_image_format(png_structrp png_ptr)
  1392    png_uint_32 format = 0;
  1394    if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  1395       format |= PNG_FORMAT_FLAG_COLOR;
  1397    if (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1398       format |= PNG_FORMAT_FLAG_ALPHA;
  1400    /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
  1401     * sets the png_struct fields; that's all we are interested in here.  The
  1402     * precise interaction with an app call to png_set_tRNS and PNG file reading
  1403     * is unclear.
  1404     */
  1405    else if (png_ptr->num_trans > 0)
  1406       format |= PNG_FORMAT_FLAG_ALPHA;
  1408    if (png_ptr->bit_depth == 16)
  1409       format |= PNG_FORMAT_FLAG_LINEAR;
  1411    if (png_ptr->color_type & PNG_COLOR_MASK_PALETTE)
  1412       format |= PNG_FORMAT_FLAG_COLORMAP;
  1414    return format;
  1417 /* Is the given gamma significantly different from sRGB?  The test is the same
  1418  * one used in pngrtran.c when deciding whether to do gamma correction.  The
  1419  * arithmetic optimizes the division by using the fact that the inverse of the
  1420  * file sRGB gamma is 2.2
  1421  */
  1422 static int
  1423 png_gamma_not_sRGB(png_fixed_point g)
  1425    if (g < PNG_FP_1)
  1427       /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
  1428       if (g == 0)
  1429          return 0;
  1431       return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
  1434    return 1;
  1437 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
  1438  * header and fill in all the information.  This is executed in a safe context,
  1439  * unlike the init routine above.
  1440  */
  1441 static int
  1442 png_image_read_header(png_voidp argument)
  1444    png_imagep image = png_voidcast(png_imagep, argument);
  1445    png_structrp png_ptr = image->opaque->png_ptr;
  1446    png_inforp info_ptr = image->opaque->info_ptr;
  1448    png_set_benign_errors(png_ptr, 1/*warn*/);
  1449    png_read_info(png_ptr, info_ptr);
  1451    /* Do this the fast way; just read directly out of png_struct. */
  1452    image->width = png_ptr->width;
  1453    image->height = png_ptr->height;
  1456       png_uint_32 format = png_image_format(png_ptr);
  1458       image->format = format;
  1460 #ifdef PNG_COLORSPACE_SUPPORTED
  1461       /* Does the colorspace match sRGB?  If there is no color endpoint
  1462        * (colorant) information assume yes, otherwise require the
  1463        * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set.  If the
  1464        * colorspace has been determined to be invalid ignore it.
  1465        */
  1466       if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
  1467          & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
  1468             PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
  1469          image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
  1470 #endif
  1473    /* We need the maximum number of entries regardless of the format the
  1474     * application sets here.
  1475     */
  1477       png_uint_32 cmap_entries;
  1479       switch (png_ptr->color_type)
  1481          case PNG_COLOR_TYPE_GRAY:
  1482             cmap_entries = 1U << png_ptr->bit_depth;
  1483             break;
  1485          case PNG_COLOR_TYPE_PALETTE:
  1486             cmap_entries = png_ptr->num_palette;
  1487             break;
  1489          default:
  1490             cmap_entries = 256;
  1491             break;
  1494       if (cmap_entries > 256)
  1495          cmap_entries = 256;
  1497       image->colormap_entries = cmap_entries;
  1500    return 1;
  1503 #ifdef PNG_STDIO_SUPPORTED
  1504 int PNGAPI
  1505 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
  1507    if (image != NULL && image->version == PNG_IMAGE_VERSION)
  1509       if (file != NULL)
  1511          if (png_image_read_init(image))
  1513             /* This is slightly evil, but png_init_io doesn't do anything other
  1514              * than this and we haven't changed the standard IO functions so
  1515              * this saves a 'safe' function.
  1516              */
  1517             image->opaque->png_ptr->io_ptr = file;
  1518             return png_safe_execute(image, png_image_read_header, image);
  1522       else
  1523          return png_image_error(image,
  1524             "png_image_begin_read_from_stdio: invalid argument");
  1527    else if (image != NULL)
  1528       return png_image_error(image,
  1529          "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
  1531    return 0;
  1534 int PNGAPI
  1535 png_image_begin_read_from_file(png_imagep image, const char *file_name)
  1537    if (image != NULL && image->version == PNG_IMAGE_VERSION)
  1539       if (file_name != NULL)
  1541          FILE *fp = fopen(file_name, "rb");
  1543          if (fp != NULL)
  1545             if (png_image_read_init(image))
  1547                image->opaque->png_ptr->io_ptr = fp;
  1548                image->opaque->owned_file = 1;
  1549                return png_safe_execute(image, png_image_read_header, image);
  1552             /* Clean up: just the opened file. */
  1553             (void)fclose(fp);
  1556          else
  1557             return png_image_error(image, strerror(errno));
  1560       else
  1561          return png_image_error(image,
  1562             "png_image_begin_read_from_file: invalid argument");
  1565    else if (image != NULL)
  1566       return png_image_error(image,
  1567          "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
  1569    return 0;
  1571 #endif /* PNG_STDIO_SUPPORTED */
  1573 static void PNGCBAPI
  1574 png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
  1576    if (png_ptr != NULL)
  1578       png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
  1579       if (image != NULL)
  1581          png_controlp cp = image->opaque;
  1582          if (cp != NULL)
  1584             png_const_bytep memory = cp->memory;
  1585             png_size_t size = cp->size;
  1587             if (memory != NULL && size >= need)
  1589                memcpy(out, memory, need);
  1590                cp->memory = memory + need;
  1591                cp->size = size - need;
  1592                return;
  1595             png_error(png_ptr, "read beyond end of data");
  1599       png_error(png_ptr, "invalid memory read");
  1603 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
  1604    png_const_voidp memory, png_size_t size)
  1606    if (image != NULL && image->version == PNG_IMAGE_VERSION)
  1608       if (memory != NULL && size > 0)
  1610          if (png_image_read_init(image))
  1612             /* Now set the IO functions to read from the memory buffer and
  1613              * store it into io_ptr.  Again do this in-place to avoid calling a
  1614              * libpng function that requires error handling.
  1615              */
  1616             image->opaque->memory = png_voidcast(png_const_bytep, memory);
  1617             image->opaque->size = size;
  1618             image->opaque->png_ptr->io_ptr = image;
  1619             image->opaque->png_ptr->read_data_fn = png_image_memory_read;
  1621             return png_safe_execute(image, png_image_read_header, image);
  1625       else
  1626          return png_image_error(image,
  1627             "png_image_begin_read_from_memory: invalid argument");
  1630    else if (image != NULL)
  1631       return png_image_error(image,
  1632          "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
  1634    return 0;
  1637 /* Utility function to skip chunks that are not used by the simplified image
  1638  * read functions and an appropriate macro to call it.
  1639  */
  1640 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  1641 static void
  1642 png_image_skip_unused_chunks(png_structrp png_ptr)
  1644    /* Prepare the reader to ignore all recognized chunks whose data will not
  1645     * be used, i.e., all chunks recognized by libpng except for those
  1646     * involved in basic image reading:
  1648     *    IHDR, PLTE, IDAT, IEND
  1650     * Or image data handling:
  1652     *    tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
  1654     * This provides a small performance improvement and eliminates any
  1655     * potential vulnerability to security problems in the unused chunks.
  1657     * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
  1658     * too.  This allows the simplified API to be compiled without iCCP support,
  1659     * however if the support is there the chunk is still checked to detect
  1660     * errors (which are unfortunately quite common.)
  1661     */
  1663          static PNG_CONST png_byte chunks_to_process[] = {
  1664             98,  75,  71,  68, '\0',  /* bKGD */
  1665             99,  72,  82,  77, '\0',  /* cHRM */
  1666            103,  65,  77,  65, '\0',  /* gAMA */
  1667 #        ifdef PNG_READ_iCCP_SUPPORTED
  1668            105,  67,  67,  80, '\0',  /* iCCP */
  1669 #        endif
  1670            115,  66,  73,  84, '\0',  /* sBIT */
  1671            115,  82,  71,  66, '\0',  /* sRGB */
  1672            };
  1674        /* Ignore unknown chunks and all other chunks except for the
  1675         * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
  1676         */
  1677        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
  1678          NULL, -1);
  1680        /* But do not ignore image data handling chunks */
  1681        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
  1682          chunks_to_process, (sizeof chunks_to_process)/5);
  1686 #  define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
  1687 #else
  1688 #  define PNG_SKIP_CHUNKS(p) ((void)0)
  1689 #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */
  1691 /* The following macro gives the exact rounded answer for all values in the
  1692  * range 0..255 (it actually divides by 51.2, but the rounding still generates
  1693  * the correct numbers 0..5
  1694  */
  1695 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
  1697 /* Utility functions to make particular color-maps */
  1698 static void
  1699 set_file_encoding(png_image_read_control *display)
  1701    png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
  1702    if (png_gamma_significant(g))
  1704       if (png_gamma_not_sRGB(g))
  1706          display->file_encoding = P_FILE;
  1707          display->gamma_to_linear = png_reciprocal(g);
  1710       else
  1711          display->file_encoding = P_sRGB;
  1714    else
  1715       display->file_encoding = P_LINEAR8;
  1718 static unsigned int
  1719 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
  1721    if (encoding == P_FILE) /* double check */
  1722       encoding = display->file_encoding;
  1724    if (encoding == P_NOTSET) /* must be the file encoding */
  1726       set_file_encoding(display);
  1727       encoding = display->file_encoding;
  1730    switch (encoding)
  1732       case P_FILE:
  1733          value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
  1734          break;
  1736       case P_sRGB:
  1737          value = png_sRGB_table[value];
  1738          break;
  1740       case P_LINEAR:
  1741          break;
  1743       case P_LINEAR8:
  1744          value *= 257;
  1745          break;
  1747       default:
  1748          png_error(display->image->opaque->png_ptr,
  1749             "unexpected encoding (internal error)");
  1750          break;
  1753    return value;
  1756 static png_uint_32
  1757 png_colormap_compose(png_image_read_control *display,
  1758    png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
  1759    png_uint_32 background, int encoding)
  1761    /* The file value is composed on the background, the background has the given
  1762     * encoding and so does the result, the file is encoded with P_FILE and the
  1763     * file and alpha are 8-bit values.  The (output) encoding will always be
  1764     * P_LINEAR or P_sRGB.
  1765     */
  1766    png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
  1767    png_uint_32 b = decode_gamma(display, background, encoding);
  1769    /* The alpha is always an 8-bit value (it comes from the palette), the value
  1770     * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
  1771     */
  1772    f = f * alpha + b * (255-alpha);
  1774    if (encoding == P_LINEAR)
  1776       /* Scale to 65535; divide by 255, approximately (in fact this is extremely
  1777        * accurate, it divides by 255.00000005937181414556, with no overflow.)
  1778        */
  1779       f *= 257; /* Now scaled by 65535 */
  1780       f += f >> 16;
  1781       f = (f+32768) >> 16;
  1784    else /* P_sRGB */
  1785       f = PNG_sRGB_FROM_LINEAR(f);
  1787    return f;
  1790 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
  1791  * be 8-bit.
  1792  */
  1793 static void
  1794 png_create_colormap_entry(png_image_read_control *display,
  1795    png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
  1796    png_uint_32 alpha, int encoding)
  1798    png_imagep image = display->image;
  1799    const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) ?
  1800       P_LINEAR : P_sRGB;
  1801    const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
  1802       (red != green || green != blue);
  1804    if (ip > 255)
  1805       png_error(image->opaque->png_ptr, "color-map index out of range");
  1807    /* Update the cache with whether the file gamma is significantly different
  1808     * from sRGB.
  1809     */
  1810    if (encoding == P_FILE)
  1812       if (display->file_encoding == P_NOTSET)
  1813          set_file_encoding(display);
  1815       /* Note that the cached value may be P_FILE too, but if it is then the
  1816        * gamma_to_linear member has been set.
  1817        */
  1818       encoding = display->file_encoding;
  1821    if (encoding == P_FILE)
  1823       png_fixed_point g = display->gamma_to_linear;
  1825       red = png_gamma_16bit_correct(red*257, g);
  1826       green = png_gamma_16bit_correct(green*257, g);
  1827       blue = png_gamma_16bit_correct(blue*257, g);
  1829       if (convert_to_Y || output_encoding == P_LINEAR)
  1831          alpha *= 257;
  1832          encoding = P_LINEAR;
  1835       else
  1837          red = PNG_sRGB_FROM_LINEAR(red * 255);
  1838          green = PNG_sRGB_FROM_LINEAR(green * 255);
  1839          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
  1840          encoding = P_sRGB;
  1844    else if (encoding == P_LINEAR8)
  1846       /* This encoding occurs quite frequently in test cases because PngSuite
  1847        * includes a gAMA 1.0 chunk with most images.
  1848        */
  1849       red *= 257;
  1850       green *= 257;
  1851       blue *= 257;
  1852       alpha *= 257;
  1853       encoding = P_LINEAR;
  1856    else if (encoding == P_sRGB && (convert_to_Y || output_encoding == P_LINEAR))
  1858       /* The values are 8-bit sRGB values, but must be converted to 16-bit
  1859        * linear.
  1860        */
  1861       red = png_sRGB_table[red];
  1862       green = png_sRGB_table[green];
  1863       blue = png_sRGB_table[blue];
  1864       alpha *= 257;
  1865       encoding = P_LINEAR;
  1868    /* This is set if the color isn't gray but the output is. */
  1869    if (encoding == P_LINEAR)
  1871       if (convert_to_Y)
  1873          /* NOTE: these values are copied from png_do_rgb_to_gray */
  1874          png_uint_32 y = (png_uint_32)6968 * red  + (png_uint_32)23434 * green +
  1875             (png_uint_32)2366 * blue;
  1877          if (output_encoding == P_LINEAR)
  1878             y = (y + 16384) >> 15;
  1880          else
  1882             /* y is scaled by 32768, we need it scaled by 255: */
  1883             y = (y + 128) >> 8;
  1884             y *= 255;
  1885             y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
  1886             encoding = P_sRGB;
  1889          blue = red = green = y;
  1892       else if (output_encoding == P_sRGB)
  1894          red = PNG_sRGB_FROM_LINEAR(red * 255);
  1895          green = PNG_sRGB_FROM_LINEAR(green * 255);
  1896          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
  1897          alpha = PNG_DIV257(alpha);
  1898          encoding = P_sRGB;
  1902    if (encoding != output_encoding)
  1903       png_error(image->opaque->png_ptr, "bad encoding (internal error)");
  1905    /* Store the value. */
  1907 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
  1908          const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
  1909             (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
  1910 #     else
  1911 #        define afirst 0
  1912 #     endif
  1913 #     ifdef PNG_FORMAT_BGR_SUPPORTED
  1914          const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) ? 2 : 0;
  1915 #     else
  1916 #        define bgr 0
  1917 #     endif
  1919       if (output_encoding == P_LINEAR)
  1921          png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
  1923          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
  1925          /* The linear 16-bit values must be pre-multiplied by the alpha channel
  1926           * value, if less than 65535 (this is, effectively, composite on black
  1927           * if the alpha channel is removed.)
  1928           */
  1929          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
  1931             case 4:
  1932                entry[afirst ? 0 : 3] = (png_uint_16)alpha;
  1933                /* FALL THROUGH */
  1935             case 3:
  1936                if (alpha < 65535)
  1938                   if (alpha > 0)
  1940                      blue = (blue * alpha + 32767U)/65535U;
  1941                      green = (green * alpha + 32767U)/65535U;
  1942                      red = (red * alpha + 32767U)/65535U;
  1945                   else
  1946                      red = green = blue = 0;
  1948                entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
  1949                entry[afirst + 1] = (png_uint_16)green;
  1950                entry[afirst + bgr] = (png_uint_16)red;
  1951                break;
  1953             case 2:
  1954                entry[1 ^ afirst] = (png_uint_16)alpha;
  1955                /* FALL THROUGH */
  1957             case 1:
  1958                if (alpha < 65535)
  1960                   if (alpha > 0)
  1961                      green = (green * alpha + 32767U)/65535U;
  1963                   else
  1964                      green = 0;
  1966                entry[afirst] = (png_uint_16)green;
  1967                break;
  1969             default:
  1970                break;
  1974       else /* output encoding is P_sRGB */
  1976          png_bytep entry = png_voidcast(png_bytep, display->colormap);
  1978          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
  1980          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
  1982             case 4:
  1983                entry[afirst ? 0 : 3] = (png_byte)alpha;
  1984             case 3:
  1985                entry[afirst + (2 ^ bgr)] = (png_byte)blue;
  1986                entry[afirst + 1] = (png_byte)green;
  1987                entry[afirst + bgr] = (png_byte)red;
  1988                break;
  1990             case 2:
  1991                entry[1 ^ afirst] = (png_byte)alpha;
  1992             case 1:
  1993                entry[afirst] = (png_byte)green;
  1994                break;
  1996             default:
  1997                break;
  2001 #     ifdef afirst
  2002 #        undef afirst
  2003 #     endif
  2004 #     ifdef bgr
  2005 #        undef bgr
  2006 #     endif
  2010 static int
  2011 make_gray_file_colormap(png_image_read_control *display)
  2013    unsigned int i;
  2015    for (i=0; i<256; ++i)
  2016       png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
  2018    return i;
  2021 static int
  2022 make_gray_colormap(png_image_read_control *display)
  2024    unsigned int i;
  2026    for (i=0; i<256; ++i)
  2027       png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
  2029    return i;
  2031 #define PNG_GRAY_COLORMAP_ENTRIES 256
  2033 static int
  2034 make_ga_colormap(png_image_read_control *display)
  2036    unsigned int i, a;
  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.
  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)
  2065       unsigned int gray = (i * 256 + 115) / 231;
  2066       png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
  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);
  2074    for (a=1; a<5; ++a)
  2076       unsigned int g;
  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);
  2083    return i;
  2086 #define PNG_GA_COLORMAP_ENTRIES 256
  2088 static int
  2089 make_rgb_colormap(png_image_read_control *display)
  2091    unsigned int i, r;
  2093    /* Build a 6x6x6 opaque RGB cube */
  2094    for (i=r=0; r<6; ++r)
  2096       unsigned int g;
  2098       for (g=0; g<6; ++g)
  2100          unsigned int b;
  2102          for (b=0; b<6; ++b)
  2103             png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
  2104                P_sRGB);
  2108    return i;
  2111 #define PNG_RGB_COLORMAP_ENTRIES 216
  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)))
  2117 static int
  2118 png_image_read_colormap(png_voidp argument)
  2120    png_image_read_control *display =
  2121       png_voidcast(png_image_read_control*, argument);
  2122    const png_imagep image = display->image;
  2124    const png_structrp png_ptr = image->opaque->png_ptr;
  2125    const png_uint_32 output_format = image->format;
  2126    const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) ?
  2127       P_LINEAR : P_sRGB;
  2129    unsigned int cmap_entries;
  2130    unsigned int output_processing;        /* Output processing option */
  2131    unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
  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;
  2139    /* Flags to accumulate things that need to be done to the input. */
  2140    int expand_tRNS = 0;
  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 */)
  2151       if (output_encoding == P_LINEAR) /* compose on black */
  2152          back_b = back_g = back_r = 0;
  2154       else if (display->background == NULL /* no way to remove it */)
  2155          png_error(png_ptr,
  2156             "a background color must be supplied to remove alpha/transparency");
  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
  2164          back_g = display->background->green;
  2165          if (output_format & PNG_FORMAT_FLAG_COLOR)
  2167             back_r = display->background->red;
  2168             back_b = display->background->blue;
  2170          else
  2171             back_b = back_r = back_g;
  2175    else if (output_encoding == P_LINEAR)
  2176       back_b = back_r = back_g = 65535;
  2178    else
  2179       back_b = back_r = back_g = 255;
  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)
  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;
  2197       else
  2198          png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
  2200       png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
  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)
  2210       case PNG_COLOR_TYPE_GRAY:
  2211          if (png_ptr->bit_depth <= 8)
  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;
  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");
  2222             step = 255 / (cmap_entries - 1);
  2223             output_processing = PNG_CMAP_NONE;
  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)
  2230                trans = png_ptr->trans_color.gray;
  2232                if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
  2233                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
  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)
  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*/);
  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.
  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);
  2266             /* We need libpng to preserve the original encoding. */
  2267             data_encoding = P_FILE;
  2269             /* The rows from libpng, while technically gray values, are now also
  2270              * color-map indicies; 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);
  2278          else /* bit depth is 16 */
  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.
  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.
  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;
  2298             if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
  2299                png_error(png_ptr, "gray[16] color-map: too few entries");
  2301             cmap_entries = make_gray_colormap(display);
  2303             if (png_ptr->num_trans > 0)
  2305                unsigned int back_alpha;
  2307                if (output_format & PNG_FORMAT_FLAG_ALPHA)
  2308                   back_alpha = 0;
  2310                else
  2312                   if (back_r == back_g && back_g == back_b)
  2314                      /* Background is gray; no special processing will be
  2315                       * required.
  2316                       */
  2317                      png_color_16 c;
  2318                      png_uint_32 gray = back_g;
  2320                      if (output_encoding == P_LINEAR)
  2322                         gray = PNG_sRGB_FROM_LINEAR(gray * 255);
  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);
  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;
  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*/);
  2345                      output_processing = PNG_CMAP_NONE;
  2346                      break;
  2349                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
  2352                /* output_processing means that the libpng-processed row will be
  2353                 * 8-bit GA and it has to be processing to single byte color-map
  2354                 * values.  Entry 254 is replaced by either a completely
  2355                 * transparent entry or by the background color at full
  2356                 * precision (and the background color is not a simple gray leve
  2357                 * in this case.)
  2358                 */
  2359                expand_tRNS = 1;
  2360                output_processing = PNG_CMAP_TRANS;
  2361                background_index = 254;
  2363                /* And set (overwrite) color-map entry 254 to the actual
  2364                 * background color at full precision.
  2365                 */
  2366                png_create_colormap_entry(display, 254, back_r, back_g, back_b,
  2367                   back_alpha, output_encoding);
  2370             else
  2371                output_processing = PNG_CMAP_NONE;
  2373          break;
  2375       case PNG_COLOR_TYPE_GRAY_ALPHA:
  2376          /* 8-bit or 16-bit PNG with two channels - gray and alpha.  A minimum
  2377           * of 65536 combinations.  If, however, the alpha channel is to be
  2378           * removed there are only 256 possibilities if the background is gray.
  2379           * (Otherwise there is a subset of the 65536 possibilities defined by
  2380           * the triangle between black, white and the background color.)
  2382           * Reduce 16-bit files to 8-bit and sRGB encode the result.  No need to
  2383           * worry about tRNS matching - tRNS is ignored if there is an alpha
  2384           * channel.
  2385           */
  2386          data_encoding = P_sRGB;
  2388          if (output_format & PNG_FORMAT_FLAG_ALPHA)
  2390             if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
  2391                png_error(png_ptr, "gray+alpha color-map: too few entries");
  2393             cmap_entries = make_ga_colormap(display);
  2395             background_index = PNG_CMAP_GA_BACKGROUND;
  2396             output_processing = PNG_CMAP_GA;
  2399          else /* alpha is removed */
  2401             /* Alpha must be removed as the PNG data is processed when the
  2402              * background is a color because the G and A channels are
  2403              * independent and the vector addition (non-parallel vectors) is a
  2404              * 2-D problem.
  2406              * This can be reduced to the same algorithm as above by making a
  2407              * colormap containing gray levels (for the opaque grays), a
  2408              * background entry (for a transparent pixel) and a set of four six
  2409              * level color values, one set for each intermediate alpha value.
  2410              * See the comments in make_ga_colormap for how this works in the
  2411              * per-pixel processing.
  2413              * If the background is gray, however, we only need a 256 entry gray
  2414              * level color map.  It is sufficient to make the entry generated
  2415              * for the background color be exactly the color specified.
  2416              */
  2417             if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
  2418                (back_r == back_g && back_g == back_b))
  2420                /* Background is gray; no special processing will be required. */
  2421                png_color_16 c;
  2422                png_uint_32 gray = back_g;
  2424                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
  2425                   png_error(png_ptr, "gray-alpha color-map: too few entries");
  2427                cmap_entries = make_gray_colormap(display);
  2429                if (output_encoding == P_LINEAR)
  2431                   gray = PNG_sRGB_FROM_LINEAR(gray * 255);
  2433                   /* And make sure the corresponding palette entry matches. */
  2434                   png_create_colormap_entry(display, gray, back_g, back_g,
  2435                      back_g, 65535, P_LINEAR);
  2438                /* The background passed to libpng, however, must be the sRGB
  2439                 * value.
  2440                 */
  2441                c.index = 0; /*unused*/
  2442                c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
  2444                png_set_background_fixed(png_ptr, &c,
  2445                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
  2446                   0/*gamma: not used*/);
  2448                output_processing = PNG_CMAP_NONE;
  2451             else
  2453                png_uint_32 i, a;
  2455                /* This is the same as png_make_ga_colormap, above, except that
  2456                 * the entries are all opaque.
  2457                 */
  2458                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
  2459                   png_error(png_ptr, "ga-alpha color-map: too few entries");
  2461                i = 0;
  2462                while (i < 231)
  2464                   png_uint_32 gray = (i * 256 + 115) / 231;
  2465                   png_create_colormap_entry(display, i++, gray, gray, gray,
  2466                      255, P_sRGB);
  2469                /* NOTE: this preserves the full precision of the application
  2470                 * background color.
  2471                 */
  2472                background_index = i;
  2473                png_create_colormap_entry(display, i++, back_r, back_g, back_b,
  2474                   output_encoding == P_LINEAR ? 65535U : 255U, output_encoding);
  2476                /* For non-opaque input composite on the sRGB background - this
  2477                 * requires inverting the encoding for each component.  The input
  2478                 * is still converted to the sRGB encoding because this is a
  2479                 * reasonable approximate to the logarithmic curve of human
  2480                 * visual sensitivity, at least over the narrow range which PNG
  2481                 * represents.  Consequently 'G' is always sRGB encoded, while
  2482                 * 'A' is linear.  We need the linear background colors.
  2483                 */
  2484                if (output_encoding == P_sRGB) /* else already linear */
  2486                   /* This may produce a value not exactly matching the
  2487                    * background, but that's ok because these numbers are only
  2488                    * used when alpha != 0
  2489                    */
  2490                   back_r = png_sRGB_table[back_r];
  2491                   back_g = png_sRGB_table[back_g];
  2492                   back_b = png_sRGB_table[back_b];
  2495                for (a=1; a<5; ++a)
  2497                   unsigned int g;
  2499                   /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
  2500                    * by an 8-bit alpha value (0..255).
  2501                    */
  2502                   png_uint_32 alpha = 51 * a;
  2503                   png_uint_32 back_rx = (255-alpha) * back_r;
  2504                   png_uint_32 back_gx = (255-alpha) * back_g;
  2505                   png_uint_32 back_bx = (255-alpha) * back_b;
  2507                   for (g=0; g<6; ++g)
  2509                      png_uint_32 gray = png_sRGB_table[g*51] * alpha;
  2511                      png_create_colormap_entry(display, i++,
  2512                         PNG_sRGB_FROM_LINEAR(gray + back_rx),
  2513                         PNG_sRGB_FROM_LINEAR(gray + back_gx),
  2514                         PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
  2518                cmap_entries = i;
  2519                output_processing = PNG_CMAP_GA;
  2522          break;
  2524       case PNG_COLOR_TYPE_RGB:
  2525       case PNG_COLOR_TYPE_RGB_ALPHA:
  2526          /* Exclude the case where the output is gray; we can always handle this
  2527           * with the cases above.
  2528           */
  2529          if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
  2531             /* The color-map will be grayscale, so we may as well convert the
  2532              * input RGB values to a simple grayscale and use the grayscale
  2533              * code above.
  2535              * NOTE: calling this apparently damages the recognition of the
  2536              * transparent color in background color handling; call
  2537              * png_set_tRNS_to_alpha before png_set_background_fixed.
  2538              */
  2539             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
  2540                -1);
  2541             data_encoding = P_sRGB;
  2543             /* The output will now be one or two 8-bit gray or gray+alpha
  2544              * channels.  The more complex case arises when the input has alpha.
  2545              */
  2546             if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
  2547                png_ptr->num_trans > 0) &&
  2548                (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
  2550                /* Both input and output have an alpha channel, so no background
  2551                 * processing is required; just map the GA bytes to the right
  2552                 * color-map entry.
  2553                 */
  2554                expand_tRNS = 1;
  2556                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
  2557                   png_error(png_ptr, "rgb[ga] color-map: too few entries");
  2559                cmap_entries = make_ga_colormap(display);
  2560                background_index = PNG_CMAP_GA_BACKGROUND;
  2561                output_processing = PNG_CMAP_GA;
  2564             else
  2566                /* Either the input or the output has no alpha channel, so there
  2567                 * will be no non-opaque pixels in the color-map; it will just be
  2568                 * grayscale.
  2569                 */
  2570                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
  2571                   png_error(png_ptr, "rgb[gray] color-map: too few entries");
  2573                /* Ideally this code would use libpng to do the gamma correction,
  2574                 * but if an input alpha channel is to be removed we will hit the
  2575                 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
  2576                 * correction bug).  Fix this by dropping the gamma correction in
  2577                 * this case and doing it in the palette; this will result in
  2578                 * duplicate palette entries, but that's better than the
  2579                 * alternative of double gamma correction.
  2580                 */
  2581                if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
  2582                   png_ptr->num_trans > 0) &&
  2583                   png_gamma_not_sRGB(png_ptr->colorspace.gamma))
  2585                   cmap_entries = make_gray_file_colormap(display);
  2586                   data_encoding = P_FILE;
  2589                else
  2590                   cmap_entries = make_gray_colormap(display);
  2592                /* But if the input has alpha or transparency it must be removed
  2593                 */
  2594                if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
  2595                   png_ptr->num_trans > 0)
  2597                   png_color_16 c;
  2598                   png_uint_32 gray = back_g;
  2600                   /* We need to ensure that the application background exists in
  2601                    * the colormap and that completely transparent pixels map to
  2602                    * it.  Achieve this simply by ensuring that the entry
  2603                    * selected for the background really is the background color.
  2604                    */
  2605                   if (data_encoding == P_FILE) /* from the fixup above */
  2607                      /* The app supplied a gray which is in output_encoding, we
  2608                       * need to convert it to a value of the input (P_FILE)
  2609                       * encoding then set this palette entry to the required
  2610                       * output encoding.
  2611                       */
  2612                      if (output_encoding == P_sRGB)
  2613                         gray = png_sRGB_table[gray]; /* now P_LINEAR */
  2615                      gray = PNG_DIV257(png_gamma_16bit_correct(gray,
  2616                         png_ptr->colorspace.gamma)); /* now P_FILE */
  2618                      /* And make sure the corresponding palette entry contains
  2619                       * exactly the required sRGB value.
  2620                       */
  2621                      png_create_colormap_entry(display, gray, back_g, back_g,
  2622                         back_g, 0/*unused*/, output_encoding);
  2625                   else if (output_encoding == P_LINEAR)
  2627                      gray = PNG_sRGB_FROM_LINEAR(gray * 255);
  2629                      /* And make sure the corresponding palette entry matches.
  2630                       */
  2631                      png_create_colormap_entry(display, gray, back_g, back_g,
  2632                         back_g, 0/*unused*/, P_LINEAR);
  2635                   /* The background passed to libpng, however, must be the
  2636                    * output (normally sRGB) value.
  2637                    */
  2638                   c.index = 0; /*unused*/
  2639                   c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
  2641                   /* NOTE: the following is apparently a bug in libpng. Without
  2642                    * it the transparent color recognition in
  2643                    * png_set_background_fixed seems to go wrong.
  2644                    */
  2645                   expand_tRNS = 1;
  2646                   png_set_background_fixed(png_ptr, &c,
  2647                      PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
  2648                      0/*gamma: not used*/);
  2651                output_processing = PNG_CMAP_NONE;
  2655          else /* output is color */
  2657             /* We could use png_quantize here so long as there is no transparent
  2658              * color or alpha; png_quantize ignores alpha.  Easier overall just
  2659              * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
  2660              * Consequently we always want libpng to produce sRGB data.
  2661              */
  2662             data_encoding = P_sRGB;
  2664             /* Is there any transparency or alpha? */
  2665             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
  2666                png_ptr->num_trans > 0)
  2668                /* Is there alpha in the output too?  If so all four channels are
  2669                 * processed into a special RGB cube with alpha support.
  2670                 */
  2671                if (output_format & PNG_FORMAT_FLAG_ALPHA)
  2673                   png_uint_32 r;
  2675                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
  2676                      png_error(png_ptr, "rgb+alpha color-map: too few entries");
  2678                   cmap_entries = make_rgb_colormap(display);
  2680                   /* Add a transparent entry. */
  2681                   png_create_colormap_entry(display, cmap_entries, 255, 255,
  2682                      255, 0, P_sRGB);
  2684                   /* This is stored as the background index for the processing
  2685                    * algorithm.
  2686                    */
  2687                   background_index = cmap_entries++;
  2689                   /* Add 27 r,g,b entries each with alpha 0.5. */
  2690                   for (r=0; r<256; r = (r << 1) | 0x7f)
  2692                      png_uint_32 g;
  2694                      for (g=0; g<256; g = (g << 1) | 0x7f)
  2696                         png_uint_32 b;
  2698                         /* This generates components with the values 0, 127 and
  2699                          * 255
  2700                          */
  2701                         for (b=0; b<256; b = (b << 1) | 0x7f)
  2702                            png_create_colormap_entry(display, cmap_entries++,
  2703                               r, g, b, 128, P_sRGB);
  2707                   expand_tRNS = 1;
  2708                   output_processing = PNG_CMAP_RGB_ALPHA;
  2711                else
  2713                   /* Alpha/transparency must be removed.  The background must
  2714                    * exist in the color map (achieved by setting adding it after
  2715                    * the 666 color-map).  If the standard processing code will
  2716                    * pick up this entry automatically that's all that is
  2717                    * required; libpng can be called to do the background
  2718                    * processing.
  2719                    */
  2720                   unsigned int sample_size =
  2721                      PNG_IMAGE_SAMPLE_SIZE(output_format);
  2722                   png_uint_32 r, g, b; /* sRGB background */
  2724                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
  2725                      png_error(png_ptr, "rgb-alpha color-map: too few entries");
  2727                   cmap_entries = make_rgb_colormap(display);
  2729                   png_create_colormap_entry(display, cmap_entries, back_r,
  2730                         back_g, back_b, 0/*unused*/, output_encoding);
  2732                   if (output_encoding == P_LINEAR)
  2734                      r = PNG_sRGB_FROM_LINEAR(back_r * 255);
  2735                      g = PNG_sRGB_FROM_LINEAR(back_g * 255);
  2736                      b = PNG_sRGB_FROM_LINEAR(back_b * 255);
  2739                   else
  2741                      r = back_r;
  2742                      g = back_g;
  2743                      b = back_g;
  2746                   /* Compare the newly-created color-map entry with the one the
  2747                    * PNG_CMAP_RGB algorithm will use.  If the two entries don't
  2748                    * match, add the new one and set this as the background
  2749                    * index.
  2750                    */
  2751                   if (memcmp((png_const_bytep)display->colormap +
  2752                         sample_size * cmap_entries,
  2753                      (png_const_bytep)display->colormap +
  2754                         sample_size * PNG_RGB_INDEX(r,g,b),
  2755                      sample_size) != 0)
  2757                      /* The background color must be added. */
  2758                      background_index = cmap_entries++;
  2760                      /* Add 27 r,g,b entries each with created by composing with
  2761                       * the background at alpha 0.5.
  2762                       */
  2763                      for (r=0; r<256; r = (r << 1) | 0x7f)
  2765                         for (g=0; g<256; g = (g << 1) | 0x7f)
  2767                            /* This generates components with the values 0, 127
  2768                             * and 255
  2769                             */
  2770                            for (b=0; b<256; b = (b << 1) | 0x7f)
  2771                               png_create_colormap_entry(display, cmap_entries++,
  2772                                  png_colormap_compose(display, r, P_sRGB, 128,
  2773                                     back_r, output_encoding),
  2774                                  png_colormap_compose(display, g, P_sRGB, 128,
  2775                                     back_g, output_encoding),
  2776                                  png_colormap_compose(display, b, P_sRGB, 128,
  2777                                     back_b, output_encoding),
  2778                                  0/*unused*/, output_encoding);
  2782                      expand_tRNS = 1;
  2783                      output_processing = PNG_CMAP_RGB_ALPHA;
  2786                   else /* background color is in the standard color-map */
  2788                      png_color_16 c;
  2790                      c.index = 0; /*unused*/
  2791                      c.red = (png_uint_16)back_r;
  2792                      c.gray = c.green = (png_uint_16)back_g;
  2793                      c.blue = (png_uint_16)back_b;
  2795                      png_set_background_fixed(png_ptr, &c,
  2796                         PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
  2797                         0/*gamma: not used*/);
  2799                      output_processing = PNG_CMAP_RGB;
  2804             else /* no alpha or transparency in the input */
  2806                /* Alpha in the output is irrelevant, simply map the opaque input
  2807                 * pixels to the 6x6x6 color-map.
  2808                 */
  2809                if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
  2810                   png_error(png_ptr, "rgb color-map: too few entries");
  2812                cmap_entries = make_rgb_colormap(display);
  2813                output_processing = PNG_CMAP_RGB;
  2816          break;
  2818       case PNG_COLOR_TYPE_PALETTE:
  2819          /* It's already got a color-map.  It may be necessary to eliminate the
  2820           * tRNS entries though.
  2821           */
  2823             unsigned int num_trans = png_ptr->num_trans;
  2824             png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
  2825             png_const_colorp colormap = png_ptr->palette;
  2826             const int do_background = trans != NULL &&
  2827                (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
  2828             unsigned int i;
  2830             /* Just in case: */
  2831             if (trans == NULL)
  2832                num_trans = 0;
  2834             output_processing = PNG_CMAP_NONE;
  2835             data_encoding = P_FILE; /* Don't change from color-map indicies */
  2836             cmap_entries = png_ptr->num_palette;
  2837             if (cmap_entries > 256)
  2838                cmap_entries = 256;
  2840             if (cmap_entries > image->colormap_entries)
  2841                png_error(png_ptr, "palette color-map: too few entries");
  2843             for (i=0; i < cmap_entries; ++i)
  2845                if (do_background && i < num_trans && trans[i] < 255)
  2847                   if (trans[i] == 0)
  2848                      png_create_colormap_entry(display, i, back_r, back_g,
  2849                         back_b, 0, output_encoding);
  2851                   else
  2853                      /* Must compose the PNG file color in the color-map entry
  2854                       * on the sRGB color in 'back'.
  2855                       */
  2856                      png_create_colormap_entry(display, i,
  2857                         png_colormap_compose(display, colormap[i].red, P_FILE,
  2858                            trans[i], back_r, output_encoding),
  2859                         png_colormap_compose(display, colormap[i].green, P_FILE,
  2860                            trans[i], back_g, output_encoding),
  2861                         png_colormap_compose(display, colormap[i].blue, P_FILE,
  2862                            trans[i], back_b, output_encoding),
  2863                         output_encoding == P_LINEAR ? trans[i] * 257U :
  2864                            trans[i],
  2865                         output_encoding);
  2869                else
  2870                   png_create_colormap_entry(display, i, colormap[i].red,
  2871                      colormap[i].green, colormap[i].blue,
  2872                      i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
  2875             /* The PNG data may have indicies packed in fewer than 8 bits, it
  2876              * must be expanded if so.
  2877              */
  2878             if (png_ptr->bit_depth < 8)
  2879                png_set_packing(png_ptr);
  2881          break;
  2883       default:
  2884          png_error(png_ptr, "invalid PNG color type");
  2885          /*NOT REACHED*/
  2886          break;
  2889    /* Now deal with the output processing */
  2890    if (expand_tRNS && png_ptr->num_trans > 0 &&
  2891       (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
  2892       png_set_tRNS_to_alpha(png_ptr);
  2894    switch (data_encoding)
  2896       default:
  2897          png_error(png_ptr, "bad data option (internal error)");
  2898          break;
  2900       case P_sRGB:
  2901          /* Change to 8-bit sRGB */
  2902          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
  2903          /* FALL THROUGH */
  2905       case P_FILE:
  2906          if (png_ptr->bit_depth > 8)
  2907             png_set_scale_16(png_ptr);
  2908          break;
  2911    if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
  2912       png_error(png_ptr, "color map overflow (BAD internal error)");
  2914    image->colormap_entries = cmap_entries;
  2916    /* Double check using the recorded background index */
  2917    switch (output_processing)
  2919       case PNG_CMAP_NONE:
  2920          if (background_index != PNG_CMAP_NONE_BACKGROUND)
  2921             goto bad_background;
  2922          break;
  2924       case PNG_CMAP_GA:
  2925          if (background_index != PNG_CMAP_GA_BACKGROUND)
  2926             goto bad_background;
  2927          break;
  2929       case PNG_CMAP_TRANS:
  2930          if (background_index >= cmap_entries ||
  2931             background_index != PNG_CMAP_TRANS_BACKGROUND)
  2932             goto bad_background;
  2933          break;
  2935       case PNG_CMAP_RGB:
  2936          if (background_index != PNG_CMAP_RGB_BACKGROUND)
  2937             goto bad_background;
  2938          break;
  2940       case PNG_CMAP_RGB_ALPHA:
  2941          if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
  2942             goto bad_background;
  2943          break;
  2945       default:
  2946          png_error(png_ptr, "bad processing option (internal error)");
  2948       bad_background:
  2949          png_error(png_ptr, "bad background index (internal error)");
  2952    display->colormap_processing = output_processing;
  2954    return 1/*ok*/;
  2957 /* The final part of the color-map read called from png_image_finish_read. */
  2958 static int
  2959 png_image_read_and_map(png_voidp argument)
  2961    png_image_read_control *display = png_voidcast(png_image_read_control*,
  2962       argument);
  2963    png_imagep image = display->image;
  2964    png_structrp png_ptr = image->opaque->png_ptr;
  2965    int passes;
  2967    /* Called when the libpng data must be transformed into the color-mapped
  2968     * form.  There is a local row buffer in display->local and this routine must
  2969     * do the interlace handling.
  2970     */
  2971    switch (png_ptr->interlaced)
  2973       case PNG_INTERLACE_NONE:
  2974          passes = 1;
  2975          break;
  2977       case PNG_INTERLACE_ADAM7:
  2978          passes = PNG_INTERLACE_ADAM7_PASSES;
  2979          break;
  2981       default:
  2982          png_error(png_ptr, "unknown interlace type");
  2986       png_uint_32  height = image->height;
  2987       png_uint_32  width = image->width;
  2988       int          proc = display->colormap_processing;
  2989       png_bytep    first_row = png_voidcast(png_bytep, display->first_row);
  2990       ptrdiff_t    step_row = display->row_bytes;
  2991       int pass;
  2993       for (pass = 0; pass < passes; ++pass)
  2995          unsigned int     startx, stepx, stepy;
  2996          png_uint_32      y;
  2998          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
  3000             /* The row may be empty for a short image: */
  3001             if (PNG_PASS_COLS(width, pass) == 0)
  3002                continue;
  3004             startx = PNG_PASS_START_COL(pass);
  3005             stepx = PNG_PASS_COL_OFFSET(pass);
  3006             y = PNG_PASS_START_ROW(pass);
  3007             stepy = PNG_PASS_ROW_OFFSET(pass);
  3010          else
  3012             y = 0;
  3013             startx = 0;
  3014             stepx = stepy = 1;
  3017          for (; y<height; y += stepy)
  3019             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
  3020             png_bytep outrow = first_row + y * step_row;
  3021             png_const_bytep end_row = outrow + width;
  3023             /* Read read the libpng data into the temporary buffer. */
  3024             png_read_row(png_ptr, inrow, NULL);
  3026             /* Now process the row according to the processing option, note
  3027              * that the caller verifies that the format of the libpng output
  3028              * data is as required.
  3029              */
  3030             outrow += startx;
  3031             switch (proc)
  3033                case PNG_CMAP_GA:
  3034                   for (; outrow < end_row; outrow += stepx)
  3036                      /* The data is always in the PNG order */
  3037                      unsigned int gray = *inrow++;
  3038                      unsigned int alpha = *inrow++;
  3039                      unsigned int entry;
  3041                      /* NOTE: this code is copied as a comment in
  3042                       * make_ga_colormap above.  Please update the
  3043                       * comment if you change this code!
  3044                       */
  3045                      if (alpha > 229) /* opaque */
  3047                         entry = (231 * gray + 128) >> 8;
  3049                      else if (alpha < 26) /* transparent */
  3051                         entry = 231;
  3053                      else /* partially opaque */
  3055                         entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
  3058                      *outrow = (png_byte)entry;
  3060                   break;
  3062                case PNG_CMAP_TRANS:
  3063                   for (; outrow < end_row; outrow += stepx)
  3065                      png_byte gray = *inrow++;
  3066                      png_byte alpha = *inrow++;
  3068                      if (alpha == 0)
  3069                         *outrow = PNG_CMAP_TRANS_BACKGROUND;
  3071                      else if (gray != PNG_CMAP_TRANS_BACKGROUND)
  3072                         *outrow = gray;
  3074                      else
  3075                         *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
  3077                   break;
  3079                case PNG_CMAP_RGB:
  3080                   for (; outrow < end_row; outrow += stepx)
  3082                      *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
  3083                      inrow += 3;
  3085                   break;
  3087                case PNG_CMAP_RGB_ALPHA:
  3088                   for (; outrow < end_row; outrow += stepx)
  3090                      unsigned int alpha = inrow[3];
  3092                      /* Because the alpha entries only hold alpha==0.5 values
  3093                       * split the processing at alpha==0.25 (64) and 0.75
  3094                       * (196).
  3095                       */
  3097                      if (alpha >= 196)
  3098                         *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
  3099                            inrow[2]);
  3101                      else if (alpha < 64)
  3102                         *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
  3104                      else
  3106                         /* Likewise there are three entries for each of r, g
  3107                          * and b.  We could select the entry by popcount on
  3108                          * the top two bits on those architectures that
  3109                          * support it, this is what the code below does,
  3110                          * crudely.
  3111                          */
  3112                         unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
  3114                         /* Here are how the values map:
  3116                          * 0x00 .. 0x3f -> 0
  3117                          * 0x40 .. 0xbf -> 1
  3118                          * 0xc0 .. 0xff -> 2
  3120                          * So, as above with the explicit alpha checks, the
  3121                          * breakpoints are at 64 and 196.
  3122                          */
  3123                         if (inrow[0] & 0x80) back_i += 9; /* red */
  3124                         if (inrow[0] & 0x40) back_i += 9;
  3125                         if (inrow[0] & 0x80) back_i += 3; /* green */
  3126                         if (inrow[0] & 0x40) back_i += 3;
  3127                         if (inrow[0] & 0x80) back_i += 1; /* blue */
  3128                         if (inrow[0] & 0x40) back_i += 1;
  3130                         *outrow = (png_byte)back_i;
  3133                      inrow += 4;
  3135                   break;
  3137                default:
  3138                   break;
  3144    return 1;
  3147 static int
  3148 png_image_read_colormapped(png_voidp argument)
  3150    png_image_read_control *display = png_voidcast(png_image_read_control*,
  3151       argument);
  3152    png_imagep image = display->image;
  3153    png_controlp control = image->opaque;
  3154    png_structrp png_ptr = control->png_ptr;
  3155    png_inforp info_ptr = control->info_ptr;
  3157    int passes = 0; /* As a flag */
  3159    PNG_SKIP_CHUNKS(png_ptr);
  3161    /* Update the 'info' structure and make sure the result is as required; first
  3162     * make sure to turn on the interlace handling if it will be required
  3163     * (because it can't be turned on *after* the call to png_read_update_info!)
  3164     */
  3165    if (display->colormap_processing == PNG_CMAP_NONE)
  3166       passes = png_set_interlace_handling(png_ptr);
  3168    png_read_update_info(png_ptr, info_ptr);
  3170    /* The expected output can be deduced from the colormap_processing option. */
  3171    switch (display->colormap_processing)
  3173       case PNG_CMAP_NONE:
  3174          /* Output must be one channel and one byte per pixel, the output
  3175           * encoding can be anything.
  3176           */
  3177          if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  3178             info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
  3179             info_ptr->bit_depth == 8)
  3180             break;
  3182          goto bad_output;
  3184       case PNG_CMAP_TRANS:
  3185       case PNG_CMAP_GA:
  3186          /* Output must be two channels and the 'G' one must be sRGB, the latter
  3187           * can be checked with an exact number because it should have been set
  3188           * to this number above!
  3189           */
  3190          if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  3191             info_ptr->bit_depth == 8 &&
  3192             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
  3193             image->colormap_entries == 256)
  3194             break;
  3196          goto bad_output;
  3198       case PNG_CMAP_RGB:
  3199          /* Output must be 8-bit sRGB encoded RGB */
  3200          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
  3201             info_ptr->bit_depth == 8 &&
  3202             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
  3203             image->colormap_entries == 216)
  3204             break;
  3206          goto bad_output;
  3208       case PNG_CMAP_RGB_ALPHA:
  3209          /* Output must be 8-bit sRGB encoded RGBA */
  3210          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  3211             info_ptr->bit_depth == 8 &&
  3212             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
  3213             image->colormap_entries == 244 /* 216 + 1 + 27 */)
  3214             break;
  3216          /* goto bad_output; */
  3217          /* FALL THROUGH */
  3219       default:
  3220       bad_output:
  3221          png_error(png_ptr, "bad color-map processing (internal error)");
  3224    /* Now read the rows.  Do this here if it is possible to read directly into
  3225     * the output buffer, otherwise allocate a local row buffer of the maximum
  3226     * size libpng requires and call the relevant processing routine safely.
  3227     */
  3229       png_voidp first_row = display->buffer;
  3230       ptrdiff_t row_bytes = display->row_stride;
  3232       /* The following expression is designed to work correctly whether it gives
  3233        * a signed or an unsigned result.
  3234        */
  3235       if (row_bytes < 0)
  3237          char *ptr = png_voidcast(char*, first_row);
  3238          ptr += (image->height-1) * (-row_bytes);
  3239          first_row = png_voidcast(png_voidp, ptr);
  3242       display->first_row = first_row;
  3243       display->row_bytes = row_bytes;
  3246    if (passes == 0)
  3248       int result;
  3249       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
  3251       display->local_row = row;
  3252       result = png_safe_execute(image, png_image_read_and_map, display);
  3253       display->local_row = NULL;
  3254       png_free(png_ptr, row);
  3256       return result;
  3259    else
  3261       png_alloc_size_t row_bytes = display->row_bytes;
  3263       while (--passes >= 0)
  3265          png_uint_32      y = image->height;
  3266          png_bytep        row = png_voidcast(png_bytep, display->first_row);
  3268          while (y-- > 0)
  3270             png_read_row(png_ptr, row, NULL);
  3271             row += row_bytes;
  3275       return 1;
  3279 /* Just the row reading part of png_image_read. */
  3280 static int
  3281 png_image_read_composite(png_voidp argument)
  3283    png_image_read_control *display = png_voidcast(png_image_read_control*,
  3284       argument);
  3285    png_imagep image = display->image;
  3286    png_structrp png_ptr = image->opaque->png_ptr;
  3287    int passes;
  3289    switch (png_ptr->interlaced)
  3291       case PNG_INTERLACE_NONE:
  3292          passes = 1;
  3293          break;
  3295       case PNG_INTERLACE_ADAM7:
  3296          passes = PNG_INTERLACE_ADAM7_PASSES;
  3297          break;
  3299       default:
  3300          png_error(png_ptr, "unknown interlace type");
  3304       png_uint_32  height = image->height;
  3305       png_uint_32  width = image->width;
  3306       ptrdiff_t    step_row = display->row_bytes;
  3307       unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) ? 3 : 1;
  3308       int pass;
  3310       for (pass = 0; pass < passes; ++pass)
  3312          unsigned int     startx, stepx, stepy;
  3313          png_uint_32      y;
  3315          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
  3317             /* The row may be empty for a short image: */
  3318             if (PNG_PASS_COLS(width, pass) == 0)
  3319                continue;
  3321             startx = PNG_PASS_START_COL(pass) * channels;
  3322             stepx = PNG_PASS_COL_OFFSET(pass) * channels;
  3323             y = PNG_PASS_START_ROW(pass);
  3324             stepy = PNG_PASS_ROW_OFFSET(pass);
  3327          else
  3329             y = 0;
  3330             startx = 0;
  3331             stepx = channels;
  3332             stepy = 1;
  3335          for (; y<height; y += stepy)
  3337             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
  3338             png_bytep outrow;
  3339             png_const_bytep end_row;
  3341             /* Read the row, which is packed: */
  3342             png_read_row(png_ptr, inrow, NULL);
  3344             outrow = png_voidcast(png_bytep, display->first_row);
  3345             outrow += y * step_row;
  3346             end_row = outrow + width * channels;
  3348             /* Now do the composition on each pixel in this row. */
  3349             outrow += startx;
  3350             for (; outrow < end_row; outrow += stepx)
  3352                png_byte alpha = inrow[channels];
  3354                if (alpha > 0) /* else no change to the output */
  3356                   unsigned int c;
  3358                   for (c=0; c<channels; ++c)
  3360                      png_uint_32 component = inrow[c];
  3362                      if (alpha < 255) /* else just use component */
  3364                         /* This is PNG_OPTIMIZED_ALPHA, the component value
  3365                          * is a linear 8-bit value.  Combine this with the
  3366                          * current outrow[c] value which is sRGB encoded.
  3367                          * Arithmetic here is 16-bits to preserve the output
  3368                          * values correctly.
  3369                          */
  3370                         component *= 257*255; /* =65535 */
  3371                         component += (255-alpha)*png_sRGB_table[outrow[c]];
  3373                         /* So 'component' is scaled by 255*65535 and is
  3374                          * therefore appropriate for the sRGB to linear
  3375                          * conversion table.
  3376                          */
  3377                         component = PNG_sRGB_FROM_LINEAR(component);
  3380                      outrow[c] = (png_byte)component;
  3384                inrow += channels+1; /* components and alpha channel */
  3390    return 1;
  3393 /* The do_local_background case; called when all the following transforms are to
  3394  * be done:
  3396  * PNG_RGB_TO_GRAY
  3397  * PNG_COMPOSITE
  3398  * PNG_GAMMA
  3400  * This is a work-round for the fact that both the PNG_RGB_TO_GRAY and
  3401  * PNG_COMPOSITE code performs gamma correction, so we get double gamma
  3402  * correction.  The fix-up is to prevent the PNG_COMPOSITE operation happening
  3403  * inside libpng, so this routine sees an 8 or 16-bit gray+alpha row and handles
  3404  * the removal or pre-multiplication of the alpha channel.
  3405  */
  3406 static int
  3407 png_image_read_background(png_voidp argument)
  3409    png_image_read_control *display = png_voidcast(png_image_read_control*,
  3410       argument);
  3411    png_imagep image = display->image;
  3412    png_structrp png_ptr = image->opaque->png_ptr;
  3413    png_inforp info_ptr = image->opaque->info_ptr;
  3414    png_uint_32 height = image->height;
  3415    png_uint_32 width = image->width;
  3416    int pass, passes;
  3418    /* Double check the convoluted logic below.  We expect to get here with
  3419     * libpng doing rgb to gray and gamma correction but background processing
  3420     * left to the png_image_read_background function.  The rows libpng produce
  3421     * might be 8 or 16-bit but should always have two channels; gray plus alpha.
  3422     */
  3423    if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
  3424       png_error(png_ptr, "lost rgb to gray");
  3426    if ((png_ptr->transformations & PNG_COMPOSE) != 0)
  3427       png_error(png_ptr, "unexpected compose");
  3429    if (png_get_channels(png_ptr, info_ptr) != 2)
  3430       png_error(png_ptr, "lost/gained channels");
  3432    /* Expect the 8-bit case to always remove the alpha channel */
  3433    if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
  3434       (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
  3435       png_error(png_ptr, "unexpected 8-bit transformation");
  3437    switch (png_ptr->interlaced)
  3439       case PNG_INTERLACE_NONE:
  3440          passes = 1;
  3441          break;
  3443       case PNG_INTERLACE_ADAM7:
  3444          passes = PNG_INTERLACE_ADAM7_PASSES;
  3445          break;
  3447       default:
  3448          png_error(png_ptr, "unknown interlace type");
  3451    /* Use direct access to info_ptr here because otherwise the simplified API
  3452     * would require PNG_EASY_ACCESS_SUPPORTED (just for this.)  Note this is
  3453     * checking the value after libpng expansions, not the original value in the
  3454     * PNG.
  3455     */
  3456    switch (info_ptr->bit_depth)
  3458       default:
  3459          png_error(png_ptr, "unexpected bit depth");
  3460          break;
  3462       case 8:
  3463          /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
  3464           * to be removed by composing on a background: either the row if
  3465           * display->background is NULL or display->background->green if not.
  3466           * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
  3467           */
  3469             png_bytep first_row = png_voidcast(png_bytep, display->first_row);
  3470             ptrdiff_t step_row = display->row_bytes;
  3472             for (pass = 0; pass < passes; ++pass)
  3474                png_bytep        row = png_voidcast(png_bytep,
  3475                                                    display->first_row);
  3476                unsigned int     startx, stepx, stepy;
  3477                png_uint_32      y;
  3479                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
  3481                   /* The row may be empty for a short image: */
  3482                   if (PNG_PASS_COLS(width, pass) == 0)
  3483                      continue;
  3485                   startx = PNG_PASS_START_COL(pass);
  3486                   stepx = PNG_PASS_COL_OFFSET(pass);
  3487                   y = PNG_PASS_START_ROW(pass);
  3488                   stepy = PNG_PASS_ROW_OFFSET(pass);
  3491                else
  3493                   y = 0;
  3494                   startx = 0;
  3495                   stepx = stepy = 1;
  3498                if (display->background == NULL)
  3500                   for (; y<height; y += stepy)
  3502                      png_bytep inrow = png_voidcast(png_bytep,
  3503                         display->local_row);
  3504                      png_bytep outrow = first_row + y * step_row;
  3505                      png_const_bytep end_row = outrow + width;
  3507                      /* Read the row, which is packed: */
  3508                      png_read_row(png_ptr, inrow, NULL);
  3510                      /* Now do the composition on each pixel in this row. */
  3511                      outrow += startx;
  3512                      for (; outrow < end_row; outrow += stepx)
  3514                         png_byte alpha = inrow[1];
  3516                         if (alpha > 0) /* else no change to the output */
  3518                            png_uint_32 component = inrow[0];
  3520                            if (alpha < 255) /* else just use component */
  3522                               /* Since PNG_OPTIMIZED_ALPHA was not set it is
  3523                                * necessary to invert the sRGB transfer
  3524                                * function and multiply the alpha out.
  3525                                */
  3526                               component = png_sRGB_table[component] * alpha;
  3527                               component += png_sRGB_table[outrow[0]] *
  3528                                  (255-alpha);
  3529                               component = PNG_sRGB_FROM_LINEAR(component);
  3532                            outrow[0] = (png_byte)component;
  3535                         inrow += 2; /* gray and alpha channel */
  3540                else /* constant background value */
  3542                   png_byte background8 = display->background->green;
  3543                   png_uint_16 background = png_sRGB_table[background8];
  3545                   for (; y<height; y += stepy)
  3547                      png_bytep inrow = png_voidcast(png_bytep,
  3548                         display->local_row);
  3549                      png_bytep outrow = first_row + y * step_row;
  3550                      png_const_bytep end_row = outrow + width;
  3552                      /* Read the row, which is packed: */
  3553                      png_read_row(png_ptr, inrow, NULL);
  3555                      /* Now do the composition on each pixel in this row. */
  3556                      outrow += startx;
  3557                      for (; outrow < end_row; outrow += stepx)
  3559                         png_byte alpha = inrow[1];
  3561                         if (alpha > 0) /* else use background */
  3563                            png_uint_32 component = inrow[0];
  3565                            if (alpha < 255) /* else just use component */
  3567                               component = png_sRGB_table[component] * alpha;
  3568                               component += background * (255-alpha);
  3569                               component = PNG_sRGB_FROM_LINEAR(component);
  3572                            outrow[0] = (png_byte)component;
  3575                         else
  3576                            outrow[0] = background8;
  3578                         inrow += 2; /* gray and alpha channel */
  3581                      row += display->row_bytes;
  3586          break;
  3588       case 16:
  3589          /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
  3590           * still be done and, maybe, the alpha channel removed.  This code also
  3591           * handles the alpha-first option.
  3592           */
  3594             png_uint_16p first_row = png_voidcast(png_uint_16p,
  3595                display->first_row);
  3596             /* The division by two is safe because the caller passed in a
  3597              * stride which was multiplied by 2 (below) to get row_bytes.
  3598              */
  3599             ptrdiff_t    step_row = display->row_bytes / 2;
  3600             int preserve_alpha = (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
  3601             unsigned int outchannels = 1+preserve_alpha;
  3602             int swap_alpha = 0;
  3604 #           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
  3605                if (preserve_alpha && (image->format & PNG_FORMAT_FLAG_AFIRST))
  3606                   swap_alpha = 1;
  3607 #           endif
  3609             for (pass = 0; pass < passes; ++pass)
  3611                unsigned int     startx, stepx, stepy;
  3612                png_uint_32      y;
  3614                /* The 'x' start and step are adjusted to output components here.
  3615                 */
  3616                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
  3618                   /* The row may be empty for a short image: */
  3619                   if (PNG_PASS_COLS(width, pass) == 0)
  3620                      continue;
  3622                   startx = PNG_PASS_START_COL(pass) * outchannels;
  3623                   stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
  3624                   y = PNG_PASS_START_ROW(pass);
  3625                   stepy = PNG_PASS_ROW_OFFSET(pass);
  3628                else
  3630                   y = 0;
  3631                   startx = 0;
  3632                   stepx = outchannels;
  3633                   stepy = 1;
  3636                for (; y<height; y += stepy)
  3638                   png_const_uint_16p inrow;
  3639                   png_uint_16p outrow = first_row + y*step_row;
  3640                   png_uint_16p end_row = outrow + width * outchannels;
  3642                   /* Read the row, which is packed: */
  3643                   png_read_row(png_ptr, png_voidcast(png_bytep,
  3644                      display->local_row), NULL);
  3645                   inrow = png_voidcast(png_const_uint_16p, display->local_row);
  3647                   /* Now do the pre-multiplication on each pixel in this row.
  3648                    */
  3649                   outrow += startx;
  3650                   for (; outrow < end_row; outrow += stepx)
  3652                      png_uint_32 component = inrow[0];
  3653                      png_uint_16 alpha = inrow[1];
  3655                      if (alpha > 0) /* else 0 */
  3657                         if (alpha < 65535) /* else just use component */
  3659                            component *= alpha;
  3660                            component += 32767;
  3661                            component /= 65535;
  3665                      else
  3666                         component = 0;
  3668                      outrow[swap_alpha] = (png_uint_16)component;
  3669                      if (preserve_alpha)
  3670                         outrow[1 ^ swap_alpha] = alpha;
  3672                      inrow += 2; /* components and alpha channel */
  3677          break;
  3680    return 1;
  3683 /* The guts of png_image_finish_read as a png_safe_execute callback. */
  3684 static int
  3685 png_image_read_direct(png_voidp argument)
  3687    png_image_read_control *display = png_voidcast(png_image_read_control*,
  3688       argument);
  3689    png_imagep image = display->image;
  3690    png_structrp png_ptr = image->opaque->png_ptr;
  3691    png_inforp info_ptr = image->opaque->info_ptr;
  3693    png_uint_32 format = image->format;
  3694    int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
  3695    int do_local_compose = 0;
  3696    int do_local_background = 0; /* to avoid double gamma correction bug */
  3697    int passes = 0;
  3699    /* Add transforms to ensure the correct output format is produced then check
  3700     * that the required implementation support is there.  Always expand; always
  3701     * need 8 bits minimum, no palette and expanded tRNS.
  3702     */
  3703    png_set_expand(png_ptr);
  3705    /* Now check the format to see if it was modified. */
  3707       png_uint_32 base_format = png_image_format(png_ptr) &
  3708          ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
  3709       png_uint_32 change = format ^ base_format;
  3710       png_fixed_point output_gamma;
  3711       int mode; /* alpha mode */
  3713       /* Do this first so that we have a record if rgb to gray is happening. */
  3714       if (change & PNG_FORMAT_FLAG_COLOR)
  3716          /* gray<->color transformation required. */
  3717          if (format & PNG_FORMAT_FLAG_COLOR)
  3718             png_set_gray_to_rgb(png_ptr);
  3720          else
  3722             /* libpng can't do both rgb to gray and
  3723              * background/pre-multiplication if there is also significant gamma
  3724              * correction, because both operations require linear colors and
  3725              * the code only supports one transform doing the gamma correction.
  3726              * Handle this by doing the pre-multiplication or background
  3727              * operation in this code, if necessary.
  3729              * TODO: fix this by rewriting pngrtran.c (!)
  3731              * For the moment (given that fixing this in pngrtran.c is an
  3732              * enormous change) 'do_local_background' is used to indicate that
  3733              * the problem exists.
  3734              */
  3735             if (base_format & PNG_FORMAT_FLAG_ALPHA)
  3736                do_local_background = 1/*maybe*/;
  3738             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
  3739                PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
  3742          change &= ~PNG_FORMAT_FLAG_COLOR;
  3745       /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
  3746        */
  3748          png_fixed_point input_gamma_default;
  3750          if ((base_format & PNG_FORMAT_FLAG_LINEAR) &&
  3751             (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
  3752             input_gamma_default = PNG_GAMMA_LINEAR;
  3753          else
  3754             input_gamma_default = PNG_DEFAULT_sRGB;
  3756          /* Call png_set_alpha_mode to set the default for the input gamma; the
  3757           * output gamma is set by a second call below.
  3758           */
  3759          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
  3762       if (linear)
  3764          /* If there *is* an alpha channel in the input it must be multiplied
  3765           * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
  3766           */
  3767          if (base_format & PNG_FORMAT_FLAG_ALPHA)
  3768             mode = PNG_ALPHA_STANDARD; /* associated alpha */
  3770          else
  3771             mode = PNG_ALPHA_PNG;
  3773          output_gamma = PNG_GAMMA_LINEAR;
  3776       else
  3778          mode = PNG_ALPHA_PNG;
  3779          output_gamma = PNG_DEFAULT_sRGB;
  3782       /* If 'do_local_background' is set check for the presence of gamma
  3783        * correction; this is part of the work-round for the libpng bug
  3784        * described above.
  3786        * TODO: fix libpng and remove this.
  3787        */
  3788       if (do_local_background)
  3790          png_fixed_point gtest;
  3792          /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
  3793           * gamma correction, the screen gamma hasn't been set on png_struct
  3794           * yet; it's set below.  png_struct::gamma, however, is set to the
  3795           * final value.
  3796           */
  3797          if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma,
  3798                PNG_FP_1) && !png_gamma_significant(gtest))
  3799             do_local_background = 0;
  3801          else if (mode == PNG_ALPHA_STANDARD)
  3803             do_local_background = 2/*required*/;
  3804             mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
  3807          /* else leave as 1 for the checks below */
  3810       /* If the bit-depth changes then handle that here. */
  3811       if (change & PNG_FORMAT_FLAG_LINEAR)
  3813          if (linear /*16-bit output*/)
  3814             png_set_expand_16(png_ptr);
  3816          else /* 8-bit output */
  3817             png_set_scale_16(png_ptr);
  3819          change &= ~PNG_FORMAT_FLAG_LINEAR;
  3822       /* Now the background/alpha channel changes. */
  3823       if (change & PNG_FORMAT_FLAG_ALPHA)
  3825          /* Removing an alpha channel requires composition for the 8-bit
  3826           * formats; for the 16-bit it is already done, above, by the
  3827           * pre-multiplication and the channel just needs to be stripped.
  3828           */
  3829          if (base_format & PNG_FORMAT_FLAG_ALPHA)
  3831             /* If RGB->gray is happening the alpha channel must be left and the
  3832              * operation completed locally.
  3834              * TODO: fix libpng and remove this.
  3835              */
  3836             if (do_local_background)
  3837                do_local_background = 2/*required*/;
  3839             /* 16-bit output: just remove the channel */
  3840             else if (linear) /* compose on black (well, pre-multiply) */
  3841                png_set_strip_alpha(png_ptr);
  3843             /* 8-bit output: do an appropriate compose */
  3844             else if (display->background != NULL)
  3846                png_color_16 c;
  3848                c.index = 0; /*unused*/
  3849                c.red = display->background->red;
  3850                c.green = display->background->green;
  3851                c.blue = display->background->blue;
  3852                c.gray = display->background->green;
  3854                /* This is always an 8-bit sRGB value, using the 'green' channel
  3855                 * for gray is much better than calculating the luminance here;
  3856                 * we can get off-by-one errors in that calculation relative to
  3857                 * the app expectations and that will show up in transparent
  3858                 * pixels.
  3859                 */
  3860                png_set_background_fixed(png_ptr, &c,
  3861                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
  3862                   0/*gamma: not used*/);
  3865             else /* compose on row: implemented below. */
  3867                do_local_compose = 1;
  3868                /* This leaves the alpha channel in the output, so it has to be
  3869                 * removed by the code below.  Set the encoding to the 'OPTIMIZE'
  3870                 * one so the code only has to hack on the pixels that require
  3871                 * composition.
  3872                 */
  3873                mode = PNG_ALPHA_OPTIMIZED;
  3877          else /* output needs an alpha channel */
  3879             /* This is tricky because it happens before the swap operation has
  3880              * been accomplished; however, the swap does *not* swap the added
  3881              * alpha channel (weird API), so it must be added in the correct
  3882              * place.
  3883              */
  3884             png_uint_32 filler; /* opaque filler */
  3885             int where;
  3887             if (linear)
  3888                filler = 65535;
  3890             else
  3891                filler = 255;
  3893 #           ifdef PNG_FORMAT_AFIRST_SUPPORTED
  3894                if (format & PNG_FORMAT_FLAG_AFIRST)
  3896                   where = PNG_FILLER_BEFORE;
  3897                   change &= ~PNG_FORMAT_FLAG_AFIRST;
  3900                else
  3901 #           endif
  3902                where = PNG_FILLER_AFTER;
  3904             png_set_add_alpha(png_ptr, filler, where);
  3907          /* This stops the (irrelevant) call to swap_alpha below. */
  3908          change &= ~PNG_FORMAT_FLAG_ALPHA;
  3911       /* Now set the alpha mode correctly; this is always done, even if there is
  3912        * no alpha channel in either the input or the output because it correctly
  3913        * sets the output gamma.
  3914        */
  3915       png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
  3917 #     ifdef PNG_FORMAT_BGR_SUPPORTED
  3918          if (change & PNG_FORMAT_FLAG_BGR)
  3920             /* Check only the output format; PNG is never BGR; don't do this if
  3921              * the output is gray, but fix up the 'format' value in that case.
  3922              */
  3923             if (format & PNG_FORMAT_FLAG_COLOR)
  3924                png_set_bgr(png_ptr);
  3926             else
  3927                format &= ~PNG_FORMAT_FLAG_BGR;
  3929             change &= ~PNG_FORMAT_FLAG_BGR;
  3931 #     endif
  3933 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
  3934          if (change & PNG_FORMAT_FLAG_AFIRST)
  3936             /* Only relevant if there is an alpha channel - it's particularly
  3937              * important to handle this correctly because do_local_compose may
  3938              * be set above and then libpng will keep the alpha channel for this
  3939              * code to remove.
  3940              */
  3941             if (format & PNG_FORMAT_FLAG_ALPHA)
  3943                /* Disable this if doing a local background,
  3944                 * TODO: remove this when local background is no longer required.
  3945                 */
  3946                if (do_local_background != 2)
  3947                   png_set_swap_alpha(png_ptr);
  3950             else
  3951                format &= ~PNG_FORMAT_FLAG_AFIRST;
  3953             change &= ~PNG_FORMAT_FLAG_AFIRST;
  3955 #     endif
  3957       /* If the *output* is 16-bit then we need to check for a byte-swap on this
  3958        * architecture.
  3959        */
  3960       if (linear)
  3962          PNG_CONST png_uint_16 le = 0x0001;
  3964          if (*(png_const_bytep)&le)
  3965             png_set_swap(png_ptr);
  3968       /* If change is not now 0 some transformation is missing - error out. */
  3969       if (change)
  3970          png_error(png_ptr, "png_read_image: unsupported transformation");
  3973    PNG_SKIP_CHUNKS(png_ptr);
  3975    /* Update the 'info' structure and make sure the result is as required; first
  3976     * make sure to turn on the interlace handling if it will be required
  3977     * (because it can't be turned on *after* the call to png_read_update_info!)
  3979     * TODO: remove the do_local_background fixup below.
  3980     */
  3981    if (!do_local_compose && do_local_background != 2)
  3982       passes = png_set_interlace_handling(png_ptr);
  3984    png_read_update_info(png_ptr, info_ptr);
  3987       png_uint_32 info_format = 0;
  3989       if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  3990          info_format |= PNG_FORMAT_FLAG_COLOR;
  3992       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  3994          /* do_local_compose removes this channel below. */
  3995          if (!do_local_compose)
  3997             /* do_local_background does the same if required. */
  3998             if (do_local_background != 2 ||
  3999                (format & PNG_FORMAT_FLAG_ALPHA) != 0)
  4000                info_format |= PNG_FORMAT_FLAG_ALPHA;
  4004       else if (do_local_compose) /* internal error */
  4005          png_error(png_ptr, "png_image_read: alpha channel lost");
  4007       if (info_ptr->bit_depth == 16)
  4008          info_format |= PNG_FORMAT_FLAG_LINEAR;
  4010 #     ifdef PNG_FORMAT_BGR_SUPPORTED
  4011          if (png_ptr->transformations & PNG_BGR)
  4012             info_format |= PNG_FORMAT_FLAG_BGR;
  4013 #     endif
  4015 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
  4016          if (do_local_background == 2)
  4018             if (format & PNG_FORMAT_FLAG_AFIRST)
  4019                info_format |= PNG_FORMAT_FLAG_AFIRST;
  4022          if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
  4023             ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
  4024             (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
  4026             if (do_local_background == 2)
  4027                png_error(png_ptr, "unexpected alpha swap transformation");
  4029             info_format |= PNG_FORMAT_FLAG_AFIRST;
  4031 #     endif
  4033       /* This is actually an internal error. */
  4034       if (info_format != format)
  4035          png_error(png_ptr, "png_read_image: invalid transformations");
  4038    /* Now read the rows.  If do_local_compose is set then it is necessary to use
  4039     * a local row buffer.  The output will be GA, RGBA or BGRA and must be
  4040     * converted to G, RGB or BGR as appropriate.  The 'local_row' member of the
  4041     * display acts as a flag.
  4042     */
  4044       png_voidp first_row = display->buffer;
  4045       ptrdiff_t row_bytes = display->row_stride;
  4047       if (linear)
  4048          row_bytes *= 2;
  4050       /* The following expression is designed to work correctly whether it gives
  4051        * a signed or an unsigned result.
  4052        */
  4053       if (row_bytes < 0)
  4055          char *ptr = png_voidcast(char*, first_row);
  4056          ptr += (image->height-1) * (-row_bytes);
  4057          first_row = png_voidcast(png_voidp, ptr);
  4060       display->first_row = first_row;
  4061       display->row_bytes = row_bytes;
  4064    if (do_local_compose)
  4066       int result;
  4067       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
  4069       display->local_row = row;
  4070       result = png_safe_execute(image, png_image_read_composite, display);
  4071       display->local_row = NULL;
  4072       png_free(png_ptr, row);
  4074       return result;
  4077    else if (do_local_background == 2)
  4079       int result;
  4080       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
  4082       display->local_row = row;
  4083       result = png_safe_execute(image, png_image_read_background, display);
  4084       display->local_row = NULL;
  4085       png_free(png_ptr, row);
  4087       return result;
  4090    else
  4092       png_alloc_size_t row_bytes = display->row_bytes;
  4094       while (--passes >= 0)
  4096          png_uint_32      y = image->height;
  4097          png_bytep        row = png_voidcast(png_bytep, display->first_row);
  4099          while (y-- > 0)
  4101             png_read_row(png_ptr, row, NULL);
  4102             row += row_bytes;
  4106       return 1;
  4110 int PNGAPI
  4111 png_image_finish_read(png_imagep image, png_const_colorp background,
  4112    void *buffer, png_int_32 row_stride, void *colormap)
  4114    if (image != NULL && image->version == PNG_IMAGE_VERSION)
  4116       png_uint_32 check;
  4118       if (row_stride == 0)
  4119          row_stride = PNG_IMAGE_ROW_STRIDE(*image);
  4121       if (row_stride < 0)
  4122          check = -row_stride;
  4124       else
  4125          check = row_stride;
  4127       if (image->opaque != NULL && buffer != NULL &&
  4128          check >= PNG_IMAGE_ROW_STRIDE(*image))
  4130          if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
  4131             (image->colormap_entries > 0 && colormap != NULL))
  4133             int result;
  4134             png_image_read_control display;
  4136             memset(&display, 0, (sizeof display));
  4137             display.image = image;
  4138             display.buffer = buffer;
  4139             display.row_stride = row_stride;
  4140             display.colormap = colormap;
  4141             display.background = background;
  4142             display.local_row = NULL;
  4144             /* Choose the correct 'end' routine; for the color-map case all the
  4145              * setup has already been done.
  4146              */
  4147             if (image->format & PNG_FORMAT_FLAG_COLORMAP)
  4148                result =
  4149                   png_safe_execute(image, png_image_read_colormap, &display) &&
  4150                   png_safe_execute(image, png_image_read_colormapped, &display);
  4152             else
  4153                result =
  4154                   png_safe_execute(image, png_image_read_direct, &display);
  4156             png_image_free(image);
  4157             return result;
  4160          else
  4161             return png_image_error(image,
  4162                "png_image_finish_read[color-map]: no color-map");
  4165       else
  4166          return png_image_error(image,
  4167             "png_image_finish_read: invalid argument");
  4170    else if (image != NULL)
  4171       return png_image_error(image,
  4172          "png_image_finish_read: damaged PNG_IMAGE_VERSION");
  4174    return 0;
  4177 #endif /* PNG_SIMPLIFIED_READ_SUPPORTED */
  4178 #endif /* PNG_READ_SUPPORTED */

mercurial