Release 9.12.
[wine.git] / libs / png / pngread.c
blob07a39df6e2e3f91a24ff1fc8a4aaf2aa5bcdd808
2 /* pngread.c - read a PNG file
4 * Copyright (c) 2018-2024 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 an application calls directly to
14 * read a PNG file or stream.
17 #include "pngpriv.h"
18 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
19 # include <errno.h>
20 #endif
22 #ifdef PNG_READ_SUPPORTED
24 /* Create a PNG structure for reading, and allocate any memory needed. */
25 PNG_FUNCTION(png_structp,PNGAPI
26 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
27 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
29 #ifndef PNG_USER_MEM_SUPPORTED
30 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
31 error_fn, warn_fn, NULL, NULL, NULL);
32 #else
33 return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
34 warn_fn, NULL, NULL, NULL);
37 /* Alternate create PNG structure for reading, and allocate any memory
38 * needed.
40 PNG_FUNCTION(png_structp,PNGAPI
41 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
42 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
43 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
45 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
46 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
47 #endif /* USER_MEM */
49 if (png_ptr != NULL)
51 png_ptr->mode = PNG_IS_READ_STRUCT;
53 /* Added in libpng-1.6.0; this can be used to detect a read structure if
54 * required (it will be zero in a write structure.)
56 # ifdef PNG_SEQUENTIAL_READ_SUPPORTED
57 png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
58 # endif
60 # ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
61 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
63 /* In stable builds only warn if an application error can be completely
64 * handled.
66 # if PNG_RELEASE_BUILD
67 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
68 # endif
69 # endif
71 /* TODO: delay this, it can be done in png_init_io (if the app doesn't
72 * do it itself) avoiding setting the default function if it is not
73 * required.
75 png_set_read_fn(png_ptr, NULL, NULL);
78 return png_ptr;
82 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
83 /* Read the information before the actual image data. This has been
84 * changed in v0.90 to allow reading a file that already has the magic
85 * bytes read from the stream. You can tell libpng how many bytes have
86 * been read from the beginning of the stream (up to the maximum of 8)
87 * via png_set_sig_bytes(), and we will only check the remaining bytes
88 * here. The application can then have access to the signature bytes we
89 * read if it is determined that this isn't a valid PNG file.
91 void PNGAPI
92 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
94 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
95 int keep;
96 #endif
98 png_debug(1, "in png_read_info");
100 if (png_ptr == NULL || info_ptr == NULL)
101 return;
103 /* Read and check the PNG file signature. */
104 png_read_sig(png_ptr, info_ptr);
106 for (;;)
108 png_uint_32 length = png_read_chunk_header(png_ptr);
109 png_uint_32 chunk_name = png_ptr->chunk_name;
111 /* IDAT logic needs to happen here to simplify getting the two flags
112 * right.
114 if (chunk_name == png_IDAT)
116 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
117 png_chunk_error(png_ptr, "Missing IHDR before IDAT");
119 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
120 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
121 png_chunk_error(png_ptr, "Missing PLTE before IDAT");
123 else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
124 png_chunk_benign_error(png_ptr, "Too many IDATs found");
126 png_ptr->mode |= PNG_HAVE_IDAT;
129 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
131 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
132 png_ptr->mode |= PNG_AFTER_IDAT;
135 /* This should be a binary subdivision search or a hash for
136 * matching the chunk name rather than a linear search.
138 if (chunk_name == png_IHDR)
139 png_handle_IHDR(png_ptr, info_ptr, length);
141 else if (chunk_name == png_IEND)
142 png_handle_IEND(png_ptr, info_ptr, length);
144 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
145 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
147 png_handle_unknown(png_ptr, info_ptr, length, keep);
149 if (chunk_name == png_PLTE)
150 png_ptr->mode |= PNG_HAVE_PLTE;
152 else if (chunk_name == png_IDAT)
154 png_ptr->idat_size = 0; /* It has been consumed */
155 break;
158 #endif
159 else if (chunk_name == png_PLTE)
160 png_handle_PLTE(png_ptr, info_ptr, length);
162 else if (chunk_name == png_IDAT)
164 png_ptr->idat_size = length;
165 break;
168 #ifdef PNG_READ_bKGD_SUPPORTED
169 else if (chunk_name == png_bKGD)
170 png_handle_bKGD(png_ptr, info_ptr, length);
171 #endif
173 #ifdef PNG_READ_cHRM_SUPPORTED
174 else if (chunk_name == png_cHRM)
175 png_handle_cHRM(png_ptr, info_ptr, length);
176 #endif
178 #ifdef PNG_READ_eXIf_SUPPORTED
179 else if (chunk_name == png_eXIf)
180 png_handle_eXIf(png_ptr, info_ptr, length);
181 #endif
183 #ifdef PNG_READ_gAMA_SUPPORTED
184 else if (chunk_name == png_gAMA)
185 png_handle_gAMA(png_ptr, info_ptr, length);
186 #endif
188 #ifdef PNG_READ_hIST_SUPPORTED
189 else if (chunk_name == png_hIST)
190 png_handle_hIST(png_ptr, info_ptr, length);
191 #endif
193 #ifdef PNG_READ_oFFs_SUPPORTED
194 else if (chunk_name == png_oFFs)
195 png_handle_oFFs(png_ptr, info_ptr, length);
196 #endif
198 #ifdef PNG_READ_pCAL_SUPPORTED
199 else if (chunk_name == png_pCAL)
200 png_handle_pCAL(png_ptr, info_ptr, length);
201 #endif
203 #ifdef PNG_READ_sCAL_SUPPORTED
204 else if (chunk_name == png_sCAL)
205 png_handle_sCAL(png_ptr, info_ptr, length);
206 #endif
208 #ifdef PNG_READ_pHYs_SUPPORTED
209 else if (chunk_name == png_pHYs)
210 png_handle_pHYs(png_ptr, info_ptr, length);
211 #endif
213 #ifdef PNG_READ_sBIT_SUPPORTED
214 else if (chunk_name == png_sBIT)
215 png_handle_sBIT(png_ptr, info_ptr, length);
216 #endif
218 #ifdef PNG_READ_sRGB_SUPPORTED
219 else if (chunk_name == png_sRGB)
220 png_handle_sRGB(png_ptr, info_ptr, length);
221 #endif
223 #ifdef PNG_READ_iCCP_SUPPORTED
224 else if (chunk_name == png_iCCP)
225 png_handle_iCCP(png_ptr, info_ptr, length);
226 #endif
228 #ifdef PNG_READ_sPLT_SUPPORTED
229 else if (chunk_name == png_sPLT)
230 png_handle_sPLT(png_ptr, info_ptr, length);
231 #endif
233 #ifdef PNG_READ_tEXt_SUPPORTED
234 else if (chunk_name == png_tEXt)
235 png_handle_tEXt(png_ptr, info_ptr, length);
236 #endif
238 #ifdef PNG_READ_tIME_SUPPORTED
239 else if (chunk_name == png_tIME)
240 png_handle_tIME(png_ptr, info_ptr, length);
241 #endif
243 #ifdef PNG_READ_tRNS_SUPPORTED
244 else if (chunk_name == png_tRNS)
245 png_handle_tRNS(png_ptr, info_ptr, length);
246 #endif
248 #ifdef PNG_READ_zTXt_SUPPORTED
249 else if (chunk_name == png_zTXt)
250 png_handle_zTXt(png_ptr, info_ptr, length);
251 #endif
253 #ifdef PNG_READ_iTXt_SUPPORTED
254 else if (chunk_name == png_iTXt)
255 png_handle_iTXt(png_ptr, info_ptr, length);
256 #endif
258 else
259 png_handle_unknown(png_ptr, info_ptr, length,
260 PNG_HANDLE_CHUNK_AS_DEFAULT);
263 #endif /* SEQUENTIAL_READ */
265 /* Optional call to update the users info_ptr structure */
266 void PNGAPI
267 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
269 png_debug(1, "in png_read_update_info");
271 if (png_ptr != NULL)
273 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
275 png_read_start_row(png_ptr);
277 # ifdef PNG_READ_TRANSFORMS_SUPPORTED
278 png_read_transform_info(png_ptr, info_ptr);
279 # else
280 PNG_UNUSED(info_ptr)
281 # endif
284 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
285 else
286 png_app_error(png_ptr,
287 "png_read_update_info/png_start_read_image: duplicate call");
291 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
292 /* Initialize palette, background, etc, after transformations
293 * are set, but before any reading takes place. This allows
294 * the user to obtain a gamma-corrected palette, for example.
295 * If the user doesn't call this, we will do it ourselves.
297 void PNGAPI
298 png_start_read_image(png_structrp png_ptr)
300 png_debug(1, "in png_start_read_image");
302 if (png_ptr != NULL)
304 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
305 png_read_start_row(png_ptr);
307 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
308 else
309 png_app_error(png_ptr,
310 "png_start_read_image/png_read_update_info: duplicate call");
313 #endif /* SEQUENTIAL_READ */
315 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
316 #ifdef PNG_MNG_FEATURES_SUPPORTED
317 /* Undoes intrapixel differencing,
318 * NOTE: this is apparently only supported in the 'sequential' reader.
320 static void
321 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
323 png_debug(1, "in png_do_read_intrapixel");
325 if (
326 (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
328 int bytes_per_pixel;
329 png_uint_32 row_width = row_info->width;
331 if (row_info->bit_depth == 8)
333 png_bytep rp;
334 png_uint_32 i;
336 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
337 bytes_per_pixel = 3;
339 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
340 bytes_per_pixel = 4;
342 else
343 return;
345 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
347 *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
348 *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
351 else if (row_info->bit_depth == 16)
353 png_bytep rp;
354 png_uint_32 i;
356 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
357 bytes_per_pixel = 6;
359 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
360 bytes_per_pixel = 8;
362 else
363 return;
365 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
367 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
368 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
369 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
370 png_uint_32 red = (s0 + s1 + 65536) & 0xffff;
371 png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
372 *(rp ) = (png_byte)((red >> 8) & 0xff);
373 *(rp + 1) = (png_byte)(red & 0xff);
374 *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
375 *(rp + 5) = (png_byte)(blue & 0xff);
380 #endif /* MNG_FEATURES */
382 void PNGAPI
383 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
385 png_row_info row_info;
387 if (png_ptr == NULL)
388 return;
390 png_debug2(1, "in png_read_row (row %lu, pass %d)",
391 (unsigned long)png_ptr->row_number, png_ptr->pass);
393 /* png_read_start_row sets the information (in particular iwidth) for this
394 * interlace pass.
396 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
397 png_read_start_row(png_ptr);
399 /* 1.5.6: row_info moved out of png_struct to a local here. */
400 row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
401 row_info.color_type = png_ptr->color_type;
402 row_info.bit_depth = png_ptr->bit_depth;
403 row_info.channels = png_ptr->channels;
404 row_info.pixel_depth = png_ptr->pixel_depth;
405 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
407 #ifdef PNG_WARNINGS_SUPPORTED
408 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
410 /* Check for transforms that have been set but were defined out */
411 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
412 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
413 png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
414 #endif
416 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
417 if ((png_ptr->transformations & PNG_FILLER) != 0)
418 png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
419 #endif
421 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
422 !defined(PNG_READ_PACKSWAP_SUPPORTED)
423 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
424 png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
425 #endif
427 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
428 if ((png_ptr->transformations & PNG_PACK) != 0)
429 png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
430 #endif
432 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
433 if ((png_ptr->transformations & PNG_SHIFT) != 0)
434 png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
435 #endif
437 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
438 if ((png_ptr->transformations & PNG_BGR) != 0)
439 png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
440 #endif
442 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
443 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
444 png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
445 #endif
447 #endif /* WARNINGS */
449 #ifdef PNG_READ_INTERLACING_SUPPORTED
450 /* If interlaced and we do not need a new row, combine row and return.
451 * Notice that the pixels we have from previous rows have been transformed
452 * already; we can only combine like with like (transformed or
453 * untransformed) and, because of the libpng API for interlaced images, this
454 * means we must transform before de-interlacing.
456 if (png_ptr->interlaced != 0 &&
457 (png_ptr->transformations & PNG_INTERLACE) != 0)
459 switch (png_ptr->pass)
461 case 0:
462 if (png_ptr->row_number & 0x07)
464 if (dsp_row != NULL)
465 png_combine_row(png_ptr, dsp_row, 1/*display*/);
466 png_read_finish_row(png_ptr);
467 return;
469 break;
471 case 1:
472 if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
474 if (dsp_row != NULL)
475 png_combine_row(png_ptr, dsp_row, 1/*display*/);
477 png_read_finish_row(png_ptr);
478 return;
480 break;
482 case 2:
483 if ((png_ptr->row_number & 0x07) != 4)
485 if (dsp_row != NULL && (png_ptr->row_number & 4))
486 png_combine_row(png_ptr, dsp_row, 1/*display*/);
488 png_read_finish_row(png_ptr);
489 return;
491 break;
493 case 3:
494 if ((png_ptr->row_number & 3) || png_ptr->width < 3)
496 if (dsp_row != NULL)
497 png_combine_row(png_ptr, dsp_row, 1/*display*/);
499 png_read_finish_row(png_ptr);
500 return;
502 break;
504 case 4:
505 if ((png_ptr->row_number & 3) != 2)
507 if (dsp_row != NULL && (png_ptr->row_number & 2))
508 png_combine_row(png_ptr, dsp_row, 1/*display*/);
510 png_read_finish_row(png_ptr);
511 return;
513 break;
515 case 5:
516 if ((png_ptr->row_number & 1) || png_ptr->width < 2)
518 if (dsp_row != NULL)
519 png_combine_row(png_ptr, dsp_row, 1/*display*/);
521 png_read_finish_row(png_ptr);
522 return;
524 break;
526 default:
527 case 6:
528 if ((png_ptr->row_number & 1) == 0)
530 png_read_finish_row(png_ptr);
531 return;
533 break;
536 #endif
538 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
539 png_error(png_ptr, "Invalid attempt to read row data");
541 /* Fill the row with IDAT data: */
542 png_ptr->row_buf[0]=255; /* to force error if no data was found */
543 png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
545 if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
547 if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
548 png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
549 png_ptr->prev_row + 1, png_ptr->row_buf[0]);
550 else
551 png_error(png_ptr, "bad adaptive filter value");
554 /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
555 * 1.5.6, while the buffer really is this big in current versions of libpng
556 * it may not be in the future, so this was changed just to copy the
557 * interlaced count:
559 memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
561 #ifdef PNG_MNG_FEATURES_SUPPORTED
562 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
563 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
565 /* Intrapixel differencing */
566 png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
568 #endif
570 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
571 if (png_ptr->transformations
572 # ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
573 || png_ptr->num_palette_max >= 0
574 # endif
576 png_do_read_transformations(png_ptr, &row_info);
577 #endif
579 /* The transformed pixel depth should match the depth now in row_info. */
580 if (png_ptr->transformed_pixel_depth == 0)
582 png_ptr->transformed_pixel_depth = row_info.pixel_depth;
583 if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
584 png_error(png_ptr, "sequential row overflow");
587 else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
588 png_error(png_ptr, "internal sequential row size calculation error");
590 #ifdef PNG_READ_INTERLACING_SUPPORTED
591 /* Expand interlaced rows to full size */
592 if (png_ptr->interlaced != 0 &&
593 (png_ptr->transformations & PNG_INTERLACE) != 0)
595 if (png_ptr->pass < 6)
596 png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
597 png_ptr->transformations);
599 if (dsp_row != NULL)
600 png_combine_row(png_ptr, dsp_row, 1/*display*/);
602 if (row != NULL)
603 png_combine_row(png_ptr, row, 0/*row*/);
606 else
607 #endif
609 if (row != NULL)
610 png_combine_row(png_ptr, row, -1/*ignored*/);
612 if (dsp_row != NULL)
613 png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
615 png_read_finish_row(png_ptr);
617 if (png_ptr->read_row_fn != NULL)
618 (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
621 #endif /* SEQUENTIAL_READ */
623 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
624 /* Read one or more rows of image data. If the image is interlaced,
625 * and png_set_interlace_handling() has been called, the rows need to
626 * contain the contents of the rows from the previous pass. If the
627 * image has alpha or transparency, and png_handle_alpha()[*] has been
628 * called, the rows contents must be initialized to the contents of the
629 * screen.
631 * "row" holds the actual image, and pixels are placed in it
632 * as they arrive. If the image is displayed after each pass, it will
633 * appear to "sparkle" in. "display_row" can be used to display a
634 * "chunky" progressive image, with finer detail added as it becomes
635 * available. If you do not want this "chunky" display, you may pass
636 * NULL for display_row. If you do not want the sparkle display, and
637 * you have not called png_handle_alpha(), you may pass NULL for rows.
638 * If you have called png_handle_alpha(), and the image has either an
639 * alpha channel or a transparency chunk, you must provide a buffer for
640 * rows. In this case, you do not have to provide a display_row buffer
641 * also, but you may. If the image is not interlaced, or if you have
642 * not called png_set_interlace_handling(), the display_row buffer will
643 * be ignored, so pass NULL to it.
645 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
648 void PNGAPI
649 png_read_rows(png_structrp png_ptr, png_bytepp row,
650 png_bytepp display_row, png_uint_32 num_rows)
652 png_uint_32 i;
653 png_bytepp rp;
654 png_bytepp dp;
656 png_debug(1, "in png_read_rows");
658 if (png_ptr == NULL)
659 return;
661 rp = row;
662 dp = display_row;
663 if (rp != NULL && dp != NULL)
664 for (i = 0; i < num_rows; i++)
666 png_bytep rptr = *rp++;
667 png_bytep dptr = *dp++;
669 png_read_row(png_ptr, rptr, dptr);
672 else if (rp != NULL)
673 for (i = 0; i < num_rows; i++)
675 png_bytep rptr = *rp;
676 png_read_row(png_ptr, rptr, NULL);
677 rp++;
680 else if (dp != NULL)
681 for (i = 0; i < num_rows; i++)
683 png_bytep dptr = *dp;
684 png_read_row(png_ptr, NULL, dptr);
685 dp++;
688 #endif /* SEQUENTIAL_READ */
690 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
691 /* Read the entire image. If the image has an alpha channel or a tRNS
692 * chunk, and you have called png_handle_alpha()[*], you will need to
693 * initialize the image to the current image that PNG will be overlaying.
694 * We set the num_rows again here, in case it was incorrectly set in
695 * png_read_start_row() by a call to png_read_update_info() or
696 * png_start_read_image() if png_set_interlace_handling() wasn't called
697 * prior to either of these functions like it should have been. You can
698 * only call this function once. If you desire to have an image for
699 * each pass of a interlaced image, use png_read_rows() instead.
701 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
703 void PNGAPI
704 png_read_image(png_structrp png_ptr, png_bytepp image)
706 png_uint_32 i, image_height;
707 int pass, j;
708 png_bytepp rp;
710 png_debug(1, "in png_read_image");
712 if (png_ptr == NULL)
713 return;
715 #ifdef PNG_READ_INTERLACING_SUPPORTED
716 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
718 pass = png_set_interlace_handling(png_ptr);
719 /* And make sure transforms are initialized. */
720 png_start_read_image(png_ptr);
722 else
724 if (png_ptr->interlaced != 0 &&
725 (png_ptr->transformations & PNG_INTERLACE) == 0)
727 /* Caller called png_start_read_image or png_read_update_info without
728 * first turning on the PNG_INTERLACE transform. We can fix this here,
729 * but the caller should do it!
731 png_warning(png_ptr, "Interlace handling should be turned on when "
732 "using png_read_image");
733 /* Make sure this is set correctly */
734 png_ptr->num_rows = png_ptr->height;
737 /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
738 * the above error case.
740 pass = png_set_interlace_handling(png_ptr);
742 #else
743 if (png_ptr->interlaced)
744 png_error(png_ptr,
745 "Cannot read interlaced image -- interlace handler disabled");
747 pass = 1;
748 #endif
750 image_height=png_ptr->height;
752 for (j = 0; j < pass; j++)
754 rp = image;
755 for (i = 0; i < image_height; i++)
757 png_read_row(png_ptr, *rp, NULL);
758 rp++;
762 #endif /* SEQUENTIAL_READ */
764 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
765 /* Read the end of the PNG file. Will not read past the end of the
766 * file, will verify the end is accurate, and will read any comments
767 * or time information at the end of the file, if info is not NULL.
769 void PNGAPI
770 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
772 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
773 int keep;
774 #endif
776 png_debug(1, "in png_read_end");
778 if (png_ptr == NULL)
779 return;
781 /* If png_read_end is called in the middle of reading the rows there may
782 * still be pending IDAT data and an owned zstream. Deal with this here.
784 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
785 if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
786 #endif
787 png_read_finish_IDAT(png_ptr);
789 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
790 /* Report invalid palette index; added at libng-1.5.10 */
791 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
792 png_ptr->num_palette_max >= png_ptr->num_palette)
793 png_benign_error(png_ptr, "Read palette index exceeding num_palette");
794 #endif
798 png_uint_32 length = png_read_chunk_header(png_ptr);
799 png_uint_32 chunk_name = png_ptr->chunk_name;
801 if (chunk_name != png_IDAT)
802 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
804 if (chunk_name == png_IEND)
805 png_handle_IEND(png_ptr, info_ptr, length);
807 else if (chunk_name == png_IHDR)
808 png_handle_IHDR(png_ptr, info_ptr, length);
810 else if (info_ptr == NULL)
811 png_crc_finish(png_ptr, length);
813 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
814 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
816 if (chunk_name == png_IDAT)
818 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
819 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
820 png_benign_error(png_ptr, ".Too many IDATs found");
822 png_handle_unknown(png_ptr, info_ptr, length, keep);
823 if (chunk_name == png_PLTE)
824 png_ptr->mode |= PNG_HAVE_PLTE;
826 #endif
828 else if (chunk_name == png_IDAT)
830 /* Zero length IDATs are legal after the last IDAT has been
831 * read, but not after other chunks have been read. 1.6 does not
832 * always read all the deflate data; specifically it cannot be relied
833 * upon to read the Adler32 at the end. If it doesn't ignore IDAT
834 * chunks which are longer than zero as well:
836 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
837 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
838 png_benign_error(png_ptr, "..Too many IDATs found");
840 png_crc_finish(png_ptr, length);
842 else if (chunk_name == png_PLTE)
843 png_handle_PLTE(png_ptr, info_ptr, length);
845 #ifdef PNG_READ_bKGD_SUPPORTED
846 else if (chunk_name == png_bKGD)
847 png_handle_bKGD(png_ptr, info_ptr, length);
848 #endif
850 #ifdef PNG_READ_cHRM_SUPPORTED
851 else if (chunk_name == png_cHRM)
852 png_handle_cHRM(png_ptr, info_ptr, length);
853 #endif
855 #ifdef PNG_READ_eXIf_SUPPORTED
856 else if (chunk_name == png_eXIf)
857 png_handle_eXIf(png_ptr, info_ptr, length);
858 #endif
860 #ifdef PNG_READ_gAMA_SUPPORTED
861 else if (chunk_name == png_gAMA)
862 png_handle_gAMA(png_ptr, info_ptr, length);
863 #endif
865 #ifdef PNG_READ_hIST_SUPPORTED
866 else if (chunk_name == png_hIST)
867 png_handle_hIST(png_ptr, info_ptr, length);
868 #endif
870 #ifdef PNG_READ_oFFs_SUPPORTED
871 else if (chunk_name == png_oFFs)
872 png_handle_oFFs(png_ptr, info_ptr, length);
873 #endif
875 #ifdef PNG_READ_pCAL_SUPPORTED
876 else if (chunk_name == png_pCAL)
877 png_handle_pCAL(png_ptr, info_ptr, length);
878 #endif
880 #ifdef PNG_READ_sCAL_SUPPORTED
881 else if (chunk_name == png_sCAL)
882 png_handle_sCAL(png_ptr, info_ptr, length);
883 #endif
885 #ifdef PNG_READ_pHYs_SUPPORTED
886 else if (chunk_name == png_pHYs)
887 png_handle_pHYs(png_ptr, info_ptr, length);
888 #endif
890 #ifdef PNG_READ_sBIT_SUPPORTED
891 else if (chunk_name == png_sBIT)
892 png_handle_sBIT(png_ptr, info_ptr, length);
893 #endif
895 #ifdef PNG_READ_sRGB_SUPPORTED
896 else if (chunk_name == png_sRGB)
897 png_handle_sRGB(png_ptr, info_ptr, length);
898 #endif
900 #ifdef PNG_READ_iCCP_SUPPORTED
901 else if (chunk_name == png_iCCP)
902 png_handle_iCCP(png_ptr, info_ptr, length);
903 #endif
905 #ifdef PNG_READ_sPLT_SUPPORTED
906 else if (chunk_name == png_sPLT)
907 png_handle_sPLT(png_ptr, info_ptr, length);
908 #endif
910 #ifdef PNG_READ_tEXt_SUPPORTED
911 else if (chunk_name == png_tEXt)
912 png_handle_tEXt(png_ptr, info_ptr, length);
913 #endif
915 #ifdef PNG_READ_tIME_SUPPORTED
916 else if (chunk_name == png_tIME)
917 png_handle_tIME(png_ptr, info_ptr, length);
918 #endif
920 #ifdef PNG_READ_tRNS_SUPPORTED
921 else if (chunk_name == png_tRNS)
922 png_handle_tRNS(png_ptr, info_ptr, length);
923 #endif
925 #ifdef PNG_READ_zTXt_SUPPORTED
926 else if (chunk_name == png_zTXt)
927 png_handle_zTXt(png_ptr, info_ptr, length);
928 #endif
930 #ifdef PNG_READ_iTXt_SUPPORTED
931 else if (chunk_name == png_iTXt)
932 png_handle_iTXt(png_ptr, info_ptr, length);
933 #endif
935 else
936 png_handle_unknown(png_ptr, info_ptr, length,
937 PNG_HANDLE_CHUNK_AS_DEFAULT);
938 } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
940 #endif /* SEQUENTIAL_READ */
942 /* Free all memory used in the read struct */
943 static void
944 png_read_destroy(png_structrp png_ptr)
946 png_debug(1, "in png_read_destroy");
948 #ifdef PNG_READ_GAMMA_SUPPORTED
949 png_destroy_gamma_table(png_ptr);
950 #endif
952 png_free(png_ptr, png_ptr->big_row_buf);
953 png_ptr->big_row_buf = NULL;
954 png_free(png_ptr, png_ptr->big_prev_row);
955 png_ptr->big_prev_row = NULL;
956 png_free(png_ptr, png_ptr->read_buffer);
957 png_ptr->read_buffer = NULL;
959 #ifdef PNG_READ_QUANTIZE_SUPPORTED
960 png_free(png_ptr, png_ptr->palette_lookup);
961 png_ptr->palette_lookup = NULL;
962 png_free(png_ptr, png_ptr->quantize_index);
963 png_ptr->quantize_index = NULL;
964 #endif
966 if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
968 png_zfree(png_ptr, png_ptr->palette);
969 png_ptr->palette = NULL;
971 png_ptr->free_me &= ~PNG_FREE_PLTE;
973 #if defined(PNG_tRNS_SUPPORTED) || \
974 defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
975 if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
977 png_free(png_ptr, png_ptr->trans_alpha);
978 png_ptr->trans_alpha = NULL;
980 png_ptr->free_me &= ~PNG_FREE_TRNS;
981 #endif
983 inflateEnd(&png_ptr->zstream);
985 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
986 png_free(png_ptr, png_ptr->save_buffer);
987 png_ptr->save_buffer = NULL;
988 #endif
990 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
991 defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
992 png_free(png_ptr, png_ptr->unknown_chunk.data);
993 png_ptr->unknown_chunk.data = NULL;
994 #endif
996 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
997 png_free(png_ptr, png_ptr->chunk_list);
998 png_ptr->chunk_list = NULL;
999 #endif
1001 #if defined(PNG_READ_EXPAND_SUPPORTED) && \
1002 defined(PNG_ARM_NEON_IMPLEMENTATION)
1003 png_free(png_ptr, png_ptr->riffled_palette);
1004 png_ptr->riffled_palette = NULL;
1005 #endif
1007 /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
1008 * callbacks are still set at this point. They are required to complete the
1009 * destruction of the png_struct itself.
1013 /* Free all memory used by the read */
1014 void PNGAPI
1015 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
1016 png_infopp end_info_ptr_ptr)
1018 png_structrp png_ptr = NULL;
1020 png_debug(1, "in png_destroy_read_struct");
1022 if (png_ptr_ptr != NULL)
1023 png_ptr = *png_ptr_ptr;
1025 if (png_ptr == NULL)
1026 return;
1028 /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1029 * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1030 * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1032 png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1033 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1035 *png_ptr_ptr = NULL;
1036 png_read_destroy(png_ptr);
1037 png_destroy_png_struct(png_ptr);
1040 void PNGAPI
1041 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1043 if (png_ptr == NULL)
1044 return;
1046 png_ptr->read_row_fn = read_row_fn;
1050 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1051 #ifdef PNG_INFO_IMAGE_SUPPORTED
1052 void PNGAPI
1053 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1054 int transforms, voidp params)
1056 png_debug(1, "in png_read_png");
1058 if (png_ptr == NULL || info_ptr == NULL)
1059 return;
1061 /* png_read_info() gives us all of the information from the
1062 * PNG file before the first IDAT (image data chunk).
1064 png_read_info(png_ptr, info_ptr);
1065 if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1066 png_error(png_ptr, "Image is too high to process with png_read_png()");
1068 /* -------------- image transformations start here ------------------- */
1069 /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1070 * is not implemented. This will only happen in de-configured (non-default)
1071 * libpng builds. The results can be unexpected - png_read_png may return
1072 * short or mal-formed rows because the transform is skipped.
1075 /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1077 if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1078 /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1079 * did in earlier versions, while "scale_16" is now more accurate.
1081 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1082 png_set_scale_16(png_ptr);
1083 #else
1084 png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1085 #endif
1087 /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1088 * latter by doing SCALE first. This is ok and allows apps not to check for
1089 * which is supported to get the right answer.
1091 if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1092 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1093 png_set_strip_16(png_ptr);
1094 #else
1095 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1096 #endif
1098 /* Strip alpha bytes from the input data without combining with
1099 * the background (not recommended).
1101 if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1102 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1103 png_set_strip_alpha(png_ptr);
1104 #else
1105 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1106 #endif
1108 /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1109 * byte into separate bytes (useful for paletted and grayscale images).
1111 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1112 #ifdef PNG_READ_PACK_SUPPORTED
1113 png_set_packing(png_ptr);
1114 #else
1115 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1116 #endif
1118 /* Change the order of packed pixels to least significant bit first
1119 * (not useful if you are using png_set_packing).
1121 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1122 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1123 png_set_packswap(png_ptr);
1124 #else
1125 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1126 #endif
1128 /* Expand paletted colors into true RGB triplets
1129 * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1130 * Expand paletted or RGB images with transparency to full alpha
1131 * channels so the data will be available as RGBA quartets.
1133 if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1134 #ifdef PNG_READ_EXPAND_SUPPORTED
1135 png_set_expand(png_ptr);
1136 #else
1137 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1138 #endif
1140 /* We don't handle background color or gamma transformation or quantizing.
1143 /* Invert monochrome files to have 0 as white and 1 as black
1145 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1146 #ifdef PNG_READ_INVERT_SUPPORTED
1147 png_set_invert_mono(png_ptr);
1148 #else
1149 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1150 #endif
1152 /* If you want to shift the pixel values from the range [0,255] or
1153 * [0,65535] to the original [0,7] or [0,31], or whatever range the
1154 * colors were originally in:
1156 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1157 #ifdef PNG_READ_SHIFT_SUPPORTED
1158 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1159 png_set_shift(png_ptr, &info_ptr->sig_bit);
1160 #else
1161 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1162 #endif
1164 /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1165 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1166 #ifdef PNG_READ_BGR_SUPPORTED
1167 png_set_bgr(png_ptr);
1168 #else
1169 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1170 #endif
1172 /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1173 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1174 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1175 png_set_swap_alpha(png_ptr);
1176 #else
1177 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1178 #endif
1180 /* Swap bytes of 16-bit files to least significant byte first */
1181 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1182 #ifdef PNG_READ_SWAP_SUPPORTED
1183 png_set_swap(png_ptr);
1184 #else
1185 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1186 #endif
1188 /* Added at libpng-1.2.41 */
1189 /* Invert the alpha channel from opacity to transparency */
1190 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1191 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1192 png_set_invert_alpha(png_ptr);
1193 #else
1194 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1195 #endif
1197 /* Added at libpng-1.2.41 */
1198 /* Expand grayscale image to RGB */
1199 if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1200 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1201 png_set_gray_to_rgb(png_ptr);
1202 #else
1203 png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1204 #endif
1206 /* Added at libpng-1.5.4 */
1207 if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1208 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1209 png_set_expand_16(png_ptr);
1210 #else
1211 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1212 #endif
1214 /* We don't handle adding filler bytes */
1216 /* We use png_read_image and rely on that for interlace handling, but we also
1217 * call png_read_update_info therefore must turn on interlace handling now:
1219 (void)png_set_interlace_handling(png_ptr);
1221 /* Optional call to gamma correct and add the background to the palette
1222 * and update info structure. REQUIRED if you are expecting libpng to
1223 * update the palette for you (i.e., you selected such a transform above).
1225 png_read_update_info(png_ptr, info_ptr);
1227 /* -------------- image transformations end here ------------------- */
1229 png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1230 if (info_ptr->row_pointers == NULL)
1232 png_uint_32 iptr;
1234 info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1235 info_ptr->height * (sizeof (png_bytep))));
1237 for (iptr=0; iptr<info_ptr->height; iptr++)
1238 info_ptr->row_pointers[iptr] = NULL;
1240 info_ptr->free_me |= PNG_FREE_ROWS;
1242 for (iptr = 0; iptr < info_ptr->height; iptr++)
1243 info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1244 png_malloc(png_ptr, info_ptr->rowbytes));
1247 png_read_image(png_ptr, info_ptr->row_pointers);
1248 info_ptr->valid |= PNG_INFO_IDAT;
1250 /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1251 png_read_end(png_ptr, info_ptr);
1253 PNG_UNUSED(params)
1255 #endif /* INFO_IMAGE */
1256 #endif /* SEQUENTIAL_READ */
1258 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1259 /* SIMPLIFIED READ
1261 * This code currently relies on the sequential reader, though it could easily
1262 * be made to work with the progressive one.
1264 /* Arguments to png_image_finish_read: */
1266 /* Encoding of PNG data (used by the color-map code) */
1267 # define P_NOTSET 0 /* File encoding not yet known */
1268 # define P_sRGB 1 /* 8-bit encoded to sRGB gamma */
1269 # define P_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1270 # define P_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */
1271 # define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1273 /* Color-map processing: after libpng has run on the PNG image further
1274 * processing may be needed to convert the data to color-map indices.
1276 #define PNG_CMAP_NONE 0
1277 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */
1278 #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */
1279 #define PNG_CMAP_RGB 3 /* Process RGB data */
1280 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1282 /* The following document where the background is for each processing case. */
1283 #define PNG_CMAP_NONE_BACKGROUND 256
1284 #define PNG_CMAP_GA_BACKGROUND 231
1285 #define PNG_CMAP_TRANS_BACKGROUND 254
1286 #define PNG_CMAP_RGB_BACKGROUND 256
1287 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1289 typedef struct
1291 /* Arguments: */
1292 png_imagep image;
1293 png_voidp buffer;
1294 png_int_32 row_stride;
1295 png_voidp colormap;
1296 png_const_colorp background;
1297 /* Local variables: */
1298 png_voidp local_row;
1299 png_voidp first_row;
1300 ptrdiff_t row_bytes; /* step between rows */
1301 int file_encoding; /* E_ values above */
1302 png_fixed_point gamma_to_linear; /* For P_FILE, reciprocal of gamma */
1303 int colormap_processing; /* PNG_CMAP_ values above */
1304 } png_image_read_control;
1306 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1307 * called, so setting up the jmp_buf is not required. This means that anything
1308 * called from here must *not* call png_malloc - it has to call png_malloc_warn
1309 * instead so that control is returned safely back to this routine.
1311 static int
1312 png_image_read_init(png_imagep image)
1314 if (image->opaque == NULL)
1316 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1317 png_safe_error, png_safe_warning);
1319 /* And set the rest of the structure to NULL to ensure that the various
1320 * fields are consistent.
1322 memset(image, 0, (sizeof *image));
1323 image->version = PNG_IMAGE_VERSION;
1325 if (png_ptr != NULL)
1327 png_infop info_ptr = png_create_info_struct(png_ptr);
1329 if (info_ptr != NULL)
1331 png_controlp control = png_voidcast(png_controlp,
1332 png_malloc_warn(png_ptr, (sizeof *control)));
1334 if (control != NULL)
1336 memset(control, 0, (sizeof *control));
1338 control->png_ptr = png_ptr;
1339 control->info_ptr = info_ptr;
1340 control->for_write = 0;
1342 image->opaque = control;
1343 return 1;
1346 /* Error clean up */
1347 png_destroy_info_struct(png_ptr, &info_ptr);
1350 png_destroy_read_struct(&png_ptr, NULL, NULL);
1353 return png_image_error(image, "png_image_read: out of memory");
1356 return png_image_error(image, "png_image_read: opaque pointer not NULL");
1359 /* Utility to find the base format of a PNG file from a png_struct. */
1360 static png_uint_32
1361 png_image_format(png_structrp png_ptr)
1363 png_uint_32 format = 0;
1365 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1366 format |= PNG_FORMAT_FLAG_COLOR;
1368 if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1369 format |= PNG_FORMAT_FLAG_ALPHA;
1371 /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1372 * sets the png_struct fields; that's all we are interested in here. The
1373 * precise interaction with an app call to png_set_tRNS and PNG file reading
1374 * is unclear.
1376 else if (png_ptr->num_trans > 0)
1377 format |= PNG_FORMAT_FLAG_ALPHA;
1379 if (png_ptr->bit_depth == 16)
1380 format |= PNG_FORMAT_FLAG_LINEAR;
1382 if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1383 format |= PNG_FORMAT_FLAG_COLORMAP;
1385 return format;
1388 /* Is the given gamma significantly different from sRGB? The test is the same
1389 * one used in pngrtran.c when deciding whether to do gamma correction. The
1390 * arithmetic optimizes the division by using the fact that the inverse of the
1391 * file sRGB gamma is 2.2
1393 static int
1394 png_gamma_not_sRGB(png_fixed_point g)
1396 if (g < PNG_FP_1)
1398 /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1399 if (g == 0)
1400 return 0;
1402 return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1405 return 1;
1408 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1409 * header and fill in all the information. This is executed in a safe context,
1410 * unlike the init routine above.
1412 static int
1413 png_image_read_header(png_voidp argument)
1415 png_imagep image = png_voidcast(png_imagep, argument);
1416 png_structrp png_ptr = image->opaque->png_ptr;
1417 png_inforp info_ptr = image->opaque->info_ptr;
1419 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1420 png_set_benign_errors(png_ptr, 1/*warn*/);
1421 #endif
1422 png_read_info(png_ptr, info_ptr);
1424 /* Do this the fast way; just read directly out of png_struct. */
1425 image->width = png_ptr->width;
1426 image->height = png_ptr->height;
1429 png_uint_32 format = png_image_format(png_ptr);
1431 image->format = format;
1433 #ifdef PNG_COLORSPACE_SUPPORTED
1434 /* Does the colorspace match sRGB? If there is no color endpoint
1435 * (colorant) information assume yes, otherwise require the
1436 * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set. If the
1437 * colorspace has been determined to be invalid ignore it.
1439 if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1440 & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1441 PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1442 image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1443 #endif
1446 /* We need the maximum number of entries regardless of the format the
1447 * application sets here.
1450 png_uint_32 cmap_entries;
1452 switch (png_ptr->color_type)
1454 case PNG_COLOR_TYPE_GRAY:
1455 cmap_entries = 1U << png_ptr->bit_depth;
1456 break;
1458 case PNG_COLOR_TYPE_PALETTE:
1459 cmap_entries = (png_uint_32)png_ptr->num_palette;
1460 break;
1462 default:
1463 cmap_entries = 256;
1464 break;
1467 if (cmap_entries > 256)
1468 cmap_entries = 256;
1470 image->colormap_entries = cmap_entries;
1473 return 1;
1476 #ifdef PNG_STDIO_SUPPORTED
1477 int PNGAPI
1478 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1480 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1482 if (file != NULL)
1484 if (png_image_read_init(image) != 0)
1486 /* This is slightly evil, but png_init_io doesn't do anything other
1487 * than this and we haven't changed the standard IO functions so
1488 * this saves a 'safe' function.
1490 image->opaque->png_ptr->io_ptr = file;
1491 return png_safe_execute(image, png_image_read_header, image);
1495 else
1496 return png_image_error(image,
1497 "png_image_begin_read_from_stdio: invalid argument");
1500 else if (image != NULL)
1501 return png_image_error(image,
1502 "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1504 return 0;
1507 int PNGAPI
1508 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1510 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1512 if (file_name != NULL)
1514 FILE *fp = fopen(file_name, "rb");
1516 if (fp != NULL)
1518 if (png_image_read_init(image) != 0)
1520 image->opaque->png_ptr->io_ptr = fp;
1521 image->opaque->owned_file = 1;
1522 return png_safe_execute(image, png_image_read_header, image);
1525 /* Clean up: just the opened file. */
1526 (void)fclose(fp);
1529 else
1530 return png_image_error(image, strerror(errno));
1533 else
1534 return png_image_error(image,
1535 "png_image_begin_read_from_file: invalid argument");
1538 else if (image != NULL)
1539 return png_image_error(image,
1540 "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1542 return 0;
1544 #endif /* STDIO */
1546 static void PNGCBAPI
1547 png_image_memory_read(png_structp png_ptr, png_bytep out, size_t need)
1549 if (png_ptr != NULL)
1551 png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1552 if (image != NULL)
1554 png_controlp cp = image->opaque;
1555 if (cp != NULL)
1557 png_const_bytep memory = cp->memory;
1558 size_t size = cp->size;
1560 if (memory != NULL && size >= need)
1562 memcpy(out, memory, need);
1563 cp->memory = memory + need;
1564 cp->size = size - need;
1565 return;
1568 png_error(png_ptr, "read beyond end of data");
1572 png_error(png_ptr, "invalid memory read");
1576 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1577 png_const_voidp memory, size_t size)
1579 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1581 if (memory != NULL && size > 0)
1583 if (png_image_read_init(image) != 0)
1585 /* Now set the IO functions to read from the memory buffer and
1586 * store it into io_ptr. Again do this in-place to avoid calling a
1587 * libpng function that requires error handling.
1589 image->opaque->memory = png_voidcast(png_const_bytep, memory);
1590 image->opaque->size = size;
1591 image->opaque->png_ptr->io_ptr = image;
1592 image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1594 return png_safe_execute(image, png_image_read_header, image);
1598 else
1599 return png_image_error(image,
1600 "png_image_begin_read_from_memory: invalid argument");
1603 else if (image != NULL)
1604 return png_image_error(image,
1605 "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1607 return 0;
1610 /* Utility function to skip chunks that are not used by the simplified image
1611 * read functions and an appropriate macro to call it.
1613 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1614 static void
1615 png_image_skip_unused_chunks(png_structrp png_ptr)
1617 /* Prepare the reader to ignore all recognized chunks whose data will not
1618 * be used, i.e., all chunks recognized by libpng except for those
1619 * involved in basic image reading:
1621 * IHDR, PLTE, IDAT, IEND
1623 * Or image data handling:
1625 * tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1627 * This provides a small performance improvement and eliminates any
1628 * potential vulnerability to security problems in the unused chunks.
1630 * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1631 * too. This allows the simplified API to be compiled without iCCP support,
1632 * however if the support is there the chunk is still checked to detect
1633 * errors (which are unfortunately quite common.)
1636 static const png_byte chunks_to_process[] = {
1637 98, 75, 71, 68, '\0', /* bKGD */
1638 99, 72, 82, 77, '\0', /* cHRM */
1639 103, 65, 77, 65, '\0', /* gAMA */
1640 # ifdef PNG_READ_iCCP_SUPPORTED
1641 105, 67, 67, 80, '\0', /* iCCP */
1642 # endif
1643 115, 66, 73, 84, '\0', /* sBIT */
1644 115, 82, 71, 66, '\0', /* sRGB */
1647 /* Ignore unknown chunks and all other chunks except for the
1648 * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1650 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1651 NULL, -1);
1653 /* But do not ignore image data handling chunks */
1654 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1655 chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1659 # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1660 #else
1661 # define PNG_SKIP_CHUNKS(p) ((void)0)
1662 #endif /* HANDLE_AS_UNKNOWN */
1664 /* The following macro gives the exact rounded answer for all values in the
1665 * range 0..255 (it actually divides by 51.2, but the rounding still generates
1666 * the correct numbers 0..5
1668 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1670 /* Utility functions to make particular color-maps */
1671 static void
1672 set_file_encoding(png_image_read_control *display)
1674 png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1675 if (png_gamma_significant(g) != 0)
1677 if (png_gamma_not_sRGB(g) != 0)
1679 display->file_encoding = P_FILE;
1680 display->gamma_to_linear = png_reciprocal(g);
1683 else
1684 display->file_encoding = P_sRGB;
1687 else
1688 display->file_encoding = P_LINEAR8;
1691 static unsigned int
1692 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1694 if (encoding == P_FILE) /* double check */
1695 encoding = display->file_encoding;
1697 if (encoding == P_NOTSET) /* must be the file encoding */
1699 set_file_encoding(display);
1700 encoding = display->file_encoding;
1703 switch (encoding)
1705 case P_FILE:
1706 value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1707 break;
1709 case P_sRGB:
1710 value = png_sRGB_table[value];
1711 break;
1713 case P_LINEAR:
1714 break;
1716 case P_LINEAR8:
1717 value *= 257;
1718 break;
1720 #ifdef __GNUC__
1721 default:
1722 png_error(display->image->opaque->png_ptr,
1723 "unexpected encoding (internal error)");
1724 #endif
1727 return value;
1730 static png_uint_32
1731 png_colormap_compose(png_image_read_control *display,
1732 png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1733 png_uint_32 background, int encoding)
1735 /* The file value is composed on the background, the background has the given
1736 * encoding and so does the result, the file is encoded with P_FILE and the
1737 * file and alpha are 8-bit values. The (output) encoding will always be
1738 * P_LINEAR or P_sRGB.
1740 png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1741 png_uint_32 b = decode_gamma(display, background, encoding);
1743 /* The alpha is always an 8-bit value (it comes from the palette), the value
1744 * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1746 f = f * alpha + b * (255-alpha);
1748 if (encoding == P_LINEAR)
1750 /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1751 * accurate, it divides by 255.00000005937181414556, with no overflow.)
1753 f *= 257; /* Now scaled by 65535 */
1754 f += f >> 16;
1755 f = (f+32768) >> 16;
1758 else /* P_sRGB */
1759 f = PNG_sRGB_FROM_LINEAR(f);
1761 return f;
1764 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1765 * be 8-bit.
1767 static void
1768 png_create_colormap_entry(png_image_read_control *display,
1769 png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1770 png_uint_32 alpha, int encoding)
1772 png_imagep image = display->image;
1773 int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1774 P_LINEAR : P_sRGB;
1775 int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1776 (red != green || green != blue);
1778 if (ip > 255)
1779 png_error(image->opaque->png_ptr, "color-map index out of range");
1781 /* Update the cache with whether the file gamma is significantly different
1782 * from sRGB.
1784 if (encoding == P_FILE)
1786 if (display->file_encoding == P_NOTSET)
1787 set_file_encoding(display);
1789 /* Note that the cached value may be P_FILE too, but if it is then the
1790 * gamma_to_linear member has been set.
1792 encoding = display->file_encoding;
1795 if (encoding == P_FILE)
1797 png_fixed_point g = display->gamma_to_linear;
1799 red = png_gamma_16bit_correct(red*257, g);
1800 green = png_gamma_16bit_correct(green*257, g);
1801 blue = png_gamma_16bit_correct(blue*257, g);
1803 if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1805 alpha *= 257;
1806 encoding = P_LINEAR;
1809 else
1811 red = PNG_sRGB_FROM_LINEAR(red * 255);
1812 green = PNG_sRGB_FROM_LINEAR(green * 255);
1813 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1814 encoding = P_sRGB;
1818 else if (encoding == P_LINEAR8)
1820 /* This encoding occurs quite frequently in test cases because PngSuite
1821 * includes a gAMA 1.0 chunk with most images.
1823 red *= 257;
1824 green *= 257;
1825 blue *= 257;
1826 alpha *= 257;
1827 encoding = P_LINEAR;
1830 else if (encoding == P_sRGB &&
1831 (convert_to_Y != 0 || output_encoding == P_LINEAR))
1833 /* The values are 8-bit sRGB values, but must be converted to 16-bit
1834 * linear.
1836 red = png_sRGB_table[red];
1837 green = png_sRGB_table[green];
1838 blue = png_sRGB_table[blue];
1839 alpha *= 257;
1840 encoding = P_LINEAR;
1843 /* This is set if the color isn't gray but the output is. */
1844 if (encoding == P_LINEAR)
1846 if (convert_to_Y != 0)
1848 /* NOTE: these values are copied from png_do_rgb_to_gray */
1849 png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green +
1850 (png_uint_32)2366 * blue;
1852 if (output_encoding == P_LINEAR)
1853 y = (y + 16384) >> 15;
1855 else
1857 /* y is scaled by 32768, we need it scaled by 255: */
1858 y = (y + 128) >> 8;
1859 y *= 255;
1860 y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1861 alpha = PNG_DIV257(alpha);
1862 encoding = P_sRGB;
1865 blue = red = green = y;
1868 else if (output_encoding == P_sRGB)
1870 red = PNG_sRGB_FROM_LINEAR(red * 255);
1871 green = PNG_sRGB_FROM_LINEAR(green * 255);
1872 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1873 alpha = PNG_DIV257(alpha);
1874 encoding = P_sRGB;
1878 if (encoding != output_encoding)
1879 png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1881 /* Store the value. */
1883 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
1884 int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1885 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1886 # else
1887 # define afirst 0
1888 # endif
1889 # ifdef PNG_FORMAT_BGR_SUPPORTED
1890 int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1891 # else
1892 # define bgr 0
1893 # endif
1895 if (output_encoding == P_LINEAR)
1897 png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1899 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1901 /* The linear 16-bit values must be pre-multiplied by the alpha channel
1902 * value, if less than 65535 (this is, effectively, composite on black
1903 * if the alpha channel is removed.)
1905 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1907 case 4:
1908 entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1909 /* FALLTHROUGH */
1911 case 3:
1912 if (alpha < 65535)
1914 if (alpha > 0)
1916 blue = (blue * alpha + 32767U)/65535U;
1917 green = (green * alpha + 32767U)/65535U;
1918 red = (red * alpha + 32767U)/65535U;
1921 else
1922 red = green = blue = 0;
1924 entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1925 entry[afirst + 1] = (png_uint_16)green;
1926 entry[afirst + bgr] = (png_uint_16)red;
1927 break;
1929 case 2:
1930 entry[1 ^ afirst] = (png_uint_16)alpha;
1931 /* FALLTHROUGH */
1933 case 1:
1934 if (alpha < 65535)
1936 if (alpha > 0)
1937 green = (green * alpha + 32767U)/65535U;
1939 else
1940 green = 0;
1942 entry[afirst] = (png_uint_16)green;
1943 break;
1945 default:
1946 break;
1950 else /* output encoding is P_sRGB */
1952 png_bytep entry = png_voidcast(png_bytep, display->colormap);
1954 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1956 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1958 case 4:
1959 entry[afirst ? 0 : 3] = (png_byte)alpha;
1960 /* FALLTHROUGH */
1961 case 3:
1962 entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1963 entry[afirst + 1] = (png_byte)green;
1964 entry[afirst + bgr] = (png_byte)red;
1965 break;
1967 case 2:
1968 entry[1 ^ afirst] = (png_byte)alpha;
1969 /* FALLTHROUGH */
1970 case 1:
1971 entry[afirst] = (png_byte)green;
1972 break;
1974 default:
1975 break;
1979 # ifdef afirst
1980 # undef afirst
1981 # endif
1982 # ifdef bgr
1983 # undef bgr
1984 # endif
1988 static int
1989 make_gray_file_colormap(png_image_read_control *display)
1991 unsigned int i;
1993 for (i=0; i<256; ++i)
1994 png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1996 return (int)i;
1999 static int
2000 make_gray_colormap(png_image_read_control *display)
2002 unsigned int i;
2004 for (i=0; i<256; ++i)
2005 png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
2007 return (int)i;
2009 #define PNG_GRAY_COLORMAP_ENTRIES 256
2011 static int
2012 make_ga_colormap(png_image_read_control *display)
2014 unsigned int i, a;
2016 /* Alpha is retained, the output will be a color-map with entries
2017 * selected by six levels of alpha. One transparent entry, 6 gray
2018 * levels for all the intermediate alpha values, leaving 230 entries
2019 * for the opaque grays. The color-map entries are the six values
2020 * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
2021 * relevant entry.
2023 * if (alpha > 229) // opaque
2025 * // The 231 entries are selected to make the math below work:
2026 * base = 0;
2027 * entry = (231 * gray + 128) >> 8;
2029 * else if (alpha < 26) // transparent
2031 * base = 231;
2032 * entry = 0;
2034 * else // partially opaque
2036 * base = 226 + 6 * PNG_DIV51(alpha);
2037 * entry = PNG_DIV51(gray);
2040 i = 0;
2041 while (i < 231)
2043 unsigned int gray = (i * 256 + 115) / 231;
2044 png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2047 /* 255 is used here for the component values for consistency with the code
2048 * that undoes premultiplication in pngwrite.c.
2050 png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2052 for (a=1; a<5; ++a)
2054 unsigned int g;
2056 for (g=0; g<6; ++g)
2057 png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2058 P_sRGB);
2061 return (int)i;
2064 #define PNG_GA_COLORMAP_ENTRIES 256
2066 static int
2067 make_rgb_colormap(png_image_read_control *display)
2069 unsigned int i, r;
2071 /* Build a 6x6x6 opaque RGB cube */
2072 for (i=r=0; r<6; ++r)
2074 unsigned int g;
2076 for (g=0; g<6; ++g)
2078 unsigned int b;
2080 for (b=0; b<6; ++b)
2081 png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2082 P_sRGB);
2086 return (int)i;
2089 #define PNG_RGB_COLORMAP_ENTRIES 216
2091 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2092 #define PNG_RGB_INDEX(r,g,b) \
2093 ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2095 static int
2096 png_image_read_colormap(png_voidp argument)
2098 png_image_read_control *display =
2099 png_voidcast(png_image_read_control*, argument);
2100 png_imagep image = display->image;
2102 png_structrp png_ptr = image->opaque->png_ptr;
2103 png_uint_32 output_format = image->format;
2104 int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2105 P_LINEAR : P_sRGB;
2107 unsigned int cmap_entries;
2108 unsigned int output_processing; /* Output processing option */
2109 unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2111 /* Background information; the background color and the index of this color
2112 * in the color-map if it exists (else 256).
2114 unsigned int background_index = 256;
2115 png_uint_32 back_r, back_g, back_b;
2117 /* Flags to accumulate things that need to be done to the input. */
2118 int expand_tRNS = 0;
2120 /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2121 * very difficult to do, the results look awful, and it is difficult to see
2122 * what possible use it is because the application can't control the
2123 * color-map.
2125 if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2126 png_ptr->num_trans > 0) /* alpha in input */ &&
2127 ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2129 if (output_encoding == P_LINEAR) /* compose on black */
2130 back_b = back_g = back_r = 0;
2132 else if (display->background == NULL /* no way to remove it */)
2133 png_error(png_ptr,
2134 "background color must be supplied to remove alpha/transparency");
2136 /* Get a copy of the background color (this avoids repeating the checks
2137 * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the
2138 * output format.
2140 else
2142 back_g = display->background->green;
2143 if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2145 back_r = display->background->red;
2146 back_b = display->background->blue;
2148 else
2149 back_b = back_r = back_g;
2153 else if (output_encoding == P_LINEAR)
2154 back_b = back_r = back_g = 65535;
2156 else
2157 back_b = back_r = back_g = 255;
2159 /* Default the input file gamma if required - this is necessary because
2160 * libpng assumes that if no gamma information is present the data is in the
2161 * output format, but the simplified API deduces the gamma from the input
2162 * format.
2164 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2166 /* Do this directly, not using the png_colorspace functions, to ensure
2167 * that it happens even if the colorspace is invalid (though probably if
2168 * it is the setting will be ignored) Note that the same thing can be
2169 * achieved at the application interface with png_set_gAMA.
2171 if (png_ptr->bit_depth == 16 &&
2172 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2173 png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2175 else
2176 png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2178 png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2181 /* Decide what to do based on the PNG color type of the input data. The
2182 * utility function png_create_colormap_entry deals with most aspects of the
2183 * output transformations; this code works out how to produce bytes of
2184 * color-map entries from the original format.
2186 switch (png_ptr->color_type)
2188 case PNG_COLOR_TYPE_GRAY:
2189 if (png_ptr->bit_depth <= 8)
2191 /* There at most 256 colors in the output, regardless of
2192 * transparency.
2194 unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2196 cmap_entries = 1U << png_ptr->bit_depth;
2197 if (cmap_entries > image->colormap_entries)
2198 png_error(png_ptr, "gray[8] color-map: too few entries");
2200 step = 255 / (cmap_entries - 1);
2201 output_processing = PNG_CMAP_NONE;
2203 /* If there is a tRNS chunk then this either selects a transparent
2204 * value or, if the output has no alpha, the background color.
2206 if (png_ptr->num_trans > 0)
2208 trans = png_ptr->trans_color.gray;
2210 if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2211 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2214 /* png_create_colormap_entry just takes an RGBA and writes the
2215 * corresponding color-map entry using the format from 'image',
2216 * including the required conversion to sRGB or linear as
2217 * appropriate. The input values are always either sRGB (if the
2218 * gamma correction flag is 0) or 0..255 scaled file encoded values
2219 * (if the function must gamma correct them).
2221 for (i=val=0; i<cmap_entries; ++i, val += step)
2223 /* 'i' is a file value. While this will result in duplicated
2224 * entries for 8-bit non-sRGB encoded files it is necessary to
2225 * have non-gamma corrected values to do tRNS handling.
2227 if (i != trans)
2228 png_create_colormap_entry(display, i, val, val, val, 255,
2229 P_FILE/*8-bit with file gamma*/);
2231 /* Else this entry is transparent. The colors don't matter if
2232 * there is an alpha channel (back_alpha == 0), but it does no
2233 * harm to pass them in; the values are not set above so this
2234 * passes in white.
2236 * NOTE: this preserves the full precision of the application
2237 * supplied background color when it is used.
2239 else
2240 png_create_colormap_entry(display, i, back_r, back_g, back_b,
2241 back_alpha, output_encoding);
2244 /* We need libpng to preserve the original encoding. */
2245 data_encoding = P_FILE;
2247 /* The rows from libpng, while technically gray values, are now also
2248 * color-map indices; however, they may need to be expanded to 1
2249 * byte per pixel. This is what png_set_packing does (i.e., it
2250 * unpacks the bit values into bytes.)
2252 if (png_ptr->bit_depth < 8)
2253 png_set_packing(png_ptr);
2256 else /* bit depth is 16 */
2258 /* The 16-bit input values can be converted directly to 8-bit gamma
2259 * encoded values; however, if a tRNS chunk is present 257 color-map
2260 * entries are required. This means that the extra entry requires
2261 * special processing; add an alpha channel, sacrifice gray level
2262 * 254 and convert transparent (alpha==0) entries to that.
2264 * Use libpng to chop the data to 8 bits. Convert it to sRGB at the
2265 * same time to minimize quality loss. If a tRNS chunk is present
2266 * this means libpng must handle it too; otherwise it is impossible
2267 * to do the exact match on the 16-bit value.
2269 * If the output has no alpha channel *and* the background color is
2270 * gray then it is possible to let libpng handle the substitution by
2271 * ensuring that the corresponding gray level matches the background
2272 * color exactly.
2274 data_encoding = P_sRGB;
2276 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2277 png_error(png_ptr, "gray[16] color-map: too few entries");
2279 cmap_entries = (unsigned int)make_gray_colormap(display);
2281 if (png_ptr->num_trans > 0)
2283 unsigned int back_alpha;
2285 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2286 back_alpha = 0;
2288 else
2290 if (back_r == back_g && back_g == back_b)
2292 /* Background is gray; no special processing will be
2293 * required.
2295 png_color_16 c;
2296 png_uint_32 gray = back_g;
2298 if (output_encoding == P_LINEAR)
2300 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2302 /* And make sure the corresponding palette entry
2303 * matches.
2305 png_create_colormap_entry(display, gray, back_g, back_g,
2306 back_g, 65535, P_LINEAR);
2309 /* The background passed to libpng, however, must be the
2310 * sRGB value.
2312 c.index = 0; /*unused*/
2313 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2315 /* NOTE: does this work without expanding tRNS to alpha?
2316 * It should be the color->gray case below apparently
2317 * doesn't.
2319 png_set_background_fixed(png_ptr, &c,
2320 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2321 0/*gamma: not used*/);
2323 output_processing = PNG_CMAP_NONE;
2324 break;
2326 #ifdef __COVERITY__
2327 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2328 * here.
2330 back_alpha = 255;
2331 #else
2332 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2333 #endif
2336 /* output_processing means that the libpng-processed row will be
2337 * 8-bit GA and it has to be processing to single byte color-map
2338 * values. Entry 254 is replaced by either a completely
2339 * transparent entry or by the background color at full
2340 * precision (and the background color is not a simple gray
2341 * level in this case.)
2343 expand_tRNS = 1;
2344 output_processing = PNG_CMAP_TRANS;
2345 background_index = 254;
2347 /* And set (overwrite) color-map entry 254 to the actual
2348 * background color at full precision.
2350 png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2351 back_alpha, output_encoding);
2354 else
2355 output_processing = PNG_CMAP_NONE;
2357 break;
2359 case PNG_COLOR_TYPE_GRAY_ALPHA:
2360 /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum
2361 * of 65536 combinations. If, however, the alpha channel is to be
2362 * removed there are only 256 possibilities if the background is gray.
2363 * (Otherwise there is a subset of the 65536 possibilities defined by
2364 * the triangle between black, white and the background color.)
2366 * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to
2367 * worry about tRNS matching - tRNS is ignored if there is an alpha
2368 * channel.
2370 data_encoding = P_sRGB;
2372 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2374 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2375 png_error(png_ptr, "gray+alpha color-map: too few entries");
2377 cmap_entries = (unsigned int)make_ga_colormap(display);
2379 background_index = PNG_CMAP_GA_BACKGROUND;
2380 output_processing = PNG_CMAP_GA;
2383 else /* alpha is removed */
2385 /* Alpha must be removed as the PNG data is processed when the
2386 * background is a color because the G and A channels are
2387 * independent and the vector addition (non-parallel vectors) is a
2388 * 2-D problem.
2390 * This can be reduced to the same algorithm as above by making a
2391 * colormap containing gray levels (for the opaque grays), a
2392 * background entry (for a transparent pixel) and a set of four six
2393 * level color values, one set for each intermediate alpha value.
2394 * See the comments in make_ga_colormap for how this works in the
2395 * per-pixel processing.
2397 * If the background is gray, however, we only need a 256 entry gray
2398 * level color map. It is sufficient to make the entry generated
2399 * for the background color be exactly the color specified.
2401 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2402 (back_r == back_g && back_g == back_b))
2404 /* Background is gray; no special processing will be required. */
2405 png_color_16 c;
2406 png_uint_32 gray = back_g;
2408 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2409 png_error(png_ptr, "gray-alpha color-map: too few entries");
2411 cmap_entries = (unsigned int)make_gray_colormap(display);
2413 if (output_encoding == P_LINEAR)
2415 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2417 /* And make sure the corresponding palette entry matches. */
2418 png_create_colormap_entry(display, gray, back_g, back_g,
2419 back_g, 65535, P_LINEAR);
2422 /* The background passed to libpng, however, must be the sRGB
2423 * value.
2425 c.index = 0; /*unused*/
2426 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2428 png_set_background_fixed(png_ptr, &c,
2429 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2430 0/*gamma: not used*/);
2432 output_processing = PNG_CMAP_NONE;
2435 else
2437 png_uint_32 i, a;
2439 /* This is the same as png_make_ga_colormap, above, except that
2440 * the entries are all opaque.
2442 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2443 png_error(png_ptr, "ga-alpha color-map: too few entries");
2445 i = 0;
2446 while (i < 231)
2448 png_uint_32 gray = (i * 256 + 115) / 231;
2449 png_create_colormap_entry(display, i++, gray, gray, gray,
2450 255, P_sRGB);
2453 /* NOTE: this preserves the full precision of the application
2454 * background color.
2456 background_index = i;
2457 png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2458 #ifdef __COVERITY__
2459 /* Coverity claims that output_encoding
2460 * cannot be 2 (P_LINEAR) here.
2461 */ 255U,
2462 #else
2463 output_encoding == P_LINEAR ? 65535U : 255U,
2464 #endif
2465 output_encoding);
2467 /* For non-opaque input composite on the sRGB background - this
2468 * requires inverting the encoding for each component. The input
2469 * is still converted to the sRGB encoding because this is a
2470 * reasonable approximate to the logarithmic curve of human
2471 * visual sensitivity, at least over the narrow range which PNG
2472 * represents. Consequently 'G' is always sRGB encoded, while
2473 * 'A' is linear. We need the linear background colors.
2475 if (output_encoding == P_sRGB) /* else already linear */
2477 /* This may produce a value not exactly matching the
2478 * background, but that's ok because these numbers are only
2479 * used when alpha != 0
2481 back_r = png_sRGB_table[back_r];
2482 back_g = png_sRGB_table[back_g];
2483 back_b = png_sRGB_table[back_b];
2486 for (a=1; a<5; ++a)
2488 unsigned int g;
2490 /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2491 * by an 8-bit alpha value (0..255).
2493 png_uint_32 alpha = 51 * a;
2494 png_uint_32 back_rx = (255-alpha) * back_r;
2495 png_uint_32 back_gx = (255-alpha) * back_g;
2496 png_uint_32 back_bx = (255-alpha) * back_b;
2498 for (g=0; g<6; ++g)
2500 png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2502 png_create_colormap_entry(display, i++,
2503 PNG_sRGB_FROM_LINEAR(gray + back_rx),
2504 PNG_sRGB_FROM_LINEAR(gray + back_gx),
2505 PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2509 cmap_entries = i;
2510 output_processing = PNG_CMAP_GA;
2513 break;
2515 case PNG_COLOR_TYPE_RGB:
2516 case PNG_COLOR_TYPE_RGB_ALPHA:
2517 /* Exclude the case where the output is gray; we can always handle this
2518 * with the cases above.
2520 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2522 /* The color-map will be grayscale, so we may as well convert the
2523 * input RGB values to a simple grayscale and use the grayscale
2524 * code above.
2526 * NOTE: calling this apparently damages the recognition of the
2527 * transparent color in background color handling; call
2528 * png_set_tRNS_to_alpha before png_set_background_fixed.
2530 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2531 -1);
2532 data_encoding = P_sRGB;
2534 /* The output will now be one or two 8-bit gray or gray+alpha
2535 * channels. The more complex case arises when the input has alpha.
2537 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2538 png_ptr->num_trans > 0) &&
2539 (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2541 /* Both input and output have an alpha channel, so no background
2542 * processing is required; just map the GA bytes to the right
2543 * color-map entry.
2545 expand_tRNS = 1;
2547 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2548 png_error(png_ptr, "rgb[ga] color-map: too few entries");
2550 cmap_entries = (unsigned int)make_ga_colormap(display);
2551 background_index = PNG_CMAP_GA_BACKGROUND;
2552 output_processing = PNG_CMAP_GA;
2555 else
2557 /* Either the input or the output has no alpha channel, so there
2558 * will be no non-opaque pixels in the color-map; it will just be
2559 * grayscale.
2561 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2562 png_error(png_ptr, "rgb[gray] color-map: too few entries");
2564 /* Ideally this code would use libpng to do the gamma correction,
2565 * but if an input alpha channel is to be removed we will hit the
2566 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2567 * correction bug). Fix this by dropping the gamma correction in
2568 * this case and doing it in the palette; this will result in
2569 * duplicate palette entries, but that's better than the
2570 * alternative of double gamma correction.
2572 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2573 png_ptr->num_trans > 0) &&
2574 png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2576 cmap_entries = (unsigned int)make_gray_file_colormap(display);
2577 data_encoding = P_FILE;
2580 else
2581 cmap_entries = (unsigned int)make_gray_colormap(display);
2583 /* But if the input has alpha or transparency it must be removed
2585 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2586 png_ptr->num_trans > 0)
2588 png_color_16 c;
2589 png_uint_32 gray = back_g;
2591 /* We need to ensure that the application background exists in
2592 * the colormap and that completely transparent pixels map to
2593 * it. Achieve this simply by ensuring that the entry
2594 * selected for the background really is the background color.
2596 if (data_encoding == P_FILE) /* from the fixup above */
2598 /* The app supplied a gray which is in output_encoding, we
2599 * need to convert it to a value of the input (P_FILE)
2600 * encoding then set this palette entry to the required
2601 * output encoding.
2603 if (output_encoding == P_sRGB)
2604 gray = png_sRGB_table[gray]; /* now P_LINEAR */
2606 gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2607 png_ptr->colorspace.gamma)); /* now P_FILE */
2609 /* And make sure the corresponding palette entry contains
2610 * exactly the required sRGB value.
2612 png_create_colormap_entry(display, gray, back_g, back_g,
2613 back_g, 0/*unused*/, output_encoding);
2616 else if (output_encoding == P_LINEAR)
2618 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2620 /* And make sure the corresponding palette entry matches.
2622 png_create_colormap_entry(display, gray, back_g, back_g,
2623 back_g, 0/*unused*/, P_LINEAR);
2626 /* The background passed to libpng, however, must be the
2627 * output (normally sRGB) value.
2629 c.index = 0; /*unused*/
2630 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2632 /* NOTE: the following is apparently a bug in libpng. Without
2633 * it the transparent color recognition in
2634 * png_set_background_fixed seems to go wrong.
2636 expand_tRNS = 1;
2637 png_set_background_fixed(png_ptr, &c,
2638 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2639 0/*gamma: not used*/);
2642 output_processing = PNG_CMAP_NONE;
2646 else /* output is color */
2648 /* We could use png_quantize here so long as there is no transparent
2649 * color or alpha; png_quantize ignores alpha. Easier overall just
2650 * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2651 * Consequently we always want libpng to produce sRGB data.
2653 data_encoding = P_sRGB;
2655 /* Is there any transparency or alpha? */
2656 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2657 png_ptr->num_trans > 0)
2659 /* Is there alpha in the output too? If so all four channels are
2660 * processed into a special RGB cube with alpha support.
2662 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2664 png_uint_32 r;
2666 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2667 png_error(png_ptr, "rgb+alpha color-map: too few entries");
2669 cmap_entries = (unsigned int)make_rgb_colormap(display);
2671 /* Add a transparent entry. */
2672 png_create_colormap_entry(display, cmap_entries, 255, 255,
2673 255, 0, P_sRGB);
2675 /* This is stored as the background index for the processing
2676 * algorithm.
2678 background_index = cmap_entries++;
2680 /* Add 27 r,g,b entries each with alpha 0.5. */
2681 for (r=0; r<256; r = (r << 1) | 0x7f)
2683 png_uint_32 g;
2685 for (g=0; g<256; g = (g << 1) | 0x7f)
2687 png_uint_32 b;
2689 /* This generates components with the values 0, 127 and
2690 * 255
2692 for (b=0; b<256; b = (b << 1) | 0x7f)
2693 png_create_colormap_entry(display, cmap_entries++,
2694 r, g, b, 128, P_sRGB);
2698 expand_tRNS = 1;
2699 output_processing = PNG_CMAP_RGB_ALPHA;
2702 else
2704 /* Alpha/transparency must be removed. The background must
2705 * exist in the color map (achieved by setting adding it after
2706 * the 666 color-map). If the standard processing code will
2707 * pick up this entry automatically that's all that is
2708 * required; libpng can be called to do the background
2709 * processing.
2711 unsigned int sample_size =
2712 PNG_IMAGE_SAMPLE_SIZE(output_format);
2713 png_uint_32 r, g, b; /* sRGB background */
2715 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2716 png_error(png_ptr, "rgb-alpha color-map: too few entries");
2718 cmap_entries = (unsigned int)make_rgb_colormap(display);
2720 png_create_colormap_entry(display, cmap_entries, back_r,
2721 back_g, back_b, 0/*unused*/, output_encoding);
2723 if (output_encoding == P_LINEAR)
2725 r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2726 g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2727 b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2730 else
2732 r = back_r;
2733 g = back_g;
2734 b = back_g;
2737 /* Compare the newly-created color-map entry with the one the
2738 * PNG_CMAP_RGB algorithm will use. If the two entries don't
2739 * match, add the new one and set this as the background
2740 * index.
2742 if (memcmp((png_const_bytep)display->colormap +
2743 sample_size * cmap_entries,
2744 (png_const_bytep)display->colormap +
2745 sample_size * PNG_RGB_INDEX(r,g,b),
2746 sample_size) != 0)
2748 /* The background color must be added. */
2749 background_index = cmap_entries++;
2751 /* Add 27 r,g,b entries each with created by composing with
2752 * the background at alpha 0.5.
2754 for (r=0; r<256; r = (r << 1) | 0x7f)
2756 for (g=0; g<256; g = (g << 1) | 0x7f)
2758 /* This generates components with the values 0, 127
2759 * and 255
2761 for (b=0; b<256; b = (b << 1) | 0x7f)
2762 png_create_colormap_entry(display, cmap_entries++,
2763 png_colormap_compose(display, r, P_sRGB, 128,
2764 back_r, output_encoding),
2765 png_colormap_compose(display, g, P_sRGB, 128,
2766 back_g, output_encoding),
2767 png_colormap_compose(display, b, P_sRGB, 128,
2768 back_b, output_encoding),
2769 0/*unused*/, output_encoding);
2773 expand_tRNS = 1;
2774 output_processing = PNG_CMAP_RGB_ALPHA;
2777 else /* background color is in the standard color-map */
2779 png_color_16 c;
2781 c.index = 0; /*unused*/
2782 c.red = (png_uint_16)back_r;
2783 c.gray = c.green = (png_uint_16)back_g;
2784 c.blue = (png_uint_16)back_b;
2786 png_set_background_fixed(png_ptr, &c,
2787 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2788 0/*gamma: not used*/);
2790 output_processing = PNG_CMAP_RGB;
2795 else /* no alpha or transparency in the input */
2797 /* Alpha in the output is irrelevant, simply map the opaque input
2798 * pixels to the 6x6x6 color-map.
2800 if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2801 png_error(png_ptr, "rgb color-map: too few entries");
2803 cmap_entries = (unsigned int)make_rgb_colormap(display);
2804 output_processing = PNG_CMAP_RGB;
2807 break;
2809 case PNG_COLOR_TYPE_PALETTE:
2810 /* It's already got a color-map. It may be necessary to eliminate the
2811 * tRNS entries though.
2814 unsigned int num_trans = png_ptr->num_trans;
2815 png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2816 png_const_colorp colormap = png_ptr->palette;
2817 int do_background = trans != NULL &&
2818 (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2819 unsigned int i;
2821 /* Just in case: */
2822 if (trans == NULL)
2823 num_trans = 0;
2825 output_processing = PNG_CMAP_NONE;
2826 data_encoding = P_FILE; /* Don't change from color-map indices */
2827 cmap_entries = (unsigned int)png_ptr->num_palette;
2828 if (cmap_entries > 256)
2829 cmap_entries = 256;
2831 if (cmap_entries > (unsigned int)image->colormap_entries)
2832 png_error(png_ptr, "palette color-map: too few entries");
2834 for (i=0; i < cmap_entries; ++i)
2836 if (do_background != 0 && i < num_trans && trans[i] < 255)
2838 if (trans[i] == 0)
2839 png_create_colormap_entry(display, i, back_r, back_g,
2840 back_b, 0, output_encoding);
2842 else
2844 /* Must compose the PNG file color in the color-map entry
2845 * on the sRGB color in 'back'.
2847 png_create_colormap_entry(display, i,
2848 png_colormap_compose(display, colormap[i].red,
2849 P_FILE, trans[i], back_r, output_encoding),
2850 png_colormap_compose(display, colormap[i].green,
2851 P_FILE, trans[i], back_g, output_encoding),
2852 png_colormap_compose(display, colormap[i].blue,
2853 P_FILE, trans[i], back_b, output_encoding),
2854 output_encoding == P_LINEAR ? trans[i] * 257U :
2855 trans[i],
2856 output_encoding);
2860 else
2861 png_create_colormap_entry(display, i, colormap[i].red,
2862 colormap[i].green, colormap[i].blue,
2863 i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2866 /* The PNG data may have indices packed in fewer than 8 bits, it
2867 * must be expanded if so.
2869 if (png_ptr->bit_depth < 8)
2870 png_set_packing(png_ptr);
2872 break;
2874 default:
2875 png_error(png_ptr, "invalid PNG color type");
2876 /*NOT REACHED*/
2879 /* Now deal with the output processing */
2880 if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2881 (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2882 png_set_tRNS_to_alpha(png_ptr);
2884 switch (data_encoding)
2886 case P_sRGB:
2887 /* Change to 8-bit sRGB */
2888 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2889 /* FALLTHROUGH */
2891 case P_FILE:
2892 if (png_ptr->bit_depth > 8)
2893 png_set_scale_16(png_ptr);
2894 break;
2896 #ifdef __GNUC__
2897 default:
2898 png_error(png_ptr, "bad data option (internal error)");
2899 #endif
2902 if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2903 png_error(png_ptr, "color map overflow (BAD internal error)");
2905 image->colormap_entries = cmap_entries;
2907 /* Double check using the recorded background index */
2908 switch (output_processing)
2910 case PNG_CMAP_NONE:
2911 if (background_index != PNG_CMAP_NONE_BACKGROUND)
2912 goto bad_background;
2913 break;
2915 case PNG_CMAP_GA:
2916 if (background_index != PNG_CMAP_GA_BACKGROUND)
2917 goto bad_background;
2918 break;
2920 case PNG_CMAP_TRANS:
2921 if (background_index >= cmap_entries ||
2922 background_index != PNG_CMAP_TRANS_BACKGROUND)
2923 goto bad_background;
2924 break;
2926 case PNG_CMAP_RGB:
2927 if (background_index != PNG_CMAP_RGB_BACKGROUND)
2928 goto bad_background;
2929 break;
2931 case PNG_CMAP_RGB_ALPHA:
2932 if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2933 goto bad_background;
2934 break;
2936 default:
2937 png_error(png_ptr, "bad processing option (internal error)");
2939 bad_background:
2940 png_error(png_ptr, "bad background index (internal error)");
2943 display->colormap_processing = (int)output_processing;
2945 return 1/*ok*/;
2948 /* The final part of the color-map read called from png_image_finish_read. */
2949 static int
2950 png_image_read_and_map(png_voidp argument)
2952 png_image_read_control *display = png_voidcast(png_image_read_control*,
2953 argument);
2954 png_imagep image = display->image;
2955 png_structrp png_ptr = image->opaque->png_ptr;
2956 int passes;
2958 /* Called when the libpng data must be transformed into the color-mapped
2959 * form. There is a local row buffer in display->local and this routine must
2960 * do the interlace handling.
2962 switch (png_ptr->interlaced)
2964 case PNG_INTERLACE_NONE:
2965 passes = 1;
2966 break;
2968 case PNG_INTERLACE_ADAM7:
2969 passes = PNG_INTERLACE_ADAM7_PASSES;
2970 break;
2972 default:
2973 png_error(png_ptr, "unknown interlace type");
2977 png_uint_32 height = image->height;
2978 png_uint_32 width = image->width;
2979 int proc = display->colormap_processing;
2980 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
2981 ptrdiff_t step_row = display->row_bytes;
2982 int pass;
2984 for (pass = 0; pass < passes; ++pass)
2986 unsigned int startx, stepx, stepy;
2987 png_uint_32 y;
2989 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2991 /* The row may be empty for a short image: */
2992 if (PNG_PASS_COLS(width, pass) == 0)
2993 continue;
2995 startx = PNG_PASS_START_COL(pass);
2996 stepx = PNG_PASS_COL_OFFSET(pass);
2997 y = PNG_PASS_START_ROW(pass);
2998 stepy = PNG_PASS_ROW_OFFSET(pass);
3001 else
3003 y = 0;
3004 startx = 0;
3005 stepx = stepy = 1;
3008 for (; y<height; y += stepy)
3010 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3011 png_bytep outrow = first_row + y * step_row;
3012 png_const_bytep end_row = outrow + width;
3014 /* Read read the libpng data into the temporary buffer. */
3015 png_read_row(png_ptr, inrow, NULL);
3017 /* Now process the row according to the processing option, note
3018 * that the caller verifies that the format of the libpng output
3019 * data is as required.
3021 outrow += startx;
3022 switch (proc)
3024 case PNG_CMAP_GA:
3025 for (; outrow < end_row; outrow += stepx)
3027 /* The data is always in the PNG order */
3028 unsigned int gray = *inrow++;
3029 unsigned int alpha = *inrow++;
3030 unsigned int entry;
3032 /* NOTE: this code is copied as a comment in
3033 * make_ga_colormap above. Please update the
3034 * comment if you change this code!
3036 if (alpha > 229) /* opaque */
3038 entry = (231 * gray + 128) >> 8;
3040 else if (alpha < 26) /* transparent */
3042 entry = 231;
3044 else /* partially opaque */
3046 entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3049 *outrow = (png_byte)entry;
3051 break;
3053 case PNG_CMAP_TRANS:
3054 for (; outrow < end_row; outrow += stepx)
3056 png_byte gray = *inrow++;
3057 png_byte alpha = *inrow++;
3059 if (alpha == 0)
3060 *outrow = PNG_CMAP_TRANS_BACKGROUND;
3062 else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3063 *outrow = gray;
3065 else
3066 *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3068 break;
3070 case PNG_CMAP_RGB:
3071 for (; outrow < end_row; outrow += stepx)
3073 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3074 inrow += 3;
3076 break;
3078 case PNG_CMAP_RGB_ALPHA:
3079 for (; outrow < end_row; outrow += stepx)
3081 unsigned int alpha = inrow[3];
3083 /* Because the alpha entries only hold alpha==0.5 values
3084 * split the processing at alpha==0.25 (64) and 0.75
3085 * (196).
3088 if (alpha >= 196)
3089 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3090 inrow[2]);
3092 else if (alpha < 64)
3093 *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3095 else
3097 /* Likewise there are three entries for each of r, g
3098 * and b. We could select the entry by popcount on
3099 * the top two bits on those architectures that
3100 * support it, this is what the code below does,
3101 * crudely.
3103 unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3105 /* Here are how the values map:
3107 * 0x00 .. 0x3f -> 0
3108 * 0x40 .. 0xbf -> 1
3109 * 0xc0 .. 0xff -> 2
3111 * So, as above with the explicit alpha checks, the
3112 * breakpoints are at 64 and 196.
3114 if (inrow[0] & 0x80) back_i += 9; /* red */
3115 if (inrow[0] & 0x40) back_i += 9;
3116 if (inrow[0] & 0x80) back_i += 3; /* green */
3117 if (inrow[0] & 0x40) back_i += 3;
3118 if (inrow[0] & 0x80) back_i += 1; /* blue */
3119 if (inrow[0] & 0x40) back_i += 1;
3121 *outrow = (png_byte)back_i;
3124 inrow += 4;
3126 break;
3128 default:
3129 break;
3135 return 1;
3138 static int
3139 png_image_read_colormapped(png_voidp argument)
3141 png_image_read_control *display = png_voidcast(png_image_read_control*,
3142 argument);
3143 png_imagep image = display->image;
3144 png_controlp control = image->opaque;
3145 png_structrp png_ptr = control->png_ptr;
3146 png_inforp info_ptr = control->info_ptr;
3148 int passes = 0; /* As a flag */
3150 PNG_SKIP_CHUNKS(png_ptr);
3152 /* Update the 'info' structure and make sure the result is as required; first
3153 * make sure to turn on the interlace handling if it will be required
3154 * (because it can't be turned on *after* the call to png_read_update_info!)
3156 if (display->colormap_processing == PNG_CMAP_NONE)
3157 passes = png_set_interlace_handling(png_ptr);
3159 png_read_update_info(png_ptr, info_ptr);
3161 /* The expected output can be deduced from the colormap_processing option. */
3162 switch (display->colormap_processing)
3164 case PNG_CMAP_NONE:
3165 /* Output must be one channel and one byte per pixel, the output
3166 * encoding can be anything.
3168 if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3169 info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3170 info_ptr->bit_depth == 8)
3171 break;
3173 goto bad_output;
3175 case PNG_CMAP_TRANS:
3176 case PNG_CMAP_GA:
3177 /* Output must be two channels and the 'G' one must be sRGB, the latter
3178 * can be checked with an exact number because it should have been set
3179 * to this number above!
3181 if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3182 info_ptr->bit_depth == 8 &&
3183 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3184 image->colormap_entries == 256)
3185 break;
3187 goto bad_output;
3189 case PNG_CMAP_RGB:
3190 /* Output must be 8-bit sRGB encoded RGB */
3191 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3192 info_ptr->bit_depth == 8 &&
3193 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3194 image->colormap_entries == 216)
3195 break;
3197 goto bad_output;
3199 case PNG_CMAP_RGB_ALPHA:
3200 /* Output must be 8-bit sRGB encoded RGBA */
3201 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3202 info_ptr->bit_depth == 8 &&
3203 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3204 image->colormap_entries == 244 /* 216 + 1 + 27 */)
3205 break;
3207 goto bad_output;
3209 default:
3210 bad_output:
3211 png_error(png_ptr, "bad color-map processing (internal error)");
3214 /* Now read the rows. Do this here if it is possible to read directly into
3215 * the output buffer, otherwise allocate a local row buffer of the maximum
3216 * size libpng requires and call the relevant processing routine safely.
3219 png_voidp first_row = display->buffer;
3220 ptrdiff_t row_bytes = display->row_stride;
3222 /* The following expression is designed to work correctly whether it gives
3223 * a signed or an unsigned result.
3225 if (row_bytes < 0)
3227 char *ptr = png_voidcast(char*, first_row);
3228 ptr += (image->height-1) * (-row_bytes);
3229 first_row = png_voidcast(png_voidp, ptr);
3232 display->first_row = first_row;
3233 display->row_bytes = row_bytes;
3236 if (passes == 0)
3238 int result;
3239 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3241 display->local_row = row;
3242 result = png_safe_execute(image, png_image_read_and_map, display);
3243 display->local_row = NULL;
3244 png_free(png_ptr, row);
3246 return result;
3249 else
3251 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3253 while (--passes >= 0)
3255 png_uint_32 y = image->height;
3256 png_bytep row = png_voidcast(png_bytep, display->first_row);
3258 for (; y > 0; --y)
3260 png_read_row(png_ptr, row, NULL);
3261 row += row_bytes;
3265 return 1;
3269 /* Just the row reading part of png_image_read. */
3270 static int
3271 png_image_read_composite(png_voidp argument)
3273 png_image_read_control *display = png_voidcast(png_image_read_control*,
3274 argument);
3275 png_imagep image = display->image;
3276 png_structrp png_ptr = image->opaque->png_ptr;
3277 int passes;
3279 switch (png_ptr->interlaced)
3281 case PNG_INTERLACE_NONE:
3282 passes = 1;
3283 break;
3285 case PNG_INTERLACE_ADAM7:
3286 passes = PNG_INTERLACE_ADAM7_PASSES;
3287 break;
3289 default:
3290 png_error(png_ptr, "unknown interlace type");
3294 png_uint_32 height = image->height;
3295 png_uint_32 width = image->width;
3296 ptrdiff_t step_row = display->row_bytes;
3297 unsigned int channels =
3298 (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3299 int pass;
3301 for (pass = 0; pass < passes; ++pass)
3303 unsigned int startx, stepx, stepy;
3304 png_uint_32 y;
3306 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3308 /* The row may be empty for a short image: */
3309 if (PNG_PASS_COLS(width, pass) == 0)
3310 continue;
3312 startx = PNG_PASS_START_COL(pass) * channels;
3313 stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3314 y = PNG_PASS_START_ROW(pass);
3315 stepy = PNG_PASS_ROW_OFFSET(pass);
3318 else
3320 y = 0;
3321 startx = 0;
3322 stepx = channels;
3323 stepy = 1;
3326 for (; y<height; y += stepy)
3328 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3329 png_bytep outrow;
3330 png_const_bytep end_row;
3332 /* Read the row, which is packed: */
3333 png_read_row(png_ptr, inrow, NULL);
3335 outrow = png_voidcast(png_bytep, display->first_row);
3336 outrow += y * step_row;
3337 end_row = outrow + width * channels;
3339 /* Now do the composition on each pixel in this row. */
3340 outrow += startx;
3341 for (; outrow < end_row; outrow += stepx)
3343 png_byte alpha = inrow[channels];
3345 if (alpha > 0) /* else no change to the output */
3347 unsigned int c;
3349 for (c=0; c<channels; ++c)
3351 png_uint_32 component = inrow[c];
3353 if (alpha < 255) /* else just use component */
3355 /* This is PNG_OPTIMIZED_ALPHA, the component value
3356 * is a linear 8-bit value. Combine this with the
3357 * current outrow[c] value which is sRGB encoded.
3358 * Arithmetic here is 16-bits to preserve the output
3359 * values correctly.
3361 component *= 257*255; /* =65535 */
3362 component += (255-alpha)*png_sRGB_table[outrow[c]];
3364 /* So 'component' is scaled by 255*65535 and is
3365 * therefore appropriate for the sRGB to linear
3366 * conversion table.
3368 component = PNG_sRGB_FROM_LINEAR(component);
3371 outrow[c] = (png_byte)component;
3375 inrow += channels+1; /* components and alpha channel */
3381 return 1;
3384 /* The do_local_background case; called when all the following transforms are to
3385 * be done:
3387 * PNG_RGB_TO_GRAY
3388 * PNG_COMPOSITE
3389 * PNG_GAMMA
3391 * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3392 * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3393 * correction. The fix-up is to prevent the PNG_COMPOSITE operation from
3394 * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3395 * row and handles the removal or pre-multiplication of the alpha channel.
3397 static int
3398 png_image_read_background(png_voidp argument)
3400 png_image_read_control *display = png_voidcast(png_image_read_control*,
3401 argument);
3402 png_imagep image = display->image;
3403 png_structrp png_ptr = image->opaque->png_ptr;
3404 png_inforp info_ptr = image->opaque->info_ptr;
3405 png_uint_32 height = image->height;
3406 png_uint_32 width = image->width;
3407 int pass, passes;
3409 /* Double check the convoluted logic below. We expect to get here with
3410 * libpng doing rgb to gray and gamma correction but background processing
3411 * left to the png_image_read_background function. The rows libpng produce
3412 * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3414 if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3415 png_error(png_ptr, "lost rgb to gray");
3417 if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3418 png_error(png_ptr, "unexpected compose");
3420 if (png_get_channels(png_ptr, info_ptr) != 2)
3421 png_error(png_ptr, "lost/gained channels");
3423 /* Expect the 8-bit case to always remove the alpha channel */
3424 if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3425 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3426 png_error(png_ptr, "unexpected 8-bit transformation");
3428 switch (png_ptr->interlaced)
3430 case PNG_INTERLACE_NONE:
3431 passes = 1;
3432 break;
3434 case PNG_INTERLACE_ADAM7:
3435 passes = PNG_INTERLACE_ADAM7_PASSES;
3436 break;
3438 default:
3439 png_error(png_ptr, "unknown interlace type");
3442 /* Use direct access to info_ptr here because otherwise the simplified API
3443 * would require PNG_EASY_ACCESS_SUPPORTED (just for this.) Note this is
3444 * checking the value after libpng expansions, not the original value in the
3445 * PNG.
3447 switch (info_ptr->bit_depth)
3449 case 8:
3450 /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3451 * to be removed by composing on a background: either the row if
3452 * display->background is NULL or display->background->green if not.
3453 * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3456 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3457 ptrdiff_t step_row = display->row_bytes;
3459 for (pass = 0; pass < passes; ++pass)
3461 unsigned int startx, stepx, stepy;
3462 png_uint_32 y;
3464 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3466 /* The row may be empty for a short image: */
3467 if (PNG_PASS_COLS(width, pass) == 0)
3468 continue;
3470 startx = PNG_PASS_START_COL(pass);
3471 stepx = PNG_PASS_COL_OFFSET(pass);
3472 y = PNG_PASS_START_ROW(pass);
3473 stepy = PNG_PASS_ROW_OFFSET(pass);
3476 else
3478 y = 0;
3479 startx = 0;
3480 stepx = stepy = 1;
3483 if (display->background == NULL)
3485 for (; y<height; y += stepy)
3487 png_bytep inrow = png_voidcast(png_bytep,
3488 display->local_row);
3489 png_bytep outrow = first_row + y * step_row;
3490 png_const_bytep end_row = outrow + width;
3492 /* Read the row, which is packed: */
3493 png_read_row(png_ptr, inrow, NULL);
3495 /* Now do the composition on each pixel in this row. */
3496 outrow += startx;
3497 for (; outrow < end_row; outrow += stepx)
3499 png_byte alpha = inrow[1];
3501 if (alpha > 0) /* else no change to the output */
3503 png_uint_32 component = inrow[0];
3505 if (alpha < 255) /* else just use component */
3507 /* Since PNG_OPTIMIZED_ALPHA was not set it is
3508 * necessary to invert the sRGB transfer
3509 * function and multiply the alpha out.
3511 component = png_sRGB_table[component] * alpha;
3512 component += png_sRGB_table[outrow[0]] *
3513 (255-alpha);
3514 component = PNG_sRGB_FROM_LINEAR(component);
3517 outrow[0] = (png_byte)component;
3520 inrow += 2; /* gray and alpha channel */
3525 else /* constant background value */
3527 png_byte background8 = display->background->green;
3528 png_uint_16 background = png_sRGB_table[background8];
3530 for (; y<height; y += stepy)
3532 png_bytep inrow = png_voidcast(png_bytep,
3533 display->local_row);
3534 png_bytep outrow = first_row + y * step_row;
3535 png_const_bytep end_row = outrow + width;
3537 /* Read the row, which is packed: */
3538 png_read_row(png_ptr, inrow, NULL);
3540 /* Now do the composition on each pixel in this row. */
3541 outrow += startx;
3542 for (; outrow < end_row; outrow += stepx)
3544 png_byte alpha = inrow[1];
3546 if (alpha > 0) /* else use background */
3548 png_uint_32 component = inrow[0];
3550 if (alpha < 255) /* else just use component */
3552 component = png_sRGB_table[component] * alpha;
3553 component += background * (255-alpha);
3554 component = PNG_sRGB_FROM_LINEAR(component);
3557 outrow[0] = (png_byte)component;
3560 else
3561 outrow[0] = background8;
3563 inrow += 2; /* gray and alpha channel */
3569 break;
3571 case 16:
3572 /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3573 * still be done and, maybe, the alpha channel removed. This code also
3574 * handles the alpha-first option.
3577 png_uint_16p first_row = png_voidcast(png_uint_16p,
3578 display->first_row);
3579 /* The division by two is safe because the caller passed in a
3580 * stride which was multiplied by 2 (below) to get row_bytes.
3582 ptrdiff_t step_row = display->row_bytes / 2;
3583 unsigned int preserve_alpha = (image->format &
3584 PNG_FORMAT_FLAG_ALPHA) != 0;
3585 unsigned int outchannels = 1U+preserve_alpha;
3586 int swap_alpha = 0;
3588 # ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3589 if (preserve_alpha != 0 &&
3590 (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3591 swap_alpha = 1;
3592 # endif
3594 for (pass = 0; pass < passes; ++pass)
3596 unsigned int startx, stepx, stepy;
3597 png_uint_32 y;
3599 /* The 'x' start and step are adjusted to output components here.
3601 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3603 /* The row may be empty for a short image: */
3604 if (PNG_PASS_COLS(width, pass) == 0)
3605 continue;
3607 startx = PNG_PASS_START_COL(pass) * outchannels;
3608 stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3609 y = PNG_PASS_START_ROW(pass);
3610 stepy = PNG_PASS_ROW_OFFSET(pass);
3613 else
3615 y = 0;
3616 startx = 0;
3617 stepx = outchannels;
3618 stepy = 1;
3621 for (; y<height; y += stepy)
3623 png_const_uint_16p inrow;
3624 png_uint_16p outrow = first_row + y*step_row;
3625 png_uint_16p end_row = outrow + width * outchannels;
3627 /* Read the row, which is packed: */
3628 png_read_row(png_ptr, png_voidcast(png_bytep,
3629 display->local_row), NULL);
3630 inrow = png_voidcast(png_const_uint_16p, display->local_row);
3632 /* Now do the pre-multiplication on each pixel in this row.
3634 outrow += startx;
3635 for (; outrow < end_row; outrow += stepx)
3637 png_uint_32 component = inrow[0];
3638 png_uint_16 alpha = inrow[1];
3640 if (alpha > 0) /* else 0 */
3642 if (alpha < 65535) /* else just use component */
3644 component *= alpha;
3645 component += 32767;
3646 component /= 65535;
3650 else
3651 component = 0;
3653 outrow[swap_alpha] = (png_uint_16)component;
3654 if (preserve_alpha != 0)
3655 outrow[1 ^ swap_alpha] = alpha;
3657 inrow += 2; /* components and alpha channel */
3662 break;
3664 #ifdef __GNUC__
3665 default:
3666 png_error(png_ptr, "unexpected bit depth");
3667 #endif
3670 return 1;
3673 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3674 static int
3675 png_image_read_direct(png_voidp argument)
3677 png_image_read_control *display = png_voidcast(png_image_read_control*,
3678 argument);
3679 png_imagep image = display->image;
3680 png_structrp png_ptr = image->opaque->png_ptr;
3681 png_inforp info_ptr = image->opaque->info_ptr;
3683 png_uint_32 format = image->format;
3684 int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3685 int do_local_compose = 0;
3686 int do_local_background = 0; /* to avoid double gamma correction bug */
3687 int passes = 0;
3689 /* Add transforms to ensure the correct output format is produced then check
3690 * that the required implementation support is there. Always expand; always
3691 * need 8 bits minimum, no palette and expanded tRNS.
3693 png_set_expand(png_ptr);
3695 /* Now check the format to see if it was modified. */
3697 png_uint_32 base_format = png_image_format(png_ptr) &
3698 ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3699 png_uint_32 change = format ^ base_format;
3700 png_fixed_point output_gamma;
3701 int mode; /* alpha mode */
3703 /* Do this first so that we have a record if rgb to gray is happening. */
3704 if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3706 /* gray<->color transformation required. */
3707 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3708 png_set_gray_to_rgb(png_ptr);
3710 else
3712 /* libpng can't do both rgb to gray and
3713 * background/pre-multiplication if there is also significant gamma
3714 * correction, because both operations require linear colors and
3715 * the code only supports one transform doing the gamma correction.
3716 * Handle this by doing the pre-multiplication or background
3717 * operation in this code, if necessary.
3719 * TODO: fix this by rewriting pngrtran.c (!)
3721 * For the moment (given that fixing this in pngrtran.c is an
3722 * enormous change) 'do_local_background' is used to indicate that
3723 * the problem exists.
3725 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3726 do_local_background = 1/*maybe*/;
3728 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3729 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3732 change &= ~PNG_FORMAT_FLAG_COLOR;
3735 /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3738 png_fixed_point input_gamma_default;
3740 if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3741 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3742 input_gamma_default = PNG_GAMMA_LINEAR;
3743 else
3744 input_gamma_default = PNG_DEFAULT_sRGB;
3746 /* Call png_set_alpha_mode to set the default for the input gamma; the
3747 * output gamma is set by a second call below.
3749 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3752 if (linear != 0)
3754 /* If there *is* an alpha channel in the input it must be multiplied
3755 * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3757 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3758 mode = PNG_ALPHA_STANDARD; /* associated alpha */
3760 else
3761 mode = PNG_ALPHA_PNG;
3763 output_gamma = PNG_GAMMA_LINEAR;
3766 else
3768 mode = PNG_ALPHA_PNG;
3769 output_gamma = PNG_DEFAULT_sRGB;
3772 if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
3774 mode = PNG_ALPHA_OPTIMIZED;
3775 change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3778 /* If 'do_local_background' is set check for the presence of gamma
3779 * correction; this is part of the work-round for the libpng bug
3780 * described above.
3782 * TODO: fix libpng and remove this.
3784 if (do_local_background != 0)
3786 png_fixed_point gtest;
3788 /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3789 * gamma correction, the screen gamma hasn't been set on png_struct
3790 * yet; it's set below. png_struct::gamma, however, is set to the
3791 * final value.
3793 if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma,
3794 PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
3795 do_local_background = 0;
3797 else if (mode == PNG_ALPHA_STANDARD)
3799 do_local_background = 2/*required*/;
3800 mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3803 /* else leave as 1 for the checks below */
3806 /* If the bit-depth changes then handle that here. */
3807 if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3809 if (linear != 0 /*16-bit output*/)
3810 png_set_expand_16(png_ptr);
3812 else /* 8-bit output */
3813 png_set_scale_16(png_ptr);
3815 change &= ~PNG_FORMAT_FLAG_LINEAR;
3818 /* Now the background/alpha channel changes. */
3819 if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3821 /* Removing an alpha channel requires composition for the 8-bit
3822 * formats; for the 16-bit it is already done, above, by the
3823 * pre-multiplication and the channel just needs to be stripped.
3825 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3827 /* If RGB->gray is happening the alpha channel must be left and the
3828 * operation completed locally.
3830 * TODO: fix libpng and remove this.
3832 if (do_local_background != 0)
3833 do_local_background = 2/*required*/;
3835 /* 16-bit output: just remove the channel */
3836 else if (linear != 0) /* compose on black (well, pre-multiply) */
3837 png_set_strip_alpha(png_ptr);
3839 /* 8-bit output: do an appropriate compose */
3840 else if (display->background != NULL)
3842 png_color_16 c;
3844 c.index = 0; /*unused*/
3845 c.red = display->background->red;
3846 c.green = display->background->green;
3847 c.blue = display->background->blue;
3848 c.gray = display->background->green;
3850 /* This is always an 8-bit sRGB value, using the 'green' channel
3851 * for gray is much better than calculating the luminance here;
3852 * we can get off-by-one errors in that calculation relative to
3853 * the app expectations and that will show up in transparent
3854 * pixels.
3856 png_set_background_fixed(png_ptr, &c,
3857 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3858 0/*gamma: not used*/);
3861 else /* compose on row: implemented below. */
3863 do_local_compose = 1;
3864 /* This leaves the alpha channel in the output, so it has to be
3865 * removed by the code below. Set the encoding to the 'OPTIMIZE'
3866 * one so the code only has to hack on the pixels that require
3867 * composition.
3869 mode = PNG_ALPHA_OPTIMIZED;
3873 else /* output needs an alpha channel */
3875 /* This is tricky because it happens before the swap operation has
3876 * been accomplished; however, the swap does *not* swap the added
3877 * alpha channel (weird API), so it must be added in the correct
3878 * place.
3880 png_uint_32 filler; /* opaque filler */
3881 int where;
3883 if (linear != 0)
3884 filler = 65535;
3886 else
3887 filler = 255;
3889 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
3890 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3892 where = PNG_FILLER_BEFORE;
3893 change &= ~PNG_FORMAT_FLAG_AFIRST;
3896 else
3897 #endif
3898 where = PNG_FILLER_AFTER;
3900 png_set_add_alpha(png_ptr, filler, where);
3903 /* This stops the (irrelevant) call to swap_alpha below. */
3904 change &= ~PNG_FORMAT_FLAG_ALPHA;
3907 /* Now set the alpha mode correctly; this is always done, even if there is
3908 * no alpha channel in either the input or the output because it correctly
3909 * sets the output gamma.
3911 png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3913 # ifdef PNG_FORMAT_BGR_SUPPORTED
3914 if ((change & PNG_FORMAT_FLAG_BGR) != 0)
3916 /* Check only the output format; PNG is never BGR; don't do this if
3917 * the output is gray, but fix up the 'format' value in that case.
3919 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3920 png_set_bgr(png_ptr);
3922 else
3923 format &= ~PNG_FORMAT_FLAG_BGR;
3925 change &= ~PNG_FORMAT_FLAG_BGR;
3927 # endif
3929 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
3930 if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
3932 /* Only relevant if there is an alpha channel - it's particularly
3933 * important to handle this correctly because do_local_compose may
3934 * be set above and then libpng will keep the alpha channel for this
3935 * code to remove.
3937 if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
3939 /* Disable this if doing a local background,
3940 * TODO: remove this when local background is no longer required.
3942 if (do_local_background != 2)
3943 png_set_swap_alpha(png_ptr);
3946 else
3947 format &= ~PNG_FORMAT_FLAG_AFIRST;
3949 change &= ~PNG_FORMAT_FLAG_AFIRST;
3951 # endif
3953 /* If the *output* is 16-bit then we need to check for a byte-swap on this
3954 * architecture.
3956 if (linear != 0)
3958 png_uint_16 le = 0x0001;
3960 if ((*(png_const_bytep) & le) != 0)
3961 png_set_swap(png_ptr);
3964 /* If change is not now 0 some transformation is missing - error out. */
3965 if (change != 0)
3966 png_error(png_ptr, "png_read_image: unsupported transformation");
3969 PNG_SKIP_CHUNKS(png_ptr);
3971 /* Update the 'info' structure and make sure the result is as required; first
3972 * make sure to turn on the interlace handling if it will be required
3973 * (because it can't be turned on *after* the call to png_read_update_info!)
3975 * TODO: remove the do_local_background fixup below.
3977 if (do_local_compose == 0 && do_local_background != 2)
3978 passes = png_set_interlace_handling(png_ptr);
3980 png_read_update_info(png_ptr, info_ptr);
3983 png_uint_32 info_format = 0;
3985 if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3986 info_format |= PNG_FORMAT_FLAG_COLOR;
3988 if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
3990 /* do_local_compose removes this channel below. */
3991 if (do_local_compose == 0)
3993 /* do_local_background does the same if required. */
3994 if (do_local_background != 2 ||
3995 (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3996 info_format |= PNG_FORMAT_FLAG_ALPHA;
4000 else if (do_local_compose != 0) /* internal error */
4001 png_error(png_ptr, "png_image_read: alpha channel lost");
4003 if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
4004 info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
4007 if (info_ptr->bit_depth == 16)
4008 info_format |= PNG_FORMAT_FLAG_LINEAR;
4010 #ifdef PNG_FORMAT_BGR_SUPPORTED
4011 if ((png_ptr->transformations & PNG_BGR) != 0)
4012 info_format |= PNG_FORMAT_FLAG_BGR;
4013 #endif
4015 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4016 if (do_local_background == 2)
4018 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4019 info_format |= PNG_FORMAT_FLAG_AFIRST;
4022 if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
4023 ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
4024 (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
4026 if (do_local_background == 2)
4027 png_error(png_ptr, "unexpected alpha swap transformation");
4029 info_format |= PNG_FORMAT_FLAG_AFIRST;
4031 # endif
4033 /* This is actually an internal error. */
4034 if (info_format != format)
4035 png_error(png_ptr, "png_read_image: invalid transformations");
4038 /* Now read the rows. If do_local_compose is set then it is necessary to use
4039 * a local row buffer. The output will be GA, RGBA or BGRA and must be
4040 * converted to G, RGB or BGR as appropriate. The 'local_row' member of the
4041 * display acts as a flag.
4044 png_voidp first_row = display->buffer;
4045 ptrdiff_t row_bytes = display->row_stride;
4047 if (linear != 0)
4048 row_bytes *= 2;
4050 /* The following expression is designed to work correctly whether it gives
4051 * a signed or an unsigned result.
4053 if (row_bytes < 0)
4055 char *ptr = png_voidcast(char*, first_row);
4056 ptr += (image->height-1) * (-row_bytes);
4057 first_row = png_voidcast(png_voidp, ptr);
4060 display->first_row = first_row;
4061 display->row_bytes = row_bytes;
4064 if (do_local_compose != 0)
4066 int result;
4067 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4069 display->local_row = row;
4070 result = png_safe_execute(image, png_image_read_composite, display);
4071 display->local_row = NULL;
4072 png_free(png_ptr, row);
4074 return result;
4077 else if (do_local_background == 2)
4079 int result;
4080 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4082 display->local_row = row;
4083 result = png_safe_execute(image, png_image_read_background, display);
4084 display->local_row = NULL;
4085 png_free(png_ptr, row);
4087 return result;
4090 else
4092 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4094 while (--passes >= 0)
4096 png_uint_32 y = image->height;
4097 png_bytep row = png_voidcast(png_bytep, display->first_row);
4099 for (; y > 0; --y)
4101 png_read_row(png_ptr, row, NULL);
4102 row += row_bytes;
4106 return 1;
4110 int PNGAPI
4111 png_image_finish_read(png_imagep image, png_const_colorp background,
4112 void *buffer, png_int_32 row_stride, void *colormap)
4114 if (image != NULL && image->version == PNG_IMAGE_VERSION)
4116 /* Check for row_stride overflow. This check is not performed on the
4117 * original PNG format because it may not occur in the output PNG format
4118 * and libpng deals with the issues of reading the original.
4120 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4122 /* The following checks just the 'row_stride' calculation to ensure it
4123 * fits in a signed 32-bit value. Because channels/components can be
4124 * either 1 or 2 bytes in size the length of a row can still overflow 32
4125 * bits; this is just to verify that the 'row_stride' argument can be
4126 * represented.
4128 if (image->width <= 0x7fffffffU/channels) /* no overflow */
4130 png_uint_32 check;
4131 png_uint_32 png_row_stride = image->width * channels;
4133 if (row_stride == 0)
4134 row_stride = (png_int_32)/*SAFE*/png_row_stride;
4136 if (row_stride < 0)
4137 check = (png_uint_32)(-row_stride);
4139 else
4140 check = (png_uint_32)row_stride;
4142 /* This verifies 'check', the absolute value of the actual stride
4143 * passed in and detects overflow in the application calculation (i.e.
4144 * if the app did actually pass in a non-zero 'row_stride'.
4146 if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4148 /* Now check for overflow of the image buffer calculation; this
4149 * limits the whole image size to 32 bits for API compatibility with
4150 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4152 * The PNG_IMAGE_BUFFER_SIZE macro is:
4154 * (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4156 * And the component size is always 1 or 2, so make sure that the
4157 * number of *bytes* that the application is saying are available
4158 * does actually fit into a 32-bit number.
4160 * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4161 * will be changed to use png_alloc_size_t; bigger images can be
4162 * accommodated on 64-bit systems.
4164 if (image->height <=
4165 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4167 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4168 (image->colormap_entries > 0 && colormap != NULL))
4170 int result;
4171 png_image_read_control display;
4173 memset(&display, 0, (sizeof display));
4174 display.image = image;
4175 display.buffer = buffer;
4176 display.row_stride = row_stride;
4177 display.colormap = colormap;
4178 display.background = background;
4179 display.local_row = NULL;
4181 /* Choose the correct 'end' routine; for the color-map case
4182 * all the setup has already been done.
4184 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4185 result =
4186 png_safe_execute(image,
4187 png_image_read_colormap, &display) &&
4188 png_safe_execute(image,
4189 png_image_read_colormapped, &display);
4191 else
4192 result =
4193 png_safe_execute(image,
4194 png_image_read_direct, &display);
4196 png_image_free(image);
4197 return result;
4200 else
4201 return png_image_error(image,
4202 "png_image_finish_read[color-map]: no color-map");
4205 else
4206 return png_image_error(image,
4207 "png_image_finish_read: image too large");
4210 else
4211 return png_image_error(image,
4212 "png_image_finish_read: invalid argument");
4215 else
4216 return png_image_error(image,
4217 "png_image_finish_read: row_stride too large");
4220 else if (image != NULL)
4221 return png_image_error(image,
4222 "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4224 return 0;
4227 #endif /* SIMPLIFIED_READ */
4228 #endif /* READ */