2 /* pngrutil.c - utilities to read a PNG file
4 * Last changed in libpng 1.6.20 [December 3, 2014]
5 * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
13 * This file contains routines that are only called from within
14 * libpng itself during the course of reading an image.
22 #ifdef PNG_READ_SUPPORTED
25 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
27 png_uint_32 uval = png_get_uint_32(buf);
29 if (uval > PNG_UINT_31_MAX)
30 png_error(png_ptr, "PNG unsigned integer out of range");
35 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
36 /* The following is a variation on the above for use with the fixed
37 * point values used for gAMA and cHRM. Instead of png_error it
38 * issues a warning and returns (-1) - an invalid value because both
39 * gAMA and cHRM use *unsigned* integers for fixed point values.
41 #define PNG_FIXED_ERROR (-1)
43 static png_fixed_point /* PRIVATE */
44 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
46 png_uint_32 uval = png_get_uint_32(buf);
48 if (uval <= PNG_UINT_31_MAX)
49 return (png_fixed_point)uval; /* known to be in range */
51 /* The caller can turn off the warning by passing NULL. */
53 png_warning(png_ptr, "PNG fixed point integer out of range");
55 return PNG_FIXED_ERROR;
59 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
60 /* NOTE: the read macros will obscure these definitions, so that if
61 * PNG_USE_READ_MACROS is set the library will not use them internally,
62 * but the APIs will still be available externally.
64 * The parentheses around "PNGAPI function_name" in the following three
65 * functions are necessary because they allow the macros to co-exist with
66 * these (unused but exported) functions.
69 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
71 png_get_uint_32)(png_const_bytep buf)
74 ((png_uint_32)(*(buf )) << 24) +
75 ((png_uint_32)(*(buf + 1)) << 16) +
76 ((png_uint_32)(*(buf + 2)) << 8) +
77 ((png_uint_32)(*(buf + 3)) ) ;
82 /* Grab a signed 32-bit integer from a buffer in big-endian format. The
83 * data is stored in the PNG file in two's complement format and there
84 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
85 * the following code does a two's complement to native conversion.
88 png_get_int_32)(png_const_bytep buf)
90 png_uint_32 uval = png_get_uint_32(buf);
91 if ((uval & 0x80000000) == 0) /* non-negative */
94 uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */
95 if ((uval & 0x80000000) == 0) /* no overflow */
96 return -(png_int_32)uval;
97 /* The following has to be safe; this function only gets called on PNG data
98 * and if we get here that data is invalid. 0 is the most safe value and
99 * if not then an attacker would surely just generate a PNG with 0 instead.
104 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
106 png_get_uint_16)(png_const_bytep buf)
108 /* ANSI-C requires an int value to accomodate at least 16 bits so this
109 * works and allows the compiler not to worry about possible narrowing
110 * on 32-bit systems. (Pre-ANSI systems did not make integers smaller
111 * than 16 bits either.)
114 ((unsigned int)(*buf) << 8) +
115 ((unsigned int)(*(buf + 1)));
117 return (png_uint_16)val;
120 #endif /* READ_INT_FUNCTIONS */
122 /* Read and check the PNG file signature */
124 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
126 png_size_t num_checked, num_to_check;
128 /* Exit if the user application does not expect a signature. */
129 if (png_ptr->sig_bytes >= 8)
132 num_checked = png_ptr->sig_bytes;
133 num_to_check = 8 - num_checked;
135 #ifdef PNG_IO_STATE_SUPPORTED
136 png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
139 /* The signature must be serialized in a single I/O call. */
140 png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
141 png_ptr->sig_bytes = 8;
143 if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
145 if (num_checked < 4 &&
146 png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
147 png_error(png_ptr, "Not a PNG file");
149 png_error(png_ptr, "PNG file corrupted by ASCII conversion");
152 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
155 /* Read the chunk header (length + type name).
156 * Put the type name into png_ptr->chunk_name, and return the length.
158 png_uint_32 /* PRIVATE */
159 png_read_chunk_header(png_structrp png_ptr)
164 #ifdef PNG_IO_STATE_SUPPORTED
165 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
168 /* Read the length and the chunk name.
169 * This must be performed in a single I/O call.
171 png_read_data(png_ptr, buf, 8);
172 length = png_get_uint_31(png_ptr, buf);
174 /* Put the chunk name into png_ptr->chunk_name. */
175 png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
177 png_debug2(0, "Reading %lx chunk, length = %lu",
178 (unsigned long)png_ptr->chunk_name, (unsigned long)length);
180 /* Reset the crc and run it over the chunk name. */
181 png_reset_crc(png_ptr);
182 png_calculate_crc(png_ptr, buf + 4, 4);
184 /* Check to see if chunk name is valid. */
185 png_check_chunk_name(png_ptr, png_ptr->chunk_name);
187 #ifdef PNG_IO_STATE_SUPPORTED
188 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
194 /* Read data, and (optionally) run it through the CRC. */
196 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
201 png_read_data(png_ptr, buf, length);
202 png_calculate_crc(png_ptr, buf, length);
205 /* Optionally skip data and then check the CRC. Depending on whether we
206 * are reading an ancillary or critical chunk, and how the program has set
207 * things up, we may calculate the CRC on the data and print a message.
208 * Returns '1' if there was a CRC error, '0' otherwise.
211 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
213 /* The size of the local buffer for inflate is a good guess as to a
214 * reasonable size to use for buffering reads from the application.
219 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
221 len = (sizeof tmpbuf);
226 png_crc_read(png_ptr, tmpbuf, len);
229 if (png_crc_error(png_ptr) != 0)
231 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
232 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
233 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
235 png_chunk_warning(png_ptr, "CRC error");
239 png_chunk_error(png_ptr, "CRC error");
247 /* Compare the CRC stored in the PNG file with that calculated by libpng from
248 * the data it has read thus far.
251 png_crc_error(png_structrp png_ptr)
253 png_byte crc_bytes[4];
257 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
259 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
260 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
266 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
270 #ifdef PNG_IO_STATE_SUPPORTED
271 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
274 /* The chunk CRC must be serialized in a single I/O call. */
275 png_read_data(png_ptr, crc_bytes, 4);
279 crc = png_get_uint_32(crc_bytes);
280 return ((int)(crc != png_ptr->crc));
287 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
288 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
289 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
290 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
291 /* Manage the read buffer; this simply reallocates the buffer if it is not small
292 * enough (or if it is not allocated). The routine returns a pointer to the
293 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
294 * it will call png_error (via png_malloc) on failure. (warn == 2 means
298 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
300 png_bytep buffer = png_ptr->read_buffer;
302 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
304 png_ptr->read_buffer = NULL;
305 png_ptr->read_buffer = NULL;
306 png_ptr->read_buffer_size = 0;
307 png_free(png_ptr, buffer);
313 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
317 png_ptr->read_buffer = buffer;
318 png_ptr->read_buffer_size = new_size;
321 else if (warn < 2) /* else silent */
324 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
327 png_chunk_error(png_ptr, "insufficient memory to read chunk");
333 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
335 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
336 * decompression. Returns Z_OK on success, else a zlib error code. It checks
337 * the owner but, in final release builds, just issues a warning if some other
338 * chunk apparently owns the stream. Prior to release it does a png_error.
341 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
343 if (png_ptr->zowner != 0)
347 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
348 /* So the message that results is "<chunk> using zstream"; this is an
349 * internal error, but is very useful for debugging. i18n requirements
352 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
353 #if PNG_RELEASE_BUILD
354 png_chunk_warning(png_ptr, msg);
357 png_chunk_error(png_ptr, msg);
361 /* Implementation note: unlike 'png_deflate_claim' this internal function
362 * does not take the size of the data as an argument. Some efficiency could
363 * be gained by using this when it is known *if* the zlib stream itself does
364 * not record the number; however, this is an illusion: the original writer
365 * of the PNG may have selected a lower window size, and we really must
366 * follow that because, for systems with with limited capabilities, we
367 * would otherwise reject the application's attempts to use a smaller window
368 * size (zlib doesn't have an interface to say "this or lower"!).
370 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
371 * reset, therefore it is necessary to always allocate the maximum window
372 * size with earlier zlibs just in case later compressed chunks need it.
375 int ret; /* zlib return code */
376 #if PNG_ZLIB_VERNUM >= 0x1240
378 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
381 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
385 png_ptr->zstream_start = 0; /* fixed window size */
391 png_ptr->zstream_start = 1;
394 # define window_bits 0
398 /* Set this for safety, just in case the previous owner left pointers to
399 * memory allocations.
401 png_ptr->zstream.next_in = NULL;
402 png_ptr->zstream.avail_in = 0;
403 png_ptr->zstream.next_out = NULL;
404 png_ptr->zstream.avail_out = 0;
406 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
408 #if PNG_ZLIB_VERNUM < 0x1240
409 ret = inflateReset(&png_ptr->zstream);
411 ret = inflateReset2(&png_ptr->zstream, window_bits);
417 #if PNG_ZLIB_VERNUM < 0x1240
418 ret = inflateInit(&png_ptr->zstream);
420 ret = inflateInit2(&png_ptr->zstream, window_bits);
424 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
428 png_ptr->zowner = owner;
431 png_zstream_error(png_ptr, ret);
441 #if PNG_ZLIB_VERNUM >= 0x1240
442 /* Handle the start of the inflate stream if we called inflateInit2(strm,0);
443 * in this case some zlib versions skip validation of the CINFO field and, in
444 * certain circumstances, libpng may end up displaying an invalid image, in
445 * contrast to implementations that call zlib in the normal way (e.g. libpng
449 png_zlib_inflate(png_structrp png_ptr, int flush)
451 if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0)
453 if ((*png_ptr->zstream.next_in >> 4) > 7)
455 png_ptr->zstream.msg = "invalid window size (libpng)";
459 png_ptr->zstream_start = 0;
462 return inflate(&png_ptr->zstream, flush);
464 #endif /* Zlib >= 1.2.4 */
466 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
467 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
468 * allow the caller to do multiple calls if required. If the 'finish' flag is
469 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
470 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
471 * Z_OK or Z_STREAM_END will be returned on success.
473 * The input and output sizes are updated to the actual amounts of data consumed
474 * or written, not the amount available (as in a z_stream). The data pointers
475 * are not changed, so the next input is (data+input_size) and the next
476 * available output is (output+output_size).
479 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
480 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
481 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
483 if (png_ptr->zowner == owner) /* Else not claimed */
486 png_alloc_size_t avail_out = *output_size_ptr;
487 png_uint_32 avail_in = *input_size_ptr;
489 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
490 * can't even necessarily handle 65536 bytes) because the type uInt is
491 * "16 bits or more". Consequently it is necessary to chunk the input to
492 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
493 * maximum value that can be stored in a uInt.) It is possible to set
494 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
495 * a performance advantage, because it reduces the amount of data accessed
496 * at each step and that may give the OS more time to page it in.
498 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
499 /* avail_in and avail_out are set below from 'size' */
500 png_ptr->zstream.avail_in = 0;
501 png_ptr->zstream.avail_out = 0;
503 /* Read directly into the output if it is available (this is set to
504 * a local buffer below if output is NULL).
507 png_ptr->zstream.next_out = output;
512 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
514 /* zlib INPUT BUFFER */
515 /* The setting of 'avail_in' used to be outside the loop; by setting it
516 * inside it is possible to chunk the input to zlib and simply rely on
517 * zlib to advance the 'next_in' pointer. This allows arbitrary
518 * amounts of data to be passed through zlib at the unavoidable cost of
519 * requiring a window save (memcpy of up to 32768 output bytes)
520 * every ZLIB_IO_MAX input bytes.
522 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
526 if (avail_in < avail)
527 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
530 png_ptr->zstream.avail_in = avail;
532 /* zlib OUTPUT BUFFER */
533 avail_out += png_ptr->zstream.avail_out; /* not written last time */
535 avail = ZLIB_IO_MAX; /* maximum zlib can process */
539 /* Reset the output buffer each time round if output is NULL and
540 * make available the full buffer, up to 'remaining_space'
542 png_ptr->zstream.next_out = local_buffer;
543 if ((sizeof local_buffer) < avail)
544 avail = (sizeof local_buffer);
547 if (avail_out < avail)
548 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
550 png_ptr->zstream.avail_out = avail;
553 /* zlib inflate call */
554 /* In fact 'avail_out' may be 0 at this point, that happens at the end
555 * of the read when the final LZ end code was not passed at the end of
556 * the previous chunk of input data. Tell zlib if we have reached the
557 * end of the output buffer.
559 ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH :
560 (finish ? Z_FINISH : Z_SYNC_FLUSH));
561 } while (ret == Z_OK);
563 /* For safety kill the local buffer pointer now */
565 png_ptr->zstream.next_out = NULL;
567 /* Claw back the 'size' and 'remaining_space' byte counts. */
568 avail_in += png_ptr->zstream.avail_in;
569 avail_out += png_ptr->zstream.avail_out;
571 /* Update the input and output sizes; the updated values are the amount
572 * consumed or written, effectively the inverse of what zlib uses.
575 *output_size_ptr -= avail_out;
578 *input_size_ptr -= avail_in;
580 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
581 png_zstream_error(png_ptr, ret);
587 /* This is a bad internal error. The recovery assigns to the zstream msg
588 * pointer, which is not owned by the caller, but this is safe; it's only
591 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
592 return Z_STREAM_ERROR;
597 * Decompress trailing data in a chunk. The assumption is that read_buffer
598 * points at an allocated area holding the contents of a chunk with a
599 * trailing compressed part. What we get back is an allocated area
600 * holding the original prefix part and an uncompressed version of the
601 * trailing part (the malloc area passed in is freed).
604 png_decompress_chunk(png_structrp png_ptr,
605 png_uint_32 chunklength, png_uint_32 prefix_size,
606 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
607 int terminate /*add a '\0' to the end of the uncompressed data*/)
609 /* TODO: implement different limits for different types of chunk.
611 * The caller supplies *newlength set to the maximum length of the
612 * uncompressed data, but this routine allocates space for the prefix and
613 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
614 * limited only by the maximum chunk size.
616 png_alloc_size_t limit = PNG_SIZE_MAX;
618 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
619 if (png_ptr->user_chunk_malloc_max > 0 &&
620 png_ptr->user_chunk_malloc_max < limit)
621 limit = png_ptr->user_chunk_malloc_max;
622 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
623 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
624 limit = PNG_USER_CHUNK_MALLOC_MAX;
627 if (limit >= prefix_size + (terminate != 0))
631 limit -= prefix_size + (terminate != 0);
633 if (limit < *newlength)
636 /* Now try to claim the stream. */
637 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
641 png_uint_32 lzsize = chunklength - prefix_size;
643 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
644 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
645 /* output: */ NULL, newlength);
647 if (ret == Z_STREAM_END)
649 /* Use 'inflateReset' here, not 'inflateReset2' because this
650 * preserves the previously decided window size (otherwise it would
651 * be necessary to store the previous window size.) In practice
652 * this doesn't matter anyway, because png_inflate will call inflate
653 * with Z_FINISH in almost all cases, so the window will not be
656 if (inflateReset(&png_ptr->zstream) == Z_OK)
658 /* Because of the limit checks above we know that the new,
659 * expanded, size will fit in a size_t (let alone an
660 * png_alloc_size_t). Use png_malloc_base here to avoid an
663 png_alloc_size_t new_size = *newlength;
664 png_alloc_size_t buffer_size = prefix_size + new_size +
666 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
671 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
672 png_ptr->read_buffer + prefix_size, &lzsize,
673 text + prefix_size, newlength);
675 if (ret == Z_STREAM_END)
677 if (new_size == *newlength)
680 text[prefix_size + *newlength] = 0;
683 memcpy(text, png_ptr->read_buffer, prefix_size);
686 png_bytep old_ptr = png_ptr->read_buffer;
688 png_ptr->read_buffer = text;
689 png_ptr->read_buffer_size = buffer_size;
690 text = old_ptr; /* freed below */
696 /* The size changed on the second read, there can be no
697 * guarantee that anything is correct at this point.
698 * The 'msg' pointer has been set to "unexpected end of
699 * LZ stream", which is fine, but return an error code
700 * that the caller won't accept.
702 ret = PNG_UNEXPECTED_ZLIB_RETURN;
706 else if (ret == Z_OK)
707 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
709 /* Free the text pointer (this is the old read_buffer on
712 png_free(png_ptr, text);
714 /* This really is very benign, but it's still an error because
715 * the extra space may otherwise be used as a Trojan Horse.
717 if (ret == Z_STREAM_END &&
718 chunklength - prefix_size != lzsize)
719 png_chunk_benign_error(png_ptr, "extra compressed data");
724 /* Out of memory allocating the buffer */
726 png_zstream_error(png_ptr, Z_MEM_ERROR);
732 /* inflateReset failed, store the error message */
733 png_zstream_error(png_ptr, ret);
735 if (ret == Z_STREAM_END)
736 ret = PNG_UNEXPECTED_ZLIB_RETURN;
740 else if (ret == Z_OK)
741 ret = PNG_UNEXPECTED_ZLIB_RETURN;
743 /* Release the claimed stream */
747 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
748 ret = PNG_UNEXPECTED_ZLIB_RETURN;
755 /* Application/configuration limits exceeded */
756 png_zstream_error(png_ptr, Z_MEM_ERROR);
760 #endif /* READ_COMPRESSED_TEXT */
762 #ifdef PNG_READ_iCCP_SUPPORTED
763 /* Perform a partial read and decompress, producing 'avail_out' bytes and
764 * reading from the current chunk as required.
767 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
768 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
771 if (png_ptr->zowner == png_ptr->chunk_name)
775 /* next_in and avail_in must have been initialized by the caller. */
776 png_ptr->zstream.next_out = next_out;
777 png_ptr->zstream.avail_out = 0; /* set in the loop */
781 if (png_ptr->zstream.avail_in == 0)
783 if (read_size > *chunk_bytes)
784 read_size = (uInt)*chunk_bytes;
785 *chunk_bytes -= read_size;
788 png_crc_read(png_ptr, read_buffer, read_size);
790 png_ptr->zstream.next_in = read_buffer;
791 png_ptr->zstream.avail_in = read_size;
794 if (png_ptr->zstream.avail_out == 0)
796 uInt avail = ZLIB_IO_MAX;
797 if (avail > *out_size)
798 avail = (uInt)*out_size;
801 png_ptr->zstream.avail_out = avail;
804 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
805 * the available output is produced; this allows reading of truncated
808 ret = PNG_INFLATE(png_ptr,
809 *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
811 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
813 *out_size += png_ptr->zstream.avail_out;
814 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
816 /* Ensure the error message pointer is always set: */
817 png_zstream_error(png_ptr, ret);
823 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
824 return Z_STREAM_ERROR;
829 /* Read and check the IDHR chunk */
832 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
835 png_uint_32 width, height;
836 int bit_depth, color_type, compression_type, filter_type;
839 png_debug(1, "in png_handle_IHDR");
841 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
842 png_chunk_error(png_ptr, "out of place");
844 /* Check the length */
846 png_chunk_error(png_ptr, "invalid");
848 png_ptr->mode |= PNG_HAVE_IHDR;
850 png_crc_read(png_ptr, buf, 13);
851 png_crc_finish(png_ptr, 0);
853 width = png_get_uint_31(png_ptr, buf);
854 height = png_get_uint_31(png_ptr, buf + 4);
857 compression_type = buf[10];
858 filter_type = buf[11];
859 interlace_type = buf[12];
861 /* Set internal variables */
862 png_ptr->width = width;
863 png_ptr->height = height;
864 png_ptr->bit_depth = (png_byte)bit_depth;
865 png_ptr->interlaced = (png_byte)interlace_type;
866 png_ptr->color_type = (png_byte)color_type;
867 #ifdef PNG_MNG_FEATURES_SUPPORTED
868 png_ptr->filter_type = (png_byte)filter_type;
870 png_ptr->compression_type = (png_byte)compression_type;
872 /* Find number of channels */
873 switch (png_ptr->color_type)
875 default: /* invalid, png_set_IHDR calls png_error */
876 case PNG_COLOR_TYPE_GRAY:
877 case PNG_COLOR_TYPE_PALETTE:
878 png_ptr->channels = 1;
881 case PNG_COLOR_TYPE_RGB:
882 png_ptr->channels = 3;
885 case PNG_COLOR_TYPE_GRAY_ALPHA:
886 png_ptr->channels = 2;
889 case PNG_COLOR_TYPE_RGB_ALPHA:
890 png_ptr->channels = 4;
894 /* Set up other useful info */
895 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
896 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
897 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
898 png_debug1(3, "channels = %d", png_ptr->channels);
899 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
900 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
901 color_type, interlace_type, compression_type, filter_type);
904 /* Read and check the palette */
906 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
908 png_color palette[PNG_MAX_PALETTE_LENGTH];
909 int max_palette_length, num, i;
910 #ifdef PNG_POINTER_INDEXING_SUPPORTED
914 png_debug(1, "in png_handle_PLTE");
916 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
917 png_chunk_error(png_ptr, "missing IHDR");
919 /* Moved to before the 'after IDAT' check below because otherwise duplicate
920 * PLTE chunks are potentially ignored (the spec says there shall not be more
921 * than one PLTE, the error is not treated as benign, so this check trumps
922 * the requirement that PLTE appears before IDAT.)
924 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
925 png_chunk_error(png_ptr, "duplicate");
927 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
929 /* This is benign because the non-benign error happened before, when an
930 * IDAT was encountered in a color-mapped image with no PLTE.
932 png_crc_finish(png_ptr, length);
933 png_chunk_benign_error(png_ptr, "out of place");
937 png_ptr->mode |= PNG_HAVE_PLTE;
939 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
941 png_crc_finish(png_ptr, length);
942 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
946 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
947 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
949 png_crc_finish(png_ptr, length);
954 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
956 png_crc_finish(png_ptr, length);
958 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
959 png_chunk_benign_error(png_ptr, "invalid");
962 png_chunk_error(png_ptr, "invalid");
967 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
968 num = (int)length / 3;
970 /* If the palette has 256 or fewer entries but is too large for the bit
971 * depth, we don't issue an error, to preserve the behavior of previous
972 * libpng versions. We silently truncate the unused extra palette entries
975 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
976 max_palette_length = (1 << png_ptr->bit_depth);
978 max_palette_length = PNG_MAX_PALETTE_LENGTH;
980 if (num > max_palette_length)
981 num = max_palette_length;
983 #ifdef PNG_POINTER_INDEXING_SUPPORTED
984 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
988 png_crc_read(png_ptr, buf, 3);
989 pal_ptr->red = buf[0];
990 pal_ptr->green = buf[1];
991 pal_ptr->blue = buf[2];
994 for (i = 0; i < num; i++)
998 png_crc_read(png_ptr, buf, 3);
999 /* Don't depend upon png_color being any order */
1000 palette[i].red = buf[0];
1001 palette[i].green = buf[1];
1002 palette[i].blue = buf[2];
1006 /* If we actually need the PLTE chunk (ie for a paletted image), we do
1007 * whatever the normal CRC configuration tells us. However, if we
1008 * have an RGB image, the PLTE can be considered ancillary, so
1009 * we will act as though it is.
1011 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1012 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1015 png_crc_finish(png_ptr, (int) length - num * 3);
1018 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1019 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
1021 /* If we don't want to use the data from an ancillary chunk,
1022 * we have two options: an error abort, or a warning and we
1023 * ignore the data in this chunk (which should be OK, since
1024 * it's considered ancillary for a RGB or RGBA image).
1026 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
1027 * chunk type to determine whether to check the ancillary or the critical
1030 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
1032 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
1036 png_chunk_error(png_ptr, "CRC error");
1039 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1040 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1041 png_chunk_warning(png_ptr, "CRC error");
1045 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1046 * own copy of the palette. This has the side effect that when png_start_row
1047 * is called (this happens after any call to png_read_update_info) the
1048 * info_ptr palette gets changed. This is extremely unexpected and
1051 * Fix this by not sharing the palette in this way.
1053 png_set_PLTE(png_ptr, info_ptr, palette, num);
1055 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1056 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1057 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1058 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1059 * therefore does a benign error if the erroneous condition is detected *and*
1060 * cancels the tRNS if the benign error returns. The alternative is to
1061 * amend the standard since it would be rather hypocritical of the standards
1062 * maintainers to ignore it.
1064 #ifdef PNG_READ_tRNS_SUPPORTED
1065 if (png_ptr->num_trans > 0 ||
1066 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1068 /* Cancel this because otherwise it would be used if the transforms
1069 * require it. Don't cancel the 'valid' flag because this would prevent
1070 * detection of duplicate chunks.
1072 png_ptr->num_trans = 0;
1074 if (info_ptr != NULL)
1075 info_ptr->num_trans = 0;
1077 png_chunk_benign_error(png_ptr, "tRNS must be after");
1081 #ifdef PNG_READ_hIST_SUPPORTED
1082 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1083 png_chunk_benign_error(png_ptr, "hIST must be after");
1086 #ifdef PNG_READ_bKGD_SUPPORTED
1087 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1088 png_chunk_benign_error(png_ptr, "bKGD must be after");
1093 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1095 png_debug(1, "in png_handle_IEND");
1097 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1098 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1099 png_chunk_error(png_ptr, "out of place");
1101 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1103 png_crc_finish(png_ptr, length);
1106 png_chunk_benign_error(png_ptr, "invalid");
1108 PNG_UNUSED(info_ptr)
1111 #ifdef PNG_READ_gAMA_SUPPORTED
1113 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1115 png_fixed_point igamma;
1118 png_debug(1, "in png_handle_gAMA");
1120 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1121 png_chunk_error(png_ptr, "missing IHDR");
1123 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1125 png_crc_finish(png_ptr, length);
1126 png_chunk_benign_error(png_ptr, "out of place");
1132 png_crc_finish(png_ptr, length);
1133 png_chunk_benign_error(png_ptr, "invalid");
1137 png_crc_read(png_ptr, buf, 4);
1139 if (png_crc_finish(png_ptr, 0) != 0)
1142 igamma = png_get_fixed_point(NULL, buf);
1144 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1145 png_colorspace_sync(png_ptr, info_ptr);
1149 #ifdef PNG_READ_sBIT_SUPPORTED
1151 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1153 unsigned int truelen, i;
1154 png_byte sample_depth;
1157 png_debug(1, "in png_handle_sBIT");
1159 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1160 png_chunk_error(png_ptr, "missing IHDR");
1162 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1164 png_crc_finish(png_ptr, length);
1165 png_chunk_benign_error(png_ptr, "out of place");
1169 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1171 png_crc_finish(png_ptr, length);
1172 png_chunk_benign_error(png_ptr, "duplicate");
1176 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1184 truelen = png_ptr->channels;
1185 sample_depth = png_ptr->bit_depth;
1188 if (length != truelen || length > 4)
1190 png_chunk_benign_error(png_ptr, "invalid");
1191 png_crc_finish(png_ptr, length);
1195 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1196 png_crc_read(png_ptr, buf, truelen);
1198 if (png_crc_finish(png_ptr, 0) != 0)
1201 for (i=0; i<truelen; ++i)
1203 if (buf[i] == 0 || buf[i] > sample_depth)
1205 png_chunk_benign_error(png_ptr, "invalid");
1210 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1212 png_ptr->sig_bit.red = buf[0];
1213 png_ptr->sig_bit.green = buf[1];
1214 png_ptr->sig_bit.blue = buf[2];
1215 png_ptr->sig_bit.alpha = buf[3];
1220 png_ptr->sig_bit.gray = buf[0];
1221 png_ptr->sig_bit.red = buf[0];
1222 png_ptr->sig_bit.green = buf[0];
1223 png_ptr->sig_bit.blue = buf[0];
1224 png_ptr->sig_bit.alpha = buf[1];
1227 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1231 #ifdef PNG_READ_cHRM_SUPPORTED
1233 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1238 png_debug(1, "in png_handle_cHRM");
1240 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1241 png_chunk_error(png_ptr, "missing IHDR");
1243 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1245 png_crc_finish(png_ptr, length);
1246 png_chunk_benign_error(png_ptr, "out of place");
1252 png_crc_finish(png_ptr, length);
1253 png_chunk_benign_error(png_ptr, "invalid");
1257 png_crc_read(png_ptr, buf, 32);
1259 if (png_crc_finish(png_ptr, 0) != 0)
1262 xy.whitex = png_get_fixed_point(NULL, buf);
1263 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1264 xy.redx = png_get_fixed_point(NULL, buf + 8);
1265 xy.redy = png_get_fixed_point(NULL, buf + 12);
1266 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1267 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1268 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1269 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1271 if (xy.whitex == PNG_FIXED_ERROR ||
1272 xy.whitey == PNG_FIXED_ERROR ||
1273 xy.redx == PNG_FIXED_ERROR ||
1274 xy.redy == PNG_FIXED_ERROR ||
1275 xy.greenx == PNG_FIXED_ERROR ||
1276 xy.greeny == PNG_FIXED_ERROR ||
1277 xy.bluex == PNG_FIXED_ERROR ||
1278 xy.bluey == PNG_FIXED_ERROR)
1280 png_chunk_benign_error(png_ptr, "invalid values");
1284 /* If a colorspace error has already been output skip this chunk */
1285 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1288 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1290 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1291 png_colorspace_sync(png_ptr, info_ptr);
1292 png_chunk_benign_error(png_ptr, "duplicate");
1296 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1297 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1298 1/*prefer cHRM values*/);
1299 png_colorspace_sync(png_ptr, info_ptr);
1303 #ifdef PNG_READ_sRGB_SUPPORTED
1305 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1309 png_debug(1, "in png_handle_sRGB");
1311 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1312 png_chunk_error(png_ptr, "missing IHDR");
1314 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1316 png_crc_finish(png_ptr, length);
1317 png_chunk_benign_error(png_ptr, "out of place");
1323 png_crc_finish(png_ptr, length);
1324 png_chunk_benign_error(png_ptr, "invalid");
1328 png_crc_read(png_ptr, &intent, 1);
1330 if (png_crc_finish(png_ptr, 0) != 0)
1333 /* If a colorspace error has already been output skip this chunk */
1334 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1337 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1340 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1342 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1343 png_colorspace_sync(png_ptr, info_ptr);
1344 png_chunk_benign_error(png_ptr, "too many profiles");
1348 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1349 png_colorspace_sync(png_ptr, info_ptr);
1351 #endif /* READ_sRGB */
1353 #ifdef PNG_READ_iCCP_SUPPORTED
1355 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1356 /* Note: this does not properly handle profiles that are > 64K under DOS */
1358 png_const_charp errmsg = NULL; /* error message output, or no error */
1359 int finished = 0; /* crc checked */
1361 png_debug(1, "in png_handle_iCCP");
1363 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1364 png_chunk_error(png_ptr, "missing IHDR");
1366 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1368 png_crc_finish(png_ptr, length);
1369 png_chunk_benign_error(png_ptr, "out of place");
1373 /* Consistent with all the above colorspace handling an obviously *invalid*
1374 * chunk is just ignored, so does not invalidate the color space. An
1375 * alternative is to set the 'invalid' flags at the start of this routine
1376 * and only clear them in they were not set before and all the tests pass.
1377 * The minimum 'deflate' stream is assumed to be just the 2 byte header and
1378 * 4 byte checksum. The keyword must be at least one character and there is
1379 * a terminator (0) byte and the compression method.
1383 png_crc_finish(png_ptr, length);
1384 png_chunk_benign_error(png_ptr, "too short");
1388 /* If a colorspace error has already been output skip this chunk */
1389 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1391 png_crc_finish(png_ptr, length);
1395 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1398 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1400 uInt read_length, keyword_length;
1403 /* Find the keyword; the keyword plus separator and compression method
1404 * bytes can be at most 81 characters long.
1406 read_length = 81; /* maximum */
1407 if (read_length > length)
1408 read_length = (uInt)length;
1410 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1411 length -= read_length;
1414 while (keyword_length < 80 && keyword_length < read_length &&
1415 keyword[keyword_length] != 0)
1418 /* TODO: make the keyword checking common */
1419 if (keyword_length >= 1 && keyword_length <= 79)
1421 /* We only understand '0' compression - deflate - so if we get a
1422 * different value we can't safely decode the chunk.
1424 if (keyword_length+1 < read_length &&
1425 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1427 read_length -= keyword_length+2;
1429 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1431 Byte profile_header[132];
1432 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1433 png_alloc_size_t size = (sizeof profile_header);
1435 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1436 png_ptr->zstream.avail_in = read_length;
1437 (void)png_inflate_read(png_ptr, local_buffer,
1438 (sizeof local_buffer), &length, profile_header, &size,
1439 0/*finish: don't, because the output is too small*/);
1443 /* We have the ICC profile header; do the basic header checks.
1445 const png_uint_32 profile_length =
1446 png_get_uint_32(profile_header);
1448 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1449 keyword, profile_length) != 0)
1451 /* The length is apparently ok, so we can check the 132
1454 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1455 keyword, profile_length, profile_header,
1456 png_ptr->color_type) != 0)
1458 /* Now read the tag table; a variable size buffer is
1459 * needed at this point, allocate one for the whole
1460 * profile. The header check has already validated
1461 * that none of these stuff will overflow.
1463 const png_uint_32 tag_count = png_get_uint_32(
1464 profile_header+128);
1465 png_bytep profile = png_read_buffer(png_ptr,
1466 profile_length, 2/*silent*/);
1468 if (profile != NULL)
1470 memcpy(profile, profile_header,
1471 (sizeof profile_header));
1473 size = 12 * tag_count;
1475 (void)png_inflate_read(png_ptr, local_buffer,
1476 (sizeof local_buffer), &length,
1477 profile + (sizeof profile_header), &size, 0);
1479 /* Still expect a buffer error because we expect
1480 * there to be some tag data!
1484 if (png_icc_check_tag_table(png_ptr,
1485 &png_ptr->colorspace, keyword, profile_length,
1488 /* The profile has been validated for basic
1489 * security issues, so read the whole thing in.
1491 size = profile_length - (sizeof profile_header)
1494 (void)png_inflate_read(png_ptr, local_buffer,
1495 (sizeof local_buffer), &length,
1496 profile + (sizeof profile_header) +
1497 12 * tag_count, &size, 1/*finish*/);
1499 if (length > 0 && !(png_ptr->flags &
1500 PNG_FLAG_BENIGN_ERRORS_WARN))
1501 errmsg = "extra compressed data";
1503 /* But otherwise allow extra data: */
1508 /* This can be handled completely, so
1511 png_chunk_warning(png_ptr,
1512 "extra compressed data");
1515 png_crc_finish(png_ptr, length);
1518 # ifdef PNG_sRGB_SUPPORTED
1519 /* Check for a match against sRGB */
1520 png_icc_set_sRGB(png_ptr,
1521 &png_ptr->colorspace, profile,
1522 png_ptr->zstream.adler);
1525 /* Steal the profile for info_ptr. */
1526 if (info_ptr != NULL)
1528 png_free_data(png_ptr, info_ptr,
1531 info_ptr->iccp_name = png_voidcast(char*,
1532 png_malloc_base(png_ptr,
1534 if (info_ptr->iccp_name != NULL)
1536 memcpy(info_ptr->iccp_name, keyword,
1538 info_ptr->iccp_proflen =
1540 info_ptr->iccp_profile = profile;
1541 png_ptr->read_buffer = NULL; /*steal*/
1542 info_ptr->free_me |= PNG_FREE_ICCP;
1543 info_ptr->valid |= PNG_INFO_iCCP;
1548 png_ptr->colorspace.flags |=
1549 PNG_COLORSPACE_INVALID;
1550 errmsg = "out of memory";
1554 /* else the profile remains in the read
1555 * buffer which gets reused for subsequent
1559 if (info_ptr != NULL)
1560 png_colorspace_sync(png_ptr, info_ptr);
1564 png_ptr->zowner = 0;
1570 errmsg = "truncated";
1572 #ifndef __COVERITY__
1574 errmsg = png_ptr->zstream.msg;
1578 /* else png_icc_check_tag_table output an error */
1581 else /* profile truncated */
1582 errmsg = png_ptr->zstream.msg;
1586 errmsg = "out of memory";
1589 /* else png_icc_check_header output an error */
1592 /* else png_icc_check_length output an error */
1595 else /* profile truncated */
1596 errmsg = png_ptr->zstream.msg;
1598 /* Release the stream */
1599 png_ptr->zowner = 0;
1602 else /* png_inflate_claim failed */
1603 errmsg = png_ptr->zstream.msg;
1607 errmsg = "bad compression method"; /* or missing */
1611 errmsg = "bad keyword";
1615 errmsg = "too many profiles";
1617 /* Failure: the reason is in 'errmsg' */
1619 png_crc_finish(png_ptr, length);
1621 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1622 png_colorspace_sync(png_ptr, info_ptr);
1623 if (errmsg != NULL) /* else already output */
1624 png_chunk_benign_error(png_ptr, errmsg);
1626 #endif /* READ_iCCP */
1628 #ifdef PNG_READ_sPLT_SUPPORTED
1630 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1631 /* Note: this does not properly handle chunks that are > 64K under DOS */
1633 png_bytep entry_start, buffer;
1634 png_sPLT_t new_palette;
1636 png_uint_32 data_length;
1638 png_uint_32 skip = 0;
1642 png_debug(1, "in png_handle_sPLT");
1644 #ifdef PNG_USER_LIMITS_SUPPORTED
1645 if (png_ptr->user_chunk_cache_max != 0)
1647 if (png_ptr->user_chunk_cache_max == 1)
1649 png_crc_finish(png_ptr, length);
1653 if (--png_ptr->user_chunk_cache_max == 1)
1655 png_warning(png_ptr, "No space in chunk cache for sPLT");
1656 png_crc_finish(png_ptr, length);
1662 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1663 png_chunk_error(png_ptr, "missing IHDR");
1665 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1667 png_crc_finish(png_ptr, length);
1668 png_chunk_benign_error(png_ptr, "out of place");
1672 #ifdef PNG_MAX_MALLOC_64K
1673 if (length > 65535U)
1675 png_crc_finish(png_ptr, length);
1676 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1681 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1684 png_crc_finish(png_ptr, length);
1685 png_chunk_benign_error(png_ptr, "out of memory");
1690 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1691 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1692 * potential breakage point if the types in pngconf.h aren't exactly right.
1694 png_crc_read(png_ptr, buffer, length);
1696 if (png_crc_finish(png_ptr, skip) != 0)
1701 for (entry_start = buffer; *entry_start; entry_start++)
1702 /* Empty loop to find end of name */ ;
1706 /* A sample depth should follow the separator, and we should be on it */
1707 if (length < 2U || entry_start > buffer + (length - 2U))
1709 png_warning(png_ptr, "malformed sPLT chunk");
1713 new_palette.depth = *entry_start++;
1714 entry_size = (new_palette.depth == 8 ? 6 : 10);
1715 /* This must fit in a png_uint_32 because it is derived from the original
1716 * chunk data length.
1718 data_length = length - (png_uint_32)(entry_start - buffer);
1720 /* Integrity-check the data length */
1721 if ((data_length % entry_size) != 0)
1723 png_warning(png_ptr, "sPLT chunk has bad length");
1727 dl = (png_int_32)(data_length / entry_size);
1728 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1732 png_warning(png_ptr, "sPLT chunk too long");
1736 new_palette.nentries = (png_int_32)(data_length / entry_size);
1738 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
1739 png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
1741 if (new_palette.entries == NULL)
1743 png_warning(png_ptr, "sPLT chunk requires too much memory");
1747 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1748 for (i = 0; i < new_palette.nentries; i++)
1750 pp = new_palette.entries + i;
1752 if (new_palette.depth == 8)
1754 pp->red = *entry_start++;
1755 pp->green = *entry_start++;
1756 pp->blue = *entry_start++;
1757 pp->alpha = *entry_start++;
1762 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1763 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1764 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1765 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1768 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1771 pp = new_palette.entries;
1773 for (i = 0; i < new_palette.nentries; i++)
1776 if (new_palette.depth == 8)
1778 pp[i].red = *entry_start++;
1779 pp[i].green = *entry_start++;
1780 pp[i].blue = *entry_start++;
1781 pp[i].alpha = *entry_start++;
1786 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1787 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1788 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1789 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1792 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1796 /* Discard all chunk data except the name and stash that */
1797 new_palette.name = (png_charp)buffer;
1799 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1801 png_free(png_ptr, new_palette.entries);
1803 #endif /* READ_sPLT */
1805 #ifdef PNG_READ_tRNS_SUPPORTED
1807 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1809 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1811 png_debug(1, "in png_handle_tRNS");
1813 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1814 png_chunk_error(png_ptr, "missing IHDR");
1816 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1818 png_crc_finish(png_ptr, length);
1819 png_chunk_benign_error(png_ptr, "out of place");
1823 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1825 png_crc_finish(png_ptr, length);
1826 png_chunk_benign_error(png_ptr, "duplicate");
1830 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1836 png_crc_finish(png_ptr, length);
1837 png_chunk_benign_error(png_ptr, "invalid");
1841 png_crc_read(png_ptr, buf, 2);
1842 png_ptr->num_trans = 1;
1843 png_ptr->trans_color.gray = png_get_uint_16(buf);
1846 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1852 png_crc_finish(png_ptr, length);
1853 png_chunk_benign_error(png_ptr, "invalid");
1857 png_crc_read(png_ptr, buf, length);
1858 png_ptr->num_trans = 1;
1859 png_ptr->trans_color.red = png_get_uint_16(buf);
1860 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1861 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1864 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1866 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1868 /* TODO: is this actually an error in the ISO spec? */
1869 png_crc_finish(png_ptr, length);
1870 png_chunk_benign_error(png_ptr, "out of place");
1874 if (length > (unsigned int) png_ptr->num_palette ||
1875 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1878 png_crc_finish(png_ptr, length);
1879 png_chunk_benign_error(png_ptr, "invalid");
1883 png_crc_read(png_ptr, readbuf, length);
1884 png_ptr->num_trans = (png_uint_16)length;
1889 png_crc_finish(png_ptr, length);
1890 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1894 if (png_crc_finish(png_ptr, 0) != 0)
1896 png_ptr->num_trans = 0;
1900 /* TODO: this is a horrible side effect in the palette case because the
1901 * png_struct ends up with a pointer to the tRNS buffer owned by the
1902 * png_info. Fix this.
1904 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1905 &(png_ptr->trans_color));
1909 #ifdef PNG_READ_bKGD_SUPPORTED
1911 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1913 unsigned int truelen;
1915 png_color_16 background;
1917 png_debug(1, "in png_handle_bKGD");
1919 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1920 png_chunk_error(png_ptr, "missing IHDR");
1922 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1923 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1924 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1926 png_crc_finish(png_ptr, length);
1927 png_chunk_benign_error(png_ptr, "out of place");
1931 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1933 png_crc_finish(png_ptr, length);
1934 png_chunk_benign_error(png_ptr, "duplicate");
1938 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1941 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1947 if (length != truelen)
1949 png_crc_finish(png_ptr, length);
1950 png_chunk_benign_error(png_ptr, "invalid");
1954 png_crc_read(png_ptr, buf, truelen);
1956 if (png_crc_finish(png_ptr, 0) != 0)
1959 /* We convert the index value into RGB components so that we can allow
1960 * arbitrary RGB values for background when we have transparency, and
1961 * so it is easy to determine the RGB values of the background color
1962 * from the info_ptr struct.
1964 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1966 background.index = buf[0];
1968 if (info_ptr != NULL && info_ptr->num_palette != 0)
1970 if (buf[0] >= info_ptr->num_palette)
1972 png_chunk_benign_error(png_ptr, "invalid index");
1976 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1977 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1978 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1982 background.red = background.green = background.blue = 0;
1984 background.gray = 0;
1987 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1989 background.index = 0;
1993 background.gray = png_get_uint_16(buf);
1998 background.index = 0;
1999 background.red = png_get_uint_16(buf);
2000 background.green = png_get_uint_16(buf + 2);
2001 background.blue = png_get_uint_16(buf + 4);
2002 background.gray = 0;
2005 png_set_bKGD(png_ptr, info_ptr, &background);
2009 #ifdef PNG_READ_hIST_SUPPORTED
2011 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2013 unsigned int num, i;
2014 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
2016 png_debug(1, "in png_handle_hIST");
2018 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2019 png_chunk_error(png_ptr, "missing IHDR");
2021 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
2022 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
2024 png_crc_finish(png_ptr, length);
2025 png_chunk_benign_error(png_ptr, "out of place");
2029 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
2031 png_crc_finish(png_ptr, length);
2032 png_chunk_benign_error(png_ptr, "duplicate");
2038 if (num != (unsigned int) png_ptr->num_palette ||
2039 num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
2041 png_crc_finish(png_ptr, length);
2042 png_chunk_benign_error(png_ptr, "invalid");
2046 for (i = 0; i < num; i++)
2050 png_crc_read(png_ptr, buf, 2);
2051 readbuf[i] = png_get_uint_16(buf);
2054 if (png_crc_finish(png_ptr, 0) != 0)
2057 png_set_hIST(png_ptr, info_ptr, readbuf);
2061 #ifdef PNG_READ_pHYs_SUPPORTED
2063 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2066 png_uint_32 res_x, res_y;
2069 png_debug(1, "in png_handle_pHYs");
2071 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2072 png_chunk_error(png_ptr, "missing IHDR");
2074 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2076 png_crc_finish(png_ptr, length);
2077 png_chunk_benign_error(png_ptr, "out of place");
2081 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2083 png_crc_finish(png_ptr, length);
2084 png_chunk_benign_error(png_ptr, "duplicate");
2090 png_crc_finish(png_ptr, length);
2091 png_chunk_benign_error(png_ptr, "invalid");
2095 png_crc_read(png_ptr, buf, 9);
2097 if (png_crc_finish(png_ptr, 0) != 0)
2100 res_x = png_get_uint_32(buf);
2101 res_y = png_get_uint_32(buf + 4);
2103 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2107 #ifdef PNG_READ_oFFs_SUPPORTED
2109 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2112 png_int_32 offset_x, offset_y;
2115 png_debug(1, "in png_handle_oFFs");
2117 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2118 png_chunk_error(png_ptr, "missing IHDR");
2120 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2122 png_crc_finish(png_ptr, length);
2123 png_chunk_benign_error(png_ptr, "out of place");
2127 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2129 png_crc_finish(png_ptr, length);
2130 png_chunk_benign_error(png_ptr, "duplicate");
2136 png_crc_finish(png_ptr, length);
2137 png_chunk_benign_error(png_ptr, "invalid");
2141 png_crc_read(png_ptr, buf, 9);
2143 if (png_crc_finish(png_ptr, 0) != 0)
2146 offset_x = png_get_int_32(buf);
2147 offset_y = png_get_int_32(buf + 4);
2149 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2153 #ifdef PNG_READ_pCAL_SUPPORTED
2154 /* Read the pCAL chunk (described in the PNG Extensions document) */
2156 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2159 png_byte type, nparams;
2160 png_bytep buffer, buf, units, endptr;
2164 png_debug(1, "in png_handle_pCAL");
2166 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2167 png_chunk_error(png_ptr, "missing IHDR");
2169 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2171 png_crc_finish(png_ptr, length);
2172 png_chunk_benign_error(png_ptr, "out of place");
2176 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2178 png_crc_finish(png_ptr, length);
2179 png_chunk_benign_error(png_ptr, "duplicate");
2183 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2186 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2190 png_crc_finish(png_ptr, length);
2191 png_chunk_benign_error(png_ptr, "out of memory");
2195 png_crc_read(png_ptr, buffer, length);
2197 if (png_crc_finish(png_ptr, 0) != 0)
2200 buffer[length] = 0; /* Null terminate the last string */
2202 png_debug(3, "Finding end of pCAL purpose string");
2203 for (buf = buffer; *buf; buf++)
2206 endptr = buffer + length;
2208 /* We need to have at least 12 bytes after the purpose string
2209 * in order to get the parameter information.
2211 if (endptr - buf <= 12)
2213 png_chunk_benign_error(png_ptr, "invalid");
2217 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2218 X0 = png_get_int_32((png_bytep)buf+1);
2219 X1 = png_get_int_32((png_bytep)buf+5);
2224 png_debug(3, "Checking pCAL equation type and number of parameters");
2225 /* Check that we have the right number of parameters for known
2228 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2229 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2230 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2231 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2233 png_chunk_benign_error(png_ptr, "invalid parameter count");
2237 else if (type >= PNG_EQUATION_LAST)
2239 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2242 for (buf = units; *buf; buf++)
2243 /* Empty loop to move past the units string. */ ;
2245 png_debug(3, "Allocating pCAL parameters array");
2247 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2248 nparams * (sizeof (png_charp))));
2252 png_chunk_benign_error(png_ptr, "out of memory");
2256 /* Get pointers to the start of each parameter string. */
2257 for (i = 0; i < nparams; i++)
2259 buf++; /* Skip the null string terminator from previous parameter. */
2261 png_debug1(3, "Reading pCAL parameter %d", i);
2263 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2264 /* Empty loop to move past each parameter string */ ;
2266 /* Make sure we haven't run out of data yet */
2269 png_free(png_ptr, params);
2270 png_chunk_benign_error(png_ptr, "invalid data");
2275 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2276 (png_charp)units, params);
2278 png_free(png_ptr, params);
2282 #ifdef PNG_READ_sCAL_SUPPORTED
2283 /* Read the sCAL chunk */
2285 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2291 png_debug(1, "in png_handle_sCAL");
2293 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2294 png_chunk_error(png_ptr, "missing IHDR");
2296 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2298 png_crc_finish(png_ptr, length);
2299 png_chunk_benign_error(png_ptr, "out of place");
2303 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2305 png_crc_finish(png_ptr, length);
2306 png_chunk_benign_error(png_ptr, "duplicate");
2310 /* Need unit type, width, \0, height: minimum 4 bytes */
2311 else if (length < 4)
2313 png_crc_finish(png_ptr, length);
2314 png_chunk_benign_error(png_ptr, "invalid");
2318 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2321 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2325 png_chunk_benign_error(png_ptr, "out of memory");
2326 png_crc_finish(png_ptr, length);
2330 png_crc_read(png_ptr, buffer, length);
2331 buffer[length] = 0; /* Null terminate the last string */
2333 if (png_crc_finish(png_ptr, 0) != 0)
2336 /* Validate the unit. */
2337 if (buffer[0] != 1 && buffer[0] != 2)
2339 png_chunk_benign_error(png_ptr, "invalid unit");
2343 /* Validate the ASCII numbers, need two ASCII numbers separated by
2344 * a '\0' and they need to fit exactly in the chunk data.
2349 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2350 i >= length || buffer[i++] != 0)
2351 png_chunk_benign_error(png_ptr, "bad width format");
2353 else if (PNG_FP_IS_POSITIVE(state) == 0)
2354 png_chunk_benign_error(png_ptr, "non-positive width");
2358 png_size_t heighti = i;
2361 if (png_check_fp_number((png_const_charp)buffer, length,
2362 &state, &i) == 0 || i != length)
2363 png_chunk_benign_error(png_ptr, "bad height format");
2365 else if (PNG_FP_IS_POSITIVE(state) == 0)
2366 png_chunk_benign_error(png_ptr, "non-positive height");
2369 /* This is the (only) success case. */
2370 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2371 (png_charp)buffer+1, (png_charp)buffer+heighti);
2376 #ifdef PNG_READ_tIME_SUPPORTED
2378 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2383 png_debug(1, "in png_handle_tIME");
2385 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2386 png_chunk_error(png_ptr, "missing IHDR");
2388 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2390 png_crc_finish(png_ptr, length);
2391 png_chunk_benign_error(png_ptr, "duplicate");
2395 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2396 png_ptr->mode |= PNG_AFTER_IDAT;
2400 png_crc_finish(png_ptr, length);
2401 png_chunk_benign_error(png_ptr, "invalid");
2405 png_crc_read(png_ptr, buf, 7);
2407 if (png_crc_finish(png_ptr, 0) != 0)
2410 mod_time.second = buf[6];
2411 mod_time.minute = buf[5];
2412 mod_time.hour = buf[4];
2413 mod_time.day = buf[3];
2414 mod_time.month = buf[2];
2415 mod_time.year = png_get_uint_16(buf);
2417 png_set_tIME(png_ptr, info_ptr, &mod_time);
2421 #ifdef PNG_READ_tEXt_SUPPORTED
2422 /* Note: this does not properly handle chunks that are > 64K under DOS */
2424 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2430 png_uint_32 skip = 0;
2432 png_debug(1, "in png_handle_tEXt");
2434 #ifdef PNG_USER_LIMITS_SUPPORTED
2435 if (png_ptr->user_chunk_cache_max != 0)
2437 if (png_ptr->user_chunk_cache_max == 1)
2439 png_crc_finish(png_ptr, length);
2443 if (--png_ptr->user_chunk_cache_max == 1)
2445 png_crc_finish(png_ptr, length);
2446 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2452 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2453 png_chunk_error(png_ptr, "missing IHDR");
2455 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2456 png_ptr->mode |= PNG_AFTER_IDAT;
2458 #ifdef PNG_MAX_MALLOC_64K
2459 if (length > 65535U)
2461 png_crc_finish(png_ptr, length);
2462 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2467 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2471 png_chunk_benign_error(png_ptr, "out of memory");
2475 png_crc_read(png_ptr, buffer, length);
2477 if (png_crc_finish(png_ptr, skip) != 0)
2480 key = (png_charp)buffer;
2483 for (text = key; *text; text++)
2484 /* Empty loop to find end of key */ ;
2486 if (text != key + length)
2489 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2490 text_info.key = key;
2491 text_info.lang = NULL;
2492 text_info.lang_key = NULL;
2493 text_info.itxt_length = 0;
2494 text_info.text = text;
2495 text_info.text_length = strlen(text);
2497 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2498 png_warning(png_ptr, "Insufficient memory to process text chunk");
2502 #ifdef PNG_READ_zTXt_SUPPORTED
2503 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2505 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2507 png_const_charp errmsg = NULL;
2509 png_uint_32 keyword_length;
2511 png_debug(1, "in png_handle_zTXt");
2513 #ifdef PNG_USER_LIMITS_SUPPORTED
2514 if (png_ptr->user_chunk_cache_max != 0)
2516 if (png_ptr->user_chunk_cache_max == 1)
2518 png_crc_finish(png_ptr, length);
2522 if (--png_ptr->user_chunk_cache_max == 1)
2524 png_crc_finish(png_ptr, length);
2525 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2531 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2532 png_chunk_error(png_ptr, "missing IHDR");
2534 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2535 png_ptr->mode |= PNG_AFTER_IDAT;
2537 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2541 png_crc_finish(png_ptr, length);
2542 png_chunk_benign_error(png_ptr, "out of memory");
2546 png_crc_read(png_ptr, buffer, length);
2548 if (png_crc_finish(png_ptr, 0) != 0)
2551 /* TODO: also check that the keyword contents match the spec! */
2552 for (keyword_length = 0;
2553 keyword_length < length && buffer[keyword_length] != 0;
2555 /* Empty loop to find end of name */ ;
2557 if (keyword_length > 79 || keyword_length < 1)
2558 errmsg = "bad keyword";
2560 /* zTXt must have some LZ data after the keyword, although it may expand to
2561 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2564 else if (keyword_length + 3 > length)
2565 errmsg = "truncated";
2567 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2568 errmsg = "unknown compression type";
2572 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2574 /* TODO: at present png_decompress_chunk imposes a single application
2575 * level memory limit, this should be split to different values for iCCP
2578 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2579 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2583 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
2584 * for the extra compression type byte and the fact that it isn't
2585 * necessarily '\0' terminated.
2587 buffer = png_ptr->read_buffer;
2588 buffer[uncompressed_length+(keyword_length+2)] = 0;
2590 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2591 text.key = (png_charp)buffer;
2592 text.text = (png_charp)(buffer + keyword_length+2);
2593 text.text_length = uncompressed_length;
2594 text.itxt_length = 0;
2596 text.lang_key = NULL;
2598 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2599 errmsg = "insufficient memory";
2603 errmsg = png_ptr->zstream.msg;
2607 png_chunk_benign_error(png_ptr, errmsg);
2611 #ifdef PNG_READ_iTXt_SUPPORTED
2612 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2614 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2616 png_const_charp errmsg = NULL;
2618 png_uint_32 prefix_length;
2620 png_debug(1, "in png_handle_iTXt");
2622 #ifdef PNG_USER_LIMITS_SUPPORTED
2623 if (png_ptr->user_chunk_cache_max != 0)
2625 if (png_ptr->user_chunk_cache_max == 1)
2627 png_crc_finish(png_ptr, length);
2631 if (--png_ptr->user_chunk_cache_max == 1)
2633 png_crc_finish(png_ptr, length);
2634 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2640 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2641 png_chunk_error(png_ptr, "missing IHDR");
2643 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2644 png_ptr->mode |= PNG_AFTER_IDAT;
2646 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2650 png_crc_finish(png_ptr, length);
2651 png_chunk_benign_error(png_ptr, "out of memory");
2655 png_crc_read(png_ptr, buffer, length);
2657 if (png_crc_finish(png_ptr, 0) != 0)
2660 /* First the keyword. */
2661 for (prefix_length=0;
2662 prefix_length < length && buffer[prefix_length] != 0;
2666 /* Perform a basic check on the keyword length here. */
2667 if (prefix_length > 79 || prefix_length < 1)
2668 errmsg = "bad keyword";
2670 /* Expect keyword, compression flag, compression type, language, translated
2671 * keyword (both may be empty but are 0 terminated) then the text, which may
2674 else if (prefix_length + 5 > length)
2675 errmsg = "truncated";
2677 else if (buffer[prefix_length+1] == 0 ||
2678 (buffer[prefix_length+1] == 1 &&
2679 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2681 int compressed = buffer[prefix_length+1] != 0;
2682 png_uint_32 language_offset, translated_keyword_offset;
2683 png_alloc_size_t uncompressed_length = 0;
2685 /* Now the language tag */
2687 language_offset = prefix_length;
2689 for (; prefix_length < length && buffer[prefix_length] != 0;
2693 /* WARNING: the length may be invalid here, this is checked below. */
2694 translated_keyword_offset = ++prefix_length;
2696 for (; prefix_length < length && buffer[prefix_length] != 0;
2700 /* prefix_length should now be at the trailing '\0' of the translated
2701 * keyword, but it may already be over the end. None of this arithmetic
2702 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2703 * systems the available allocation may overflow.
2707 if (compressed == 0 && prefix_length <= length)
2708 uncompressed_length = length - prefix_length;
2710 else if (compressed != 0 && prefix_length < length)
2712 uncompressed_length = PNG_SIZE_MAX;
2714 /* TODO: at present png_decompress_chunk imposes a single application
2715 * level memory limit, this should be split to different values for
2716 * iCCP and text chunks.
2718 if (png_decompress_chunk(png_ptr, length, prefix_length,
2719 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2720 buffer = png_ptr->read_buffer;
2723 errmsg = png_ptr->zstream.msg;
2727 errmsg = "truncated";
2733 buffer[uncompressed_length+prefix_length] = 0;
2735 if (compressed == 0)
2736 text.compression = PNG_ITXT_COMPRESSION_NONE;
2739 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2741 text.key = (png_charp)buffer;
2742 text.lang = (png_charp)buffer + language_offset;
2743 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2744 text.text = (png_charp)buffer + prefix_length;
2745 text.text_length = 0;
2746 text.itxt_length = uncompressed_length;
2748 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2749 errmsg = "insufficient memory";
2754 errmsg = "bad compression info";
2757 png_chunk_benign_error(png_ptr, errmsg);
2761 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2762 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2764 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2766 png_alloc_size_t limit = PNG_SIZE_MAX;
2768 if (png_ptr->unknown_chunk.data != NULL)
2770 png_free(png_ptr, png_ptr->unknown_chunk.data);
2771 png_ptr->unknown_chunk.data = NULL;
2774 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
2775 if (png_ptr->user_chunk_malloc_max > 0 &&
2776 png_ptr->user_chunk_malloc_max < limit)
2777 limit = png_ptr->user_chunk_malloc_max;
2779 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2780 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2781 limit = PNG_USER_CHUNK_MALLOC_MAX;
2784 if (length <= limit)
2786 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2787 /* The following is safe because of the PNG_SIZE_MAX init above */
2788 png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
2789 /* 'mode' is a flag array, only the bottom four bits matter here */
2790 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2793 png_ptr->unknown_chunk.data = NULL;
2797 /* Do a 'warn' here - it is handled below. */
2798 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2799 png_malloc_warn(png_ptr, length));
2803 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2805 /* This is benign because we clean up correctly */
2806 png_crc_finish(png_ptr, length);
2807 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2814 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2815 png_crc_finish(png_ptr, 0);
2819 #endif /* READ_UNKNOWN_CHUNKS */
2821 /* Handle an unknown, or known but disabled, chunk */
2823 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2824 png_uint_32 length, int keep)
2826 int handled = 0; /* the chunk was handled */
2828 png_debug(1, "in png_handle_unknown");
2830 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2831 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2832 * the bug which meant that setting a non-default behavior for a specific
2833 * chunk would be ignored (the default was always used unless a user
2834 * callback was installed).
2836 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2837 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2838 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2839 * This is just an optimization to avoid multiple calls to the lookup
2842 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2843 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2844 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2848 /* One of the following methods will read the chunk or skip it (at least one
2849 * of these is always defined because this is the only way to switch on
2850 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2852 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2853 /* The user callback takes precedence over the chunk keep value, but the
2854 * keep value is still required to validate a save of a critical chunk.
2856 if (png_ptr->read_user_chunk_fn != NULL)
2858 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2860 /* Callback to user unknown chunk handler */
2861 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2862 &png_ptr->unknown_chunk);
2865 * negative: An error occurred; png_chunk_error will be called.
2866 * zero: The chunk was not handled, the chunk will be discarded
2867 * unless png_set_keep_unknown_chunks has been used to set
2868 * a 'keep' behavior for this particular chunk, in which
2869 * case that will be used. A critical chunk will cause an
2870 * error at this point unless it is to be saved.
2871 * positive: The chunk was handled, libpng will ignore/discard it.
2874 png_chunk_error(png_ptr, "error in user chunk");
2878 /* If the keep value is 'default' or 'never' override it, but
2879 * still error out on critical chunks unless the keep value is
2880 * 'always' While this is weird it is the behavior in 1.4.12.
2881 * A possible improvement would be to obey the value set for the
2882 * chunk, but this would be an API change that would probably
2883 * damage some applications.
2885 * The png_app_warning below catches the case that matters, where
2886 * the application has not set specific save or ignore for this
2887 * chunk or global save or ignore.
2889 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2891 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2892 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2894 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2895 png_app_warning(png_ptr,
2896 "forcing save of an unhandled chunk;"
2897 " please call png_set_keep_unknown_chunks");
2898 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
2901 keep = PNG_HANDLE_CHUNK_IF_SAFE;
2905 else /* chunk was handled */
2908 /* Critical chunks can be safely discarded at this point. */
2909 keep = PNG_HANDLE_CHUNK_NEVER;
2914 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
2918 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
2919 # endif /* READ_USER_CHUNKS */
2921 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
2923 /* keep is currently just the per-chunk setting, if there was no
2924 * setting change it to the global default now (not that this may
2925 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
2926 * if not simply skip the chunk.
2928 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
2929 keep = png_ptr->unknown_default;
2931 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2932 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2933 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2935 if (png_cache_unknown_chunk(png_ptr, length) == 0)
2936 keep = PNG_HANDLE_CHUNK_NEVER;
2940 png_crc_finish(png_ptr, length);
2943 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
2944 # error no method to support READ_UNKNOWN_CHUNKS
2948 /* If here there is no read callback pointer set and no support is
2949 * compiled in to just save the unknown chunks, so simply skip this
2950 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
2951 * the app has erroneously asked for unknown chunk saving when there
2954 if (keep > PNG_HANDLE_CHUNK_NEVER)
2955 png_app_error(png_ptr, "no unknown chunk support available");
2957 png_crc_finish(png_ptr, length);
2961 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
2962 /* Now store the chunk in the chunk list if appropriate, and if the limits
2965 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2966 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2967 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2969 # ifdef PNG_USER_LIMITS_SUPPORTED
2970 switch (png_ptr->user_chunk_cache_max)
2973 png_ptr->user_chunk_cache_max = 1;
2974 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2977 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
2978 * chunk being skipped, now there will be a hard error below.
2982 default: /* not at limit */
2983 --(png_ptr->user_chunk_cache_max);
2985 case 0: /* no limit */
2986 # endif /* USER_LIMITS */
2987 /* Here when the limit isn't reached or when limits are compiled
2988 * out; store the chunk.
2990 png_set_unknown_chunks(png_ptr, info_ptr,
2991 &png_ptr->unknown_chunk, 1);
2993 # ifdef PNG_USER_LIMITS_SUPPORTED
2998 # else /* no store support: the chunk must be handled by the user callback */
2999 PNG_UNUSED(info_ptr)
3002 /* Regardless of the error handling below the cached data (if any) can be
3003 * freed now. Notice that the data is not freed if there is a png_error, but
3004 * it will be freed by destroy_read_struct.
3006 if (png_ptr->unknown_chunk.data != NULL)
3007 png_free(png_ptr, png_ptr->unknown_chunk.data);
3008 png_ptr->unknown_chunk.data = NULL;
3010 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
3011 /* There is no support to read an unknown chunk, so just skip it. */
3012 png_crc_finish(png_ptr, length);
3013 PNG_UNUSED(info_ptr)
3015 #endif /* !READ_UNKNOWN_CHUNKS */
3017 /* Check for unhandled critical chunks */
3018 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
3019 png_chunk_error(png_ptr, "unhandled critical chunk");
3022 /* This function is called to verify that a chunk name is valid.
3023 * This function can't have the "critical chunk check" incorporated
3024 * into it, since in the future we will need to be able to call user
3025 * functions to handle unknown critical chunks after we check that
3026 * the chunk name itself is valid.
3029 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
3031 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
3035 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
3039 png_debug(1, "in png_check_chunk_name");
3041 for (i=1; i<=4; ++i)
3043 int c = chunk_name & 0xff;
3045 if (c < 65 || c > 122 || (c > 90 && c < 97))
3046 png_chunk_error(png_ptr, "invalid chunk type");
3052 #ifdef _PNG_COLOR_PICK_ENABLED_
3055 copy_src_to_dst(png_bytep dp, png_bytep sp, int width,
3056 int row_stride, int nplanes, PngPickColor *png_pickcolor)
3059 unsigned char *src = (unsigned char *)sp;
3060 unsigned char *dst = (unsigned char *)dp;
3062 unsigned long long sumRGBA[4] = {0, 0, 0, 0};
3063 const int const0 = 0;
3066 uint32x4_t sumR_32x4 = vmovq_n_u32 ( 0 );
3067 uint32x4_t sumG_32x4 = vmovq_n_u32 ( 0 );
3068 uint32x4_t sumB_32x4 = vmovq_n_u32 ( 0 );
3074 uint64x1x3_t sumRGB_64x1;
3076 for(j = 0; j < width-(width&0xf); j += 16)
3080 uint8x16x3_t rgb = vld3q_u8 ( src );
3082 R_8x16 = rgb.val[0];
3083 G_8x16 = rgb.val[1];
3084 B_8x16 = rgb.val[2];
3088 uint8x16x4_t rgb = vld4q_u8 ( src );
3090 R_8x16 = rgb.val[0];
3091 G_8x16 = rgb.val[1];
3092 B_8x16 = rgb.val[2];
3095 if(png_pickcolor && png_pickcolor->enable)
3097 if(png_pickcolor->perc > 0)
3099 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3100 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3101 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3103 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3104 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3105 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3107 else if( (png_pickcolor->x1 > j) && (png_pickcolor->x1 < j + 16) )
3109 int x = png_pickcolor->x1;
3110 unsigned char *from = sp + (png_pickcolor->x1 * nplanes);
3113 png_pickcolor->sumR += from[0];
3114 png_pickcolor->sumG += from[1];
3115 png_pickcolor->sumB += from[2];
3120 else if( (png_pickcolor->x2 >= j) && (png_pickcolor->x2 < j + 16) )
3123 unsigned char *from = sp + (j * nplanes);
3124 while(x <= png_pickcolor->x2)
3126 png_pickcolor->sumR += from[0];
3127 png_pickcolor->sumG += from[1];
3128 png_pickcolor->sumB += from[2];
3133 else if ( (j >= png_pickcolor->x1) && (j+15 <= png_pickcolor->x2) )
3135 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3136 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3137 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3139 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3140 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3141 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3144 dst += (nplanes*16);
3145 src += (nplanes*16);
3148 if(png_pickcolor && png_pickcolor->enable)
3151 uint64x2_t sumR_64x2 = vpaddlq_u32 ( sumR_32x4 );
3152 uint64x2_t sumG_64x2 = vpaddlq_u32 ( sumG_32x4 );
3153 uint64x2_t sumB_64x2 = vpaddlq_u32 ( sumB_32x4 );
3155 uint64x1_t sumR_Lo_64x1 = vget_low_u64 ( sumR_64x2 );
3156 uint64x1_t sumR_Hi_64x1 = vget_high_u64 ( sumR_64x2 );
3158 uint64x1_t sumG_Lo_64x1 = vget_low_u64 ( sumG_64x2 );
3159 uint64x1_t sumG_Hi_64x1 = vget_high_u64 ( sumG_64x2 );
3161 uint64x1_t sumB_Lo_64x1 = vget_low_u64 ( sumB_64x2 );
3162 uint64x1_t sumB_Hi_64x1 = vget_high_u64 ( sumB_64x2 );
3164 sumRGB_64x1.val[0] = vadd_u64 ( sumR_Lo_64x1, sumR_Hi_64x1 );
3165 sumRGB_64x1.val[1] = vadd_u64 ( sumG_Lo_64x1, sumG_Hi_64x1 );
3166 sumRGB_64x1.val[2] = vadd_u64 ( sumB_Lo_64x1, sumB_Hi_64x1 );
3168 vst3_u64( sumRGBA, sumRGB_64x1);
3170 png_pickcolor->sumR += sumRGBA[0];
3171 png_pickcolor->sumG += sumRGBA[1];
3172 png_pickcolor->sumB += sumRGBA[2];
3175 memcpy(dst, src, (width-j)*nplanes);
3176 if(png_pickcolor && png_pickcolor->enable)
3178 if(png_pickcolor->perc <= 0)
3180 if(j < png_pickcolor->x1)
3182 j = png_pickcolor->x1;
3183 dst = dp + (j*nplanes);
3185 width = png_pickcolor->x2;
3187 for(; j < width ; j ++)
3189 png_pickcolor->sumR += dst[0];
3190 png_pickcolor->sumG += dst[1];
3191 png_pickcolor->sumB += dst[2];
3197 void copy_row(png_bytep dp, png_bytep sp, int width, int pixel_bits, PngPickColor *png_pickcolor)
3199 int row_stride = PNG_ROWBYTES(pixel_bits, width);
3200 if(pixel_bits == 24 || pixel_bits == 32)
3202 copy_src_to_dst(dp, sp, width, row_stride, pixel_bits >> 3, png_pickcolor);
3206 memcpy(dp, sp, row_stride);
3213 /* Combines the row recently read in with the existing pixels in the row. This
3214 * routine takes care of alpha and transparency if requested. This routine also
3215 * handles the two methods of progressive display of interlaced images,
3216 * depending on the 'display' value; if 'display' is true then the whole row
3217 * (dp) is filled from the start by replicating the available pixels. If
3218 * 'display' is false only those pixels present in the pass are filled in.
3221 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3223 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3224 png_const_bytep sp = png_ptr->row_buf + 1;
3225 png_alloc_size_t row_width = png_ptr->width;
3226 unsigned int pass = png_ptr->pass;
3227 png_bytep end_ptr = 0;
3228 png_byte end_byte = 0;
3229 unsigned int end_mask;
3231 png_debug(1, "in png_combine_row");
3233 /* Added in 1.5.6: it should not be possible to enter this routine until at
3234 * least one row has been read from the PNG data and transformed.
3236 if (pixel_depth == 0)
3237 png_error(png_ptr, "internal row logic error");
3239 /* Added in 1.5.4: the pixel depth should match the information returned by
3240 * any call to png_read_update_info at this point. Do not continue if we got
3243 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3244 PNG_ROWBYTES(pixel_depth, row_width))
3245 png_error(png_ptr, "internal row size calculation error");
3247 /* Don't expect this to ever happen: */
3249 png_error(png_ptr, "internal row width error");
3251 /* Preserve the last byte in cases where only part of it will be overwritten,
3252 * the multiply below may overflow, we don't care because ANSI-C guarantees
3253 * we get the low bits.
3255 end_mask = (pixel_depth * row_width) & 7;
3258 /* end_ptr == NULL is a flag to say do nothing */
3259 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3260 end_byte = *end_ptr;
3261 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3262 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3263 /* little-endian byte */
3264 end_mask = 0xff << end_mask;
3266 else /* big-endian byte */
3268 end_mask = 0xff >> end_mask;
3269 /* end_mask is now the bits to *keep* from the destination row */
3272 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3273 * will also happen if interlacing isn't supported or if the application
3274 * does not call png_set_interlace_handling(). In the latter cases the
3275 * caller just gets a sequence of the unexpanded rows from each interlace
3278 #ifdef PNG_READ_INTERLACING_SUPPORTED
3279 if (png_ptr->interlaced != 0 &&
3280 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3281 pass < 6 && (display == 0 ||
3282 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3283 (display == 1 && (pass & 1) != 0)))
3285 /* Narrow images may have no bits in a pass; the caller should handle
3286 * this, but this test is cheap:
3288 if (row_width <= PNG_PASS_START_COL(pass))
3291 if (pixel_depth < 8)
3293 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3294 * into 32 bits, then a single loop over the bytes using the four byte
3295 * values in the 32-bit mask can be used. For the 'display' option the
3296 * expanded mask may also not require any masking within a byte. To
3297 * make this work the PACKSWAP option must be taken into account - it
3298 * simply requires the pixels to be reversed in each byte.
3300 * The 'regular' case requires a mask for each of the first 6 passes,
3301 * the 'display' case does a copy for the even passes in the range
3302 * 0..6. This has already been handled in the test above.
3304 * The masks are arranged as four bytes with the first byte to use in
3305 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3306 * not) of the pixels in each byte.
3308 * NOTE: the whole of this logic depends on the caller of this function
3309 * only calling it on rows appropriate to the pass. This function only
3310 * understands the 'x' logic; the 'y' logic is handled by the caller.
3312 * The following defines allow generation of compile time constant bit
3313 * masks for each pixel depth and each possibility of swapped or not
3314 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3315 * is in the range 0..7; and the result is 1 if the pixel is to be
3316 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3317 * for the block method.
3319 * With some compilers a compile time expression of the general form:
3321 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3323 * Produces warnings with values of 'shift' in the range 33 to 63
3324 * because the right hand side of the ?: expression is evaluated by
3325 * the compiler even though it isn't used. Microsoft Visual C (various
3326 * versions) and the Intel C compiler are known to do this. To avoid
3327 * this the following macros are used in 1.5.6. This is a temporary
3328 * solution to avoid destabilizing the code during the release process.
3330 # if PNG_USE_COMPILE_TIME_MASKS
3331 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3332 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3334 # define PNG_LSR(x,s) ((x)>>(s))
3335 # define PNG_LSL(x,s) ((x)<<(s))
3337 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3338 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3339 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3340 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3342 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3343 * little endian - the first pixel is at bit 0 - however the extra
3344 * parameter 's' can be set to cause the mask position to be swapped
3345 * within each byte, to match the PNG format. This is done by XOR of
3346 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3348 # define PIXEL_MASK(p,x,d,s) \
3349 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3351 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3353 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3354 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3356 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3357 * cases the result needs replicating, for the 4-bpp case the above
3358 * generates a full 32 bits.
3360 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3362 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3363 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3364 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3366 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3367 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3368 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3370 #if PNG_USE_COMPILE_TIME_MASKS
3371 /* Utility macros to construct all the masks for a depth/swap
3372 * combination. The 's' parameter says whether the format is PNG
3373 * (big endian bytes) or not. Only the three odd-numbered passes are
3374 * required for the display/block algorithm.
3376 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3377 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3379 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3381 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3383 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3386 static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3388 /* Little-endian byte masks for PACKSWAP */
3389 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3390 /* Normal (big-endian byte) masks - PNG format */
3391 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3394 /* display_mask has only three entries for the odd passes, so index by
3397 static PNG_CONST png_uint_32 display_mask[2][3][3] =
3399 /* Little-endian byte masks for PACKSWAP */
3400 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3401 /* Normal (big-endian byte) masks - PNG format */
3402 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3405 # define MASK(pass,depth,display,png)\
3406 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3407 row_mask[png][DEPTH_INDEX(depth)][pass])
3409 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3410 /* This is the runtime alternative: it seems unlikely that this will
3411 * ever be either smaller or faster than the compile time approach.
3413 # define MASK(pass,depth,display,png)\
3414 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3415 #endif /* !USE_COMPILE_TIME_MASKS */
3417 /* Use the appropriate mask to copy the required bits. In some cases
3418 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3419 * the number of pixels, but the code copies bytes, so it is necessary
3420 * to special case the end.
3422 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3425 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3426 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3427 mask = MASK(pass, pixel_depth, display, 0);
3431 mask = MASK(pass, pixel_depth, display, 1);
3437 /* It doesn't matter in the following if png_uint_32 has more than
3438 * 32 bits because the high bits always match those in m<<24; it is,
3439 * however, essential to use OR here, not +, because of this.
3442 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3445 if (m != 0) /* something to copy */
3448 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3453 /* NOTE: this may overwrite the last byte with garbage if the image
3454 * is not an exact number of bytes wide; libpng has always done
3457 if (row_width <= pixels_per_byte)
3458 break; /* May need to restore part of the last byte */
3460 row_width -= pixels_per_byte;
3466 else /* pixel_depth >= 8 */
3468 unsigned int bytes_to_copy, bytes_to_jump;
3470 /* Validate the depth - it must be a multiple of 8 */
3471 if (pixel_depth & 7)
3472 png_error(png_ptr, "invalid user transform pixel depth");
3474 pixel_depth >>= 3; /* now in bytes */
3475 row_width *= pixel_depth;
3477 /* Regardless of pass number the Adam 7 interlace always results in a
3478 * fixed number of pixels to copy then to skip. There may be a
3479 * different number of pixels to skip at the start though.
3482 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3484 row_width -= offset;
3489 /* Work out the bytes to copy. */
3492 /* When doing the 'block' algorithm the pixel in the pass gets
3493 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3494 * passes are skipped above - the entire expanded row is copied.
3496 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3498 /* But don't allow this number to exceed the actual row width. */
3499 if (bytes_to_copy > row_width)
3500 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3503 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3504 bytes_to_copy = pixel_depth;
3506 /* In Adam7 there is a constant offset between where the pixels go. */
3507 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3509 /* And simply copy these bytes. Some optimization is possible here,
3510 * depending on the value of 'bytes_to_copy'. Special case the low
3511 * byte counts, which we know to be frequent.
3513 * Notice that these cases all 'return' rather than 'break' - this
3514 * avoids an unnecessary test on whether to restore the last byte
3517 switch (bytes_to_copy)
3524 if (row_width <= bytes_to_jump)
3527 dp += bytes_to_jump;
3528 sp += bytes_to_jump;
3529 row_width -= bytes_to_jump;
3533 /* There is a possibility of a partial copy at the end here; this
3534 * slows the code down somewhat.
3538 dp[0] = sp[0], dp[1] = sp[1];
3540 if (row_width <= bytes_to_jump)
3543 sp += bytes_to_jump;
3544 dp += bytes_to_jump;
3545 row_width -= bytes_to_jump;
3547 while (row_width > 1);
3549 /* And there can only be one byte left at this point: */
3554 /* This can only be the RGB case, so each copy is exactly one
3555 * pixel and it is not necessary to check for a partial copy.
3559 dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
3561 if (row_width <= bytes_to_jump)
3564 sp += bytes_to_jump;
3565 dp += bytes_to_jump;
3566 row_width -= bytes_to_jump;
3570 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3571 /* Check for double byte alignment and, if possible, use a
3572 * 16-bit copy. Don't attempt this for narrow images - ones that
3573 * are less than an interlace panel wide. Don't attempt it for
3574 * wide bytes_to_copy either - use the memcpy there.
3576 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3577 png_isaligned(dp, png_uint_16) &&
3578 png_isaligned(sp, png_uint_16) &&
3579 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3580 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3582 /* Everything is aligned for png_uint_16 copies, but try for
3583 * png_uint_32 first.
3585 if (png_isaligned(dp, png_uint_32) != 0 &&
3586 png_isaligned(sp, png_uint_32) != 0 &&
3587 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3588 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3590 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3591 png_const_uint_32p sp32 = png_aligncastconst(
3592 png_const_uint_32p, sp);
3593 size_t skip = (bytes_to_jump-bytes_to_copy) /
3594 (sizeof (png_uint_32));
3598 size_t c = bytes_to_copy;
3602 c -= (sizeof (png_uint_32));
3606 if (row_width <= bytes_to_jump)
3611 row_width -= bytes_to_jump;
3613 while (bytes_to_copy <= row_width);
3615 /* Get to here when the row_width truncates the final copy.
3616 * There will be 1-3 bytes left to copy, so don't try the
3617 * 16-bit loop below.
3619 dp = (png_bytep)dp32;
3620 sp = (png_const_bytep)sp32;
3623 while (--row_width > 0);
3627 /* Else do it in 16-bit quantities, but only if the size is
3632 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3633 png_const_uint_16p sp16 = png_aligncastconst(
3634 png_const_uint_16p, sp);
3635 size_t skip = (bytes_to_jump-bytes_to_copy) /
3636 (sizeof (png_uint_16));
3640 size_t c = bytes_to_copy;
3644 c -= (sizeof (png_uint_16));
3648 if (row_width <= bytes_to_jump)
3653 row_width -= bytes_to_jump;
3655 while (bytes_to_copy <= row_width);
3657 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3658 dp = (png_bytep)dp16;
3659 sp = (png_const_bytep)sp16;
3662 while (--row_width > 0);
3666 #endif /* ALIGN_TYPE code */
3668 /* The true default - use a memcpy: */
3671 memcpy(dp, sp, bytes_to_copy);
3673 if (row_width <= bytes_to_jump)
3676 sp += bytes_to_jump;
3677 dp += bytes_to_jump;
3678 row_width -= bytes_to_jump;
3679 if (bytes_to_copy > row_width)
3680 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3685 } /* pixel_depth >= 8 */
3687 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3690 #endif /* READ_INTERLACING */
3692 /* If here then the switch above wasn't used so just memcpy the whole row
3693 * from the temporary row buffer (notice that this overwrites the end of the
3694 * destination row if it is a partial byte.)
3696 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3698 /* Restore the overwritten bits from the last byte if necessary. */
3699 if (end_ptr != NULL)
3700 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3703 #ifdef PNG_READ_INTERLACING_SUPPORTED
3705 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3706 png_uint_32 transformations /* Because these may affect the byte layout */)
3708 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3709 /* Offset to next interlace block */
3710 static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3712 png_debug(1, "in png_do_read_interlace");
3713 if (row != NULL && row_info != NULL)
3715 png_uint_32 final_width;
3717 final_width = row_info->width * png_pass_inc[pass];
3719 switch (row_info->pixel_depth)
3723 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
3724 png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
3726 int s_start, s_end, s_inc;
3727 int jstop = png_pass_inc[pass];
3732 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3733 if ((transformations & PNG_PACKSWAP) != 0)
3735 sshift = (int)((row_info->width + 7) & 0x07);
3736 dshift = (int)((final_width + 7) & 0x07);
3745 sshift = 7 - (int)((row_info->width + 7) & 0x07);
3746 dshift = 7 - (int)((final_width + 7) & 0x07);
3752 for (i = 0; i < row_info->width; i++)
3754 v = (png_byte)((*sp >> sshift) & 0x01);
3755 for (j = 0; j < jstop; j++)
3757 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3759 *dp = (png_byte)(tmp & 0xff);
3761 if (dshift == s_end)
3771 if (sshift == s_end)
3785 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3786 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3788 int s_start, s_end, s_inc;
3789 int jstop = png_pass_inc[pass];
3792 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3793 if ((transformations & PNG_PACKSWAP) != 0)
3795 sshift = (int)(((row_info->width + 3) & 0x03) << 1);
3796 dshift = (int)(((final_width + 3) & 0x03) << 1);
3805 sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
3806 dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
3812 for (i = 0; i < row_info->width; i++)
3817 v = (png_byte)((*sp >> sshift) & 0x03);
3818 for (j = 0; j < jstop; j++)
3820 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3822 *dp = (png_byte)(tmp & 0xff);
3824 if (dshift == s_end)
3834 if (sshift == s_end)
3848 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
3849 png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
3851 int s_start, s_end, s_inc;
3853 int jstop = png_pass_inc[pass];
3855 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3856 if ((transformations & PNG_PACKSWAP) != 0)
3858 sshift = (int)(((row_info->width + 1) & 0x01) << 2);
3859 dshift = (int)(((final_width + 1) & 0x01) << 2);
3868 sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
3869 dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
3875 for (i = 0; i < row_info->width; i++)
3877 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
3880 for (j = 0; j < jstop; j++)
3882 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
3884 *dp = (png_byte)(tmp & 0xff);
3886 if (dshift == s_end)
3896 if (sshift == s_end)
3910 png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
3912 png_bytep sp = row + (png_size_t)(row_info->width - 1)
3915 png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
3917 int jstop = png_pass_inc[pass];
3920 for (i = 0; i < row_info->width; i++)
3922 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
3925 memcpy(v, sp, pixel_bytes);
3927 for (j = 0; j < jstop; j++)
3929 memcpy(dp, v, pixel_bytes);
3939 row_info->width = final_width;
3940 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
3942 #ifndef PNG_READ_PACKSWAP_SUPPORTED
3943 PNG_UNUSED(transformations) /* Silence compiler warning */
3946 #endif /* READ_INTERLACING */
3949 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
3950 png_const_bytep prev_row)
3953 png_size_t istop = row_info->rowbytes;
3954 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3955 png_bytep rp = row + bpp;
3957 PNG_UNUSED(prev_row)
3959 for (i = bpp; i < istop; i++)
3961 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
3967 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
3968 png_const_bytep prev_row)
3971 png_size_t istop = row_info->rowbytes;
3973 png_const_bytep pp = prev_row;
3975 for (i = 0; i < istop; i++)
3977 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
3983 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
3984 png_const_bytep prev_row)
3988 png_const_bytep pp = prev_row;
3989 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3990 png_size_t istop = row_info->rowbytes - bpp;
3992 for (i = 0; i < bpp; i++)
3994 *rp = (png_byte)(((int)(*rp) +
3995 ((int)(*pp++) / 2 )) & 0xff);
4000 for (i = 0; i < istop; i++)
4002 *rp = (png_byte)(((int)(*rp) +
4003 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
4010 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
4011 png_const_bytep prev_row)
4013 png_bytep rp_end = row + row_info->rowbytes;
4016 /* First pixel/byte */
4019 *row++ = (png_byte)a;
4022 while (row < rp_end)
4024 int b, pa, pb, pc, p;
4026 a &= 0xff; /* From previous iteration or start */
4037 pa = p < 0 ? -p : p;
4038 pb = pc < 0 ? -pc : pc;
4039 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4042 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
4043 * ones in the case of a tie.
4045 if (pb < pa) pa = pb, a = b;
4048 /* Calculate the current pixel in a, and move the previous row pixel to c
4049 * for the next time round the loop
4053 *row++ = (png_byte)a;
4058 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
4059 png_const_bytep prev_row)
4061 int bpp = (row_info->pixel_depth + 7) >> 3;
4062 png_bytep rp_end = row + bpp;
4064 /* Process the first pixel in the row completely (this is the same as 'up'
4065 * because there is only one candidate predictor for the first row).
4067 while (row < rp_end)
4069 int a = *row + *prev_row++;
4070 *row++ = (png_byte)a;
4074 rp_end += row_info->rowbytes - bpp;
4076 while (row < rp_end)
4078 int a, b, c, pa, pb, pc, p;
4080 c = *(prev_row - bpp);
4092 pa = p < 0 ? -p : p;
4093 pb = pc < 0 ? -pc : pc;
4094 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4097 if (pb < pa) pa = pb, a = b;
4101 *row++ = (png_byte)a;
4106 png_init_filter_functions(png_structrp pp)
4107 /* This function is called once for every PNG image (except for PNG images
4108 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
4109 * implementations required to reverse the filtering of PNG rows. Reversing
4110 * the filter is the first transformation performed on the row data. It is
4111 * performed in place, therefore an implementation can be selected based on
4112 * the image pixel format. If the implementation depends on image width then
4113 * take care to ensure that it works correctly if the image is interlaced -
4114 * interlacing causes the actual row width to vary.
4117 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
4119 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
4120 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
4121 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
4123 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4124 png_read_filter_row_paeth_1byte_pixel;
4126 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4127 png_read_filter_row_paeth_multibyte_pixel;
4129 #ifdef PNG_FILTER_OPTIMIZATIONS
4130 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
4131 * call to install hardware optimizations for the above functions; simply
4132 * replace whatever elements of the pp->read_filter[] array with a hardware
4133 * specific (or, for that matter, generic) optimization.
4135 * To see an example of this examine what configure.ac does when
4136 * --enable-arm-neon is specified on the command line.
4138 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
4143 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
4144 png_const_bytep prev_row, int filter)
4146 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
4147 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
4148 * implementations. See png_init_filter_functions above.
4150 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
4152 if (pp->read_filter[0] == NULL)
4153 png_init_filter_functions(pp);
4155 pp->read_filter[filter-1](row_info, row, prev_row);
4159 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
4161 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
4162 png_alloc_size_t avail_out)
4164 /* Loop reading IDATs and decompressing the result into output[avail_out] */
4165 png_ptr->zstream.next_out = output;
4166 png_ptr->zstream.avail_out = 0; /* safety: set below */
4174 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
4176 if (png_ptr->zstream.avail_in == 0)
4181 while (png_ptr->idat_size == 0)
4183 png_crc_finish(png_ptr, 0);
4185 png_ptr->idat_size = png_read_chunk_header(png_ptr);
4186 /* This is an error even in the 'check' case because the code just
4187 * consumed a non-IDAT header.
4189 if (png_ptr->chunk_name != png_IDAT)
4190 png_error(png_ptr, "Not enough image data");
4193 avail_in = png_ptr->IDAT_read_size;
4195 if (avail_in > png_ptr->idat_size)
4196 avail_in = (uInt)png_ptr->idat_size;
4198 /* A PNG with a gradually increasing IDAT size will defeat this attempt
4199 * to minimize memory usage by causing lots of re-allocs, but
4200 * realistically doing IDAT_read_size re-allocs is not likely to be a
4203 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
4205 png_crc_read(png_ptr, buffer, avail_in);
4206 png_ptr->idat_size -= avail_in;
4208 png_ptr->zstream.next_in = buffer;
4209 png_ptr->zstream.avail_in = avail_in;
4212 /* And set up the output side. */
4213 if (output != NULL) /* standard read */
4215 uInt out = ZLIB_IO_MAX;
4217 if (out > avail_out)
4218 out = (uInt)avail_out;
4221 png_ptr->zstream.avail_out = out;
4224 else /* after last row, checking for end */
4226 png_ptr->zstream.next_out = tmpbuf;
4227 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4230 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4231 * process. If the LZ stream is truncated the sequential reader will
4232 * terminally damage the stream, above, by reading the chunk header of the
4233 * following chunk (it then exits with png_error).
4235 * TODO: deal more elegantly with truncated IDAT lists.
4237 ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);
4239 /* Take the unconsumed output back. */
4241 avail_out += png_ptr->zstream.avail_out;
4243 else /* avail_out counts the extra bytes */
4244 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4246 png_ptr->zstream.avail_out = 0;
4248 if (ret == Z_STREAM_END)
4250 /* Do this for safety; we won't read any more into this row. */
4251 png_ptr->zstream.next_out = NULL;
4253 png_ptr->mode |= PNG_AFTER_IDAT;
4254 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4256 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4257 png_chunk_benign_error(png_ptr, "Extra compressed data");
4263 png_zstream_error(png_ptr, ret);
4266 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4270 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4274 } while (avail_out > 0);
4278 /* The stream ended before the image; this is the same as too few IDATs so
4279 * should be handled the same way.
4282 png_error(png_ptr, "Not enough image data");
4284 else /* the deflate stream contained extra data */
4285 png_chunk_benign_error(png_ptr, "Too much image data");
4290 png_read_finish_IDAT(png_structrp png_ptr)
4292 /* We don't need any more data and the stream should have ended, however the
4293 * LZ end code may actually not have been processed. In this case we must
4294 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4295 * may still remain to be consumed.
4297 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4299 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4300 * the compressed stream, but the stream may be damaged too, so even after
4301 * this call we may need to terminate the zstream ownership.
4303 png_read_IDAT_data(png_ptr, NULL, 0);
4304 png_ptr->zstream.next_out = NULL; /* safety */
4306 /* Now clear everything out for safety; the following may not have been
4309 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4311 png_ptr->mode |= PNG_AFTER_IDAT;
4312 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4316 /* If the zstream has not been released do it now *and* terminate the reading
4317 * of the final IDAT chunk.
4319 if (png_ptr->zowner == png_IDAT)
4321 /* Always do this; the pointers otherwise point into the read buffer. */
4322 png_ptr->zstream.next_in = NULL;
4323 png_ptr->zstream.avail_in = 0;
4325 /* Now we no longer own the zstream. */
4326 png_ptr->zowner = 0;
4328 /* The slightly weird semantics of the sequential IDAT reading is that we
4329 * are always in or at the end of an IDAT chunk, so we always need to do a
4330 * crc_finish here. If idat_size is non-zero we also need to read the
4331 * spurious bytes at the end of the chunk now.
4333 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4338 png_read_finish_row(png_structrp png_ptr)
4340 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4342 /* Start of interlace block */
4343 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4345 /* Offset to next interlace block */
4346 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4348 /* Start of interlace block in the y direction */
4349 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4351 /* Offset to next interlace block in the y direction */
4352 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4354 png_debug(1, "in png_read_finish_row");
4355 png_ptr->row_number++;
4356 if (png_ptr->row_number < png_ptr->num_rows)
4359 if (png_ptr->interlaced != 0)
4361 png_ptr->row_number = 0;
4363 /* TO DO: don't do this if prev_row isn't needed (requires
4364 * read-ahead of the next row's filter byte.
4366 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4372 if (png_ptr->pass >= 7)
4375 png_ptr->iwidth = (png_ptr->width +
4376 png_pass_inc[png_ptr->pass] - 1 -
4377 png_pass_start[png_ptr->pass]) /
4378 png_pass_inc[png_ptr->pass];
4380 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4382 png_ptr->num_rows = (png_ptr->height +
4383 png_pass_yinc[png_ptr->pass] - 1 -
4384 png_pass_ystart[png_ptr->pass]) /
4385 png_pass_yinc[png_ptr->pass];
4388 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4389 break; /* libpng deinterlacing sees every row */
4391 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4393 if (png_ptr->pass < 7)
4397 /* Here after at the end of the last row of the last pass. */
4398 png_read_finish_IDAT(png_ptr);
4400 #endif /* SEQUENTIAL_READ */
4403 png_read_start_row(png_structrp png_ptr)
4405 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4407 /* Start of interlace block */
4408 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4410 /* Offset to next interlace block */
4411 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4413 /* Start of interlace block in the y direction */
4414 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4416 /* Offset to next interlace block in the y direction */
4417 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4419 int max_pixel_depth;
4420 png_size_t row_bytes;
4422 png_debug(1, "in png_read_start_row");
4424 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4425 png_init_read_transformations(png_ptr);
4427 if (png_ptr->interlaced != 0)
4429 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4430 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4431 png_pass_ystart[0]) / png_pass_yinc[0];
4434 png_ptr->num_rows = png_ptr->height;
4436 png_ptr->iwidth = (png_ptr->width +
4437 png_pass_inc[png_ptr->pass] - 1 -
4438 png_pass_start[png_ptr->pass]) /
4439 png_pass_inc[png_ptr->pass];
4444 png_ptr->num_rows = png_ptr->height;
4445 png_ptr->iwidth = png_ptr->width;
4448 max_pixel_depth = png_ptr->pixel_depth;
4450 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4451 * calculations to calculate the final pixel depth, then
4452 * png_do_read_transforms actually does the transforms. This means that the
4453 * code which effectively calculates this value is actually repeated in three
4454 * separate places. They must all match. Innocent changes to the order of
4455 * transformations can and will break libpng in a way that causes memory
4460 #ifdef PNG_READ_PACK_SUPPORTED
4461 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4462 max_pixel_depth = 8;
4465 #ifdef PNG_READ_EXPAND_SUPPORTED
4466 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4468 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4470 if (png_ptr->num_trans != 0)
4471 max_pixel_depth = 32;
4474 max_pixel_depth = 24;
4477 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4479 if (max_pixel_depth < 8)
4480 max_pixel_depth = 8;
4482 if (png_ptr->num_trans != 0)
4483 max_pixel_depth *= 2;
4486 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4488 if (png_ptr->num_trans != 0)
4490 max_pixel_depth *= 4;
4491 max_pixel_depth /= 3;
4497 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4498 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4500 # ifdef PNG_READ_EXPAND_SUPPORTED
4501 /* In fact it is an error if it isn't supported, but checking is
4504 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4506 if (png_ptr->bit_depth < 16)
4507 max_pixel_depth *= 2;
4511 png_ptr->transformations &= ~PNG_EXPAND_16;
4515 #ifdef PNG_READ_FILLER_SUPPORTED
4516 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4518 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4520 if (max_pixel_depth <= 8)
4521 max_pixel_depth = 16;
4524 max_pixel_depth = 32;
4527 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4528 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4530 if (max_pixel_depth <= 32)
4531 max_pixel_depth = 32;
4534 max_pixel_depth = 64;
4539 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4540 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4543 #ifdef PNG_READ_EXPAND_SUPPORTED
4544 (png_ptr->num_trans != 0 &&
4545 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4547 #ifdef PNG_READ_FILLER_SUPPORTED
4548 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4550 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4552 if (max_pixel_depth <= 16)
4553 max_pixel_depth = 32;
4556 max_pixel_depth = 64;
4561 if (max_pixel_depth <= 8)
4563 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4564 max_pixel_depth = 32;
4567 max_pixel_depth = 24;
4570 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4571 max_pixel_depth = 64;
4574 max_pixel_depth = 48;
4579 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4580 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4581 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4583 int user_pixel_depth = png_ptr->user_transform_depth *
4584 png_ptr->user_transform_channels;
4586 if (user_pixel_depth > max_pixel_depth)
4587 max_pixel_depth = user_pixel_depth;
4591 /* This value is stored in png_struct and double checked in the row read
4594 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4595 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4597 /* Align the width on the next larger 8 pixels. Mainly used
4600 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4601 /* Calculate the maximum bytes needed, adding a byte and a pixel
4604 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4605 1 + ((max_pixel_depth + 7) >> 3);
4607 #ifdef PNG_MAX_MALLOC_64K
4608 if (row_bytes > (png_uint_32)65536L)
4609 png_error(png_ptr, "This image requires a row greater than 64KB");
4612 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4614 png_free(png_ptr, png_ptr->big_row_buf);
4615 png_free(png_ptr, png_ptr->big_prev_row);
4617 if (png_ptr->interlaced != 0)
4618 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4622 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4624 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4626 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4627 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4628 * of padding before and after row_buf; treat prev_row similarly.
4629 * NOTE: the alignment is to the start of the pixels, one beyond the start
4630 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4631 * was incorrect; the filter byte was aligned, which had the exact
4632 * opposite effect of that intended.
4635 png_bytep temp = png_ptr->big_row_buf + 32;
4636 int extra = (int)((temp - (png_bytep)0) & 0x0f);
4637 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4639 temp = png_ptr->big_prev_row + 32;
4640 extra = (int)((temp - (png_bytep)0) & 0x0f);
4641 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4645 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4646 png_ptr->row_buf = png_ptr->big_row_buf + 31;
4647 png_ptr->prev_row = png_ptr->big_prev_row + 31;
4649 png_ptr->old_big_row_buf_size = row_bytes + 48;
4652 #ifdef PNG_MAX_MALLOC_64K
4653 if (png_ptr->rowbytes > 65535)
4654 png_error(png_ptr, "This image requires a row greater than 64KB");
4657 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4658 png_error(png_ptr, "Row has too many bytes to allocate in memory");
4660 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4662 png_debug1(3, "width = %u,", png_ptr->width);
4663 png_debug1(3, "height = %u,", png_ptr->height);
4664 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4665 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4666 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4667 png_debug1(3, "irowbytes = %lu",
4668 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4670 /* The sequential reader needs a buffer for IDAT, but the progressive reader
4671 * does not, so free the read buffer now regardless; the sequential reader
4672 * reallocates it on demand.
4674 if (png_ptr->read_buffer != 0)
4676 png_bytep buffer = png_ptr->read_buffer;
4678 png_ptr->read_buffer_size = 0;
4679 png_ptr->read_buffer = NULL;
4680 png_free(png_ptr, buffer);
4683 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4684 * value from the stream (note that this will result in a fatal error if the
4685 * IDAT stream has a bogus deflate header window_bits value, but this should
4686 * not be happening any longer!)
4688 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4689 png_error(png_ptr, png_ptr->zstream.msg);
4691 png_ptr->flags |= PNG_FLAG_ROW_INIT;