2 /* pngrutil.c - utilities to read a PNG file
4 * Copyright (c) 2018-2022 Cosmin Truta
5 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6 * Copyright (c) 1996-1997 Andreas Dilger
7 * 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 */
92 return (png_int_32)uval;
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 accommodate 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 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 /* Check for too-large chunk length */
188 png_check_chunk_length(png_ptr, length);
190 #ifdef PNG_IO_STATE_SUPPORTED
191 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
197 /* Read data, and (optionally) run it through the CRC. */
199 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
204 png_read_data(png_ptr, buf, length);
205 png_calculate_crc(png_ptr, buf, length);
208 /* Optionally skip data and then check the CRC. Depending on whether we
209 * are reading an ancillary or critical chunk, and how the program has set
210 * things up, we may calculate the CRC on the data and print a message.
211 * Returns '1' if there was a CRC error, '0' otherwise.
214 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
216 /* The size of the local buffer for inflate is a good guess as to a
217 * reasonable size to use for buffering reads from the application.
222 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
224 len = (sizeof tmpbuf);
229 png_crc_read(png_ptr, tmpbuf, len);
232 if (png_crc_error(png_ptr) != 0)
234 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
235 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
236 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
238 png_chunk_warning(png_ptr, "CRC error");
242 png_chunk_error(png_ptr, "CRC error");
250 /* Compare the CRC stored in the PNG file with that calculated by libpng from
251 * the data it has read thus far.
254 png_crc_error(png_structrp png_ptr)
256 png_byte crc_bytes[4];
260 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
262 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
263 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
269 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
273 #ifdef PNG_IO_STATE_SUPPORTED
274 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
277 /* The chunk CRC must be serialized in a single I/O call. */
278 png_read_data(png_ptr, crc_bytes, 4);
282 crc = png_get_uint_32(crc_bytes);
283 return ((int)(crc != png_ptr->crc));
290 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
291 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
292 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
293 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
294 /* Manage the read buffer; this simply reallocates the buffer if it is not small
295 * enough (or if it is not allocated). The routine returns a pointer to the
296 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
297 * it will call png_error (via png_malloc) on failure. (warn == 2 means
301 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
303 png_bytep buffer = png_ptr->read_buffer;
305 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
307 png_ptr->read_buffer = NULL;
308 png_ptr->read_buffer_size = 0;
309 png_free(png_ptr, buffer);
315 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
319 memset(buffer, 0, new_size); /* just in case */
320 png_ptr->read_buffer = buffer;
321 png_ptr->read_buffer_size = new_size;
324 else if (warn < 2) /* else silent */
327 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
330 png_chunk_error(png_ptr, "insufficient memory to read chunk");
336 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
338 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
339 * decompression. Returns Z_OK on success, else a zlib error code. It checks
340 * the owner but, in final release builds, just issues a warning if some other
341 * chunk apparently owns the stream. Prior to release it does a png_error.
344 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
346 if (png_ptr->zowner != 0)
350 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
351 /* So the message that results is "<chunk> using zstream"; this is an
352 * internal error, but is very useful for debugging. i18n requirements
355 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
356 #if PNG_RELEASE_BUILD
357 png_chunk_warning(png_ptr, msg);
360 png_chunk_error(png_ptr, msg);
364 /* Implementation note: unlike 'png_deflate_claim' this internal function
365 * does not take the size of the data as an argument. Some efficiency could
366 * be gained by using this when it is known *if* the zlib stream itself does
367 * not record the number; however, this is an illusion: the original writer
368 * of the PNG may have selected a lower window size, and we really must
369 * follow that because, for systems with with limited capabilities, we
370 * would otherwise reject the application's attempts to use a smaller window
371 * size (zlib doesn't have an interface to say "this or lower"!).
373 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
374 * reset, therefore it is necessary to always allocate the maximum window
375 * size with earlier zlibs just in case later compressed chunks need it.
378 int ret; /* zlib return code */
379 #if ZLIB_VERNUM >= 0x1240
382 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
383 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
387 png_ptr->zstream_start = 0; /* fixed window size */
392 png_ptr->zstream_start = 1;
396 #endif /* ZLIB_VERNUM >= 0x1240 */
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 ZLIB_VERNUM >= 0x1240
409 ret = inflateReset2(&png_ptr->zstream, window_bits);
411 ret = inflateReset(&png_ptr->zstream);
417 #if ZLIB_VERNUM >= 0x1240
418 ret = inflateInit2(&png_ptr->zstream, window_bits);
420 ret = inflateInit(&png_ptr->zstream);
424 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
427 #if ZLIB_VERNUM >= 0x1290 && \
428 defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32)
429 if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
430 /* Turn off validation of the ADLER32 checksum in IDAT chunks */
431 ret = inflateValidate(&png_ptr->zstream, 0);
435 png_ptr->zowner = owner;
438 png_zstream_error(png_ptr, ret);
448 #if ZLIB_VERNUM >= 0x1240
449 /* Handle the start of the inflate stream if we called inflateInit2(strm,0);
450 * in this case some zlib versions skip validation of the CINFO field and, in
451 * certain circumstances, libpng may end up displaying an invalid image, in
452 * contrast to implementations that call zlib in the normal way (e.g. libpng
456 png_zlib_inflate(png_structrp png_ptr, int flush)
458 if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0)
460 if ((*png_ptr->zstream.next_in >> 4) > 7)
462 png_ptr->zstream.msg = "invalid window size (libpng)";
466 png_ptr->zstream_start = 0;
469 return inflate(&png_ptr->zstream, flush);
471 #endif /* Zlib >= 1.2.4 */
473 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
474 #if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED)
475 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
476 * allow the caller to do multiple calls if required. If the 'finish' flag is
477 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
478 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
479 * Z_OK or Z_STREAM_END will be returned on success.
481 * The input and output sizes are updated to the actual amounts of data consumed
482 * or written, not the amount available (as in a z_stream). The data pointers
483 * are not changed, so the next input is (data+input_size) and the next
484 * available output is (output+output_size).
487 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
488 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
489 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
491 if (png_ptr->zowner == owner) /* Else not claimed */
494 png_alloc_size_t avail_out = *output_size_ptr;
495 png_uint_32 avail_in = *input_size_ptr;
497 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
498 * can't even necessarily handle 65536 bytes) because the type uInt is
499 * "16 bits or more". Consequently it is necessary to chunk the input to
500 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
501 * maximum value that can be stored in a uInt.) It is possible to set
502 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
503 * a performance advantage, because it reduces the amount of data accessed
504 * at each step and that may give the OS more time to page it in.
506 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
507 /* avail_in and avail_out are set below from 'size' */
508 png_ptr->zstream.avail_in = 0;
509 png_ptr->zstream.avail_out = 0;
511 /* Read directly into the output if it is available (this is set to
512 * a local buffer below if output is NULL).
515 png_ptr->zstream.next_out = output;
520 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
522 /* zlib INPUT BUFFER */
523 /* The setting of 'avail_in' used to be outside the loop; by setting it
524 * inside it is possible to chunk the input to zlib and simply rely on
525 * zlib to advance the 'next_in' pointer. This allows arbitrary
526 * amounts of data to be passed through zlib at the unavoidable cost of
527 * requiring a window save (memcpy of up to 32768 output bytes)
528 * every ZLIB_IO_MAX input bytes.
530 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
534 if (avail_in < avail)
535 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
538 png_ptr->zstream.avail_in = avail;
540 /* zlib OUTPUT BUFFER */
541 avail_out += png_ptr->zstream.avail_out; /* not written last time */
543 avail = ZLIB_IO_MAX; /* maximum zlib can process */
547 /* Reset the output buffer each time round if output is NULL and
548 * make available the full buffer, up to 'remaining_space'
550 png_ptr->zstream.next_out = local_buffer;
551 if ((sizeof local_buffer) < avail)
552 avail = (sizeof local_buffer);
555 if (avail_out < avail)
556 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
558 png_ptr->zstream.avail_out = avail;
561 /* zlib inflate call */
562 /* In fact 'avail_out' may be 0 at this point, that happens at the end
563 * of the read when the final LZ end code was not passed at the end of
564 * the previous chunk of input data. Tell zlib if we have reached the
565 * end of the output buffer.
567 ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH :
568 (finish ? Z_FINISH : Z_SYNC_FLUSH));
569 } while (ret == Z_OK);
571 /* For safety kill the local buffer pointer now */
573 png_ptr->zstream.next_out = NULL;
575 /* Claw back the 'size' and 'remaining_space' byte counts. */
576 avail_in += png_ptr->zstream.avail_in;
577 avail_out += png_ptr->zstream.avail_out;
579 /* Update the input and output sizes; the updated values are the amount
580 * consumed or written, effectively the inverse of what zlib uses.
583 *output_size_ptr -= avail_out;
586 *input_size_ptr -= avail_in;
588 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
589 png_zstream_error(png_ptr, ret);
595 /* This is a bad internal error. The recovery assigns to the zstream msg
596 * pointer, which is not owned by the caller, but this is safe; it's only
599 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
600 return Z_STREAM_ERROR;
605 * Decompress trailing data in a chunk. The assumption is that read_buffer
606 * points at an allocated area holding the contents of a chunk with a
607 * trailing compressed part. What we get back is an allocated area
608 * holding the original prefix part and an uncompressed version of the
609 * trailing part (the malloc area passed in is freed).
612 png_decompress_chunk(png_structrp png_ptr,
613 png_uint_32 chunklength, png_uint_32 prefix_size,
614 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
615 int terminate /*add a '\0' to the end of the uncompressed data*/)
617 /* TODO: implement different limits for different types of chunk.
619 * The caller supplies *newlength set to the maximum length of the
620 * uncompressed data, but this routine allocates space for the prefix and
621 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
622 * limited only by the maximum chunk size.
624 png_alloc_size_t limit = PNG_SIZE_MAX;
626 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
627 if (png_ptr->user_chunk_malloc_max > 0 &&
628 png_ptr->user_chunk_malloc_max < limit)
629 limit = png_ptr->user_chunk_malloc_max;
630 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
631 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
632 limit = PNG_USER_CHUNK_MALLOC_MAX;
635 if (limit >= prefix_size + (terminate != 0))
639 limit -= prefix_size + (terminate != 0);
641 if (limit < *newlength)
644 /* Now try to claim the stream. */
645 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
649 png_uint_32 lzsize = chunklength - prefix_size;
651 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
652 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
653 /* output: */ NULL, newlength);
655 if (ret == Z_STREAM_END)
657 /* Use 'inflateReset' here, not 'inflateReset2' because this
658 * preserves the previously decided window size (otherwise it would
659 * be necessary to store the previous window size.) In practice
660 * this doesn't matter anyway, because png_inflate will call inflate
661 * with Z_FINISH in almost all cases, so the window will not be
664 if (inflateReset(&png_ptr->zstream) == Z_OK)
666 /* Because of the limit checks above we know that the new,
667 * expanded, size will fit in a size_t (let alone an
668 * png_alloc_size_t). Use png_malloc_base here to avoid an
671 png_alloc_size_t new_size = *newlength;
672 png_alloc_size_t buffer_size = prefix_size + new_size +
674 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
679 memset(text, 0, buffer_size);
681 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
682 png_ptr->read_buffer + prefix_size, &lzsize,
683 text + prefix_size, newlength);
685 if (ret == Z_STREAM_END)
687 if (new_size == *newlength)
690 text[prefix_size + *newlength] = 0;
693 memcpy(text, png_ptr->read_buffer, prefix_size);
696 png_bytep old_ptr = png_ptr->read_buffer;
698 png_ptr->read_buffer = text;
699 png_ptr->read_buffer_size = buffer_size;
700 text = old_ptr; /* freed below */
706 /* The size changed on the second read, there can be no
707 * guarantee that anything is correct at this point.
708 * The 'msg' pointer has been set to "unexpected end of
709 * LZ stream", which is fine, but return an error code
710 * that the caller won't accept.
712 ret = PNG_UNEXPECTED_ZLIB_RETURN;
716 else if (ret == Z_OK)
717 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
719 /* Free the text pointer (this is the old read_buffer on
722 png_free(png_ptr, text);
724 /* This really is very benign, but it's still an error because
725 * the extra space may otherwise be used as a Trojan Horse.
727 if (ret == Z_STREAM_END &&
728 chunklength - prefix_size != lzsize)
729 png_chunk_benign_error(png_ptr, "extra compressed data");
734 /* Out of memory allocating the buffer */
736 png_zstream_error(png_ptr, Z_MEM_ERROR);
742 /* inflateReset failed, store the error message */
743 png_zstream_error(png_ptr, ret);
744 ret = PNG_UNEXPECTED_ZLIB_RETURN;
748 else if (ret == Z_OK)
749 ret = PNG_UNEXPECTED_ZLIB_RETURN;
751 /* Release the claimed stream */
755 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
756 ret = PNG_UNEXPECTED_ZLIB_RETURN;
763 /* Application/configuration limits exceeded */
764 png_zstream_error(png_ptr, Z_MEM_ERROR);
768 #endif /* READ_zTXt || READ_iTXt */
769 #endif /* READ_COMPRESSED_TEXT */
771 #ifdef PNG_READ_iCCP_SUPPORTED
772 /* Perform a partial read and decompress, producing 'avail_out' bytes and
773 * reading from the current chunk as required.
776 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
777 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
780 if (png_ptr->zowner == png_ptr->chunk_name)
784 /* next_in and avail_in must have been initialized by the caller. */
785 png_ptr->zstream.next_out = next_out;
786 png_ptr->zstream.avail_out = 0; /* set in the loop */
790 if (png_ptr->zstream.avail_in == 0)
792 if (read_size > *chunk_bytes)
793 read_size = (uInt)*chunk_bytes;
794 *chunk_bytes -= read_size;
797 png_crc_read(png_ptr, read_buffer, read_size);
799 png_ptr->zstream.next_in = read_buffer;
800 png_ptr->zstream.avail_in = read_size;
803 if (png_ptr->zstream.avail_out == 0)
805 uInt avail = ZLIB_IO_MAX;
806 if (avail > *out_size)
807 avail = (uInt)*out_size;
810 png_ptr->zstream.avail_out = avail;
813 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
814 * the available output is produced; this allows reading of truncated
817 ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ?
818 Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
820 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
822 *out_size += png_ptr->zstream.avail_out;
823 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
825 /* Ensure the error message pointer is always set: */
826 png_zstream_error(png_ptr, ret);
832 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
833 return Z_STREAM_ERROR;
836 #endif /* READ_iCCP */
838 /* Read and check the IDHR chunk */
841 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
844 png_uint_32 width, height;
845 int bit_depth, color_type, compression_type, filter_type;
848 png_debug(1, "in png_handle_IHDR");
850 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
851 png_chunk_error(png_ptr, "out of place");
853 /* Check the length */
855 png_chunk_error(png_ptr, "invalid");
857 png_ptr->mode |= PNG_HAVE_IHDR;
859 png_crc_read(png_ptr, buf, 13);
860 png_crc_finish(png_ptr, 0);
862 width = png_get_uint_31(png_ptr, buf);
863 height = png_get_uint_31(png_ptr, buf + 4);
866 compression_type = buf[10];
867 filter_type = buf[11];
868 interlace_type = buf[12];
870 #ifdef PNG_READ_APNG_SUPPORTED
871 png_ptr->first_frame_width = width;
872 png_ptr->first_frame_height = height;
875 /* Set internal variables */
876 png_ptr->width = width;
877 png_ptr->height = height;
878 png_ptr->bit_depth = (png_byte)bit_depth;
879 png_ptr->interlaced = (png_byte)interlace_type;
880 png_ptr->color_type = (png_byte)color_type;
881 #ifdef PNG_MNG_FEATURES_SUPPORTED
882 png_ptr->filter_type = (png_byte)filter_type;
884 png_ptr->compression_type = (png_byte)compression_type;
886 /* Find number of channels */
887 switch (png_ptr->color_type)
889 default: /* invalid, png_set_IHDR calls png_error */
890 case PNG_COLOR_TYPE_GRAY:
891 case PNG_COLOR_TYPE_PALETTE:
892 png_ptr->channels = 1;
895 case PNG_COLOR_TYPE_RGB:
896 png_ptr->channels = 3;
899 case PNG_COLOR_TYPE_GRAY_ALPHA:
900 png_ptr->channels = 2;
903 case PNG_COLOR_TYPE_RGB_ALPHA:
904 png_ptr->channels = 4;
908 /* Set up other useful info */
909 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
910 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
911 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
912 png_debug1(3, "channels = %d", png_ptr->channels);
913 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
914 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
915 color_type, interlace_type, compression_type, filter_type);
918 /* Read and check the palette */
920 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
922 png_color palette[PNG_MAX_PALETTE_LENGTH];
923 int max_palette_length, num, i;
924 #ifdef PNG_POINTER_INDEXING_SUPPORTED
928 png_debug(1, "in png_handle_PLTE");
930 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
931 png_chunk_error(png_ptr, "missing IHDR");
933 /* Moved to before the 'after IDAT' check below because otherwise duplicate
934 * PLTE chunks are potentially ignored (the spec says there shall not be more
935 * than one PLTE, the error is not treated as benign, so this check trumps
936 * the requirement that PLTE appears before IDAT.)
938 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
939 png_chunk_error(png_ptr, "duplicate");
941 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
943 /* This is benign because the non-benign error happened before, when an
944 * IDAT was encountered in a color-mapped image with no PLTE.
946 png_crc_finish(png_ptr, length);
947 png_chunk_benign_error(png_ptr, "out of place");
951 png_ptr->mode |= PNG_HAVE_PLTE;
953 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
955 png_crc_finish(png_ptr, length);
956 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
960 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
961 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
963 png_crc_finish(png_ptr, length);
968 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
970 png_crc_finish(png_ptr, length);
972 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
973 png_chunk_benign_error(png_ptr, "invalid");
976 png_chunk_error(png_ptr, "invalid");
981 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
982 num = (int)length / 3;
984 /* If the palette has 256 or fewer entries but is too large for the bit
985 * depth, we don't issue an error, to preserve the behavior of previous
986 * libpng versions. We silently truncate the unused extra palette entries
989 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
990 max_palette_length = (1 << png_ptr->bit_depth);
992 max_palette_length = PNG_MAX_PALETTE_LENGTH;
994 if (num > max_palette_length)
995 num = max_palette_length;
997 #ifdef PNG_POINTER_INDEXING_SUPPORTED
998 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
1002 png_crc_read(png_ptr, buf, 3);
1003 pal_ptr->red = buf[0];
1004 pal_ptr->green = buf[1];
1005 pal_ptr->blue = buf[2];
1008 for (i = 0; i < num; i++)
1012 png_crc_read(png_ptr, buf, 3);
1013 /* Don't depend upon png_color being any order */
1014 palette[i].red = buf[0];
1015 palette[i].green = buf[1];
1016 palette[i].blue = buf[2];
1020 /* If we actually need the PLTE chunk (ie for a paletted image), we do
1021 * whatever the normal CRC configuration tells us. However, if we
1022 * have an RGB image, the PLTE can be considered ancillary, so
1023 * we will act as though it is.
1025 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1026 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1029 png_crc_finish(png_ptr, (png_uint_32) (length - (unsigned int)num * 3));
1032 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1033 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
1035 /* If we don't want to use the data from an ancillary chunk,
1036 * we have two options: an error abort, or a warning and we
1037 * ignore the data in this chunk (which should be OK, since
1038 * it's considered ancillary for a RGB or RGBA image).
1040 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
1041 * chunk type to determine whether to check the ancillary or the critical
1044 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
1046 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
1050 png_chunk_error(png_ptr, "CRC error");
1053 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1054 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1055 png_chunk_warning(png_ptr, "CRC error");
1059 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1060 * own copy of the palette. This has the side effect that when png_start_row
1061 * is called (this happens after any call to png_read_update_info) the
1062 * info_ptr palette gets changed. This is extremely unexpected and
1065 * Fix this by not sharing the palette in this way.
1067 png_set_PLTE(png_ptr, info_ptr, palette, num);
1069 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1070 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1071 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1072 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1073 * therefore does a benign error if the erroneous condition is detected *and*
1074 * cancels the tRNS if the benign error returns. The alternative is to
1075 * amend the standard since it would be rather hypocritical of the standards
1076 * maintainers to ignore it.
1078 #ifdef PNG_READ_tRNS_SUPPORTED
1079 if (png_ptr->num_trans > 0 ||
1080 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1082 /* Cancel this because otherwise it would be used if the transforms
1083 * require it. Don't cancel the 'valid' flag because this would prevent
1084 * detection of duplicate chunks.
1086 png_ptr->num_trans = 0;
1088 if (info_ptr != NULL)
1089 info_ptr->num_trans = 0;
1091 png_chunk_benign_error(png_ptr, "tRNS must be after");
1095 #ifdef PNG_READ_hIST_SUPPORTED
1096 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1097 png_chunk_benign_error(png_ptr, "hIST must be after");
1100 #ifdef PNG_READ_bKGD_SUPPORTED
1101 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1102 png_chunk_benign_error(png_ptr, "bKGD must be after");
1107 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1109 png_debug(1, "in png_handle_IEND");
1111 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1112 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1113 png_chunk_error(png_ptr, "out of place");
1115 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1117 png_crc_finish(png_ptr, length);
1120 png_chunk_benign_error(png_ptr, "invalid");
1122 PNG_UNUSED(info_ptr)
1125 #ifdef PNG_READ_gAMA_SUPPORTED
1127 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1129 png_fixed_point igamma;
1132 png_debug(1, "in png_handle_gAMA");
1134 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1135 png_chunk_error(png_ptr, "missing IHDR");
1137 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1139 png_crc_finish(png_ptr, length);
1140 png_chunk_benign_error(png_ptr, "out of place");
1146 png_crc_finish(png_ptr, length);
1147 png_chunk_benign_error(png_ptr, "invalid");
1151 png_crc_read(png_ptr, buf, 4);
1153 if (png_crc_finish(png_ptr, 0) != 0)
1156 igamma = png_get_fixed_point(NULL, buf);
1158 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1159 png_colorspace_sync(png_ptr, info_ptr);
1163 #ifdef PNG_READ_sBIT_SUPPORTED
1165 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1167 unsigned int truelen, i;
1168 png_byte sample_depth;
1171 png_debug(1, "in png_handle_sBIT");
1173 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1174 png_chunk_error(png_ptr, "missing IHDR");
1176 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1178 png_crc_finish(png_ptr, length);
1179 png_chunk_benign_error(png_ptr, "out of place");
1183 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1185 png_crc_finish(png_ptr, length);
1186 png_chunk_benign_error(png_ptr, "duplicate");
1190 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1198 truelen = png_ptr->channels;
1199 sample_depth = png_ptr->bit_depth;
1202 if (length != truelen || length > 4)
1204 png_chunk_benign_error(png_ptr, "invalid");
1205 png_crc_finish(png_ptr, length);
1209 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1210 png_crc_read(png_ptr, buf, truelen);
1212 if (png_crc_finish(png_ptr, 0) != 0)
1215 for (i=0; i<truelen; ++i)
1217 if (buf[i] == 0 || buf[i] > sample_depth)
1219 png_chunk_benign_error(png_ptr, "invalid");
1224 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1226 png_ptr->sig_bit.red = buf[0];
1227 png_ptr->sig_bit.green = buf[1];
1228 png_ptr->sig_bit.blue = buf[2];
1229 png_ptr->sig_bit.alpha = buf[3];
1234 png_ptr->sig_bit.gray = buf[0];
1235 png_ptr->sig_bit.red = buf[0];
1236 png_ptr->sig_bit.green = buf[0];
1237 png_ptr->sig_bit.blue = buf[0];
1238 png_ptr->sig_bit.alpha = buf[1];
1241 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1245 #ifdef PNG_READ_cHRM_SUPPORTED
1247 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1252 png_debug(1, "in png_handle_cHRM");
1254 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1255 png_chunk_error(png_ptr, "missing IHDR");
1257 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1259 png_crc_finish(png_ptr, length);
1260 png_chunk_benign_error(png_ptr, "out of place");
1266 png_crc_finish(png_ptr, length);
1267 png_chunk_benign_error(png_ptr, "invalid");
1271 png_crc_read(png_ptr, buf, 32);
1273 if (png_crc_finish(png_ptr, 0) != 0)
1276 xy.whitex = png_get_fixed_point(NULL, buf);
1277 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1278 xy.redx = png_get_fixed_point(NULL, buf + 8);
1279 xy.redy = png_get_fixed_point(NULL, buf + 12);
1280 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1281 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1282 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1283 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1285 if (xy.whitex == PNG_FIXED_ERROR ||
1286 xy.whitey == PNG_FIXED_ERROR ||
1287 xy.redx == PNG_FIXED_ERROR ||
1288 xy.redy == PNG_FIXED_ERROR ||
1289 xy.greenx == PNG_FIXED_ERROR ||
1290 xy.greeny == PNG_FIXED_ERROR ||
1291 xy.bluex == PNG_FIXED_ERROR ||
1292 xy.bluey == PNG_FIXED_ERROR)
1294 png_chunk_benign_error(png_ptr, "invalid values");
1298 /* If a colorspace error has already been output skip this chunk */
1299 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1302 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1304 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1305 png_colorspace_sync(png_ptr, info_ptr);
1306 png_chunk_benign_error(png_ptr, "duplicate");
1310 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1311 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1312 1/*prefer cHRM values*/);
1313 png_colorspace_sync(png_ptr, info_ptr);
1317 #ifdef PNG_READ_sRGB_SUPPORTED
1319 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1323 png_debug(1, "in png_handle_sRGB");
1325 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1326 png_chunk_error(png_ptr, "missing IHDR");
1328 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1330 png_crc_finish(png_ptr, length);
1331 png_chunk_benign_error(png_ptr, "out of place");
1337 png_crc_finish(png_ptr, length);
1338 png_chunk_benign_error(png_ptr, "invalid");
1342 png_crc_read(png_ptr, &intent, 1);
1344 if (png_crc_finish(png_ptr, 0) != 0)
1347 /* If a colorspace error has already been output skip this chunk */
1348 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1351 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1354 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1356 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1357 png_colorspace_sync(png_ptr, info_ptr);
1358 png_chunk_benign_error(png_ptr, "too many profiles");
1362 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1363 png_colorspace_sync(png_ptr, info_ptr);
1365 #endif /* READ_sRGB */
1367 #ifdef PNG_READ_iCCP_SUPPORTED
1369 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1370 /* Note: this does not properly handle profiles that are > 64K under DOS */
1372 png_const_charp errmsg = NULL; /* error message output, or no error */
1373 int finished = 0; /* crc checked */
1375 png_debug(1, "in png_handle_iCCP");
1377 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1378 png_chunk_error(png_ptr, "missing IHDR");
1380 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1382 png_crc_finish(png_ptr, length);
1383 png_chunk_benign_error(png_ptr, "out of place");
1387 /* Consistent with all the above colorspace handling an obviously *invalid*
1388 * chunk is just ignored, so does not invalidate the color space. An
1389 * alternative is to set the 'invalid' flags at the start of this routine
1390 * and only clear them in they were not set before and all the tests pass.
1393 /* The keyword must be at least one character and there is a
1394 * terminator (0) byte and the compression method byte, and the
1395 * 'zlib' datastream is at least 11 bytes.
1399 png_crc_finish(png_ptr, length);
1400 png_chunk_benign_error(png_ptr, "too short");
1404 /* If a colorspace error has already been output skip this chunk */
1405 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1407 png_crc_finish(png_ptr, length);
1411 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1414 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1416 uInt read_length, keyword_length;
1419 /* Find the keyword; the keyword plus separator and compression method
1420 * bytes can be at most 81 characters long.
1422 read_length = 81; /* maximum */
1423 if (read_length > length)
1424 read_length = (uInt)length;
1426 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1427 length -= read_length;
1429 /* The minimum 'zlib' stream is assumed to be just the 2 byte header,
1430 * 5 bytes minimum 'deflate' stream, and the 4 byte checksum.
1434 png_crc_finish(png_ptr, length);
1435 png_chunk_benign_error(png_ptr, "too short");
1440 while (keyword_length < 80 && keyword_length < read_length &&
1441 keyword[keyword_length] != 0)
1444 /* TODO: make the keyword checking common */
1445 if (keyword_length >= 1 && keyword_length <= 79)
1447 /* We only understand '0' compression - deflate - so if we get a
1448 * different value we can't safely decode the chunk.
1450 if (keyword_length+1 < read_length &&
1451 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1453 read_length -= keyword_length+2;
1455 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1457 Byte profile_header[132]={0};
1458 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1459 png_alloc_size_t size = (sizeof profile_header);
1461 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1462 png_ptr->zstream.avail_in = read_length;
1463 (void)png_inflate_read(png_ptr, local_buffer,
1464 (sizeof local_buffer), &length, profile_header, &size,
1465 0/*finish: don't, because the output is too small*/);
1469 /* We have the ICC profile header; do the basic header checks.
1471 png_uint_32 profile_length = png_get_uint_32(profile_header);
1473 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1474 keyword, profile_length) != 0)
1476 /* The length is apparently ok, so we can check the 132
1479 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1480 keyword, profile_length, profile_header,
1481 png_ptr->color_type) != 0)
1483 /* Now read the tag table; a variable size buffer is
1484 * needed at this point, allocate one for the whole
1485 * profile. The header check has already validated
1486 * that none of this stuff will overflow.
1488 png_uint_32 tag_count =
1489 png_get_uint_32(profile_header + 128);
1490 png_bytep profile = png_read_buffer(png_ptr,
1491 profile_length, 2/*silent*/);
1493 if (profile != NULL)
1495 memcpy(profile, profile_header,
1496 (sizeof profile_header));
1498 size = 12 * tag_count;
1500 (void)png_inflate_read(png_ptr, local_buffer,
1501 (sizeof local_buffer), &length,
1502 profile + (sizeof profile_header), &size, 0);
1504 /* Still expect a buffer error because we expect
1505 * there to be some tag data!
1509 if (png_icc_check_tag_table(png_ptr,
1510 &png_ptr->colorspace, keyword, profile_length,
1513 /* The profile has been validated for basic
1514 * security issues, so read the whole thing in.
1516 size = profile_length - (sizeof profile_header)
1519 (void)png_inflate_read(png_ptr, local_buffer,
1520 (sizeof local_buffer), &length,
1521 profile + (sizeof profile_header) +
1522 12 * tag_count, &size, 1/*finish*/);
1524 if (length > 0 && !(png_ptr->flags &
1525 PNG_FLAG_BENIGN_ERRORS_WARN))
1526 errmsg = "extra compressed data";
1528 /* But otherwise allow extra data: */
1533 /* This can be handled completely, so
1536 png_chunk_warning(png_ptr,
1537 "extra compressed data");
1540 png_crc_finish(png_ptr, length);
1543 # if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 0
1544 /* Check for a match against sRGB */
1545 png_icc_set_sRGB(png_ptr,
1546 &png_ptr->colorspace, profile,
1547 png_ptr->zstream.adler);
1550 /* Steal the profile for info_ptr. */
1551 if (info_ptr != NULL)
1553 png_free_data(png_ptr, info_ptr,
1556 info_ptr->iccp_name = png_voidcast(char*,
1557 png_malloc_base(png_ptr,
1559 if (info_ptr->iccp_name != NULL)
1561 memcpy(info_ptr->iccp_name, keyword,
1563 info_ptr->iccp_proflen =
1565 info_ptr->iccp_profile = profile;
1566 png_ptr->read_buffer = NULL; /*steal*/
1567 info_ptr->free_me |= PNG_FREE_ICCP;
1568 info_ptr->valid |= PNG_INFO_iCCP;
1573 png_ptr->colorspace.flags |=
1574 PNG_COLORSPACE_INVALID;
1575 errmsg = "out of memory";
1579 /* else the profile remains in the read
1580 * buffer which gets reused for subsequent
1584 if (info_ptr != NULL)
1585 png_colorspace_sync(png_ptr, info_ptr);
1589 png_ptr->zowner = 0;
1594 errmsg = png_ptr->zstream.msg;
1596 /* else png_icc_check_tag_table output an error */
1598 else /* profile truncated */
1599 errmsg = png_ptr->zstream.msg;
1603 errmsg = "out of memory";
1606 /* else png_icc_check_header output an error */
1609 /* else png_icc_check_length output an error */
1612 else /* profile truncated */
1613 errmsg = png_ptr->zstream.msg;
1615 /* Release the stream */
1616 png_ptr->zowner = 0;
1619 else /* png_inflate_claim failed */
1620 errmsg = png_ptr->zstream.msg;
1624 errmsg = "bad compression method"; /* or missing */
1628 errmsg = "bad keyword";
1632 errmsg = "too many profiles";
1634 /* Failure: the reason is in 'errmsg' */
1636 png_crc_finish(png_ptr, length);
1638 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1639 png_colorspace_sync(png_ptr, info_ptr);
1640 if (errmsg != NULL) /* else already output */
1641 png_chunk_benign_error(png_ptr, errmsg);
1643 #endif /* READ_iCCP */
1645 #ifdef PNG_READ_sPLT_SUPPORTED
1647 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1648 /* Note: this does not properly handle chunks that are > 64K under DOS */
1650 png_bytep entry_start, buffer;
1651 png_sPLT_t new_palette;
1653 png_uint_32 data_length;
1655 png_uint_32 skip = 0;
1659 png_debug(1, "in png_handle_sPLT");
1661 #ifdef PNG_USER_LIMITS_SUPPORTED
1662 if (png_ptr->user_chunk_cache_max != 0)
1664 if (png_ptr->user_chunk_cache_max == 1)
1666 png_crc_finish(png_ptr, length);
1670 if (--png_ptr->user_chunk_cache_max == 1)
1672 png_warning(png_ptr, "No space in chunk cache for sPLT");
1673 png_crc_finish(png_ptr, length);
1679 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1680 png_chunk_error(png_ptr, "missing IHDR");
1682 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1684 png_crc_finish(png_ptr, length);
1685 png_chunk_benign_error(png_ptr, "out of place");
1689 #ifdef PNG_MAX_MALLOC_64K
1690 if (length > 65535U)
1692 png_crc_finish(png_ptr, length);
1693 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1698 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1701 png_crc_finish(png_ptr, length);
1702 png_chunk_benign_error(png_ptr, "out of memory");
1707 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1708 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1709 * potential breakage point if the types in pngconf.h aren't exactly right.
1711 png_crc_read(png_ptr, buffer, length);
1713 if (png_crc_finish(png_ptr, skip) != 0)
1718 for (entry_start = buffer; *entry_start; entry_start++)
1719 /* Empty loop to find end of name */ ;
1723 /* A sample depth should follow the separator, and we should be on it */
1724 if (length < 2U || entry_start > buffer + (length - 2U))
1726 png_warning(png_ptr, "malformed sPLT chunk");
1730 new_palette.depth = *entry_start++;
1731 entry_size = (new_palette.depth == 8 ? 6 : 10);
1732 /* This must fit in a png_uint_32 because it is derived from the original
1733 * chunk data length.
1735 data_length = length - (png_uint_32)(entry_start - buffer);
1737 /* Integrity-check the data length */
1738 if ((data_length % (unsigned int)entry_size) != 0)
1740 png_warning(png_ptr, "sPLT chunk has bad length");
1744 dl = (png_uint_32)(data_length / (unsigned int)entry_size);
1745 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1749 png_warning(png_ptr, "sPLT chunk too long");
1753 new_palette.nentries = (png_int_32)(data_length / (unsigned int)entry_size);
1755 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
1756 (png_alloc_size_t) new_palette.nentries * (sizeof (png_sPLT_entry)));
1758 if (new_palette.entries == NULL)
1760 png_warning(png_ptr, "sPLT chunk requires too much memory");
1764 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1765 for (i = 0; i < new_palette.nentries; i++)
1767 pp = new_palette.entries + i;
1769 if (new_palette.depth == 8)
1771 pp->red = *entry_start++;
1772 pp->green = *entry_start++;
1773 pp->blue = *entry_start++;
1774 pp->alpha = *entry_start++;
1779 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1780 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1781 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1782 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1785 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1788 pp = new_palette.entries;
1790 for (i = 0; i < new_palette.nentries; i++)
1793 if (new_palette.depth == 8)
1795 pp[i].red = *entry_start++;
1796 pp[i].green = *entry_start++;
1797 pp[i].blue = *entry_start++;
1798 pp[i].alpha = *entry_start++;
1803 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1804 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1805 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1806 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1809 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1813 /* Discard all chunk data except the name and stash that */
1814 new_palette.name = (png_charp)buffer;
1816 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1818 png_free(png_ptr, new_palette.entries);
1820 #endif /* READ_sPLT */
1822 #ifdef PNG_READ_tRNS_SUPPORTED
1824 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1826 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1828 png_debug(1, "in png_handle_tRNS");
1830 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1831 png_chunk_error(png_ptr, "missing IHDR");
1833 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1835 png_crc_finish(png_ptr, length);
1836 png_chunk_benign_error(png_ptr, "out of place");
1840 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1842 png_crc_finish(png_ptr, length);
1843 png_chunk_benign_error(png_ptr, "duplicate");
1847 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1853 png_crc_finish(png_ptr, length);
1854 png_chunk_benign_error(png_ptr, "invalid");
1858 png_crc_read(png_ptr, buf, 2);
1859 png_ptr->num_trans = 1;
1860 png_ptr->trans_color.gray = png_get_uint_16(buf);
1863 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1869 png_crc_finish(png_ptr, length);
1870 png_chunk_benign_error(png_ptr, "invalid");
1874 png_crc_read(png_ptr, buf, length);
1875 png_ptr->num_trans = 1;
1876 png_ptr->trans_color.red = png_get_uint_16(buf);
1877 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1878 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1881 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1883 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1885 /* TODO: is this actually an error in the ISO spec? */
1886 png_crc_finish(png_ptr, length);
1887 png_chunk_benign_error(png_ptr, "out of place");
1891 if (length > (unsigned int) png_ptr->num_palette ||
1892 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1895 png_crc_finish(png_ptr, length);
1896 png_chunk_benign_error(png_ptr, "invalid");
1900 png_crc_read(png_ptr, readbuf, length);
1901 png_ptr->num_trans = (png_uint_16)length;
1906 png_crc_finish(png_ptr, length);
1907 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1911 if (png_crc_finish(png_ptr, 0) != 0)
1913 png_ptr->num_trans = 0;
1917 /* TODO: this is a horrible side effect in the palette case because the
1918 * png_struct ends up with a pointer to the tRNS buffer owned by the
1919 * png_info. Fix this.
1921 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1922 &(png_ptr->trans_color));
1926 #ifdef PNG_READ_bKGD_SUPPORTED
1928 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1930 unsigned int truelen;
1932 png_color_16 background;
1934 png_debug(1, "in png_handle_bKGD");
1936 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1937 png_chunk_error(png_ptr, "missing IHDR");
1939 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1940 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1941 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1943 png_crc_finish(png_ptr, length);
1944 png_chunk_benign_error(png_ptr, "out of place");
1948 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1950 png_crc_finish(png_ptr, length);
1951 png_chunk_benign_error(png_ptr, "duplicate");
1955 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1958 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1964 if (length != truelen)
1966 png_crc_finish(png_ptr, length);
1967 png_chunk_benign_error(png_ptr, "invalid");
1971 png_crc_read(png_ptr, buf, truelen);
1973 if (png_crc_finish(png_ptr, 0) != 0)
1976 /* We convert the index value into RGB components so that we can allow
1977 * arbitrary RGB values for background when we have transparency, and
1978 * so it is easy to determine the RGB values of the background color
1979 * from the info_ptr struct.
1981 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1983 background.index = buf[0];
1985 if (info_ptr != NULL && info_ptr->num_palette != 0)
1987 if (buf[0] >= info_ptr->num_palette)
1989 png_chunk_benign_error(png_ptr, "invalid index");
1993 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1994 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1995 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1999 background.red = background.green = background.blue = 0;
2001 background.gray = 0;
2004 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
2006 if (png_ptr->bit_depth <= 8)
2008 if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth))
2010 png_chunk_benign_error(png_ptr, "invalid gray level");
2015 background.index = 0;
2019 background.gray = png_get_uint_16(buf);
2024 if (png_ptr->bit_depth <= 8)
2026 if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0)
2028 png_chunk_benign_error(png_ptr, "invalid color");
2033 background.index = 0;
2034 background.red = png_get_uint_16(buf);
2035 background.green = png_get_uint_16(buf + 2);
2036 background.blue = png_get_uint_16(buf + 4);
2037 background.gray = 0;
2040 png_set_bKGD(png_ptr, info_ptr, &background);
2044 #ifdef PNG_READ_eXIf_SUPPORTED
2046 png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2050 png_debug(1, "in png_handle_eXIf");
2052 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2053 png_chunk_error(png_ptr, "missing IHDR");
2057 png_crc_finish(png_ptr, length);
2058 png_chunk_benign_error(png_ptr, "too short");
2062 else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0)
2064 png_crc_finish(png_ptr, length);
2065 png_chunk_benign_error(png_ptr, "duplicate");
2069 info_ptr->free_me |= PNG_FREE_EXIF;
2071 info_ptr->eXIf_buf = png_voidcast(png_bytep,
2072 png_malloc_warn(png_ptr, length));
2074 if (info_ptr->eXIf_buf == NULL)
2076 png_crc_finish(png_ptr, length);
2077 png_chunk_benign_error(png_ptr, "out of memory");
2081 for (i = 0; i < length; i++)
2084 png_crc_read(png_ptr, buf, 1);
2085 info_ptr->eXIf_buf[i] = buf[0];
2088 if ((buf[0] != 'M' && buf[0] != 'I') ||
2089 (info_ptr->eXIf_buf[0] != buf[0]))
2091 png_crc_finish(png_ptr, length - 2);
2092 png_chunk_benign_error(png_ptr, "incorrect byte-order specifier");
2093 png_free(png_ptr, info_ptr->eXIf_buf);
2094 info_ptr->eXIf_buf = NULL;
2100 if (png_crc_finish(png_ptr, 0) == 0)
2101 png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf);
2103 png_free(png_ptr, info_ptr->eXIf_buf);
2104 info_ptr->eXIf_buf = NULL;
2108 #ifdef PNG_READ_hIST_SUPPORTED
2110 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2112 unsigned int num, i;
2113 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
2115 png_debug(1, "in png_handle_hIST");
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 ||
2121 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
2123 png_crc_finish(png_ptr, length);
2124 png_chunk_benign_error(png_ptr, "out of place");
2128 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
2130 png_crc_finish(png_ptr, length);
2131 png_chunk_benign_error(png_ptr, "duplicate");
2137 if (length != num * 2 ||
2138 num != (unsigned int)png_ptr->num_palette ||
2139 num > (unsigned int)PNG_MAX_PALETTE_LENGTH)
2141 png_crc_finish(png_ptr, length);
2142 png_chunk_benign_error(png_ptr, "invalid");
2146 for (i = 0; i < num; i++)
2150 png_crc_read(png_ptr, buf, 2);
2151 readbuf[i] = png_get_uint_16(buf);
2154 if (png_crc_finish(png_ptr, 0) != 0)
2157 png_set_hIST(png_ptr, info_ptr, readbuf);
2161 #ifdef PNG_READ_pHYs_SUPPORTED
2163 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2166 png_uint_32 res_x, res_y;
2169 png_debug(1, "in png_handle_pHYs");
2171 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2172 png_chunk_error(png_ptr, "missing IHDR");
2174 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2176 png_crc_finish(png_ptr, length);
2177 png_chunk_benign_error(png_ptr, "out of place");
2181 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2183 png_crc_finish(png_ptr, length);
2184 png_chunk_benign_error(png_ptr, "duplicate");
2190 png_crc_finish(png_ptr, length);
2191 png_chunk_benign_error(png_ptr, "invalid");
2195 png_crc_read(png_ptr, buf, 9);
2197 if (png_crc_finish(png_ptr, 0) != 0)
2200 res_x = png_get_uint_32(buf);
2201 res_y = png_get_uint_32(buf + 4);
2203 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2207 #ifdef PNG_READ_oFFs_SUPPORTED
2209 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2212 png_int_32 offset_x, offset_y;
2215 png_debug(1, "in png_handle_oFFs");
2217 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2218 png_chunk_error(png_ptr, "missing IHDR");
2220 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2222 png_crc_finish(png_ptr, length);
2223 png_chunk_benign_error(png_ptr, "out of place");
2227 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2229 png_crc_finish(png_ptr, length);
2230 png_chunk_benign_error(png_ptr, "duplicate");
2236 png_crc_finish(png_ptr, length);
2237 png_chunk_benign_error(png_ptr, "invalid");
2241 png_crc_read(png_ptr, buf, 9);
2243 if (png_crc_finish(png_ptr, 0) != 0)
2246 offset_x = png_get_int_32(buf);
2247 offset_y = png_get_int_32(buf + 4);
2249 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2253 #ifdef PNG_READ_pCAL_SUPPORTED
2254 /* Read the pCAL chunk (described in the PNG Extensions document) */
2256 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2259 png_byte type, nparams;
2260 png_bytep buffer, buf, units, endptr;
2264 png_debug(1, "in png_handle_pCAL");
2266 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2267 png_chunk_error(png_ptr, "missing IHDR");
2269 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2271 png_crc_finish(png_ptr, length);
2272 png_chunk_benign_error(png_ptr, "out of place");
2276 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2278 png_crc_finish(png_ptr, length);
2279 png_chunk_benign_error(png_ptr, "duplicate");
2283 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2286 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2290 png_crc_finish(png_ptr, length);
2291 png_chunk_benign_error(png_ptr, "out of memory");
2295 png_crc_read(png_ptr, buffer, length);
2297 if (png_crc_finish(png_ptr, 0) != 0)
2300 buffer[length] = 0; /* Null terminate the last string */
2302 png_debug(3, "Finding end of pCAL purpose string");
2303 for (buf = buffer; *buf; buf++)
2306 endptr = buffer + length;
2308 /* We need to have at least 12 bytes after the purpose string
2309 * in order to get the parameter information.
2311 if (endptr - buf <= 12)
2313 png_chunk_benign_error(png_ptr, "invalid");
2317 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2318 X0 = png_get_int_32((png_bytep)buf+1);
2319 X1 = png_get_int_32((png_bytep)buf+5);
2324 png_debug(3, "Checking pCAL equation type and number of parameters");
2325 /* Check that we have the right number of parameters for known
2328 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2329 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2330 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2331 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2333 png_chunk_benign_error(png_ptr, "invalid parameter count");
2337 else if (type >= PNG_EQUATION_LAST)
2339 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2342 for (buf = units; *buf; buf++)
2343 /* Empty loop to move past the units string. */ ;
2345 png_debug(3, "Allocating pCAL parameters array");
2347 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2348 nparams * (sizeof (png_charp))));
2352 png_chunk_benign_error(png_ptr, "out of memory");
2356 /* Get pointers to the start of each parameter string. */
2357 for (i = 0; i < nparams; i++)
2359 buf++; /* Skip the null string terminator from previous parameter. */
2361 png_debug1(3, "Reading pCAL parameter %d", i);
2363 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2364 /* Empty loop to move past each parameter string */ ;
2366 /* Make sure we haven't run out of data yet */
2369 png_free(png_ptr, params);
2370 png_chunk_benign_error(png_ptr, "invalid data");
2375 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2376 (png_charp)units, params);
2378 png_free(png_ptr, params);
2382 #ifdef PNG_READ_sCAL_SUPPORTED
2383 /* Read the sCAL chunk */
2385 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2391 png_debug(1, "in png_handle_sCAL");
2393 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2394 png_chunk_error(png_ptr, "missing IHDR");
2396 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2398 png_crc_finish(png_ptr, length);
2399 png_chunk_benign_error(png_ptr, "out of place");
2403 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2405 png_crc_finish(png_ptr, length);
2406 png_chunk_benign_error(png_ptr, "duplicate");
2410 /* Need unit type, width, \0, height: minimum 4 bytes */
2411 else if (length < 4)
2413 png_crc_finish(png_ptr, length);
2414 png_chunk_benign_error(png_ptr, "invalid");
2418 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2421 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2425 png_chunk_benign_error(png_ptr, "out of memory");
2426 png_crc_finish(png_ptr, length);
2430 png_crc_read(png_ptr, buffer, length);
2431 buffer[length] = 0; /* Null terminate the last string */
2433 if (png_crc_finish(png_ptr, 0) != 0)
2436 /* Validate the unit. */
2437 if (buffer[0] != 1 && buffer[0] != 2)
2439 png_chunk_benign_error(png_ptr, "invalid unit");
2443 /* Validate the ASCII numbers, need two ASCII numbers separated by
2444 * a '\0' and they need to fit exactly in the chunk data.
2449 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2450 i >= length || buffer[i++] != 0)
2451 png_chunk_benign_error(png_ptr, "bad width format");
2453 else if (PNG_FP_IS_POSITIVE(state) == 0)
2454 png_chunk_benign_error(png_ptr, "non-positive width");
2461 if (png_check_fp_number((png_const_charp)buffer, length,
2462 &state, &i) == 0 || i != length)
2463 png_chunk_benign_error(png_ptr, "bad height format");
2465 else if (PNG_FP_IS_POSITIVE(state) == 0)
2466 png_chunk_benign_error(png_ptr, "non-positive height");
2469 /* This is the (only) success case. */
2470 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2471 (png_charp)buffer+1, (png_charp)buffer+heighti);
2476 #ifdef PNG_READ_tIME_SUPPORTED
2478 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2483 png_debug(1, "in png_handle_tIME");
2485 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2486 png_chunk_error(png_ptr, "missing IHDR");
2488 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2490 png_crc_finish(png_ptr, length);
2491 png_chunk_benign_error(png_ptr, "duplicate");
2495 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2496 png_ptr->mode |= PNG_AFTER_IDAT;
2500 png_crc_finish(png_ptr, length);
2501 png_chunk_benign_error(png_ptr, "invalid");
2505 png_crc_read(png_ptr, buf, 7);
2507 if (png_crc_finish(png_ptr, 0) != 0)
2510 mod_time.second = buf[6];
2511 mod_time.minute = buf[5];
2512 mod_time.hour = buf[4];
2513 mod_time.day = buf[3];
2514 mod_time.month = buf[2];
2515 mod_time.year = png_get_uint_16(buf);
2517 png_set_tIME(png_ptr, info_ptr, &mod_time);
2521 #ifdef PNG_READ_tEXt_SUPPORTED
2522 /* Note: this does not properly handle chunks that are > 64K under DOS */
2524 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2530 png_uint_32 skip = 0;
2532 png_debug(1, "in png_handle_tEXt");
2534 #ifdef PNG_USER_LIMITS_SUPPORTED
2535 if (png_ptr->user_chunk_cache_max != 0)
2537 if (png_ptr->user_chunk_cache_max == 1)
2539 png_crc_finish(png_ptr, length);
2543 if (--png_ptr->user_chunk_cache_max == 1)
2545 png_crc_finish(png_ptr, length);
2546 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2552 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2553 png_chunk_error(png_ptr, "missing IHDR");
2555 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2556 png_ptr->mode |= PNG_AFTER_IDAT;
2558 #ifdef PNG_MAX_MALLOC_64K
2559 if (length > 65535U)
2561 png_crc_finish(png_ptr, length);
2562 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2567 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2571 png_chunk_benign_error(png_ptr, "out of memory");
2575 png_crc_read(png_ptr, buffer, length);
2577 if (png_crc_finish(png_ptr, skip) != 0)
2580 key = (png_charp)buffer;
2583 for (text = key; *text; text++)
2584 /* Empty loop to find end of key */ ;
2586 if (text != key + length)
2589 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2590 text_info.key = key;
2591 text_info.lang = NULL;
2592 text_info.lang_key = NULL;
2593 text_info.itxt_length = 0;
2594 text_info.text = text;
2595 text_info.text_length = strlen(text);
2597 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2598 png_warning(png_ptr, "Insufficient memory to process text chunk");
2602 #ifdef PNG_READ_zTXt_SUPPORTED
2603 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2605 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2607 png_const_charp errmsg = NULL;
2609 png_uint_32 keyword_length;
2611 png_debug(1, "in png_handle_zTXt");
2613 #ifdef PNG_USER_LIMITS_SUPPORTED
2614 if (png_ptr->user_chunk_cache_max != 0)
2616 if (png_ptr->user_chunk_cache_max == 1)
2618 png_crc_finish(png_ptr, length);
2622 if (--png_ptr->user_chunk_cache_max == 1)
2624 png_crc_finish(png_ptr, length);
2625 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2631 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2632 png_chunk_error(png_ptr, "missing IHDR");
2634 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2635 png_ptr->mode |= PNG_AFTER_IDAT;
2637 /* Note, "length" is sufficient here; we won't be adding
2638 * a null terminator later.
2640 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2644 png_crc_finish(png_ptr, length);
2645 png_chunk_benign_error(png_ptr, "out of memory");
2649 png_crc_read(png_ptr, buffer, length);
2651 if (png_crc_finish(png_ptr, 0) != 0)
2654 /* TODO: also check that the keyword contents match the spec! */
2655 for (keyword_length = 0;
2656 keyword_length < length && buffer[keyword_length] != 0;
2658 /* Empty loop to find end of name */ ;
2660 if (keyword_length > 79 || keyword_length < 1)
2661 errmsg = "bad keyword";
2663 /* zTXt must have some LZ data after the keyword, although it may expand to
2664 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2667 else if (keyword_length + 3 > length)
2668 errmsg = "truncated";
2670 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2671 errmsg = "unknown compression type";
2675 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2677 /* TODO: at present png_decompress_chunk imposes a single application
2678 * level memory limit, this should be split to different values for iCCP
2681 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2682 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2686 if (png_ptr->read_buffer == NULL)
2687 errmsg="Read failure in png_handle_zTXt";
2690 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk
2691 * except for the extra compression type byte and the fact that
2692 * it isn't necessarily '\0' terminated.
2694 buffer = png_ptr->read_buffer;
2695 buffer[uncompressed_length+(keyword_length+2)] = 0;
2697 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2698 text.key = (png_charp)buffer;
2699 text.text = (png_charp)(buffer + keyword_length+2);
2700 text.text_length = uncompressed_length;
2701 text.itxt_length = 0;
2703 text.lang_key = NULL;
2705 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2706 errmsg = "insufficient memory";
2711 errmsg = png_ptr->zstream.msg;
2715 png_chunk_benign_error(png_ptr, errmsg);
2719 #ifdef PNG_READ_iTXt_SUPPORTED
2720 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2722 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2724 png_const_charp errmsg = NULL;
2726 png_uint_32 prefix_length;
2728 png_debug(1, "in png_handle_iTXt");
2730 #ifdef PNG_USER_LIMITS_SUPPORTED
2731 if (png_ptr->user_chunk_cache_max != 0)
2733 if (png_ptr->user_chunk_cache_max == 1)
2735 png_crc_finish(png_ptr, length);
2739 if (--png_ptr->user_chunk_cache_max == 1)
2741 png_crc_finish(png_ptr, length);
2742 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2748 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2749 png_chunk_error(png_ptr, "missing IHDR");
2751 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2752 png_ptr->mode |= PNG_AFTER_IDAT;
2754 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2758 png_crc_finish(png_ptr, length);
2759 png_chunk_benign_error(png_ptr, "out of memory");
2763 png_crc_read(png_ptr, buffer, length);
2765 if (png_crc_finish(png_ptr, 0) != 0)
2768 /* First the keyword. */
2769 for (prefix_length=0;
2770 prefix_length < length && buffer[prefix_length] != 0;
2774 /* Perform a basic check on the keyword length here. */
2775 if (prefix_length > 79 || prefix_length < 1)
2776 errmsg = "bad keyword";
2778 /* Expect keyword, compression flag, compression type, language, translated
2779 * keyword (both may be empty but are 0 terminated) then the text, which may
2782 else if (prefix_length + 5 > length)
2783 errmsg = "truncated";
2785 else if (buffer[prefix_length+1] == 0 ||
2786 (buffer[prefix_length+1] == 1 &&
2787 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2789 int compressed = buffer[prefix_length+1] != 0;
2790 png_uint_32 language_offset, translated_keyword_offset;
2791 png_alloc_size_t uncompressed_length = 0;
2793 /* Now the language tag */
2795 language_offset = prefix_length;
2797 for (; prefix_length < length && buffer[prefix_length] != 0;
2801 /* WARNING: the length may be invalid here, this is checked below. */
2802 translated_keyword_offset = ++prefix_length;
2804 for (; prefix_length < length && buffer[prefix_length] != 0;
2808 /* prefix_length should now be at the trailing '\0' of the translated
2809 * keyword, but it may already be over the end. None of this arithmetic
2810 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2811 * systems the available allocation may overflow.
2815 if (compressed == 0 && prefix_length <= length)
2816 uncompressed_length = length - prefix_length;
2818 else if (compressed != 0 && prefix_length < length)
2820 uncompressed_length = PNG_SIZE_MAX;
2822 /* TODO: at present png_decompress_chunk imposes a single application
2823 * level memory limit, this should be split to different values for
2824 * iCCP and text chunks.
2826 if (png_decompress_chunk(png_ptr, length, prefix_length,
2827 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2828 buffer = png_ptr->read_buffer;
2831 errmsg = png_ptr->zstream.msg;
2835 errmsg = "truncated";
2841 buffer[uncompressed_length+prefix_length] = 0;
2843 if (compressed == 0)
2844 text.compression = PNG_ITXT_COMPRESSION_NONE;
2847 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2849 text.key = (png_charp)buffer;
2850 text.lang = (png_charp)buffer + language_offset;
2851 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2852 text.text = (png_charp)buffer + prefix_length;
2853 text.text_length = 0;
2854 text.itxt_length = uncompressed_length;
2856 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2857 errmsg = "insufficient memory";
2862 errmsg = "bad compression info";
2865 png_chunk_benign_error(png_ptr, errmsg);
2869 #ifdef PNG_READ_APNG_SUPPORTED
2871 png_handle_acTL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
2874 png_uint_32 num_frames;
2875 png_uint_32 num_plays;
2878 png_debug(1, "in png_handle_acTL");
2880 if (!(png_ptr->mode & PNG_HAVE_IHDR))
2882 png_error(png_ptr, "Missing IHDR before acTL");
2884 else if (png_ptr->mode & PNG_HAVE_IDAT)
2886 png_warning(png_ptr, "Invalid acTL after IDAT skipped");
2887 png_crc_finish(png_ptr, length);
2890 else if (png_ptr->mode & PNG_HAVE_acTL)
2892 png_warning(png_ptr, "Duplicate acTL skipped");
2893 png_crc_finish(png_ptr, length);
2896 else if (length != 8)
2898 png_warning(png_ptr, "acTL with invalid length skipped");
2899 png_crc_finish(png_ptr, length);
2903 png_crc_read(png_ptr, data, 8);
2904 png_crc_finish(png_ptr, 0);
2906 num_frames = png_get_uint_31(png_ptr, data);
2907 num_plays = png_get_uint_31(png_ptr, data + 4);
2909 /* the set function will do error checking on num_frames */
2910 didSet = png_set_acTL(png_ptr, info_ptr, num_frames, num_plays);
2912 png_ptr->mode |= PNG_HAVE_acTL;
2916 png_handle_fcTL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
2921 png_uint_32 x_offset;
2922 png_uint_32 y_offset;
2923 png_uint_16 delay_num;
2924 png_uint_16 delay_den;
2925 png_byte dispose_op;
2928 png_debug(1, "in png_handle_fcTL");
2930 png_ensure_sequence_number(png_ptr, length);
2932 if (!(png_ptr->mode & PNG_HAVE_IHDR))
2934 png_error(png_ptr, "Missing IHDR before fcTL");
2936 else if (png_ptr->mode & PNG_HAVE_IDAT)
2938 /* for any frames other then the first this message may be misleading,
2939 * but correct. PNG_HAVE_IDAT is unset before the frame head is read
2940 * i can't think of a better message */
2941 png_warning(png_ptr, "Invalid fcTL after IDAT skipped");
2942 png_crc_finish(png_ptr, length-4);
2945 else if (png_ptr->mode & PNG_HAVE_fcTL)
2947 png_warning(png_ptr, "Duplicate fcTL within one frame skipped");
2948 png_crc_finish(png_ptr, length-4);
2951 else if (length != 26)
2953 png_warning(png_ptr, "fcTL with invalid length skipped");
2954 png_crc_finish(png_ptr, length-4);
2958 png_crc_read(png_ptr, data, 22);
2959 png_crc_finish(png_ptr, 0);
2961 width = png_get_uint_31(png_ptr, data);
2962 height = png_get_uint_31(png_ptr, data + 4);
2963 x_offset = png_get_uint_31(png_ptr, data + 8);
2964 y_offset = png_get_uint_31(png_ptr, data + 12);
2965 delay_num = png_get_uint_16(data + 16);
2966 delay_den = png_get_uint_16(data + 18);
2967 dispose_op = data[20];
2968 blend_op = data[21];
2970 if (png_ptr->num_frames_read == 0 && (x_offset != 0 || y_offset != 0))
2972 png_warning(png_ptr, "fcTL for the first frame must have zero offset");
2976 if (info_ptr != NULL)
2978 if (png_ptr->num_frames_read == 0 &&
2979 (width != info_ptr->width || height != info_ptr->height))
2981 png_warning(png_ptr, "size in first frame's fcTL must match "
2982 "the size in IHDR");
2986 /* The set function will do more error checking */
2987 png_set_next_frame_fcTL(png_ptr, info_ptr, width, height,
2988 x_offset, y_offset, delay_num, delay_den,
2989 dispose_op, blend_op);
2991 png_read_reinit(png_ptr, info_ptr);
2993 png_ptr->mode |= PNG_HAVE_fcTL;
2998 png_have_info(png_structp png_ptr, png_infop info_ptr)
3000 if((info_ptr->valid & PNG_INFO_acTL) && !(info_ptr->valid & PNG_INFO_fcTL))
3002 png_ptr->apng_flags |= PNG_FIRST_FRAME_HIDDEN;
3003 info_ptr->num_frames++;
3008 png_handle_fdAT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
3010 png_ensure_sequence_number(png_ptr, length);
3012 /* This function is only called from png_read_end(), png_read_info(),
3013 * and png_push_read_chunk() which means that:
3014 * - the user doesn't want to read this frame
3015 * - or this is an out-of-place fdAT
3016 * in either case it is safe to ignore the chunk with a warning */
3017 png_warning(png_ptr, "ignoring fdAT chunk");
3018 png_crc_finish(png_ptr, length - 4);
3019 PNG_UNUSED(info_ptr)
3023 png_ensure_sequence_number(png_structp png_ptr, png_uint_32 length)
3026 png_uint_32 sequence_number;
3029 png_error(png_ptr, "invalid fcTL or fdAT chunk found");
3031 png_crc_read(png_ptr, data, 4);
3032 sequence_number = png_get_uint_31(png_ptr, data);
3034 if (sequence_number != png_ptr->next_seq_num)
3035 png_error(png_ptr, "fcTL or fdAT chunk with out-of-order sequence "
3038 png_ptr->next_seq_num++;
3040 #endif /* PNG_READ_APNG_SUPPORTED */
3042 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
3043 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
3045 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
3047 png_alloc_size_t limit = PNG_SIZE_MAX;
3049 if (png_ptr->unknown_chunk.data != NULL)
3051 png_free(png_ptr, png_ptr->unknown_chunk.data);
3052 png_ptr->unknown_chunk.data = NULL;
3055 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
3056 if (png_ptr->user_chunk_malloc_max > 0 &&
3057 png_ptr->user_chunk_malloc_max < limit)
3058 limit = png_ptr->user_chunk_malloc_max;
3060 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
3061 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
3062 limit = PNG_USER_CHUNK_MALLOC_MAX;
3065 if (length <= limit)
3067 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
3068 /* The following is safe because of the PNG_SIZE_MAX init above */
3069 png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/;
3070 /* 'mode' is a flag array, only the bottom four bits matter here */
3071 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
3074 png_ptr->unknown_chunk.data = NULL;
3078 /* Do a 'warn' here - it is handled below. */
3079 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
3080 png_malloc_warn(png_ptr, length));
3084 if (png_ptr->unknown_chunk.data == NULL && length > 0)
3086 /* This is benign because we clean up correctly */
3087 png_crc_finish(png_ptr, length);
3088 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
3095 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
3096 png_crc_finish(png_ptr, 0);
3100 #endif /* READ_UNKNOWN_CHUNKS */
3102 /* Handle an unknown, or known but disabled, chunk */
3104 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
3105 png_uint_32 length, int keep)
3107 int handled = 0; /* the chunk was handled */
3109 png_debug(1, "in png_handle_unknown");
3111 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
3112 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
3113 * the bug which meant that setting a non-default behavior for a specific
3114 * chunk would be ignored (the default was always used unless a user
3115 * callback was installed).
3117 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
3118 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
3119 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
3120 * This is just an optimization to avoid multiple calls to the lookup
3123 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
3124 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
3125 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
3129 /* One of the following methods will read the chunk or skip it (at least one
3130 * of these is always defined because this is the only way to switch on
3131 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
3133 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
3134 /* The user callback takes precedence over the chunk keep value, but the
3135 * keep value is still required to validate a save of a critical chunk.
3137 if (png_ptr->read_user_chunk_fn != NULL)
3139 if (png_cache_unknown_chunk(png_ptr, length) != 0)
3141 /* Callback to user unknown chunk handler */
3142 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
3143 &png_ptr->unknown_chunk);
3146 * negative: An error occurred; png_chunk_error will be called.
3147 * zero: The chunk was not handled, the chunk will be discarded
3148 * unless png_set_keep_unknown_chunks has been used to set
3149 * a 'keep' behavior for this particular chunk, in which
3150 * case that will be used. A critical chunk will cause an
3151 * error at this point unless it is to be saved.
3152 * positive: The chunk was handled, libpng will ignore/discard it.
3155 png_chunk_error(png_ptr, "error in user chunk");
3159 /* If the keep value is 'default' or 'never' override it, but
3160 * still error out on critical chunks unless the keep value is
3161 * 'always' While this is weird it is the behavior in 1.4.12.
3162 * A possible improvement would be to obey the value set for the
3163 * chunk, but this would be an API change that would probably
3164 * damage some applications.
3166 * The png_app_warning below catches the case that matters, where
3167 * the application has not set specific save or ignore for this
3168 * chunk or global save or ignore.
3170 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
3172 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
3173 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
3175 png_chunk_warning(png_ptr, "Saving unknown chunk:");
3176 png_app_warning(png_ptr,
3177 "forcing save of an unhandled chunk;"
3178 " please call png_set_keep_unknown_chunks");
3179 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
3182 keep = PNG_HANDLE_CHUNK_IF_SAFE;
3186 else /* chunk was handled */
3189 /* Critical chunks can be safely discarded at this point. */
3190 keep = PNG_HANDLE_CHUNK_NEVER;
3195 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
3199 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
3200 # endif /* READ_USER_CHUNKS */
3202 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
3204 /* keep is currently just the per-chunk setting, if there was no
3205 * setting change it to the global default now (not that this may
3206 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
3207 * if not simply skip the chunk.
3209 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
3210 keep = png_ptr->unknown_default;
3212 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3213 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3214 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3216 if (png_cache_unknown_chunk(png_ptr, length) == 0)
3217 keep = PNG_HANDLE_CHUNK_NEVER;
3221 png_crc_finish(png_ptr, length);
3224 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
3225 # error no method to support READ_UNKNOWN_CHUNKS
3229 /* If here there is no read callback pointer set and no support is
3230 * compiled in to just save the unknown chunks, so simply skip this
3231 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
3232 * the app has erroneously asked for unknown chunk saving when there
3235 if (keep > PNG_HANDLE_CHUNK_NEVER)
3236 png_app_error(png_ptr, "no unknown chunk support available");
3238 png_crc_finish(png_ptr, length);
3242 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
3243 /* Now store the chunk in the chunk list if appropriate, and if the limits
3246 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3247 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3248 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3250 # ifdef PNG_USER_LIMITS_SUPPORTED
3251 switch (png_ptr->user_chunk_cache_max)
3254 png_ptr->user_chunk_cache_max = 1;
3255 png_chunk_benign_error(png_ptr, "no space in chunk cache");
3258 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
3259 * chunk being skipped, now there will be a hard error below.
3263 default: /* not at limit */
3264 --(png_ptr->user_chunk_cache_max);
3266 case 0: /* no limit */
3267 # endif /* USER_LIMITS */
3268 /* Here when the limit isn't reached or when limits are compiled
3269 * out; store the chunk.
3271 png_set_unknown_chunks(png_ptr, info_ptr,
3272 &png_ptr->unknown_chunk, 1);
3274 # ifdef PNG_USER_LIMITS_SUPPORTED
3279 # else /* no store support: the chunk must be handled by the user callback */
3280 PNG_UNUSED(info_ptr)
3283 /* Regardless of the error handling below the cached data (if any) can be
3284 * freed now. Notice that the data is not freed if there is a png_error, but
3285 * it will be freed by destroy_read_struct.
3287 if (png_ptr->unknown_chunk.data != NULL)
3288 png_free(png_ptr, png_ptr->unknown_chunk.data);
3289 png_ptr->unknown_chunk.data = NULL;
3291 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
3292 /* There is no support to read an unknown chunk, so just skip it. */
3293 png_crc_finish(png_ptr, length);
3294 PNG_UNUSED(info_ptr)
3296 #endif /* !READ_UNKNOWN_CHUNKS */
3298 /* Check for unhandled critical chunks */
3299 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
3300 png_chunk_error(png_ptr, "unhandled critical chunk");
3303 /* This function is called to verify that a chunk name is valid.
3304 * This function can't have the "critical chunk check" incorporated
3305 * into it, since in the future we will need to be able to call user
3306 * functions to handle unknown critical chunks after we check that
3307 * the chunk name itself is valid.
3310 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
3312 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
3316 png_check_chunk_name(png_const_structrp png_ptr, png_uint_32 chunk_name)
3319 png_uint_32 cn=chunk_name;
3321 png_debug(1, "in png_check_chunk_name");
3323 for (i=1; i<=4; ++i)
3327 if (c < 65 || c > 122 || (c > 90 && c < 97))
3328 png_chunk_error(png_ptr, "invalid chunk type");
3335 png_check_chunk_length(png_const_structrp png_ptr, png_uint_32 length)
3337 png_alloc_size_t limit = PNG_UINT_31_MAX;
3339 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
3340 if (png_ptr->user_chunk_malloc_max > 0 &&
3341 png_ptr->user_chunk_malloc_max < limit)
3342 limit = png_ptr->user_chunk_malloc_max;
3343 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
3344 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
3345 limit = PNG_USER_CHUNK_MALLOC_MAX;
3347 if (png_ptr->chunk_name == png_IDAT)
3349 png_alloc_size_t idat_limit = PNG_UINT_31_MAX;
3351 (size_t)png_ptr->width
3352 * (size_t)png_ptr->channels
3353 * (png_ptr->bit_depth > 8? 2: 1)
3355 + (png_ptr->interlaced? 6: 0);
3356 if (png_ptr->height > PNG_UINT_32_MAX/row_factor)
3357 idat_limit = PNG_UINT_31_MAX;
3359 idat_limit = png_ptr->height * row_factor;
3360 row_factor = row_factor > 32566? 32566 : row_factor;
3361 idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */
3362 idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;
3363 limit = limit < idat_limit? idat_limit : limit;
3368 png_debug2(0," length = %lu, limit = %lu",
3369 (unsigned long)length,(unsigned long)limit);
3370 png_benign_error(png_ptr, "chunk data is too large");
3377 copy_src_to_dst(png_bytep dp, png_bytep sp, int width,
3378 int row_stride, int nplanes, PngPickColor *png_pickcolor)
3381 unsigned char *src = (unsigned char *)sp;
3382 unsigned char *dst = (unsigned char *)dp;
3384 unsigned long long sumRGBA[4] = {0, 0, 0, 0};
3385 const int const0 = 0;
3388 uint32x4_t sumR_32x4 = vmovq_n_u32 ( 0 );
3389 uint32x4_t sumG_32x4 = vmovq_n_u32 ( 0 );
3390 uint32x4_t sumB_32x4 = vmovq_n_u32 ( 0 );
3396 uint64x1x3_t sumRGB_64x1;
3398 for(j = 0; j < width-(width&0xf); j += 16)
3402 uint8x16x3_t rgb = vld3q_u8 ( src );
3404 R_8x16 = rgb.val[0];
3405 G_8x16 = rgb.val[1];
3406 B_8x16 = rgb.val[2];
3410 uint8x16x4_t rgb = vld4q_u8 ( src );
3412 R_8x16 = rgb.val[0];
3413 G_8x16 = rgb.val[1];
3414 B_8x16 = rgb.val[2];
3417 if(png_pickcolor && png_pickcolor->enable)
3419 if(png_pickcolor->perc > 0)
3421 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3422 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3423 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3425 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3426 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3427 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3429 else if( (png_pickcolor->x1 > j) && (png_pickcolor->x1 < j + 16) )
3431 int x = png_pickcolor->x1;
3432 unsigned char *from = sp + (png_pickcolor->x1 * nplanes);
3435 png_pickcolor->sumR += from[0];
3436 png_pickcolor->sumG += from[1];
3437 png_pickcolor->sumB += from[2];
3442 else if( (png_pickcolor->x2 >= j) && (png_pickcolor->x2 < j + 16) )
3445 unsigned char *from = sp + (j * nplanes);
3446 while(x <= png_pickcolor->x2)
3448 png_pickcolor->sumR += from[0];
3449 png_pickcolor->sumG += from[1];
3450 png_pickcolor->sumB += from[2];
3455 else if ( (j >= png_pickcolor->x1) && (j+15 <= png_pickcolor->x2) )
3457 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3458 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3459 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3461 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3462 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3463 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3466 dst += (nplanes*16);
3467 src += (nplanes*16);
3470 if(png_pickcolor && png_pickcolor->enable)
3473 uint64x2_t sumR_64x2 = vpaddlq_u32 ( sumR_32x4 );
3474 uint64x2_t sumG_64x2 = vpaddlq_u32 ( sumG_32x4 );
3475 uint64x2_t sumB_64x2 = vpaddlq_u32 ( sumB_32x4 );
3477 uint64x1_t sumR_Lo_64x1 = vget_low_u64 ( sumR_64x2 );
3478 uint64x1_t sumR_Hi_64x1 = vget_high_u64 ( sumR_64x2 );
3480 uint64x1_t sumG_Lo_64x1 = vget_low_u64 ( sumG_64x2 );
3481 uint64x1_t sumG_Hi_64x1 = vget_high_u64 ( sumG_64x2 );
3483 uint64x1_t sumB_Lo_64x1 = vget_low_u64 ( sumB_64x2 );
3484 uint64x1_t sumB_Hi_64x1 = vget_high_u64 ( sumB_64x2 );
3486 sumRGB_64x1.val[0] = vadd_u64 ( sumR_Lo_64x1, sumR_Hi_64x1 );
3487 sumRGB_64x1.val[1] = vadd_u64 ( sumG_Lo_64x1, sumG_Hi_64x1 );
3488 sumRGB_64x1.val[2] = vadd_u64 ( sumB_Lo_64x1, sumB_Hi_64x1 );
3490 vst3_u64( sumRGBA, sumRGB_64x1);
3492 png_pickcolor->sumR += sumRGBA[0];
3493 png_pickcolor->sumG += sumRGBA[1];
3494 png_pickcolor->sumB += sumRGBA[2];
3497 memcpy(dst, src, (width-j)*nplanes);
3498 if(png_pickcolor && png_pickcolor->enable)
3500 if(png_pickcolor->perc <= 0)
3502 if(j < png_pickcolor->x1)
3504 j = png_pickcolor->x1;
3505 dst = dp + (j*nplanes);
3507 width = png_pickcolor->x2;
3509 for(; j < width ; j ++)
3511 png_pickcolor->sumR += dst[0];
3512 png_pickcolor->sumG += dst[1];
3513 png_pickcolor->sumB += dst[2];
3519 void copy_row(png_bytep dp, png_bytep sp, int width, int pixel_bits, PngPickColor *png_pickcolor)
3521 int row_stride = PNG_ROWBYTES(pixel_bits, width);
3522 if(pixel_bits == 24 || pixel_bits == 32)
3524 copy_src_to_dst(dp, sp, width, row_stride, pixel_bits >> 3, png_pickcolor);
3528 memcpy(dp, sp, row_stride);
3533 #endif /* __TIZEN__ */
3535 /* Combines the row recently read in with the existing pixels in the row. This
3536 * routine takes care of alpha and transparency if requested. This routine also
3537 * handles the two methods of progressive display of interlaced images,
3538 * depending on the 'display' value; if 'display' is true then the whole row
3539 * (dp) is filled from the start by replicating the available pixels. If
3540 * 'display' is false only those pixels present in the pass are filled in.
3543 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3545 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3546 png_const_bytep sp = png_ptr->row_buf + 1;
3547 png_alloc_size_t row_width = png_ptr->width;
3548 unsigned int pass = png_ptr->pass;
3549 png_bytep end_ptr = 0;
3550 png_byte end_byte = 0;
3551 unsigned int end_mask;
3553 png_debug(1, "in png_combine_row");
3555 /* Added in 1.5.6: it should not be possible to enter this routine until at
3556 * least one row has been read from the PNG data and transformed.
3558 if (pixel_depth == 0)
3559 png_error(png_ptr, "internal row logic error");
3561 /* Added in 1.5.4: the pixel depth should match the information returned by
3562 * any call to png_read_update_info at this point. Do not continue if we got
3565 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3566 PNG_ROWBYTES(pixel_depth, row_width))
3567 png_error(png_ptr, "internal row size calculation error");
3569 /* Don't expect this to ever happen: */
3571 png_error(png_ptr, "internal row width error");
3573 /* Preserve the last byte in cases where only part of it will be overwritten,
3574 * the multiply below may overflow, we don't care because ANSI-C guarantees
3575 * we get the low bits.
3577 end_mask = (pixel_depth * row_width) & 7;
3580 /* end_ptr == NULL is a flag to say do nothing */
3581 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3582 end_byte = *end_ptr;
3583 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3584 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3585 /* little-endian byte */
3586 end_mask = (unsigned int)(0xff << end_mask);
3588 else /* big-endian byte */
3590 end_mask = 0xff >> end_mask;
3591 /* end_mask is now the bits to *keep* from the destination row */
3594 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3595 * will also happen if interlacing isn't supported or if the application
3596 * does not call png_set_interlace_handling(). In the latter cases the
3597 * caller just gets a sequence of the unexpanded rows from each interlace
3600 #ifdef PNG_READ_INTERLACING_SUPPORTED
3601 if (png_ptr->interlaced != 0 &&
3602 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3603 pass < 6 && (display == 0 ||
3604 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3605 (display == 1 && (pass & 1) != 0)))
3607 /* Narrow images may have no bits in a pass; the caller should handle
3608 * this, but this test is cheap:
3610 if (row_width <= PNG_PASS_START_COL(pass))
3613 if (pixel_depth < 8)
3615 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3616 * into 32 bits, then a single loop over the bytes using the four byte
3617 * values in the 32-bit mask can be used. For the 'display' option the
3618 * expanded mask may also not require any masking within a byte. To
3619 * make this work the PACKSWAP option must be taken into account - it
3620 * simply requires the pixels to be reversed in each byte.
3622 * The 'regular' case requires a mask for each of the first 6 passes,
3623 * the 'display' case does a copy for the even passes in the range
3624 * 0..6. This has already been handled in the test above.
3626 * The masks are arranged as four bytes with the first byte to use in
3627 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3628 * not) of the pixels in each byte.
3630 * NOTE: the whole of this logic depends on the caller of this function
3631 * only calling it on rows appropriate to the pass. This function only
3632 * understands the 'x' logic; the 'y' logic is handled by the caller.
3634 * The following defines allow generation of compile time constant bit
3635 * masks for each pixel depth and each possibility of swapped or not
3636 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3637 * is in the range 0..7; and the result is 1 if the pixel is to be
3638 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3639 * for the block method.
3641 * With some compilers a compile time expression of the general form:
3643 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3645 * Produces warnings with values of 'shift' in the range 33 to 63
3646 * because the right hand side of the ?: expression is evaluated by
3647 * the compiler even though it isn't used. Microsoft Visual C (various
3648 * versions) and the Intel C compiler are known to do this. To avoid
3649 * this the following macros are used in 1.5.6. This is a temporary
3650 * solution to avoid destabilizing the code during the release process.
3652 # if PNG_USE_COMPILE_TIME_MASKS
3653 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3654 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3656 # define PNG_LSR(x,s) ((x)>>(s))
3657 # define PNG_LSL(x,s) ((x)<<(s))
3659 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3660 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3661 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3662 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3664 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3665 * little endian - the first pixel is at bit 0 - however the extra
3666 * parameter 's' can be set to cause the mask position to be swapped
3667 * within each byte, to match the PNG format. This is done by XOR of
3668 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3670 # define PIXEL_MASK(p,x,d,s) \
3671 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3673 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3675 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3676 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3678 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3679 * cases the result needs replicating, for the 4-bpp case the above
3680 * generates a full 32 bits.
3682 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3684 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3685 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3686 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3688 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3689 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3690 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3692 #if PNG_USE_COMPILE_TIME_MASKS
3693 /* Utility macros to construct all the masks for a depth/swap
3694 * combination. The 's' parameter says whether the format is PNG
3695 * (big endian bytes) or not. Only the three odd-numbered passes are
3696 * required for the display/block algorithm.
3698 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3699 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3701 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3703 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3705 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3708 static const png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3710 /* Little-endian byte masks for PACKSWAP */
3711 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3712 /* Normal (big-endian byte) masks - PNG format */
3713 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3716 /* display_mask has only three entries for the odd passes, so index by
3719 static const png_uint_32 display_mask[2][3][3] =
3721 /* Little-endian byte masks for PACKSWAP */
3722 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3723 /* Normal (big-endian byte) masks - PNG format */
3724 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3727 # define MASK(pass,depth,display,png)\
3728 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3729 row_mask[png][DEPTH_INDEX(depth)][pass])
3731 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3732 /* This is the runtime alternative: it seems unlikely that this will
3733 * ever be either smaller or faster than the compile time approach.
3735 # define MASK(pass,depth,display,png)\
3736 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3737 #endif /* !USE_COMPILE_TIME_MASKS */
3739 /* Use the appropriate mask to copy the required bits. In some cases
3740 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3741 * the number of pixels, but the code copies bytes, so it is necessary
3742 * to special case the end.
3744 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3747 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3748 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3749 mask = MASK(pass, pixel_depth, display, 0);
3753 mask = MASK(pass, pixel_depth, display, 1);
3759 /* It doesn't matter in the following if png_uint_32 has more than
3760 * 32 bits because the high bits always match those in m<<24; it is,
3761 * however, essential to use OR here, not +, because of this.
3764 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3767 if (m != 0) /* something to copy */
3770 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3775 /* NOTE: this may overwrite the last byte with garbage if the image
3776 * is not an exact number of bytes wide; libpng has always done
3779 if (row_width <= pixels_per_byte)
3780 break; /* May need to restore part of the last byte */
3782 row_width -= pixels_per_byte;
3788 else /* pixel_depth >= 8 */
3790 unsigned int bytes_to_copy, bytes_to_jump;
3792 /* Validate the depth - it must be a multiple of 8 */
3793 if (pixel_depth & 7)
3794 png_error(png_ptr, "invalid user transform pixel depth");
3796 pixel_depth >>= 3; /* now in bytes */
3797 row_width *= pixel_depth;
3799 /* Regardless of pass number the Adam 7 interlace always results in a
3800 * fixed number of pixels to copy then to skip. There may be a
3801 * different number of pixels to skip at the start though.
3804 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3806 row_width -= offset;
3811 /* Work out the bytes to copy. */
3814 /* When doing the 'block' algorithm the pixel in the pass gets
3815 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3816 * passes are skipped above - the entire expanded row is copied.
3818 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3820 /* But don't allow this number to exceed the actual row width. */
3821 if (bytes_to_copy > row_width)
3822 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3825 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3826 bytes_to_copy = pixel_depth;
3828 /* In Adam7 there is a constant offset between where the pixels go. */
3829 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3831 /* And simply copy these bytes. Some optimization is possible here,
3832 * depending on the value of 'bytes_to_copy'. Special case the low
3833 * byte counts, which we know to be frequent.
3835 * Notice that these cases all 'return' rather than 'break' - this
3836 * avoids an unnecessary test on whether to restore the last byte
3839 switch (bytes_to_copy)
3846 if (row_width <= bytes_to_jump)
3849 dp += bytes_to_jump;
3850 sp += bytes_to_jump;
3851 row_width -= bytes_to_jump;
3855 /* There is a possibility of a partial copy at the end here; this
3856 * slows the code down somewhat.
3860 dp[0] = sp[0]; dp[1] = sp[1];
3862 if (row_width <= bytes_to_jump)
3865 sp += bytes_to_jump;
3866 dp += bytes_to_jump;
3867 row_width -= bytes_to_jump;
3869 while (row_width > 1);
3871 /* And there can only be one byte left at this point: */
3876 /* This can only be the RGB case, so each copy is exactly one
3877 * pixel and it is not necessary to check for a partial copy.
3881 dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2];
3883 if (row_width <= bytes_to_jump)
3886 sp += bytes_to_jump;
3887 dp += bytes_to_jump;
3888 row_width -= bytes_to_jump;
3892 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3893 /* Check for double byte alignment and, if possible, use a
3894 * 16-bit copy. Don't attempt this for narrow images - ones that
3895 * are less than an interlace panel wide. Don't attempt it for
3896 * wide bytes_to_copy either - use the memcpy there.
3898 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3899 png_isaligned(dp, png_uint_16) &&
3900 png_isaligned(sp, png_uint_16) &&
3901 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3902 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3904 /* Everything is aligned for png_uint_16 copies, but try for
3905 * png_uint_32 first.
3907 if (png_isaligned(dp, png_uint_32) &&
3908 png_isaligned(sp, png_uint_32) &&
3909 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3910 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3912 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3913 png_const_uint_32p sp32 = png_aligncastconst(
3914 png_const_uint_32p, sp);
3915 size_t skip = (bytes_to_jump-bytes_to_copy) /
3916 (sizeof (png_uint_32));
3920 size_t c = bytes_to_copy;
3924 c -= (sizeof (png_uint_32));
3928 if (row_width <= bytes_to_jump)
3933 row_width -= bytes_to_jump;
3935 while (bytes_to_copy <= row_width);
3937 /* Get to here when the row_width truncates the final copy.
3938 * There will be 1-3 bytes left to copy, so don't try the
3939 * 16-bit loop below.
3941 dp = (png_bytep)dp32;
3942 sp = (png_const_bytep)sp32;
3945 while (--row_width > 0);
3949 /* Else do it in 16-bit quantities, but only if the size is
3954 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3955 png_const_uint_16p sp16 = png_aligncastconst(
3956 png_const_uint_16p, sp);
3957 size_t skip = (bytes_to_jump-bytes_to_copy) /
3958 (sizeof (png_uint_16));
3962 size_t c = bytes_to_copy;
3966 c -= (sizeof (png_uint_16));
3970 if (row_width <= bytes_to_jump)
3975 row_width -= bytes_to_jump;
3977 while (bytes_to_copy <= row_width);
3979 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3980 dp = (png_bytep)dp16;
3981 sp = (png_const_bytep)sp16;
3984 while (--row_width > 0);
3988 #endif /* ALIGN_TYPE code */
3990 /* The true default - use a memcpy: */
3993 memcpy(dp, sp, bytes_to_copy);
3995 if (row_width <= bytes_to_jump)
3998 sp += bytes_to_jump;
3999 dp += bytes_to_jump;
4000 row_width -= bytes_to_jump;
4001 if (bytes_to_copy > row_width)
4002 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
4007 } /* pixel_depth >= 8 */
4009 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
4012 #endif /* READ_INTERLACING */
4014 /* If here then the switch above wasn't used so just memcpy the whole row
4015 * from the temporary row buffer (notice that this overwrites the end of the
4016 * destination row if it is a partial byte.)
4018 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
4020 /* Restore the overwritten bits from the last byte if necessary. */
4021 if (end_ptr != NULL)
4022 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
4025 #ifdef PNG_READ_INTERLACING_SUPPORTED
4027 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
4028 png_uint_32 transformations /* Because these may affect the byte layout */)
4030 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4031 /* Offset to next interlace block */
4032 static const unsigned int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4034 png_debug(1, "in png_do_read_interlace");
4035 if (row != NULL && row_info != NULL)
4037 png_uint_32 final_width;
4039 final_width = row_info->width * png_pass_inc[pass];
4041 switch (row_info->pixel_depth)
4045 png_bytep sp = row + (size_t)((row_info->width - 1) >> 3);
4046 png_bytep dp = row + (size_t)((final_width - 1) >> 3);
4047 unsigned int sshift, dshift;
4048 unsigned int s_start, s_end;
4050 int jstop = (int)png_pass_inc[pass];
4055 #ifdef PNG_READ_PACKSWAP_SUPPORTED
4056 if ((transformations & PNG_PACKSWAP) != 0)
4058 sshift = ((row_info->width + 7) & 0x07);
4059 dshift = ((final_width + 7) & 0x07);
4068 sshift = 7 - ((row_info->width + 7) & 0x07);
4069 dshift = 7 - ((final_width + 7) & 0x07);
4075 for (i = 0; i < row_info->width; i++)
4077 v = (png_byte)((*sp >> sshift) & 0x01);
4078 for (j = 0; j < jstop; j++)
4080 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
4081 tmp |= (unsigned int)(v << dshift);
4082 *dp = (png_byte)(tmp & 0xff);
4084 if (dshift == s_end)
4091 dshift = (unsigned int)((int)dshift + s_inc);
4094 if (sshift == s_end)
4101 sshift = (unsigned int)((int)sshift + s_inc);
4108 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
4109 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
4110 unsigned int sshift, dshift;
4111 unsigned int s_start, s_end;
4113 int jstop = (int)png_pass_inc[pass];
4116 #ifdef PNG_READ_PACKSWAP_SUPPORTED
4117 if ((transformations & PNG_PACKSWAP) != 0)
4119 sshift = (((row_info->width + 3) & 0x03) << 1);
4120 dshift = (((final_width + 3) & 0x03) << 1);
4129 sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1);
4130 dshift = ((3 - ((final_width + 3) & 0x03)) << 1);
4136 for (i = 0; i < row_info->width; i++)
4141 v = (png_byte)((*sp >> sshift) & 0x03);
4142 for (j = 0; j < jstop; j++)
4144 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
4145 tmp |= (unsigned int)(v << dshift);
4146 *dp = (png_byte)(tmp & 0xff);
4148 if (dshift == s_end)
4155 dshift = (unsigned int)((int)dshift + s_inc);
4158 if (sshift == s_end)
4165 sshift = (unsigned int)((int)sshift + s_inc);
4172 png_bytep sp = row + (size_t)((row_info->width - 1) >> 1);
4173 png_bytep dp = row + (size_t)((final_width - 1) >> 1);
4174 unsigned int sshift, dshift;
4175 unsigned int s_start, s_end;
4178 int jstop = (int)png_pass_inc[pass];
4180 #ifdef PNG_READ_PACKSWAP_SUPPORTED
4181 if ((transformations & PNG_PACKSWAP) != 0)
4183 sshift = (((row_info->width + 1) & 0x01) << 2);
4184 dshift = (((final_width + 1) & 0x01) << 2);
4193 sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2);
4194 dshift = ((1 - ((final_width + 1) & 0x01)) << 2);
4200 for (i = 0; i < row_info->width; i++)
4202 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
4205 for (j = 0; j < jstop; j++)
4207 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
4208 tmp |= (unsigned int)(v << dshift);
4209 *dp = (png_byte)(tmp & 0xff);
4211 if (dshift == s_end)
4218 dshift = (unsigned int)((int)dshift + s_inc);
4221 if (sshift == s_end)
4228 sshift = (unsigned int)((int)sshift + s_inc);
4235 size_t pixel_bytes = (row_info->pixel_depth >> 3);
4237 png_bytep sp = row + (size_t)(row_info->width - 1)
4240 png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes;
4242 int jstop = (int)png_pass_inc[pass];
4245 for (i = 0; i < row_info->width; i++)
4247 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
4250 memcpy(v, sp, pixel_bytes);
4252 for (j = 0; j < jstop; j++)
4254 memcpy(dp, v, pixel_bytes);
4264 row_info->width = final_width;
4265 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
4267 #ifndef PNG_READ_PACKSWAP_SUPPORTED
4268 PNG_UNUSED(transformations) /* Silence compiler warning */
4271 #endif /* READ_INTERLACING */
4274 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
4275 png_const_bytep prev_row)
4278 size_t istop = row_info->rowbytes;
4279 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4280 png_bytep rp = row + bpp;
4282 PNG_UNUSED(prev_row)
4284 for (i = bpp; i < istop; i++)
4286 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
4292 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
4293 png_const_bytep prev_row)
4296 size_t istop = row_info->rowbytes;
4298 png_const_bytep pp = prev_row;
4300 for (i = 0; i < istop; i++)
4302 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
4308 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
4309 png_const_bytep prev_row)
4313 png_const_bytep pp = prev_row;
4314 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4315 size_t istop = row_info->rowbytes - bpp;
4317 for (i = 0; i < bpp; i++)
4319 *rp = (png_byte)(((int)(*rp) +
4320 ((int)(*pp++) / 2 )) & 0xff);
4325 for (i = 0; i < istop; i++)
4327 *rp = (png_byte)(((int)(*rp) +
4328 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
4335 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
4336 png_const_bytep prev_row)
4338 png_bytep rp_end = row + row_info->rowbytes;
4341 /* First pixel/byte */
4344 *row++ = (png_byte)a;
4347 while (row < rp_end)
4349 int b, pa, pb, pc, p;
4351 a &= 0xff; /* From previous iteration or start */
4362 pa = p < 0 ? -p : p;
4363 pb = pc < 0 ? -pc : pc;
4364 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4367 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
4368 * ones in the case of a tie.
4376 /* Calculate the current pixel in a, and move the previous row pixel to c
4377 * for the next time round the loop
4381 *row++ = (png_byte)a;
4386 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
4387 png_const_bytep prev_row)
4389 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4390 png_bytep rp_end = row + bpp;
4392 /* Process the first pixel in the row completely (this is the same as 'up'
4393 * because there is only one candidate predictor for the first row).
4395 while (row < rp_end)
4397 int a = *row + *prev_row++;
4398 *row++ = (png_byte)a;
4402 rp_end = rp_end + (row_info->rowbytes - bpp);
4404 while (row < rp_end)
4406 int a, b, c, pa, pb, pc, p;
4408 c = *(prev_row - bpp);
4420 pa = p < 0 ? -p : p;
4421 pb = pc < 0 ? -pc : pc;
4422 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4432 *row++ = (png_byte)a;
4437 png_init_filter_functions(png_structrp pp)
4438 /* This function is called once for every PNG image (except for PNG images
4439 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
4440 * implementations required to reverse the filtering of PNG rows. Reversing
4441 * the filter is the first transformation performed on the row data. It is
4442 * performed in place, therefore an implementation can be selected based on
4443 * the image pixel format. If the implementation depends on image width then
4444 * take care to ensure that it works correctly if the image is interlaced -
4445 * interlacing causes the actual row width to vary.
4448 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
4450 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
4451 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
4452 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
4454 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4455 png_read_filter_row_paeth_1byte_pixel;
4457 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4458 png_read_filter_row_paeth_multibyte_pixel;
4460 #ifdef PNG_FILTER_OPTIMIZATIONS
4461 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
4462 * call to install hardware optimizations for the above functions; simply
4463 * replace whatever elements of the pp->read_filter[] array with a hardware
4464 * specific (or, for that matter, generic) optimization.
4466 * To see an example of this examine what configure.ac does when
4467 * --enable-arm-neon is specified on the command line.
4469 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
4474 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
4475 png_const_bytep prev_row, int filter)
4477 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
4478 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
4479 * implementations. See png_init_filter_functions above.
4481 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
4483 if (pp->read_filter[0] == NULL)
4484 png_init_filter_functions(pp);
4486 pp->read_filter[filter-1](row_info, row, prev_row);
4490 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
4492 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
4493 png_alloc_size_t avail_out)
4495 /* Loop reading IDATs and decompressing the result into output[avail_out] */
4496 png_ptr->zstream.next_out = output;
4497 png_ptr->zstream.avail_out = 0; /* safety: set below */
4505 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
4507 if (png_ptr->zstream.avail_in == 0)
4511 #ifdef PNG_READ_APNG_SUPPORTED
4512 png_uint_32 bytes_to_skip = 0;
4514 while (png_ptr->idat_size == 0 || bytes_to_skip != 0)
4516 png_crc_finish(png_ptr, bytes_to_skip);
4519 png_ptr->idat_size = png_read_chunk_header(png_ptr);
4520 if (png_ptr->num_frames_read == 0)
4522 if (png_ptr->chunk_name != png_IDAT)
4523 png_error(png_ptr, "Not enough image data");
4527 if (png_ptr->chunk_name == png_IEND)
4528 png_error(png_ptr, "Not enough image data");
4529 if (png_ptr->chunk_name != png_fdAT)
4531 png_warning(png_ptr, "Skipped (ignored) a chunk "
4532 "between APNG chunks");
4533 bytes_to_skip = png_ptr->idat_size;
4537 png_ensure_sequence_number(png_ptr, png_ptr->idat_size);
4539 png_ptr->idat_size -= 4;
4543 while (png_ptr->idat_size == 0)
4545 png_crc_finish(png_ptr, 0);
4547 png_ptr->idat_size = png_read_chunk_header(png_ptr);
4548 /* This is an error even in the 'check' case because the code just
4549 * consumed a non-IDAT header.
4551 if (png_ptr->chunk_name != png_IDAT)
4552 png_error(png_ptr, "Not enough image data");
4554 #endif /* PNG_READ_APNG_SUPPORTED */
4555 avail_in = png_ptr->IDAT_read_size;
4557 if (avail_in > png_ptr->idat_size)
4558 avail_in = (uInt)png_ptr->idat_size;
4560 /* A PNG with a gradually increasing IDAT size will defeat this attempt
4561 * to minimize memory usage by causing lots of re-allocs, but
4562 * realistically doing IDAT_read_size re-allocs is not likely to be a
4565 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
4567 png_crc_read(png_ptr, buffer, avail_in);
4568 png_ptr->idat_size -= avail_in;
4570 png_ptr->zstream.next_in = buffer;
4571 png_ptr->zstream.avail_in = avail_in;
4574 /* And set up the output side. */
4575 if (output != NULL) /* standard read */
4577 uInt out = ZLIB_IO_MAX;
4579 if (out > avail_out)
4580 out = (uInt)avail_out;
4583 png_ptr->zstream.avail_out = out;
4586 else /* after last row, checking for end */
4588 png_ptr->zstream.next_out = tmpbuf;
4589 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4592 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4593 * process. If the LZ stream is truncated the sequential reader will
4594 * terminally damage the stream, above, by reading the chunk header of the
4595 * following chunk (it then exits with png_error).
4597 * TODO: deal more elegantly with truncated IDAT lists.
4599 ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);
4601 /* Take the unconsumed output back. */
4603 avail_out += png_ptr->zstream.avail_out;
4605 else /* avail_out counts the extra bytes */
4606 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4608 png_ptr->zstream.avail_out = 0;
4610 if (ret == Z_STREAM_END)
4612 /* Do this for safety; we won't read any more into this row. */
4613 png_ptr->zstream.next_out = NULL;
4615 png_ptr->mode |= PNG_AFTER_IDAT;
4616 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4617 #ifdef PNG_READ_APNG_SUPPORTED
4618 png_ptr->num_frames_read++;
4621 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4622 png_chunk_benign_error(png_ptr, "Extra compressed data");
4628 png_zstream_error(png_ptr, ret);
4631 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4635 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4639 } while (avail_out > 0);
4643 /* The stream ended before the image; this is the same as too few IDATs so
4644 * should be handled the same way.
4647 png_error(png_ptr, "Not enough image data");
4649 else /* the deflate stream contained extra data */
4650 png_chunk_benign_error(png_ptr, "Too much image data");
4655 png_read_finish_IDAT(png_structrp png_ptr)
4657 /* We don't need any more data and the stream should have ended, however the
4658 * LZ end code may actually not have been processed. In this case we must
4659 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4660 * may still remain to be consumed.
4662 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4664 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4665 * the compressed stream, but the stream may be damaged too, so even after
4666 * this call we may need to terminate the zstream ownership.
4668 png_read_IDAT_data(png_ptr, NULL, 0);
4669 png_ptr->zstream.next_out = NULL; /* safety */
4671 /* Now clear everything out for safety; the following may not have been
4674 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4676 png_ptr->mode |= PNG_AFTER_IDAT;
4677 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4681 /* If the zstream has not been released do it now *and* terminate the reading
4682 * of the final IDAT chunk.
4684 if (png_ptr->zowner == png_IDAT)
4686 /* Always do this; the pointers otherwise point into the read buffer. */
4687 png_ptr->zstream.next_in = NULL;
4688 png_ptr->zstream.avail_in = 0;
4690 /* Now we no longer own the zstream. */
4691 png_ptr->zowner = 0;
4693 /* The slightly weird semantics of the sequential IDAT reading is that we
4694 * are always in or at the end of an IDAT chunk, so we always need to do a
4695 * crc_finish here. If idat_size is non-zero we also need to read the
4696 * spurious bytes at the end of the chunk now.
4698 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4703 png_read_finish_row(png_structrp png_ptr)
4705 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4707 /* Start of interlace block */
4708 static const png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4710 /* Offset to next interlace block */
4711 static const png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4713 /* Start of interlace block in the y direction */
4714 static const png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4716 /* Offset to next interlace block in the y direction */
4717 static const png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4719 png_debug(1, "in png_read_finish_row");
4720 png_ptr->row_number++;
4721 if (png_ptr->row_number < png_ptr->num_rows)
4724 if (png_ptr->interlaced != 0)
4726 png_ptr->row_number = 0;
4728 /* TO DO: don't do this if prev_row isn't needed (requires
4729 * read-ahead of the next row's filter byte.
4731 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4737 if (png_ptr->pass >= 7)
4740 png_ptr->iwidth = (png_ptr->width +
4741 png_pass_inc[png_ptr->pass] - 1 -
4742 png_pass_start[png_ptr->pass]) /
4743 png_pass_inc[png_ptr->pass];
4745 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4747 png_ptr->num_rows = (png_ptr->height +
4748 png_pass_yinc[png_ptr->pass] - 1 -
4749 png_pass_ystart[png_ptr->pass]) /
4750 png_pass_yinc[png_ptr->pass];
4753 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4754 break; /* libpng deinterlacing sees every row */
4756 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4758 if (png_ptr->pass < 7)
4762 /* Here after at the end of the last row of the last pass. */
4763 png_read_finish_IDAT(png_ptr);
4765 #endif /* SEQUENTIAL_READ */
4768 png_read_start_row(png_structrp png_ptr)
4770 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4772 /* Start of interlace block */
4773 static const png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4775 /* Offset to next interlace block */
4776 static const png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4778 /* Start of interlace block in the y direction */
4779 static const png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4781 /* Offset to next interlace block in the y direction */
4782 static const png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4784 unsigned int max_pixel_depth;
4787 png_debug(1, "in png_read_start_row");
4789 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4790 png_init_read_transformations(png_ptr);
4792 if (png_ptr->interlaced != 0)
4794 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4795 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4796 png_pass_ystart[0]) / png_pass_yinc[0];
4799 png_ptr->num_rows = png_ptr->height;
4801 png_ptr->iwidth = (png_ptr->width +
4802 png_pass_inc[png_ptr->pass] - 1 -
4803 png_pass_start[png_ptr->pass]) /
4804 png_pass_inc[png_ptr->pass];
4809 png_ptr->num_rows = png_ptr->height;
4810 png_ptr->iwidth = png_ptr->width;
4813 max_pixel_depth = (unsigned int)png_ptr->pixel_depth;
4815 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4816 * calculations to calculate the final pixel depth, then
4817 * png_do_read_transforms actually does the transforms. This means that the
4818 * code which effectively calculates this value is actually repeated in three
4819 * separate places. They must all match. Innocent changes to the order of
4820 * transformations can and will break libpng in a way that causes memory
4825 #ifdef PNG_READ_PACK_SUPPORTED
4826 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4827 max_pixel_depth = 8;
4830 #ifdef PNG_READ_EXPAND_SUPPORTED
4831 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4833 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4835 if (png_ptr->num_trans != 0)
4836 max_pixel_depth = 32;
4839 max_pixel_depth = 24;
4842 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4844 if (max_pixel_depth < 8)
4845 max_pixel_depth = 8;
4847 if (png_ptr->num_trans != 0)
4848 max_pixel_depth *= 2;
4851 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4853 if (png_ptr->num_trans != 0)
4855 max_pixel_depth *= 4;
4856 max_pixel_depth /= 3;
4862 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4863 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4865 # ifdef PNG_READ_EXPAND_SUPPORTED
4866 /* In fact it is an error if it isn't supported, but checking is
4869 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4871 if (png_ptr->bit_depth < 16)
4872 max_pixel_depth *= 2;
4876 png_ptr->transformations &= ~PNG_EXPAND_16;
4880 #ifdef PNG_READ_FILLER_SUPPORTED
4881 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4883 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4885 if (max_pixel_depth <= 8)
4886 max_pixel_depth = 16;
4889 max_pixel_depth = 32;
4892 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4893 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4895 if (max_pixel_depth <= 32)
4896 max_pixel_depth = 32;
4899 max_pixel_depth = 64;
4904 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4905 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4908 #ifdef PNG_READ_EXPAND_SUPPORTED
4909 (png_ptr->num_trans != 0 &&
4910 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4912 #ifdef PNG_READ_FILLER_SUPPORTED
4913 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4915 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4917 if (max_pixel_depth <= 16)
4918 max_pixel_depth = 32;
4921 max_pixel_depth = 64;
4926 if (max_pixel_depth <= 8)
4928 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4929 max_pixel_depth = 32;
4932 max_pixel_depth = 24;
4935 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4936 max_pixel_depth = 64;
4939 max_pixel_depth = 48;
4944 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4945 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4946 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4948 unsigned int user_pixel_depth = png_ptr->user_transform_depth *
4949 png_ptr->user_transform_channels;
4951 if (user_pixel_depth > max_pixel_depth)
4952 max_pixel_depth = user_pixel_depth;
4956 /* This value is stored in png_struct and double checked in the row read
4959 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4960 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4962 /* Align the width on the next larger 8 pixels. Mainly used
4965 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4966 /* Calculate the maximum bytes needed, adding a byte and a pixel
4969 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4970 1 + ((max_pixel_depth + 7) >> 3U);
4972 #ifdef PNG_MAX_MALLOC_64K
4973 if (row_bytes > (png_uint_32)65536L)
4974 png_error(png_ptr, "This image requires a row greater than 64KB");
4977 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4979 png_free(png_ptr, png_ptr->big_row_buf);
4980 png_free(png_ptr, png_ptr->big_prev_row);
4982 if (png_ptr->interlaced != 0)
4983 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4987 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4989 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4991 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4992 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4993 * of padding before and after row_buf; treat prev_row similarly.
4994 * NOTE: the alignment is to the start of the pixels, one beyond the start
4995 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4996 * was incorrect; the filter byte was aligned, which had the exact
4997 * opposite effect of that intended.
5000 png_bytep temp = png_ptr->big_row_buf + 32;
5001 size_t extra = (size_t)temp & 0x0f;
5002 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
5004 temp = png_ptr->big_prev_row + 32;
5005 extra = (size_t)temp & 0x0f;
5006 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
5009 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
5010 png_ptr->row_buf = png_ptr->big_row_buf + 31;
5011 png_ptr->prev_row = png_ptr->big_prev_row + 31;
5013 png_ptr->old_big_row_buf_size = row_bytes + 48;
5016 #ifdef PNG_MAX_MALLOC_64K
5017 if (png_ptr->rowbytes > 65535)
5018 png_error(png_ptr, "This image requires a row greater than 64KB");
5021 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
5022 png_error(png_ptr, "Row has too many bytes to allocate in memory");
5024 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
5026 png_debug1(3, "width = %u,", png_ptr->width);
5027 png_debug1(3, "height = %u,", png_ptr->height);
5028 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
5029 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
5030 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
5031 png_debug1(3, "irowbytes = %lu",
5032 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
5034 /* The sequential reader needs a buffer for IDAT, but the progressive reader
5035 * does not, so free the read buffer now regardless; the sequential reader
5036 * reallocates it on demand.
5038 if (png_ptr->read_buffer != NULL)
5040 png_bytep buffer = png_ptr->read_buffer;
5042 png_ptr->read_buffer_size = 0;
5043 png_ptr->read_buffer = NULL;
5044 png_free(png_ptr, buffer);
5047 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
5048 * value from the stream (note that this will result in a fatal error if the
5049 * IDAT stream has a bogus deflate header window_bits value, but this should
5050 * not be happening any longer!)
5052 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
5053 png_error(png_ptr, png_ptr->zstream.msg);
5055 png_ptr->flags |= PNG_FLAG_ROW_INIT;
5058 #ifdef PNG_READ_APNG_SUPPORTED
5059 /* This function is to be called after the main IDAT set has been read and
5060 * before a new IDAT is read. It resets some parts of png_ptr
5061 * to make them usable by the read functions again */
5063 png_read_reset(png_structp png_ptr)
5065 png_ptr->mode &= ~PNG_HAVE_IDAT;
5066 png_ptr->mode &= ~PNG_AFTER_IDAT;
5067 png_ptr->row_number = 0;
5072 png_read_reinit(png_structp png_ptr, png_infop info_ptr)
5074 png_ptr->width = info_ptr->next_frame_width;
5075 png_ptr->height = info_ptr->next_frame_height;
5076 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
5077 png_ptr->info_rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,
5079 if (png_ptr->prev_row)
5080 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
5083 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
5084 /* same as png_read_reset() but for the progressive reader */
5086 png_progressive_read_reset(png_structp png_ptr)
5088 #ifdef PNG_READ_INTERLACING_SUPPORTED
5089 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
5091 /* Start of interlace block */
5092 const int png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
5094 /* Offset to next interlace block */
5095 const int png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
5097 /* Start of interlace block in the y direction */
5098 const int png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
5100 /* Offset to next interlace block in the y direction */
5101 const int png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
5103 if (png_ptr->interlaced)
5105 if (!(png_ptr->transformations & PNG_INTERLACE))
5106 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
5107 png_pass_ystart[0]) / png_pass_yinc[0];
5109 png_ptr->num_rows = png_ptr->height;
5111 png_ptr->iwidth = (png_ptr->width +
5112 png_pass_inc[png_ptr->pass] - 1 -
5113 png_pass_start[png_ptr->pass]) /
5114 png_pass_inc[png_ptr->pass];
5117 #endif /* PNG_READ_INTERLACING_SUPPORTED */
5119 png_ptr->num_rows = png_ptr->height;
5120 png_ptr->iwidth = png_ptr->width;
5122 png_ptr->flags &= ~PNG_FLAG_ZSTREAM_ENDED;
5123 if (inflateReset(&(png_ptr->zstream)) != Z_OK)
5124 png_error(png_ptr, "inflateReset failed");
5125 png_ptr->zstream.avail_in = 0;
5126 png_ptr->zstream.next_in = 0;
5127 png_ptr->zstream.next_out = png_ptr->row_buf;
5128 png_ptr->zstream.avail_out = (uInt)PNG_ROWBYTES(png_ptr->pixel_depth,
5129 png_ptr->iwidth) + 1;
5131 #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
5132 #endif /* PNG_READ_APNG_SUPPORTED */