1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* pngwutil.c - utilities to write a PNG file
  26  *
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file and, per its terms, should not be removed:
  31  *
  32  * Last changed in libpng 1.6.19 [November 12, 2015]
  33  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  34  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  35  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  36  *
  37  * This code is released under the libpng license.
  38  * For conditions of distribution and use, see the disclaimer
  39  * and license in png.h
  40  */
  41 
  42 #include "pngpriv.h"
  43 
  44 #ifdef PNG_WRITE_SUPPORTED
  45 
  46 #ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
  47 /* Place a 32-bit number into a buffer in PNG byte order.  We work
  48  * with unsigned numbers for convenience, although one supported
  49  * ancillary chunk uses signed (two's complement) numbers.
  50  */
  51 void PNGAPI
  52 png_save_uint_32(png_bytep buf, png_uint_32 i)
  53 {
  54    buf[0] = (png_byte)(i >> 24);
  55    buf[1] = (png_byte)(i >> 16);
  56    buf[2] = (png_byte)(i >> 8);
  57    buf[3] = (png_byte)(i     );
  58 }
  59 
  60 /* Place a 16-bit number into a buffer in PNG byte order.
  61  * The parameter is declared unsigned int, not png_uint_16,
  62  * just to avoid potential problems on pre-ANSI C compilers.
  63  */
  64 void PNGAPI
  65 png_save_uint_16(png_bytep buf, unsigned int i)
  66 {
  67    buf[0] = (png_byte)(i >> 8);
  68    buf[1] = (png_byte)(i     );
  69 }
  70 #endif
  71 
  72 /* Simple function to write the signature.  If we have already written
  73  * the magic bytes of the signature, or more likely, the PNG stream is
  74  * being embedded into another stream and doesn't need its own signature,
  75  * we should call png_set_sig_bytes() to tell libpng how many of the
  76  * bytes have already been written.
  77  */
  78 void PNGAPI
  79 png_write_sig(png_structrp png_ptr)
  80 {
  81    png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  82 
  83 #ifdef PNG_IO_STATE_SUPPORTED
  84    /* Inform the I/O callback that the signature is being written */
  85    png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
  86 #endif
  87 
  88    /* Write the rest of the 8 byte signature */
  89    png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  90       (png_size_t)(8 - png_ptr->sig_bytes));
  91 
  92    if (png_ptr->sig_bytes < 3)
  93       png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  94 }
  95 
  96 /* Write the start of a PNG chunk.  The type is the chunk type.
  97  * The total_length is the sum of the lengths of all the data you will be
  98  * passing in png_write_chunk_data().
  99  */
 100 static void
 101 png_write_chunk_header(png_structrp png_ptr, png_uint_32 chunk_name,
 102     png_uint_32 length)
 103 {
 104    png_byte buf[8];
 105 
 106 #if defined(PNG_DEBUG) && (PNG_DEBUG > 0)
 107    PNG_CSTRING_FROM_CHUNK(buf, chunk_name);
 108    png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length);
 109 #endif
 110 
 111    if (png_ptr == NULL)
 112       return;
 113 
 114 #ifdef PNG_IO_STATE_SUPPORTED
 115    /* Inform the I/O callback that the chunk header is being written.
 116     * PNG_IO_CHUNK_HDR requires a single I/O call.
 117     */
 118    png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
 119 #endif
 120 
 121    /* Write the length and the chunk name */
 122    png_save_uint_32(buf, length);
 123    png_save_uint_32(buf + 4, chunk_name);
 124    png_write_data(png_ptr, buf, 8);
 125 
 126    /* Put the chunk name into png_ptr->chunk_name */
 127    png_ptr->chunk_name = chunk_name;
 128 
 129    /* Reset the crc and run it over the chunk name */
 130    png_reset_crc(png_ptr);
 131 
 132    png_calculate_crc(png_ptr, buf + 4, 4);
 133 
 134 #ifdef PNG_IO_STATE_SUPPORTED
 135    /* Inform the I/O callback that chunk data will (possibly) be written.
 136     * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
 137     */
 138    png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
 139 #endif
 140 }
 141 
 142 void PNGAPI
 143 png_write_chunk_start(png_structrp png_ptr, png_const_bytep chunk_string,
 144     png_uint_32 length)
 145 {
 146    png_write_chunk_header(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), length);
 147 }
 148 
 149 /* Write the data of a PNG chunk started with png_write_chunk_header().
 150  * Note that multiple calls to this function are allowed, and that the
 151  * sum of the lengths from these calls *must* add up to the total_length
 152  * given to png_write_chunk_header().
 153  */
 154 void PNGAPI
 155 png_write_chunk_data(png_structrp png_ptr, png_const_bytep data,
 156     png_size_t length)
 157 {
 158    /* Write the data, and run the CRC over it */
 159    if (png_ptr == NULL)
 160       return;
 161 
 162    if (data != NULL && length > 0)
 163    {
 164       png_write_data(png_ptr, data, length);
 165 
 166       /* Update the CRC after writing the data,
 167        * in case the user I/O routine alters it.
 168        */
 169       png_calculate_crc(png_ptr, data, length);
 170    }
 171 }
 172 
 173 /* Finish a chunk started with png_write_chunk_header(). */
 174 void PNGAPI
 175 png_write_chunk_end(png_structrp png_ptr)
 176 {
 177    png_byte buf[4];
 178 
 179    if (png_ptr == NULL) return;
 180 
 181 #ifdef PNG_IO_STATE_SUPPORTED
 182    /* Inform the I/O callback that the chunk CRC is being written.
 183     * PNG_IO_CHUNK_CRC requires a single I/O function call.
 184     */
 185    png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
 186 #endif
 187 
 188    /* Write the crc in a single operation */
 189    png_save_uint_32(buf, png_ptr->crc);
 190 
 191    png_write_data(png_ptr, buf, (png_size_t)4);
 192 }
 193 
 194 /* Write a PNG chunk all at once.  The type is an array of ASCII characters
 195  * representing the chunk name.  The array must be at least 4 bytes in
 196  * length, and does not need to be null terminated.  To be safe, pass the
 197  * pre-defined chunk names here, and if you need a new one, define it
 198  * where the others are defined.  The length is the length of the data.
 199  * All the data must be present.  If that is not possible, use the
 200  * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
 201  * functions instead.
 202  */
 203 static void
 204 png_write_complete_chunk(png_structrp png_ptr, png_uint_32 chunk_name,
 205    png_const_bytep data, png_size_t length)
 206 {
 207    if (png_ptr == NULL)
 208       return;
 209 
 210    /* On 64-bit architectures 'length' may not fit in a png_uint_32. */
 211    if (length > PNG_UINT_31_MAX)
 212       png_error(png_ptr, "length exceeds PNG maximum");
 213 
 214    png_write_chunk_header(png_ptr, chunk_name, (png_uint_32)length);
 215    png_write_chunk_data(png_ptr, data, length);
 216    png_write_chunk_end(png_ptr);
 217 }
 218 
 219 /* This is the API that calls the internal function above. */
 220 void PNGAPI
 221 png_write_chunk(png_structrp png_ptr, png_const_bytep chunk_string,
 222    png_const_bytep data, png_size_t length)
 223 {
 224    png_write_complete_chunk(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), data,
 225       length);
 226 }
 227 
 228 /* This is used below to find the size of an image to pass to png_deflate_claim,
 229  * so it only needs to be accurate if the size is less than 16384 bytes (the
 230  * point at which a lower LZ window size can be used.)
 231  */
 232 static png_alloc_size_t
 233 png_image_size(png_structrp png_ptr)
 234 {
 235    /* Only return sizes up to the maximum of a png_uint_32; do this by limiting
 236     * the width and height used to 15 bits.
 237     */
 238    png_uint_32 h = png_ptr->height;
 239 
 240    if (png_ptr->rowbytes < 32768 && h < 32768)
 241    {
 242       if (png_ptr->interlaced != 0)
 243       {
 244          /* Interlacing makes the image larger because of the replication of
 245           * both the filter byte and the padding to a byte boundary.
 246           */
 247          png_uint_32 w = png_ptr->width;
 248          unsigned int pd = png_ptr->pixel_depth;
 249          png_alloc_size_t cb_base;
 250          int pass;
 251 
 252          for (cb_base=0, pass=0; pass<=6; ++pass)
 253          {
 254             png_uint_32 pw = PNG_PASS_COLS(w, pass);
 255 
 256             if (pw > 0)
 257                cb_base += (PNG_ROWBYTES(pd, pw)+1) * PNG_PASS_ROWS(h, pass);
 258          }
 259 
 260          return cb_base;
 261       }
 262 
 263       else
 264          return (png_ptr->rowbytes+1) * h;
 265    }
 266 
 267    else
 268       return 0xffffffffU;
 269 }
 270 
 271 #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
 272    /* This is the code to hack the first two bytes of the deflate stream (the
 273     * deflate header) to correct the windowBits value to match the actual data
 274     * size.  Note that the second argument is the *uncompressed* size but the
 275     * first argument is the *compressed* data (and it must be deflate
 276     * compressed.)
 277     */
 278 static void
 279 optimize_cmf(png_bytep data, png_alloc_size_t data_size)
 280 {
 281    /* Optimize the CMF field in the zlib stream.  The resultant zlib stream is
 282     * still compliant to the stream specification.
 283     */
 284    if (data_size <= 16384) /* else windowBits must be 15 */
 285    {
 286       unsigned int z_cmf = data[0];  /* zlib compression method and flags */
 287 
 288       if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
 289       {
 290          unsigned int z_cinfo;
 291          unsigned int half_z_window_size;
 292 
 293          z_cinfo = z_cmf >> 4;
 294          half_z_window_size = 1U << (z_cinfo + 7);
 295 
 296          if (data_size <= half_z_window_size) /* else no change */
 297          {
 298             unsigned int tmp;
 299 
 300             do
 301             {
 302                half_z_window_size >>= 1;
 303                --z_cinfo;
 304             }
 305             while (z_cinfo > 0 && data_size <= half_z_window_size);
 306 
 307             z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
 308 
 309             data[0] = (png_byte)z_cmf;
 310             tmp = data[1] & 0xe0;
 311             tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
 312             data[1] = (png_byte)tmp;
 313          }
 314       }
 315    }
 316 }
 317 #endif /* WRITE_OPTIMIZE_CMF */
 318 
 319 /* Initialize the compressor for the appropriate type of compression. */
 320 static int
 321 png_deflate_claim(png_structrp png_ptr, png_uint_32 owner,
 322    png_alloc_size_t data_size)
 323 {
 324    if (png_ptr->zowner != 0)
 325    {
 326 #if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_ERROR_TEXT_SUPPORTED)
 327       char msg[64];
 328 
 329       PNG_STRING_FROM_CHUNK(msg, owner);
 330       msg[4] = ':';
 331       msg[5] = ' ';
 332       PNG_STRING_FROM_CHUNK(msg+6, png_ptr->zowner);
 333       /* So the message that results is "<chunk> using zstream"; this is an
 334        * internal error, but is very useful for debugging.  i18n requirements
 335        * are minimal.
 336        */
 337       (void)png_safecat(msg, (sizeof msg), 10, " using zstream");
 338 #endif
 339 #if PNG_RELEASE_BUILD
 340          png_warning(png_ptr, msg);
 341 
 342          /* Attempt sane error recovery */
 343          if (png_ptr->zowner == png_IDAT) /* don't steal from IDAT */
 344          {
 345             png_ptr->zstream.msg = PNGZ_MSG_CAST("in use by IDAT");
 346             return Z_STREAM_ERROR;
 347          }
 348 
 349          png_ptr->zowner = 0;
 350 #else
 351          png_error(png_ptr, msg);
 352 #endif
 353    }
 354 
 355    {
 356       int level = png_ptr->zlib_level;
 357       int method = png_ptr->zlib_method;
 358       int windowBits = png_ptr->zlib_window_bits;
 359       int memLevel = png_ptr->zlib_mem_level;
 360       int strategy; /* set below */
 361       int ret; /* zlib return code */
 362 
 363       if (owner == png_IDAT)
 364       {
 365          if ((png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY) != 0)
 366             strategy = png_ptr->zlib_strategy;
 367 
 368          else if (png_ptr->do_filter != PNG_FILTER_NONE)
 369             strategy = PNG_Z_DEFAULT_STRATEGY;
 370 
 371          else
 372             strategy = PNG_Z_DEFAULT_NOFILTER_STRATEGY;
 373       }
 374 
 375       else
 376       {
 377 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
 378             level = png_ptr->zlib_text_level;
 379             method = png_ptr->zlib_text_method;
 380             windowBits = png_ptr->zlib_text_window_bits;
 381             memLevel = png_ptr->zlib_text_mem_level;
 382             strategy = png_ptr->zlib_text_strategy;
 383 #else
 384             /* If customization is not supported the values all come from the
 385              * IDAT values except for the strategy, which is fixed to the
 386              * default.  (This is the pre-1.6.0 behavior too, although it was
 387              * implemented in a very different way.)
 388              */
 389             strategy = Z_DEFAULT_STRATEGY;
 390 #endif
 391       }
 392 
 393       /* Adjust 'windowBits' down if larger than 'data_size'; to stop this
 394        * happening just pass 32768 as the data_size parameter.  Notice that zlib
 395        * requires an extra 262 bytes in the window in addition to the data to be
 396        * able to see the whole of the data, so if data_size+262 takes us to the
 397        * next windowBits size we need to fix up the value later.  (Because even
 398        * though deflate needs the extra window, inflate does not!)
 399        */
 400       if (data_size <= 16384)
 401       {
 402          /* IMPLEMENTATION NOTE: this 'half_window_size' stuff is only here to
 403           * work round a Microsoft Visual C misbehavior which, contrary to C-90,
 404           * widens the result of the following shift to 64-bits if (and,
 405           * apparently, only if) it is used in a test.
 406           */
 407          unsigned int half_window_size = 1U << (windowBits-1);
 408 
 409          while (data_size + 262 <= half_window_size)
 410          {
 411             half_window_size >>= 1;
 412             --windowBits;
 413          }
 414       }
 415 
 416       /* Check against the previous initialized values, if any. */
 417       if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0 &&
 418          (png_ptr->zlib_set_level != level ||
 419          png_ptr->zlib_set_method != method ||
 420          png_ptr->zlib_set_window_bits != windowBits ||
 421          png_ptr->zlib_set_mem_level != memLevel ||
 422          png_ptr->zlib_set_strategy != strategy))
 423       {
 424          if (deflateEnd(&png_ptr->zstream) != Z_OK)
 425             png_warning(png_ptr, "deflateEnd failed (ignored)");
 426 
 427          png_ptr->flags &= ~PNG_FLAG_ZSTREAM_INITIALIZED;
 428       }
 429 
 430       /* For safety clear out the input and output pointers (currently zlib
 431        * doesn't use them on Init, but it might in the future).
 432        */
 433       png_ptr->zstream.next_in = NULL;
 434       png_ptr->zstream.avail_in = 0;
 435       png_ptr->zstream.next_out = NULL;
 436       png_ptr->zstream.avail_out = 0;
 437 
 438       /* Now initialize if required, setting the new parameters, otherwise just
 439        * to a simple reset to the previous parameters.
 440        */
 441       if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
 442          ret = deflateReset(&png_ptr->zstream);
 443 
 444       else
 445       {
 446          ret = deflateInit2(&png_ptr->zstream, level, method, windowBits,
 447             memLevel, strategy);
 448 
 449          if (ret == Z_OK)
 450             png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
 451       }
 452 
 453       /* The return code is from either deflateReset or deflateInit2; they have
 454        * pretty much the same set of error codes.
 455        */
 456       if (ret == Z_OK)
 457          png_ptr->zowner = owner;
 458 
 459       else
 460          png_zstream_error(png_ptr, ret);
 461 
 462       return ret;
 463    }
 464 }
 465 
 466 /* Clean up (or trim) a linked list of compression buffers. */
 467 void /* PRIVATE */
 468 png_free_buffer_list(png_structrp png_ptr, png_compression_bufferp *listp)
 469 {
 470    png_compression_bufferp list = *listp;
 471 
 472    if (list != NULL)
 473    {
 474       *listp = NULL;
 475 
 476       do
 477       {
 478          png_compression_bufferp next = list->next;
 479 
 480          png_free(png_ptr, list);
 481          list = next;
 482       }
 483       while (list != NULL);
 484    }
 485 }
 486 
 487 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
 488 /* This pair of functions encapsulates the operation of (a) compressing a
 489  * text string, and (b) issuing it later as a series of chunk data writes.
 490  * The compression_state structure is shared context for these functions
 491  * set up by the caller to allow access to the relevant local variables.
 492  *
 493  * compression_buffer (new in 1.6.0) is just a linked list of zbuffer_size
 494  * temporary buffers.  From 1.6.0 it is retained in png_struct so that it will
 495  * be correctly freed in the event of a write error (previous implementations
 496  * just leaked memory.)
 497  */
 498 typedef struct
 499 {
 500    png_const_bytep      input;        /* The uncompressed input data */
 501    png_alloc_size_t     input_len;    /* Its length */
 502    png_uint_32          output_len;   /* Final compressed length */
 503    png_byte             output[1024]; /* First block of output */
 504 } compression_state;
 505 
 506 static void
 507 png_text_compress_init(compression_state *comp, png_const_bytep input,
 508    png_alloc_size_t input_len)
 509 {
 510    comp->input = input;
 511    comp->input_len = input_len;
 512    comp->output_len = 0;
 513 }
 514 
 515 /* Compress the data in the compression state input */
 516 static int
 517 png_text_compress(png_structrp png_ptr, png_uint_32 chunk_name,
 518    compression_state *comp, png_uint_32 prefix_len)
 519 {
 520    int ret;
 521 
 522    /* To find the length of the output it is necessary to first compress the
 523     * input. The result is buffered rather than using the two-pass algorithm
 524     * that is used on the inflate side; deflate is assumed to be slower and a
 525     * PNG writer is assumed to have more memory available than a PNG reader.
 526     *
 527     * IMPLEMENTATION NOTE: the zlib API deflateBound() can be used to find an
 528     * upper limit on the output size, but it is always bigger than the input
 529     * size so it is likely to be more efficient to use this linked-list
 530     * approach.
 531     */
 532    ret = png_deflate_claim(png_ptr, chunk_name, comp->input_len);
 533 
 534    if (ret != Z_OK)
 535       return ret;
 536 
 537    /* Set up the compression buffers, we need a loop here to avoid overflowing a
 538     * uInt.  Use ZLIB_IO_MAX to limit the input.  The output is always limited
 539     * by the output buffer size, so there is no need to check that.  Since this
 540     * is ANSI-C we know that an 'int', hence a uInt, is always at least 16 bits
 541     * in size.
 542     */
 543    {
 544       png_compression_bufferp *end = &png_ptr->zbuffer_list;
 545       png_alloc_size_t input_len = comp->input_len; /* may be zero! */
 546       png_uint_32 output_len;
 547 
 548       /* zlib updates these for us: */
 549       png_ptr->zstream.next_in = PNGZ_INPUT_CAST(comp->input);
 550       png_ptr->zstream.avail_in = 0; /* Set below */
 551       png_ptr->zstream.next_out = comp->output;
 552       png_ptr->zstream.avail_out = (sizeof comp->output);
 553 
 554       output_len = png_ptr->zstream.avail_out;
 555 
 556       do
 557       {
 558          uInt avail_in = ZLIB_IO_MAX;
 559 
 560          if (avail_in > input_len)
 561             avail_in = (uInt)input_len;
 562 
 563          input_len -= avail_in;
 564 
 565          png_ptr->zstream.avail_in = avail_in;
 566 
 567          if (png_ptr->zstream.avail_out == 0)
 568          {
 569             png_compression_buffer *next;
 570 
 571             /* Chunk data is limited to 2^31 bytes in length, so the prefix
 572              * length must be counted here.
 573              */
 574             if (output_len + prefix_len > PNG_UINT_31_MAX)
 575             {
 576                ret = Z_MEM_ERROR;
 577                break;
 578             }
 579 
 580             /* Need a new (malloc'ed) buffer, but there may be one present
 581              * already.
 582              */
 583             next = *end;
 584             if (next == NULL)
 585             {
 586                next = png_voidcast(png_compression_bufferp, png_malloc_base
 587                   (png_ptr, PNG_COMPRESSION_BUFFER_SIZE(png_ptr)));
 588 
 589                if (next == NULL)
 590                {
 591                   ret = Z_MEM_ERROR;
 592                   break;
 593                }
 594 
 595                /* Link in this buffer (so that it will be freed later) */
 596                next->next = NULL;
 597                *end = next;
 598             }
 599 
 600             png_ptr->zstream.next_out = next->output;
 601             png_ptr->zstream.avail_out = png_ptr->zbuffer_size;
 602             output_len += png_ptr->zstream.avail_out;
 603 
 604             /* Move 'end' to the next buffer pointer. */
 605             end = &next->next;
 606          }
 607 
 608          /* Compress the data */
 609          ret = deflate(&png_ptr->zstream,
 610             input_len > 0 ? Z_NO_FLUSH : Z_FINISH);
 611 
 612          /* Claw back input data that was not consumed (because avail_in is
 613           * reset above every time round the loop).
 614           */
 615          input_len += png_ptr->zstream.avail_in;
 616          png_ptr->zstream.avail_in = 0; /* safety */
 617       }
 618       while (ret == Z_OK);
 619 
 620       /* There may be some space left in the last output buffer. This needs to
 621        * be subtracted from output_len.
 622        */
 623       output_len -= png_ptr->zstream.avail_out;
 624       png_ptr->zstream.avail_out = 0; /* safety */
 625       comp->output_len = output_len;
 626 
 627       /* Now double check the output length, put in a custom message if it is
 628        * too long.  Otherwise ensure the z_stream::msg pointer is set to
 629        * something.
 630        */
 631       if (output_len + prefix_len >= PNG_UINT_31_MAX)
 632       {
 633          png_ptr->zstream.msg = PNGZ_MSG_CAST("compressed data too long");
 634          ret = Z_MEM_ERROR;
 635       }
 636 
 637       else
 638          png_zstream_error(png_ptr, ret);
 639 
 640       /* Reset zlib for another zTXt/iTXt or image data */
 641       png_ptr->zowner = 0;
 642 
 643       /* The only success case is Z_STREAM_END, input_len must be 0; if not this
 644        * is an internal error.
 645        */
 646       if (ret == Z_STREAM_END && input_len == 0)
 647       {
 648 #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
 649          /* Fix up the deflate header, if required */
 650          optimize_cmf(comp->output, comp->input_len);
 651 #endif
 652          /* But Z_OK is returned, not Z_STREAM_END; this allows the claim
 653           * function above to return Z_STREAM_END on an error (though it never
 654           * does in the current versions of zlib.)
 655           */
 656          return Z_OK;
 657       }
 658 
 659       else
 660          return ret;
 661    }
 662 }
 663 
 664 /* Ship the compressed text out via chunk writes */
 665 static void
 666 png_write_compressed_data_out(png_structrp png_ptr, compression_state *comp)
 667 {
 668    png_uint_32 output_len = comp->output_len;
 669    png_const_bytep output = comp->output;
 670    png_uint_32 avail = (sizeof comp->output);
 671    png_compression_buffer *next = png_ptr->zbuffer_list;
 672 
 673    for (;;)
 674    {
 675       if (avail > output_len)
 676          avail = output_len;
 677 
 678       png_write_chunk_data(png_ptr, output, avail);
 679 
 680       output_len -= avail;
 681 
 682       if (output_len == 0 || next == NULL)
 683          break;
 684 
 685       avail = png_ptr->zbuffer_size;
 686       output = next->output;
 687       next = next->next;
 688    }
 689 
 690    /* This is an internal error; 'next' must have been NULL! */
 691    if (output_len > 0)
 692       png_error(png_ptr, "error writing ancillary chunked compressed data");
 693 }
 694 #endif /* WRITE_COMPRESSED_TEXT */
 695 
 696 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
 697     defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
 698 /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
 699  * and if invalid, correct the keyword rather than discarding the entire
 700  * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
 701  * length, forbids leading or trailing whitespace, multiple internal spaces,
 702  * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
 703  *
 704  * The 'new_key' buffer must be 80 characters in size (for the keyword plus a
 705  * trailing '\0').  If this routine returns 0 then there was no keyword, or a
 706  * valid one could not be generated, and the caller must png_error.
 707  */
 708 static png_uint_32
 709 png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)
 710 {
 711    png_const_charp orig_key = key;
 712    png_uint_32 key_len = 0;
 713    int bad_character = 0;
 714    int space = 1;
 715 
 716    png_debug(1, "in png_check_keyword");
 717 
 718    if (key == NULL)
 719    {
 720       *new_key = 0;
 721       return 0;
 722    }
 723 
 724    while (*key && key_len < 79)
 725    {
 726       png_byte ch = (png_byte)*key++;
 727 
 728       if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
 729          *new_key++ = ch, ++key_len, space = 0;
 730 
 731       else if (space == 0)
 732       {
 733          /* A space or an invalid character when one wasn't seen immediately
 734           * before; output just a space.
 735           */
 736          *new_key++ = 32, ++key_len, space = 1;
 737 
 738          /* If the character was not a space then it is invalid. */
 739          if (ch != 32)
 740             bad_character = ch;
 741       }
 742 
 743       else if (bad_character == 0)
 744          bad_character = ch; /* just skip it, record the first error */
 745    }
 746 
 747    if (key_len > 0 && space != 0) /* trailing space */
 748    {
 749       --key_len, --new_key;
 750       if (bad_character == 0)
 751          bad_character = 32;
 752    }
 753 
 754    /* Terminate the keyword */
 755    *new_key = 0;
 756 
 757    if (key_len == 0)
 758       return 0;
 759 
 760 #ifdef PNG_WARNINGS_SUPPORTED
 761    /* Try to only output one warning per keyword: */
 762    if (*key != 0) /* keyword too long */
 763       png_warning(png_ptr, "keyword truncated");
 764 
 765    else if (bad_character != 0)
 766    {
 767       PNG_WARNING_PARAMETERS(p)
 768 
 769       png_warning_parameter(p, 1, orig_key);
 770       png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);
 771 
 772       png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");
 773    }
 774 #endif /* WARNINGS */
 775 
 776    return key_len;
 777 }
 778 #endif /* WRITE_TEXT || WRITE_pCAL || WRITE_iCCP || WRITE_sPLT */
 779 
 780 /* Write the IHDR chunk, and update the png_struct with the necessary
 781  * information.  Note that the rest of this code depends upon this
 782  * information being correct.
 783  */
 784 void /* PRIVATE */
 785 png_write_IHDR(png_structrp png_ptr, png_uint_32 width, png_uint_32 height,
 786     int bit_depth, int color_type, int compression_type, int filter_type,
 787     int interlace_type)
 788 {
 789    png_byte buf[13]; /* Buffer to store the IHDR info */
 790 
 791    png_debug(1, "in png_write_IHDR");
 792 
 793    /* Check that we have valid input data from the application info */
 794    switch (color_type)
 795    {
 796       case PNG_COLOR_TYPE_GRAY:
 797          switch (bit_depth)
 798          {
 799             case 1:
 800             case 2:
 801             case 4:
 802             case 8:
 803 #ifdef PNG_WRITE_16BIT_SUPPORTED
 804             case 16:
 805 #endif
 806                png_ptr->channels = 1; break;
 807 
 808             default:
 809                png_error(png_ptr,
 810                    "Invalid bit depth for grayscale image");
 811          }
 812          break;
 813 
 814       case PNG_COLOR_TYPE_RGB:
 815 #ifdef PNG_WRITE_16BIT_SUPPORTED
 816          if (bit_depth != 8 && bit_depth != 16)
 817 #else
 818          if (bit_depth != 8)
 819 #endif
 820             png_error(png_ptr, "Invalid bit depth for RGB image");
 821 
 822          png_ptr->channels = 3;
 823          break;
 824 
 825       case PNG_COLOR_TYPE_PALETTE:
 826          switch (bit_depth)
 827          {
 828             case 1:
 829             case 2:
 830             case 4:
 831             case 8:
 832                png_ptr->channels = 1;
 833                break;
 834 
 835             default:
 836                png_error(png_ptr, "Invalid bit depth for paletted image");
 837          }
 838          break;
 839 
 840       case PNG_COLOR_TYPE_GRAY_ALPHA:
 841          if (bit_depth != 8 && bit_depth != 16)
 842             png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
 843 
 844          png_ptr->channels = 2;
 845          break;
 846 
 847       case PNG_COLOR_TYPE_RGB_ALPHA:
 848 #ifdef PNG_WRITE_16BIT_SUPPORTED
 849          if (bit_depth != 8 && bit_depth != 16)
 850 #else
 851          if (bit_depth != 8)
 852 #endif
 853             png_error(png_ptr, "Invalid bit depth for RGBA image");
 854 
 855          png_ptr->channels = 4;
 856          break;
 857 
 858       default:
 859          png_error(png_ptr, "Invalid image color type specified");
 860    }
 861 
 862    if (compression_type != PNG_COMPRESSION_TYPE_BASE)
 863    {
 864       png_warning(png_ptr, "Invalid compression type specified");
 865       compression_type = PNG_COMPRESSION_TYPE_BASE;
 866    }
 867 
 868    /* Write filter_method 64 (intrapixel differencing) only if
 869     * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
 870     * 2. Libpng did not write a PNG signature (this filter_method is only
 871     *    used in PNG datastreams that are embedded in MNG datastreams) and
 872     * 3. The application called png_permit_mng_features with a mask that
 873     *    included PNG_FLAG_MNG_FILTER_64 and
 874     * 4. The filter_method is 64 and
 875     * 5. The color_type is RGB or RGBA
 876     */
 877    if (
 878 #ifdef PNG_MNG_FEATURES_SUPPORTED
 879        !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
 880        ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
 881        (color_type == PNG_COLOR_TYPE_RGB ||
 882         color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
 883        (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
 884 #endif
 885        filter_type != PNG_FILTER_TYPE_BASE)
 886    {
 887       png_warning(png_ptr, "Invalid filter type specified");
 888       filter_type = PNG_FILTER_TYPE_BASE;
 889    }
 890 
 891 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
 892    if (interlace_type != PNG_INTERLACE_NONE &&
 893        interlace_type != PNG_INTERLACE_ADAM7)
 894    {
 895       png_warning(png_ptr, "Invalid interlace type specified");
 896       interlace_type = PNG_INTERLACE_ADAM7;
 897    }
 898 #else
 899    interlace_type=PNG_INTERLACE_NONE;
 900 #endif
 901 
 902    /* Save the relevant information */
 903    png_ptr->bit_depth = (png_byte)bit_depth;
 904    png_ptr->color_type = (png_byte)color_type;
 905    png_ptr->interlaced = (png_byte)interlace_type;
 906 #ifdef PNG_MNG_FEATURES_SUPPORTED
 907    png_ptr->filter_type = (png_byte)filter_type;
 908 #endif
 909    png_ptr->compression_type = (png_byte)compression_type;
 910    png_ptr->width = width;
 911    png_ptr->height = height;
 912 
 913    png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
 914    png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
 915    /* Set the usr info, so any transformations can modify it */
 916    png_ptr->usr_width = png_ptr->width;
 917    png_ptr->usr_bit_depth = png_ptr->bit_depth;
 918    png_ptr->usr_channels = png_ptr->channels;
 919 
 920    /* Pack the header information into the buffer */
 921    png_save_uint_32(buf, width);
 922    png_save_uint_32(buf + 4, height);
 923    buf[8] = (png_byte)bit_depth;
 924    buf[9] = (png_byte)color_type;
 925    buf[10] = (png_byte)compression_type;
 926    buf[11] = (png_byte)filter_type;
 927    buf[12] = (png_byte)interlace_type;
 928 
 929    /* Write the chunk */
 930    png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
 931 
 932    if ((png_ptr->do_filter) == PNG_NO_FILTERS)
 933    {
 934       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
 935           png_ptr->bit_depth < 8)
 936          png_ptr->do_filter = PNG_FILTER_NONE;
 937 
 938       else
 939          png_ptr->do_filter = PNG_ALL_FILTERS;
 940    }
 941 
 942    png_ptr->mode = PNG_HAVE_IHDR; /* not READY_FOR_ZTXT */
 943 }
 944 
 945 /* Write the palette.  We are careful not to trust png_color to be in the
 946  * correct order for PNG, so people can redefine it to any convenient
 947  * structure.
 948  */
 949 void /* PRIVATE */
 950 png_write_PLTE(png_structrp png_ptr, png_const_colorp palette,
 951     png_uint_32 num_pal)
 952 {
 953    png_uint_32 max_palette_length, i;
 954    png_const_colorp pal_ptr;
 955    png_byte buf[3];
 956 
 957    png_debug(1, "in png_write_PLTE");
 958 
 959    max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
 960       (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
 961 
 962    if ((
 963 #ifdef PNG_MNG_FEATURES_SUPPORTED
 964        (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 &&
 965 #endif
 966        num_pal == 0) || num_pal > max_palette_length)
 967    {
 968       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 969       {
 970          png_error(png_ptr, "Invalid number of colors in palette");
 971       }
 972 
 973       else
 974       {
 975          png_warning(png_ptr, "Invalid number of colors in palette");
 976          return;
 977       }
 978    }
 979 
 980    if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
 981    {
 982       png_warning(png_ptr,
 983           "Ignoring request to write a PLTE chunk in grayscale PNG");
 984 
 985       return;
 986    }
 987 
 988    png_ptr->num_palette = (png_uint_16)num_pal;
 989    png_debug1(3, "num_palette = %d", png_ptr->num_palette);
 990 
 991    png_write_chunk_header(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
 992 #ifdef PNG_POINTER_INDEXING_SUPPORTED
 993 
 994    for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
 995    {
 996       buf[0] = pal_ptr->red;
 997       buf[1] = pal_ptr->green;
 998       buf[2] = pal_ptr->blue;
 999       png_write_chunk_data(png_ptr, buf, (png_size_t)3);
1000    }
1001 
1002 #else
1003    /* This is a little slower but some buggy compilers need to do this
1004     * instead
1005     */
1006    pal_ptr=palette;
1007 
1008    for (i = 0; i < num_pal; i++)
1009    {
1010       buf[0] = pal_ptr[i].red;
1011       buf[1] = pal_ptr[i].green;
1012       buf[2] = pal_ptr[i].blue;
1013       png_write_chunk_data(png_ptr, buf, (png_size_t)3);
1014    }
1015 
1016 #endif
1017    png_write_chunk_end(png_ptr);
1018    png_ptr->mode |= PNG_HAVE_PLTE;
1019 }
1020 
1021 /* This is similar to png_text_compress, above, except that it does not require
1022  * all of the data at once and, instead of buffering the compressed result,
1023  * writes it as IDAT chunks.  Unlike png_text_compress it *can* png_error out
1024  * because it calls the write interface.  As a result it does its own error
1025  * reporting and does not return an error code.  In the event of error it will
1026  * just call png_error.  The input data length may exceed 32-bits.  The 'flush'
1027  * parameter is exactly the same as that to deflate, with the following
1028  * meanings:
1029  *
1030  * Z_NO_FLUSH: normal incremental output of compressed data
1031  * Z_SYNC_FLUSH: do a SYNC_FLUSH, used by png_write_flush
1032  * Z_FINISH: this is the end of the input, do a Z_FINISH and clean up
1033  *
1034  * The routine manages the acquire and release of the png_ptr->zstream by
1035  * checking and (at the end) clearing png_ptr->zowner; it does some sanity
1036  * checks on the 'mode' flags while doing this.
1037  */
1038 void /* PRIVATE */
1039 png_compress_IDAT(png_structrp png_ptr, png_const_bytep input,
1040    png_alloc_size_t input_len, int flush)
1041 {
1042    if (png_ptr->zowner != png_IDAT)
1043    {
1044       /* First time.   Ensure we have a temporary buffer for compression and
1045        * trim the buffer list if it has more than one entry to free memory.
1046        * If 'WRITE_COMPRESSED_TEXT' is not set the list will never have been
1047        * created at this point, but the check here is quick and safe.
1048        */
1049       if (png_ptr->zbuffer_list == NULL)
1050       {
1051          png_ptr->zbuffer_list = png_voidcast(png_compression_bufferp,
1052             png_malloc(png_ptr, PNG_COMPRESSION_BUFFER_SIZE(png_ptr)));
1053          png_ptr->zbuffer_list->next = NULL;
1054       }
1055 
1056       else
1057          png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list->next);
1058 
1059       /* It is a terminal error if we can't claim the zstream. */
1060       if (png_deflate_claim(png_ptr, png_IDAT, png_image_size(png_ptr)) != Z_OK)
1061          png_error(png_ptr, png_ptr->zstream.msg);
1062 
1063       /* The output state is maintained in png_ptr->zstream, so it must be
1064        * initialized here after the claim.
1065        */
1066       png_ptr->zstream.next_out = png_ptr->zbuffer_list->output;
1067       png_ptr->zstream.avail_out = png_ptr->zbuffer_size;
1068    }
1069 
1070    /* Now loop reading and writing until all the input is consumed or an error
1071     * terminates the operation.  The _out values are maintained across calls to
1072     * this function, but the input must be reset each time.
1073     */
1074    png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
1075    png_ptr->zstream.avail_in = 0; /* set below */
1076    for (;;)
1077    {
1078       int ret;
1079 
1080       /* INPUT: from the row data */
1081       uInt avail = ZLIB_IO_MAX;
1082 
1083       if (avail > input_len)
1084          avail = (uInt)input_len; /* safe because of the check */
1085 
1086       png_ptr->zstream.avail_in = avail;
1087       input_len -= avail;
1088 
1089       ret = deflate(&png_ptr->zstream, input_len > 0 ? Z_NO_FLUSH : flush);
1090 
1091       /* Include as-yet unconsumed input */
1092       input_len += png_ptr->zstream.avail_in;
1093       png_ptr->zstream.avail_in = 0;
1094 
1095       /* OUTPUT: write complete IDAT chunks when avail_out drops to zero. Note
1096        * that these two zstream fields are preserved across the calls, therefore
1097        * there is no need to set these up on entry to the loop.
1098        */
1099       if (png_ptr->zstream.avail_out == 0)
1100       {
1101          png_bytep data = png_ptr->zbuffer_list->output;
1102          uInt size = png_ptr->zbuffer_size;
1103 
1104          /* Write an IDAT containing the data then reset the buffer.  The
1105           * first IDAT may need deflate header optimization.
1106           */
1107 #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
1108             if ((png_ptr->mode & PNG_HAVE_IDAT) == 0 &&
1109                 png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
1110                optimize_cmf(data, png_image_size(png_ptr));
1111 #endif
1112 
1113          png_write_complete_chunk(png_ptr, png_IDAT, data, size);
1114          png_ptr->mode |= PNG_HAVE_IDAT;
1115 
1116          png_ptr->zstream.next_out = data;
1117          png_ptr->zstream.avail_out = size;
1118 
1119          /* For SYNC_FLUSH or FINISH it is essential to keep calling zlib with
1120           * the same flush parameter until it has finished output, for NO_FLUSH
1121           * it doesn't matter.
1122           */
1123          if (ret == Z_OK && flush != Z_NO_FLUSH)
1124             continue;
1125       }
1126 
1127       /* The order of these checks doesn't matter much; it just affects which
1128        * possible error might be detected if multiple things go wrong at once.
1129        */
1130       if (ret == Z_OK) /* most likely return code! */
1131       {
1132          /* If all the input has been consumed then just return.  If Z_FINISH
1133           * was used as the flush parameter something has gone wrong if we get
1134           * here.
1135           */
1136          if (input_len == 0)
1137          {
1138             if (flush == Z_FINISH)
1139                png_error(png_ptr, "Z_OK on Z_FINISH with output space");
1140 
1141             return;
1142          }
1143       }
1144 
1145       else if (ret == Z_STREAM_END && flush == Z_FINISH)
1146       {
1147          /* This is the end of the IDAT data; any pending output must be
1148           * flushed.  For small PNG files we may still be at the beginning.
1149           */
1150          png_bytep data = png_ptr->zbuffer_list->output;
1151          uInt size = png_ptr->zbuffer_size - png_ptr->zstream.avail_out;
1152 
1153 #ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
1154          if ((png_ptr->mode & PNG_HAVE_IDAT) == 0 &&
1155              png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
1156             optimize_cmf(data, png_image_size(png_ptr));
1157 #endif
1158 
1159          png_write_complete_chunk(png_ptr, png_IDAT, data, size);
1160          png_ptr->zstream.avail_out = 0;
1161          png_ptr->zstream.next_out = NULL;
1162          png_ptr->mode |= PNG_HAVE_IDAT | PNG_AFTER_IDAT;
1163 
1164          png_ptr->zowner = 0; /* Release the stream */
1165          return;
1166       }
1167 
1168       else
1169       {
1170          /* This is an error condition. */
1171          png_zstream_error(png_ptr, ret);
1172          png_error(png_ptr, png_ptr->zstream.msg);
1173       }
1174    }
1175 }
1176 
1177 /* Write an IEND chunk */
1178 void /* PRIVATE */
1179 png_write_IEND(png_structrp png_ptr)
1180 {
1181    png_debug(1, "in png_write_IEND");
1182 
1183    png_write_complete_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
1184    png_ptr->mode |= PNG_HAVE_IEND;
1185 }
1186 
1187 #ifdef PNG_WRITE_gAMA_SUPPORTED
1188 /* Write a gAMA chunk */
1189 void /* PRIVATE */
1190 png_write_gAMA_fixed(png_structrp png_ptr, png_fixed_point file_gamma)
1191 {
1192    png_byte buf[4];
1193 
1194    png_debug(1, "in png_write_gAMA");
1195 
1196    /* file_gamma is saved in 1/100,000ths */
1197    png_save_uint_32(buf, (png_uint_32)file_gamma);
1198    png_write_complete_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
1199 }
1200 #endif
1201 
1202 #ifdef PNG_WRITE_sRGB_SUPPORTED
1203 /* Write a sRGB chunk */
1204 void /* PRIVATE */
1205 png_write_sRGB(png_structrp png_ptr, int srgb_intent)
1206 {
1207    png_byte buf[1];
1208 
1209    png_debug(1, "in png_write_sRGB");
1210 
1211    if (srgb_intent >= PNG_sRGB_INTENT_LAST)
1212       png_warning(png_ptr,
1213           "Invalid sRGB rendering intent specified");
1214 
1215    buf[0]=(png_byte)srgb_intent;
1216    png_write_complete_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
1217 }
1218 #endif
1219 
1220 #ifdef PNG_WRITE_iCCP_SUPPORTED
1221 /* Write an iCCP chunk */
1222 void /* PRIVATE */
1223 png_write_iCCP(png_structrp png_ptr, png_const_charp name,
1224     png_const_bytep profile)
1225 {
1226    png_uint_32 name_len;
1227    png_uint_32 profile_len;
1228    png_byte new_name[81]; /* 1 byte for the compression byte */
1229    compression_state comp;
1230    png_uint_32 temp;
1231 
1232    png_debug(1, "in png_write_iCCP");
1233 
1234    /* These are all internal problems: the profile should have been checked
1235     * before when it was stored.
1236     */
1237    if (profile == NULL)
1238       png_error(png_ptr, "No profile for iCCP chunk"); /* internal error */
1239 
1240    profile_len = png_get_uint_32(profile);
1241 
1242    if (profile_len < 132)
1243       png_error(png_ptr, "ICC profile too short");
1244 
1245    temp = (png_uint_32) (*(profile+8));
1246    if (temp > 3 && (profile_len & 0x03))
1247       png_error(png_ptr, "ICC profile length invalid (not a multiple of 4)");
1248 
1249    {
1250       png_uint_32 embedded_profile_len = png_get_uint_32(profile);
1251 
1252       if (profile_len != embedded_profile_len)
1253          png_error(png_ptr, "Profile length does not match profile");
1254    }
1255 
1256    name_len = png_check_keyword(png_ptr, name, new_name);
1257 
1258    if (name_len == 0)
1259       png_error(png_ptr, "iCCP: invalid keyword");
1260 
1261    new_name[++name_len] = PNG_COMPRESSION_TYPE_BASE;
1262 
1263    /* Make sure we include the NULL after the name and the compression type */
1264    ++name_len;
1265 
1266    png_text_compress_init(&comp, profile, profile_len);
1267 
1268    /* Allow for keyword terminator and compression byte */
1269    if (png_text_compress(png_ptr, png_iCCP, &comp, name_len) != Z_OK)
1270       png_error(png_ptr, png_ptr->zstream.msg);
1271 
1272    png_write_chunk_header(png_ptr, png_iCCP, name_len + comp.output_len);
1273 
1274    png_write_chunk_data(png_ptr, new_name, name_len);
1275 
1276    png_write_compressed_data_out(png_ptr, &comp);
1277 
1278    png_write_chunk_end(png_ptr);
1279 }
1280 #endif
1281 
1282 #ifdef PNG_WRITE_sPLT_SUPPORTED
1283 /* Write a sPLT chunk */
1284 void /* PRIVATE */
1285 png_write_sPLT(png_structrp png_ptr, png_const_sPLT_tp spalette)
1286 {
1287    png_uint_32 name_len;
1288    png_byte new_name[80];
1289    png_byte entrybuf[10];
1290    png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
1291    png_size_t palette_size = entry_size * spalette->nentries;
1292    png_sPLT_entryp ep;
1293 #ifndef PNG_POINTER_INDEXING_SUPPORTED
1294    int i;
1295 #endif
1296 
1297    png_debug(1, "in png_write_sPLT");
1298 
1299    name_len = png_check_keyword(png_ptr, spalette->name, new_name);
1300 
1301    if (name_len == 0)
1302       png_error(png_ptr, "sPLT: invalid keyword");
1303 
1304    /* Make sure we include the NULL after the name */
1305    png_write_chunk_header(png_ptr, png_sPLT,
1306        (png_uint_32)(name_len + 2 + palette_size));
1307 
1308    png_write_chunk_data(png_ptr, (png_bytep)new_name,
1309        (png_size_t)(name_len + 1));
1310 
1311    png_write_chunk_data(png_ptr, &spalette->depth, (png_size_t)1);
1312 
1313    /* Loop through each palette entry, writing appropriately */
1314 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1315    for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
1316    {
1317       if (spalette->depth == 8)
1318       {
1319          entrybuf[0] = (png_byte)ep->red;
1320          entrybuf[1] = (png_byte)ep->green;
1321          entrybuf[2] = (png_byte)ep->blue;
1322          entrybuf[3] = (png_byte)ep->alpha;
1323          png_save_uint_16(entrybuf + 4, ep->frequency);
1324       }
1325 
1326       else
1327       {
1328          png_save_uint_16(entrybuf + 0, ep->red);
1329          png_save_uint_16(entrybuf + 2, ep->green);
1330          png_save_uint_16(entrybuf + 4, ep->blue);
1331          png_save_uint_16(entrybuf + 6, ep->alpha);
1332          png_save_uint_16(entrybuf + 8, ep->frequency);
1333       }
1334 
1335       png_write_chunk_data(png_ptr, entrybuf, entry_size);
1336    }
1337 #else
1338    ep=spalette->entries;
1339    for (i = 0; i>spalette->nentries; i++)
1340    {
1341       if (spalette->depth == 8)
1342       {
1343          entrybuf[0] = (png_byte)ep[i].red;
1344          entrybuf[1] = (png_byte)ep[i].green;
1345          entrybuf[2] = (png_byte)ep[i].blue;
1346          entrybuf[3] = (png_byte)ep[i].alpha;
1347          png_save_uint_16(entrybuf + 4, ep[i].frequency);
1348       }
1349 
1350       else
1351       {
1352          png_save_uint_16(entrybuf + 0, ep[i].red);
1353          png_save_uint_16(entrybuf + 2, ep[i].green);
1354          png_save_uint_16(entrybuf + 4, ep[i].blue);
1355          png_save_uint_16(entrybuf + 6, ep[i].alpha);
1356          png_save_uint_16(entrybuf + 8, ep[i].frequency);
1357       }
1358 
1359       png_write_chunk_data(png_ptr, entrybuf, entry_size);
1360    }
1361 #endif
1362 
1363    png_write_chunk_end(png_ptr);
1364 }
1365 #endif
1366 
1367 #ifdef PNG_WRITE_sBIT_SUPPORTED
1368 /* Write the sBIT chunk */
1369 void /* PRIVATE */
1370 png_write_sBIT(png_structrp png_ptr, png_const_color_8p sbit, int color_type)
1371 {
1372    png_byte buf[4];
1373    png_size_t size;
1374 
1375    png_debug(1, "in png_write_sBIT");
1376 
1377    /* Make sure we don't depend upon the order of PNG_COLOR_8 */
1378    if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
1379    {
1380       png_byte maxbits;
1381 
1382       maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
1383           png_ptr->usr_bit_depth);
1384 
1385       if (sbit->red == 0 || sbit->red > maxbits ||
1386           sbit->green == 0 || sbit->green > maxbits ||
1387           sbit->blue == 0 || sbit->blue > maxbits)
1388       {
1389          png_warning(png_ptr, "Invalid sBIT depth specified");
1390          return;
1391       }
1392 
1393       buf[0] = sbit->red;
1394       buf[1] = sbit->green;
1395       buf[2] = sbit->blue;
1396       size = 3;
1397    }
1398 
1399    else
1400    {
1401       if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
1402       {
1403          png_warning(png_ptr, "Invalid sBIT depth specified");
1404          return;
1405       }
1406 
1407       buf[0] = sbit->gray;
1408       size = 1;
1409    }
1410 
1411    if ((color_type & PNG_COLOR_MASK_ALPHA) != 0)
1412    {
1413       if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
1414       {
1415          png_warning(png_ptr, "Invalid sBIT depth specified");
1416          return;
1417       }
1418 
1419       buf[size++] = sbit->alpha;
1420    }
1421 
1422    png_write_complete_chunk(png_ptr, png_sBIT, buf, size);
1423 }
1424 #endif
1425 
1426 #ifdef PNG_WRITE_cHRM_SUPPORTED
1427 /* Write the cHRM chunk */
1428 void /* PRIVATE */
1429 png_write_cHRM_fixed(png_structrp png_ptr, const png_xy *xy)
1430 {
1431    png_byte buf[32];
1432 
1433    png_debug(1, "in png_write_cHRM");
1434 
1435    /* Each value is saved in 1/100,000ths */
1436    png_save_int_32(buf,      xy->whitex);
1437    png_save_int_32(buf +  4, xy->whitey);
1438 
1439    png_save_int_32(buf +  8, xy->redx);
1440    png_save_int_32(buf + 12, xy->redy);
1441 
1442    png_save_int_32(buf + 16, xy->greenx);
1443    png_save_int_32(buf + 20, xy->greeny);
1444 
1445    png_save_int_32(buf + 24, xy->bluex);
1446    png_save_int_32(buf + 28, xy->bluey);
1447 
1448    png_write_complete_chunk(png_ptr, png_cHRM, buf, 32);
1449 }
1450 #endif
1451 
1452 #ifdef PNG_WRITE_tRNS_SUPPORTED
1453 /* Write the tRNS chunk */
1454 void /* PRIVATE */
1455 png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha,
1456     png_const_color_16p tran, int num_trans, int color_type)
1457 {
1458    png_byte buf[6];
1459 
1460    png_debug(1, "in png_write_tRNS");
1461 
1462    if (color_type == PNG_COLOR_TYPE_PALETTE)
1463    {
1464       if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
1465       {
1466          png_app_warning(png_ptr,
1467              "Invalid number of transparent colors specified");
1468          return;
1469       }
1470 
1471       /* Write the chunk out as it is */
1472       png_write_complete_chunk(png_ptr, png_tRNS, trans_alpha,
1473          (png_size_t)num_trans);
1474    }
1475 
1476    else if (color_type == PNG_COLOR_TYPE_GRAY)
1477    {
1478       /* One 16-bit value */
1479       if (tran->gray >= (1 << png_ptr->bit_depth))
1480       {
1481          png_app_warning(png_ptr,
1482              "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1483 
1484          return;
1485       }
1486 
1487       png_save_uint_16(buf, tran->gray);
1488       png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
1489    }
1490 
1491    else if (color_type == PNG_COLOR_TYPE_RGB)
1492    {
1493       /* Three 16-bit values */
1494       png_save_uint_16(buf, tran->red);
1495       png_save_uint_16(buf + 2, tran->green);
1496       png_save_uint_16(buf + 4, tran->blue);
1497 #ifdef PNG_WRITE_16BIT_SUPPORTED
1498       if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0)
1499 #else
1500       if ((buf[0] | buf[2] | buf[4]) != 0)
1501 #endif
1502       {
1503          png_app_warning(png_ptr,
1504            "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1505          return;
1506       }
1507 
1508       png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
1509    }
1510 
1511    else
1512    {
1513       png_app_warning(png_ptr, "Can't write tRNS with an alpha channel");
1514    }
1515 }
1516 #endif
1517 
1518 #ifdef PNG_WRITE_bKGD_SUPPORTED
1519 /* Write the background chunk */
1520 void /* PRIVATE */
1521 png_write_bKGD(png_structrp png_ptr, png_const_color_16p back, int color_type)
1522 {
1523    png_byte buf[6];
1524 
1525    png_debug(1, "in png_write_bKGD");
1526 
1527    if (color_type == PNG_COLOR_TYPE_PALETTE)
1528    {
1529       if (
1530 #ifdef PNG_MNG_FEATURES_SUPPORTED
1531           (png_ptr->num_palette != 0 ||
1532           (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0) &&
1533 #endif
1534          back->index >= png_ptr->num_palette)
1535       {
1536          png_warning(png_ptr, "Invalid background palette index");
1537          return;
1538       }
1539 
1540       buf[0] = back->index;
1541       png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
1542    }
1543 
1544    else if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
1545    {
1546       png_save_uint_16(buf, back->red);
1547       png_save_uint_16(buf + 2, back->green);
1548       png_save_uint_16(buf + 4, back->blue);
1549 #ifdef PNG_WRITE_16BIT_SUPPORTED
1550       if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0)
1551 #else
1552       if ((buf[0] | buf[2] | buf[4]) != 0)
1553 #endif
1554       {
1555          png_warning(png_ptr,
1556              "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1557 
1558          return;
1559       }
1560 
1561       png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
1562    }
1563 
1564    else
1565    {
1566       if (back->gray >= (1 << png_ptr->bit_depth))
1567       {
1568          png_warning(png_ptr,
1569              "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1570 
1571          return;
1572       }
1573 
1574       png_save_uint_16(buf, back->gray);
1575       png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
1576    }
1577 }
1578 #endif
1579 
1580 #ifdef PNG_WRITE_hIST_SUPPORTED
1581 /* Write the histogram */
1582 void /* PRIVATE */
1583 png_write_hIST(png_structrp png_ptr, png_const_uint_16p hist, int num_hist)
1584 {
1585    int i;
1586    png_byte buf[3];
1587 
1588    png_debug(1, "in png_write_hIST");
1589 
1590    if (num_hist > (int)png_ptr->num_palette)
1591    {
1592       png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1593           png_ptr->num_palette);
1594 
1595       png_warning(png_ptr, "Invalid number of histogram entries specified");
1596       return;
1597    }
1598 
1599    png_write_chunk_header(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
1600 
1601    for (i = 0; i < num_hist; i++)
1602    {
1603       png_save_uint_16(buf, hist[i]);
1604       png_write_chunk_data(png_ptr, buf, (png_size_t)2);
1605    }
1606 
1607    png_write_chunk_end(png_ptr);
1608 }
1609 #endif
1610 
1611 #ifdef PNG_WRITE_tEXt_SUPPORTED
1612 /* Write a tEXt chunk */
1613 void /* PRIVATE */
1614 png_write_tEXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,
1615     png_size_t text_len)
1616 {
1617    png_uint_32 key_len;
1618    png_byte new_key[80];
1619 
1620    png_debug(1, "in png_write_tEXt");
1621 
1622    key_len = png_check_keyword(png_ptr, key, new_key);
1623 
1624    if (key_len == 0)
1625       png_error(png_ptr, "tEXt: invalid keyword");
1626 
1627    if (text == NULL || *text == '\0')
1628       text_len = 0;
1629 
1630    else
1631       text_len = strlen(text);
1632 
1633    if (text_len > PNG_UINT_31_MAX - (key_len+1))
1634       png_error(png_ptr, "tEXt: text too long");
1635 
1636    /* Make sure we include the 0 after the key */
1637    png_write_chunk_header(png_ptr, png_tEXt,
1638        (png_uint_32)/*checked above*/(key_len + text_len + 1));
1639    /*
1640     * We leave it to the application to meet PNG-1.0 requirements on the
1641     * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
1642     * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
1643     * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1644     */
1645    png_write_chunk_data(png_ptr, new_key, key_len + 1);
1646 
1647    if (text_len != 0)
1648       png_write_chunk_data(png_ptr, (png_const_bytep)text, text_len);
1649 
1650    png_write_chunk_end(png_ptr);
1651 }
1652 #endif
1653 
1654 #ifdef PNG_WRITE_zTXt_SUPPORTED
1655 /* Write a compressed text chunk */
1656 void /* PRIVATE */
1657 png_write_zTXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,
1658     int compression)
1659 {
1660    png_uint_32 key_len;
1661    png_byte new_key[81];
1662    compression_state comp;
1663 
1664    png_debug(1, "in png_write_zTXt");
1665 
1666    if (compression == PNG_TEXT_COMPRESSION_NONE)
1667    {
1668       png_write_tEXt(png_ptr, key, text, 0);
1669       return;
1670    }
1671 
1672    if (compression != PNG_TEXT_COMPRESSION_zTXt)
1673       png_error(png_ptr, "zTXt: invalid compression type");
1674 
1675    key_len = png_check_keyword(png_ptr, key, new_key);
1676 
1677    if (key_len == 0)
1678       png_error(png_ptr, "zTXt: invalid keyword");
1679 
1680    /* Add the compression method and 1 for the keyword separator. */
1681    new_key[++key_len] = PNG_COMPRESSION_TYPE_BASE;
1682    ++key_len;
1683 
1684    /* Compute the compressed data; do it now for the length */
1685    png_text_compress_init(&comp, (png_const_bytep)text,
1686       text == NULL ? 0 : strlen(text));
1687 
1688    if (png_text_compress(png_ptr, png_zTXt, &comp, key_len) != Z_OK)
1689       png_error(png_ptr, png_ptr->zstream.msg);
1690 
1691    /* Write start of chunk */
1692    png_write_chunk_header(png_ptr, png_zTXt, key_len + comp.output_len);
1693 
1694    /* Write key */
1695    png_write_chunk_data(png_ptr, new_key, key_len);
1696 
1697    /* Write the compressed data */
1698    png_write_compressed_data_out(png_ptr, &comp);
1699 
1700    /* Close the chunk */
1701    png_write_chunk_end(png_ptr);
1702 }
1703 #endif
1704 
1705 #ifdef PNG_WRITE_iTXt_SUPPORTED
1706 /* Write an iTXt chunk */
1707 void /* PRIVATE */
1708 png_write_iTXt(png_structrp png_ptr, int compression, png_const_charp key,
1709     png_const_charp lang, png_const_charp lang_key, png_const_charp text)
1710 {
1711    png_uint_32 key_len, prefix_len;
1712    png_size_t lang_len, lang_key_len;
1713    png_byte new_key[82];
1714    compression_state comp;
1715 
1716    png_debug(1, "in png_write_iTXt");
1717 
1718    key_len = png_check_keyword(png_ptr, key, new_key);
1719 
1720    if (key_len == 0)
1721       png_error(png_ptr, "iTXt: invalid keyword");
1722 
1723    /* Set the compression flag */
1724    switch (compression)
1725    {
1726       case PNG_ITXT_COMPRESSION_NONE:
1727       case PNG_TEXT_COMPRESSION_NONE:
1728          compression = new_key[++key_len] = 0; /* no compression */
1729          break;
1730 
1731       case PNG_TEXT_COMPRESSION_zTXt:
1732       case PNG_ITXT_COMPRESSION_zTXt:
1733          compression = new_key[++key_len] = 1; /* compressed */
1734          break;
1735 
1736       default:
1737          png_error(png_ptr, "iTXt: invalid compression");
1738    }
1739 
1740    new_key[++key_len] = PNG_COMPRESSION_TYPE_BASE;
1741    ++key_len; /* for the keywod separator */
1742 
1743    /* We leave it to the application to meet PNG-1.0 requirements on the
1744     * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
1745     * any non-Latin-1 characters except for NEWLINE.  ISO PNG, however,
1746     * specifies that the text is UTF-8 and this really doesn't require any
1747     * checking.
1748     *
1749     * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1750     *
1751     * TODO: validate the language tag correctly (see the spec.)
1752     */
1753    if (lang == NULL) lang = ""; /* empty language is valid */
1754    lang_len = strlen(lang)+1;
1755    if (lang_key == NULL) lang_key = ""; /* may be empty */
1756    lang_key_len = strlen(lang_key)+1;
1757    if (text == NULL) text = ""; /* may be empty */
1758 
1759    prefix_len = key_len;
1760    if (lang_len > PNG_UINT_31_MAX-prefix_len)
1761       prefix_len = PNG_UINT_31_MAX;
1762    else
1763       prefix_len = (png_uint_32)(prefix_len + lang_len);
1764 
1765    if (lang_key_len > PNG_UINT_31_MAX-prefix_len)
1766       prefix_len = PNG_UINT_31_MAX;
1767    else
1768       prefix_len = (png_uint_32)(prefix_len + lang_key_len);
1769 
1770    png_text_compress_init(&comp, (png_const_bytep)text, strlen(text));
1771 
1772    if (compression != 0)
1773    {
1774       if (png_text_compress(png_ptr, png_iTXt, &comp, prefix_len) != Z_OK)
1775          png_error(png_ptr, png_ptr->zstream.msg);
1776    }
1777 
1778    else
1779    {
1780       if (comp.input_len > PNG_UINT_31_MAX-prefix_len)
1781          png_error(png_ptr, "iTXt: uncompressed text too long");
1782 
1783       /* So the string will fit in a chunk: */
1784       comp.output_len = (png_uint_32)/*SAFE*/comp.input_len;
1785    }
1786 
1787    png_write_chunk_header(png_ptr, png_iTXt, comp.output_len + prefix_len);
1788 
1789    png_write_chunk_data(png_ptr, new_key, key_len);
1790 
1791    png_write_chunk_data(png_ptr, (png_const_bytep)lang, lang_len);
1792 
1793    png_write_chunk_data(png_ptr, (png_const_bytep)lang_key, lang_key_len);
1794 
1795    if (compression != 0)
1796       png_write_compressed_data_out(png_ptr, &comp);
1797 
1798    else
1799       png_write_chunk_data(png_ptr, (png_const_bytep)text, comp.output_len);
1800 
1801    png_write_chunk_end(png_ptr);
1802 }
1803 #endif
1804 
1805 #ifdef PNG_WRITE_oFFs_SUPPORTED
1806 /* Write the oFFs chunk */
1807 void /* PRIVATE */
1808 png_write_oFFs(png_structrp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1809     int unit_type)
1810 {
1811    png_byte buf[9];
1812 
1813    png_debug(1, "in png_write_oFFs");
1814 
1815    if (unit_type >= PNG_OFFSET_LAST)
1816       png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
1817 
1818    png_save_int_32(buf, x_offset);
1819    png_save_int_32(buf + 4, y_offset);
1820    buf[8] = (png_byte)unit_type;
1821 
1822    png_write_complete_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
1823 }
1824 #endif
1825 #ifdef PNG_WRITE_pCAL_SUPPORTED
1826 /* Write the pCAL chunk (described in the PNG extensions document) */
1827 void /* PRIVATE */
1828 png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0,
1829     png_int_32 X1, int type, int nparams, png_const_charp units,
1830     png_charpp params)
1831 {
1832    png_uint_32 purpose_len;
1833    png_size_t units_len, total_len;
1834    png_size_tp params_len;
1835    png_byte buf[10];
1836    png_byte new_purpose[80];
1837    int i;
1838 
1839    png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1840 
1841    if (type >= PNG_EQUATION_LAST)
1842       png_error(png_ptr, "Unrecognized equation type for pCAL chunk");
1843 
1844    purpose_len = png_check_keyword(png_ptr, purpose, new_purpose);
1845 
1846    if (purpose_len == 0)
1847       png_error(png_ptr, "pCAL: invalid keyword");
1848 
1849    ++purpose_len; /* terminator */
1850 
1851    png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
1852    units_len = strlen(units) + (nparams == 0 ? 0 : 1);
1853    png_debug1(3, "pCAL units length = %d", (int)units_len);
1854    total_len = purpose_len + units_len + 10;
1855 
1856    params_len = (png_size_tp)png_malloc(png_ptr,
1857        (png_alloc_size_t)(nparams * (sizeof (png_size_t))));
1858 
1859    /* Find the length of each parameter, making sure we don't count the
1860     * null terminator for the last parameter.
1861     */
1862    for (i = 0; i < nparams; i++)
1863    {
1864       params_len[i] = strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1865       png_debug2(3, "pCAL parameter %d length = %lu", i,
1866           (unsigned long)params_len[i]);
1867       total_len += params_len[i];
1868    }
1869 
1870    png_debug1(3, "pCAL total length = %d", (int)total_len);
1871    png_write_chunk_header(png_ptr, png_pCAL, (png_uint_32)total_len);
1872    png_write_chunk_data(png_ptr, new_purpose, purpose_len);
1873    png_save_int_32(buf, X0);
1874    png_save_int_32(buf + 4, X1);
1875    buf[8] = (png_byte)type;
1876    buf[9] = (png_byte)nparams;
1877    png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1878    png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
1879 
1880    for (i = 0; i < nparams; i++)
1881    {
1882       png_write_chunk_data(png_ptr, (png_const_bytep)params[i], params_len[i]);
1883    }
1884 
1885    png_free(png_ptr, params_len);
1886    png_write_chunk_end(png_ptr);
1887 }
1888 #endif
1889 
1890 #ifdef PNG_WRITE_sCAL_SUPPORTED
1891 /* Write the sCAL chunk */
1892 void /* PRIVATE */
1893 png_write_sCAL_s(png_structrp png_ptr, int unit, png_const_charp width,
1894     png_const_charp height)
1895 {
1896    png_byte buf[64];
1897    png_size_t wlen, hlen, total_len;
1898 
1899    png_debug(1, "in png_write_sCAL_s");
1900 
1901    wlen = strlen(width);
1902    hlen = strlen(height);
1903    total_len = wlen + hlen + 2;
1904 
1905    if (total_len > 64)
1906    {
1907       png_warning(png_ptr, "Can't write sCAL (buffer too small)");
1908       return;
1909    }
1910 
1911    buf[0] = (png_byte)unit;
1912    memcpy(buf + 1, width, wlen + 1);      /* Append the '\0' here */
1913    memcpy(buf + wlen + 2, height, hlen);  /* Do NOT append the '\0' here */
1914 
1915    png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1916    png_write_complete_chunk(png_ptr, png_sCAL, buf, total_len);
1917 }
1918 #endif
1919 
1920 #ifdef PNG_WRITE_pHYs_SUPPORTED
1921 /* Write the pHYs chunk */
1922 void /* PRIVATE */
1923 png_write_pHYs(png_structrp png_ptr, png_uint_32 x_pixels_per_unit,
1924     png_uint_32 y_pixels_per_unit,
1925     int unit_type)
1926 {
1927    png_byte buf[9];
1928 
1929    png_debug(1, "in png_write_pHYs");
1930 
1931    if (unit_type >= PNG_RESOLUTION_LAST)
1932       png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
1933 
1934    png_save_uint_32(buf, x_pixels_per_unit);
1935    png_save_uint_32(buf + 4, y_pixels_per_unit);
1936    buf[8] = (png_byte)unit_type;
1937 
1938    png_write_complete_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
1939 }
1940 #endif
1941 
1942 #ifdef PNG_WRITE_tIME_SUPPORTED
1943 /* Write the tIME chunk.  Use either png_convert_from_struct_tm()
1944  * or png_convert_from_time_t(), or fill in the structure yourself.
1945  */
1946 void /* PRIVATE */
1947 png_write_tIME(png_structrp png_ptr, png_const_timep mod_time)
1948 {
1949    png_byte buf[7];
1950 
1951    png_debug(1, "in png_write_tIME");
1952 
1953    if (mod_time->month  > 12 || mod_time->month  < 1 ||
1954        mod_time->day    > 31 || mod_time->day    < 1 ||
1955        mod_time->hour   > 23 || mod_time->second > 60)
1956    {
1957       png_warning(png_ptr, "Invalid time specified for tIME chunk");
1958       return;
1959    }
1960 
1961    png_save_uint_16(buf, mod_time->year);
1962    buf[2] = mod_time->month;
1963    buf[3] = mod_time->day;
1964    buf[4] = mod_time->hour;
1965    buf[5] = mod_time->minute;
1966    buf[6] = mod_time->second;
1967 
1968    png_write_complete_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
1969 }
1970 #endif
1971 
1972 /* Initializes the row writing capability of libpng */
1973 void /* PRIVATE */
1974 png_write_start_row(png_structrp png_ptr)
1975 {
1976 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1977    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1978 
1979    /* Start of interlace block */
1980    static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1981 
1982    /* Offset to next interlace block */
1983    static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1984 
1985    /* Start of interlace block in the y direction */
1986    static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1987 
1988    /* Offset to next interlace block in the y direction */
1989    static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1990 #endif
1991 
1992    png_alloc_size_t buf_size;
1993    int usr_pixel_depth;
1994 
1995 #ifdef PNG_WRITE_FILTER_SUPPORTED
1996    png_byte filters;
1997 #endif
1998 
1999    png_debug(1, "in png_write_start_row");
2000 
2001    usr_pixel_depth = png_ptr->usr_channels * png_ptr->usr_bit_depth;
2002    buf_size = PNG_ROWBYTES(usr_pixel_depth, png_ptr->width) + 1;
2003 
2004    /* 1.5.6: added to allow checking in the row write code. */
2005    png_ptr->transformed_pixel_depth = png_ptr->pixel_depth;
2006    png_ptr->maximum_pixel_depth = (png_byte)usr_pixel_depth;
2007 
2008    /* Set up row buffer */
2009    png_ptr->row_buf = png_voidcast(png_bytep, png_malloc(png_ptr, buf_size));
2010 
2011    png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
2012 
2013 #ifdef PNG_WRITE_FILTER_SUPPORTED
2014    filters = png_ptr->do_filter;
2015 
2016    if (png_ptr->height == 1)
2017       filters &= 0xff & ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
2018 
2019    if (png_ptr->width == 1)
2020       filters &= 0xff & ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
2021 
2022    if (filters == 0)
2023       filters = PNG_FILTER_NONE;
2024 
2025    png_ptr->do_filter = filters;
2026 
2027    if (((filters & (PNG_FILTER_SUB | PNG_FILTER_UP | PNG_FILTER_AVG |
2028        PNG_FILTER_PAETH)) != 0) && png_ptr->try_row == NULL)
2029    {
2030       int num_filters = 0;
2031 
2032       png_ptr->try_row = png_voidcast(png_bytep, png_malloc(png_ptr, buf_size));
2033 
2034       if (filters & PNG_FILTER_SUB)
2035          num_filters++;
2036 
2037       if (filters & PNG_FILTER_UP)
2038          num_filters++;
2039 
2040       if (filters & PNG_FILTER_AVG)
2041          num_filters++;
2042 
2043       if (filters & PNG_FILTER_PAETH)
2044          num_filters++;
2045 
2046       if (num_filters > 1)
2047          png_ptr->tst_row = png_voidcast(png_bytep, png_malloc(png_ptr,
2048              buf_size));
2049    }
2050 
2051    /* We only need to keep the previous row if we are using one of the following
2052     * filters.
2053     */
2054    if ((filters & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) != 0)
2055       png_ptr->prev_row = png_voidcast(png_bytep,
2056          png_calloc(png_ptr, buf_size));
2057 #endif /* WRITE_FILTER */
2058 
2059 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
2060    /* If interlaced, we need to set up width and height of pass */
2061    if (png_ptr->interlaced != 0)
2062    {
2063       if ((png_ptr->transformations & PNG_INTERLACE) == 0)
2064       {
2065          png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
2066              png_pass_ystart[0]) / png_pass_yinc[0];
2067 
2068          png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
2069              png_pass_start[0]) / png_pass_inc[0];
2070       }
2071 
2072       else
2073       {
2074          png_ptr->num_rows = png_ptr->height;
2075          png_ptr->usr_width = png_ptr->width;
2076       }
2077    }
2078 
2079    else
2080 #endif
2081    {
2082       png_ptr->num_rows = png_ptr->height;
2083       png_ptr->usr_width = png_ptr->width;
2084    }
2085 }
2086 
2087 /* Internal use only.  Called when finished processing a row of data. */
2088 void /* PRIVATE */
2089 png_write_finish_row(png_structrp png_ptr)
2090 {
2091 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
2092    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
2093 
2094    /* Start of interlace block */
2095    static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
2096 
2097    /* Offset to next interlace block */
2098    static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
2099 
2100    /* Start of interlace block in the y direction */
2101    static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
2102 
2103    /* Offset to next interlace block in the y direction */
2104    static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
2105 #endif
2106 
2107    png_debug(1, "in png_write_finish_row");
2108 
2109    /* Next row */
2110    png_ptr->row_number++;
2111 
2112    /* See if we are done */
2113    if (png_ptr->row_number < png_ptr->num_rows)
2114       return;
2115 
2116 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
2117    /* If interlaced, go to next pass */
2118    if (png_ptr->interlaced != 0)
2119    {
2120       png_ptr->row_number = 0;
2121       if ((png_ptr->transformations & PNG_INTERLACE) != 0)
2122       {
2123          png_ptr->pass++;
2124       }
2125 
2126       else
2127       {
2128          /* Loop until we find a non-zero width or height pass */
2129          do
2130          {
2131             png_ptr->pass++;
2132 
2133             if (png_ptr->pass >= 7)
2134                break;
2135 
2136             png_ptr->usr_width = (png_ptr->width +
2137                 png_pass_inc[png_ptr->pass] - 1 -
2138                 png_pass_start[png_ptr->pass]) /
2139                 png_pass_inc[png_ptr->pass];
2140 
2141             png_ptr->num_rows = (png_ptr->height +
2142                 png_pass_yinc[png_ptr->pass] - 1 -
2143                 png_pass_ystart[png_ptr->pass]) /
2144                 png_pass_yinc[png_ptr->pass];
2145 
2146             if ((png_ptr->transformations & PNG_INTERLACE) != 0)
2147                break;
2148 
2149          } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
2150 
2151       }
2152 
2153       /* Reset the row above the image for the next pass */
2154       if (png_ptr->pass < 7)
2155       {
2156          if (png_ptr->prev_row != NULL)
2157             memset(png_ptr->prev_row, 0,
2158                 (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
2159                 png_ptr->usr_bit_depth, png_ptr->width)) + 1);
2160 
2161          return;
2162       }
2163    }
2164 #endif
2165 
2166    /* If we get here, we've just written the last row, so we need
2167       to flush the compressor */
2168    png_compress_IDAT(png_ptr, NULL, 0, Z_FINISH);
2169 }
2170 
2171 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
2172 /* Pick out the correct pixels for the interlace pass.
2173  * The basic idea here is to go through the row with a source
2174  * pointer and a destination pointer (sp and dp), and copy the
2175  * correct pixels for the pass.  As the row gets compacted,
2176  * sp will always be >= dp, so we should never overwrite anything.
2177  * See the default: case for the easiest code to understand.
2178  */
2179 void /* PRIVATE */
2180 png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
2181 {
2182    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
2183 
2184    /* Start of interlace block */
2185    static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
2186 
2187    /* Offset to next interlace block */
2188    static PNG_CONST png_byte  png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
2189 
2190    png_debug(1, "in png_do_write_interlace");
2191 
2192    /* We don't have to do anything on the last pass (6) */
2193    if (pass < 6)
2194    {
2195       /* Each pixel depth is handled separately */
2196       switch (row_info->pixel_depth)
2197       {
2198          case 1:
2199          {
2200             png_bytep sp;
2201             png_bytep dp;
2202             unsigned int shift;
2203             int d;
2204             int value;
2205             png_uint_32 i;
2206             png_uint_32 row_width = row_info->width;
2207 
2208             dp = row;
2209             d = 0;
2210             shift = 7;
2211 
2212             for (i = png_pass_start[pass]; i < row_width;
2213                i += png_pass_inc[pass])
2214             {
2215                sp = row + (png_size_t)(i >> 3);
2216                value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
2217                d |= (value << shift);
2218 
2219                if (shift == 0)
2220                {
2221                   shift = 7;
2222                   *dp++ = (png_byte)d;
2223                   d = 0;
2224                }
2225 
2226                else
2227                   shift--;
2228 
2229             }
2230             if (shift != 7)
2231                *dp = (png_byte)d;
2232 
2233             break;
2234          }
2235 
2236          case 2:
2237          {
2238             png_bytep sp;
2239             png_bytep dp;
2240             unsigned int shift;
2241             int d;
2242             int value;
2243             png_uint_32 i;
2244             png_uint_32 row_width = row_info->width;
2245 
2246             dp = row;
2247             shift = 6;
2248             d = 0;
2249 
2250             for (i = png_pass_start[pass]; i < row_width;
2251                i += png_pass_inc[pass])
2252             {
2253                sp = row + (png_size_t)(i >> 2);
2254                value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
2255                d |= (value << shift);
2256 
2257                if (shift == 0)
2258                {
2259                   shift = 6;
2260                   *dp++ = (png_byte)d;
2261                   d = 0;
2262                }
2263 
2264                else
2265                   shift -= 2;
2266             }
2267             if (shift != 6)
2268                *dp = (png_byte)d;
2269 
2270             break;
2271          }
2272 
2273          case 4:
2274          {
2275             png_bytep sp;
2276             png_bytep dp;
2277             unsigned int shift;
2278             int d;
2279             int value;
2280             png_uint_32 i;
2281             png_uint_32 row_width = row_info->width;
2282 
2283             dp = row;
2284             shift = 4;
2285             d = 0;
2286             for (i = png_pass_start[pass]; i < row_width;
2287                 i += png_pass_inc[pass])
2288             {
2289                sp = row + (png_size_t)(i >> 1);
2290                value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
2291                d |= (value << shift);
2292 
2293                if (shift == 0)
2294                {
2295                   shift = 4;
2296                   *dp++ = (png_byte)d;
2297                   d = 0;
2298                }
2299 
2300                else
2301                   shift -= 4;
2302             }
2303             if (shift != 4)
2304                *dp = (png_byte)d;
2305 
2306             break;
2307          }
2308 
2309          default:
2310          {
2311             png_bytep sp;
2312             png_bytep dp;
2313             png_uint_32 i;
2314             png_uint_32 row_width = row_info->width;
2315             png_size_t pixel_bytes;
2316 
2317             /* Start at the beginning */
2318             dp = row;
2319 
2320             /* Find out how many bytes each pixel takes up */
2321             pixel_bytes = (row_info->pixel_depth >> 3);
2322 
2323             /* Loop through the row, only looking at the pixels that matter */
2324             for (i = png_pass_start[pass]; i < row_width;
2325                i += png_pass_inc[pass])
2326             {
2327                /* Find out where the original pixel is */
2328                sp = row + (png_size_t)i * pixel_bytes;
2329 
2330                /* Move the pixel */
2331                if (dp != sp)
2332                   memcpy(dp, sp, pixel_bytes);
2333 
2334                /* Next pixel */
2335                dp += pixel_bytes;
2336             }
2337             break;
2338          }
2339       }
2340       /* Set new row width */
2341       row_info->width = (row_info->width +
2342           png_pass_inc[pass] - 1 -
2343           png_pass_start[pass]) /
2344           png_pass_inc[pass];
2345 
2346       row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
2347           row_info->width);
2348    }
2349 }
2350 #endif
2351 
2352 
2353 /* This filters the row, chooses which filter to use, if it has not already
2354  * been specified by the application, and then writes the row out with the
2355  * chosen filter.
2356  */
2357 static void /* PRIVATE */
2358 png_write_filtered_row(png_structrp png_ptr, png_bytep filtered_row,
2359    png_size_t row_bytes);
2360 
2361 #ifdef PNG_WRITE_FILTER_SUPPORTED
2362 static png_size_t /* PRIVATE */
2363 png_setup_sub_row(png_structrp png_ptr, const png_uint_32 bpp,
2364     const png_size_t row_bytes, const png_size_t lmins)
2365 {
2366    png_bytep rp, dp, lp;
2367    png_size_t i;
2368    png_size_t sum = 0;
2369    int v;
2370 
2371    png_ptr->try_row[0] = PNG_FILTER_VALUE_SUB;
2372 
2373    for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1; i < bpp;
2374         i++, rp++, dp++)
2375    {
2376       v = *dp = *rp;
2377       sum += (v < 128) ? v : 256 - v;
2378    }
2379 
2380    for (lp = png_ptr->row_buf + 1; i < row_bytes;
2381       i++, rp++, lp++, dp++)
2382    {
2383       v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2384       sum += (v < 128) ? v : 256 - v;
2385 
2386       if (sum > lmins)  /* We are already worse, don't continue. */
2387         break;
2388    }
2389 
2390    return (sum);
2391 }
2392 
2393 static png_size_t /* PRIVATE */
2394 png_setup_up_row(png_structrp png_ptr, const png_size_t row_bytes,
2395     const png_size_t lmins)
2396 {
2397    png_bytep rp, dp, pp;
2398    png_size_t i;
2399    png_size_t sum = 0;
2400    int v;
2401 
2402    png_ptr->try_row[0] = PNG_FILTER_VALUE_UP;
2403 
2404    for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
2405        pp = png_ptr->prev_row + 1; i < row_bytes;
2406        i++, rp++, pp++, dp++)
2407    {
2408       v = *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
2409       sum += (v < 128) ? v : 256 - v;
2410 
2411       if (sum > lmins)  /* We are already worse, don't continue. */
2412         break;
2413    }
2414 
2415    return (sum);
2416 }
2417 
2418 static png_size_t /* PRIVATE */
2419 png_setup_avg_row(png_structrp png_ptr, const png_uint_32 bpp,
2420       const png_size_t row_bytes, const png_size_t lmins)
2421 {
2422    png_bytep rp, dp, pp, lp;
2423    png_uint_32 i;
2424    png_size_t sum = 0;
2425    int v;
2426 
2427    png_ptr->try_row[0] = PNG_FILTER_VALUE_AVG;
2428 
2429    for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
2430         pp = png_ptr->prev_row + 1; i < bpp; i++)
2431    {
2432       v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2433 
2434       sum += (v < 128) ? v : 256 - v;
2435    }
2436 
2437    for (lp = png_ptr->row_buf + 1; i < row_bytes; i++)
2438    {
2439       v = *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
2440           & 0xff);
2441 
2442       sum += (v < 128) ? v : 256 - v;
2443 
2444       if (sum > lmins)  /* We are already worse, don't continue. */
2445         break;
2446    }
2447 
2448    return (sum);
2449 }
2450 
2451 static png_size_t /* PRIVATE */
2452 png_setup_paeth_row(png_structrp png_ptr, const png_uint_32 bpp,
2453     const png_size_t row_bytes, const png_size_t lmins)
2454 {
2455    png_bytep rp, dp, pp, cp, lp;
2456    png_size_t i;
2457    png_size_t sum = 0;
2458    int v;
2459 
2460    png_ptr->try_row[0] = PNG_FILTER_VALUE_PAETH;
2461 
2462    for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
2463        pp = png_ptr->prev_row + 1; i < bpp; i++)
2464    {
2465       v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2466 
2467       sum += (v < 128) ? v : 256 - v;
2468    }
2469 
2470    for (lp = png_ptr->row_buf + 1, cp = png_ptr->prev_row + 1; i < row_bytes;
2471         i++)
2472    {
2473       int a, b, c, pa, pb, pc, p;
2474 
2475       b = *pp++;
2476       c = *cp++;
2477       a = *lp++;
2478 
2479       p = b - c;
2480       pc = a - c;
2481 
2482 #ifdef PNG_USE_ABS
2483       pa = abs(p);
2484       pb = abs(pc);
2485       pc = abs(p + pc);
2486 #else
2487       pa = p < 0 ? -p : p;
2488       pb = pc < 0 ? -pc : pc;
2489       pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2490 #endif
2491 
2492       p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2493 
2494       v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2495 
2496       sum += (v < 128) ? v : 256 - v;
2497 
2498       if (sum > lmins)  /* We are already worse, don't continue. */
2499         break;
2500    }
2501 
2502    return (sum);
2503 }
2504 #endif /* WRITE_FILTER */
2505 
2506 void /* PRIVATE */
2507 png_write_find_filter(png_structrp png_ptr, png_row_infop row_info)
2508 {
2509 #ifndef PNG_WRITE_FILTER_SUPPORTED
2510    png_write_filtered_row(png_ptr, png_ptr->row_buf, row_info->rowbytes+1);
2511 #else
2512    png_byte filter_to_do = png_ptr->do_filter;
2513    png_bytep row_buf;
2514    png_bytep best_row;
2515    png_uint_32 bpp;
2516    png_size_t mins;
2517    png_size_t row_bytes = row_info->rowbytes;
2518 
2519    png_debug(1, "in png_write_find_filter");
2520 
2521    /* Find out how many bytes offset each pixel is */
2522    bpp = (row_info->pixel_depth + 7) >> 3;
2523 
2524    row_buf = png_ptr->row_buf;
2525    mins = PNG_SIZE_MAX - 256/* so we can detect potential overflow of the
2526                                running sum */;
2527 
2528    /* The prediction method we use is to find which method provides the
2529     * smallest value when summing the absolute values of the distances
2530     * from zero, using anything >= 128 as negative numbers.  This is known
2531     * as the "minimum sum of absolute differences" heuristic.  Other
2532     * heuristics are the "weighted minimum sum of absolute differences"
2533     * (experimental and can in theory improve compression), and the "zlib
2534     * predictive" method (not implemented yet), which does test compressions
2535     * of lines using different filter methods, and then chooses the
2536     * (series of) filter(s) that give minimum compressed data size (VERY
2537     * computationally expensive).
2538     *
2539     * GRR 980525:  consider also
2540     *
2541     *   (1) minimum sum of absolute differences from running average (i.e.,
2542     *       keep running sum of non-absolute differences & count of bytes)
2543     *       [track dispersion, too?  restart average if dispersion too large?]
2544     *
2545     *  (1b) minimum sum of absolute differences from sliding average, probably
2546     *       with window size <= deflate window (usually 32K)
2547     *
2548     *   (2) minimum sum of squared differences from zero or running average
2549     *       (i.e., ~ root-mean-square approach)
2550     */
2551 
2552 
2553    /* We don't need to test the 'no filter' case if this is the only filter
2554     * that has been chosen, as it doesn't actually do anything to the data.
2555     */
2556    best_row = png_ptr->row_buf;
2557 
2558 
2559    if ((filter_to_do & PNG_FILTER_NONE) != 0 && filter_to_do != PNG_FILTER_NONE)
2560    {
2561       png_bytep rp;
2562       png_size_t sum = 0;
2563       png_size_t i;
2564       int v;
2565 
2566       if (PNG_SIZE_MAX/128 <= row_bytes)
2567       {
2568          for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
2569          {
2570             /* Check for overflow */
2571             if (sum > PNG_SIZE_MAX/128 - 256)
2572                break;
2573 
2574             v = *rp;
2575             sum += (v < 128) ? v : 256 - v;
2576          }
2577       }
2578       else /* Overflow is not possible */
2579       {
2580          for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
2581          {
2582             v = *rp;
2583             sum += (v < 128) ? v : 256 - v;
2584          }
2585       }
2586 
2587       mins = sum;
2588    }
2589 
2590    /* Sub filter */
2591    if (filter_to_do == PNG_FILTER_SUB)
2592    /* It's the only filter so no testing is needed */
2593    {
2594       (void) png_setup_sub_row(png_ptr, bpp, row_bytes, mins);
2595       best_row = png_ptr->try_row;
2596    }
2597 
2598    else if ((filter_to_do & PNG_FILTER_SUB) != 0)
2599    {
2600       png_size_t sum;
2601       png_size_t lmins = mins;
2602 
2603       sum = png_setup_sub_row(png_ptr, bpp, row_bytes, lmins);
2604 
2605       if (sum < mins)
2606       {
2607          mins = sum;
2608          best_row = png_ptr->try_row;
2609          if (png_ptr->tst_row != NULL)
2610          {
2611             png_ptr->try_row = png_ptr->tst_row;
2612             png_ptr->tst_row = best_row;
2613          }
2614       }
2615    }
2616 
2617    /* Up filter */
2618    if (filter_to_do == PNG_FILTER_UP)
2619    {
2620       (void) png_setup_up_row(png_ptr, row_bytes, mins);
2621       best_row = png_ptr->try_row;
2622    }
2623 
2624    else if ((filter_to_do & PNG_FILTER_UP) != 0)
2625    {
2626       png_size_t sum;
2627       png_size_t lmins = mins;
2628 
2629       sum = png_setup_up_row(png_ptr, row_bytes, lmins);
2630 
2631       if (sum < mins)
2632       {
2633          mins = sum;
2634          best_row = png_ptr->try_row;
2635          if (png_ptr->tst_row != NULL)
2636          {
2637             png_ptr->try_row = png_ptr->tst_row;
2638             png_ptr->tst_row = best_row;
2639          }
2640       }
2641    }
2642 
2643    /* Avg filter */
2644    if (filter_to_do == PNG_FILTER_AVG)
2645    {
2646       (void) png_setup_avg_row(png_ptr, bpp, row_bytes, mins);
2647       best_row = png_ptr->try_row;
2648    }
2649 
2650    else if ((filter_to_do & PNG_FILTER_AVG) != 0)
2651    {
2652       png_size_t sum;
2653       png_size_t lmins = mins;
2654 
2655       sum= png_setup_avg_row(png_ptr, bpp, row_bytes, lmins);
2656 
2657       if (sum < mins)
2658       {
2659          mins = sum;
2660          best_row = png_ptr->try_row;
2661          if (png_ptr->tst_row != NULL)
2662          {
2663             png_ptr->try_row = png_ptr->tst_row;
2664             png_ptr->tst_row = best_row;
2665          }
2666       }
2667    }
2668 
2669    /* Paeth filter */
2670    if ((filter_to_do == PNG_FILTER_PAETH) != 0)
2671    {
2672       (void) png_setup_paeth_row(png_ptr, bpp, row_bytes, mins);
2673       best_row = png_ptr->try_row;
2674    }
2675 
2676    else if ((filter_to_do & PNG_FILTER_PAETH) != 0)
2677    {
2678       png_size_t sum;
2679       png_size_t lmins = mins;
2680 
2681       sum = png_setup_paeth_row(png_ptr, bpp, row_bytes, lmins);
2682 
2683       if (sum < mins)
2684       {
2685          best_row = png_ptr->try_row;
2686          if (png_ptr->tst_row != NULL)
2687          {
2688             png_ptr->try_row = png_ptr->tst_row;
2689             png_ptr->tst_row = best_row;
2690          }
2691       }
2692    }
2693 
2694    /* Do the actual writing of the filtered row data from the chosen filter. */
2695    png_write_filtered_row(png_ptr, best_row, row_info->rowbytes+1);
2696 
2697 #endif /* WRITE_FILTER */
2698 }
2699 
2700 
2701 /* Do the actual writing of a previously filtered row. */
2702 static void
2703 png_write_filtered_row(png_structrp png_ptr, png_bytep filtered_row,
2704    png_size_t full_row_length/*includes filter byte*/)
2705 {
2706    png_debug(1, "in png_write_filtered_row");
2707 
2708    png_debug1(2, "filter = %d", filtered_row[0]);
2709 
2710    png_compress_IDAT(png_ptr, filtered_row, full_row_length, Z_NO_FLUSH);
2711 
2712 #ifdef PNG_WRITE_FILTER_SUPPORTED
2713    /* Swap the current and previous rows */
2714    if (png_ptr->prev_row != NULL)
2715    {
2716       png_bytep tptr;
2717 
2718       tptr = png_ptr->prev_row;
2719       png_ptr->prev_row = png_ptr->row_buf;
2720       png_ptr->row_buf = tptr;
2721    }
2722 #endif /* WRITE_FILTER */
2723 
2724    /* Finish row - updates counters and flushes zlib if last row */
2725    png_write_finish_row(png_ptr);
2726 
2727 #ifdef PNG_WRITE_FLUSH_SUPPORTED
2728    png_ptr->flush_rows++;
2729 
2730    if (png_ptr->flush_dist > 0 &&
2731        png_ptr->flush_rows >= png_ptr->flush_dist)
2732    {
2733       png_write_flush(png_ptr);
2734    }
2735 #endif /* WRITE_FLUSH */
2736 }
2737 #endif /* WRITE */