[LIBPNG]
[reactos.git] / reactos / dll / 3rdparty / libpng / pngread.c
1
2 /* pngread.c - read a PNG file
3 *
4 * Last changed in libpng 1.6.26 [October 20, 2016]
5 * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
8 *
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
12 *
13 * This file contains routines that an application calls directly to
14 * read a PNG file or stream.
15 */
16
17 #include "pngpriv.h"
18 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
19 # include <errno.h>
20 #endif
21
22 #ifdef PNG_READ_SUPPORTED
23
24 /* Create a PNG structure for reading, and allocate any memory needed. */
25 PNG_FUNCTION(png_structp,PNGAPI
26 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
27 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
28 {
29 #ifndef PNG_USER_MEM_SUPPORTED
30 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
31 error_fn, warn_fn, NULL, NULL, NULL);
32 #else
33 return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
34 warn_fn, NULL, NULL, NULL);
35 }
36
37 /* Alternate create PNG structure for reading, and allocate any memory
38 * needed.
39 */
40 PNG_FUNCTION(png_structp,PNGAPI
41 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
42 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
43 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
44 {
45 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
46 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
47 #endif /* USER_MEM */
48
49 if (png_ptr != NULL)
50 {
51 png_ptr->mode = PNG_IS_READ_STRUCT;
52
53 /* Added in libpng-1.6.0; this can be used to detect a read structure if
54 * required (it will be zero in a write structure.)
55 */
56 # ifdef PNG_SEQUENTIAL_READ_SUPPORTED
57 png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
58 # endif
59
60 # ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
61 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
62
63 /* In stable builds only warn if an application error can be completely
64 * handled.
65 */
66 # if PNG_RELEASE_BUILD
67 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
68 # endif
69 # endif
70
71 /* TODO: delay this, it can be done in png_init_io (if the app doesn't
72 * do it itself) avoiding setting the default function if it is not
73 * required.
74 */
75 png_set_read_fn(png_ptr, NULL, NULL);
76 }
77
78 return png_ptr;
79 }
80
81
82 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
83 /* Read the information before the actual image data. This has been
84 * changed in v0.90 to allow reading a file that already has the magic
85 * bytes read from the stream. You can tell libpng how many bytes have
86 * been read from the beginning of the stream (up to the maximum of 8)
87 * via png_set_sig_bytes(), and we will only check the remaining bytes
88 * here. The application can then have access to the signature bytes we
89 * read if it is determined that this isn't a valid PNG file.
90 */
91 void PNGAPI
92 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
93 {
94 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
95 int keep;
96 #endif
97
98 png_debug(1, "in png_read_info");
99
100 if (png_ptr == NULL || info_ptr == NULL)
101 return;
102
103 /* Read and check the PNG file signature. */
104 png_read_sig(png_ptr, info_ptr);
105
106 for (;;)
107 {
108 png_uint_32 length = png_read_chunk_header(png_ptr);
109 png_uint_32 chunk_name = png_ptr->chunk_name;
110
111 /* IDAT logic needs to happen here to simplify getting the two flags
112 * right.
113 */
114 if (chunk_name == png_IDAT)
115 {
116 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
117 png_chunk_error(png_ptr, "Missing IHDR before IDAT");
118
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");
122
123 else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
124 png_chunk_benign_error(png_ptr, "Too many IDATs found");
125
126 png_ptr->mode |= PNG_HAVE_IDAT;
127 }
128
129 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
130 {
131 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
132 png_ptr->mode |= PNG_AFTER_IDAT;
133 }
134
135 /* This should be a binary subdivision search or a hash for
136 * matching the chunk name rather than a linear search.
137 */
138 if (chunk_name == png_IHDR)
139 png_handle_IHDR(png_ptr, info_ptr, length);
140
141 else if (chunk_name == png_IEND)
142 png_handle_IEND(png_ptr, info_ptr, length);
143
144 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
145 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
146 {
147 png_handle_unknown(png_ptr, info_ptr, length, keep);
148
149 if (chunk_name == png_PLTE)
150 png_ptr->mode |= PNG_HAVE_PLTE;
151
152 else if (chunk_name == png_IDAT)
153 {
154 png_ptr->idat_size = 0; /* It has been consumed */
155 break;
156 }
157 }
158 #endif
159 else if (chunk_name == png_PLTE)
160 png_handle_PLTE(png_ptr, info_ptr, length);
161
162 else if (chunk_name == png_IDAT)
163 {
164 png_ptr->idat_size = length;
165 break;
166 }
167
168 #ifdef PNG_READ_bKGD_SUPPORTED
169 else if (chunk_name == png_bKGD)
170 png_handle_bKGD(png_ptr, info_ptr, length);
171 #endif
172
173 #ifdef PNG_READ_cHRM_SUPPORTED
174 else if (chunk_name == png_cHRM)
175 png_handle_cHRM(png_ptr, info_ptr, length);
176 #endif
177
178 #ifdef PNG_READ_gAMA_SUPPORTED
179 else if (chunk_name == png_gAMA)
180 png_handle_gAMA(png_ptr, info_ptr, length);
181 #endif
182
183 #ifdef PNG_READ_hIST_SUPPORTED
184 else if (chunk_name == png_hIST)
185 png_handle_hIST(png_ptr, info_ptr, length);
186 #endif
187
188 #ifdef PNG_READ_oFFs_SUPPORTED
189 else if (chunk_name == png_oFFs)
190 png_handle_oFFs(png_ptr, info_ptr, length);
191 #endif
192
193 #ifdef PNG_READ_pCAL_SUPPORTED
194 else if (chunk_name == png_pCAL)
195 png_handle_pCAL(png_ptr, info_ptr, length);
196 #endif
197
198 #ifdef PNG_READ_sCAL_SUPPORTED
199 else if (chunk_name == png_sCAL)
200 png_handle_sCAL(png_ptr, info_ptr, length);
201 #endif
202
203 #ifdef PNG_READ_pHYs_SUPPORTED
204 else if (chunk_name == png_pHYs)
205 png_handle_pHYs(png_ptr, info_ptr, length);
206 #endif
207
208 #ifdef PNG_READ_sBIT_SUPPORTED
209 else if (chunk_name == png_sBIT)
210 png_handle_sBIT(png_ptr, info_ptr, length);
211 #endif
212
213 #ifdef PNG_READ_sRGB_SUPPORTED
214 else if (chunk_name == png_sRGB)
215 png_handle_sRGB(png_ptr, info_ptr, length);
216 #endif
217
218 #ifdef PNG_READ_iCCP_SUPPORTED
219 else if (chunk_name == png_iCCP)
220 png_handle_iCCP(png_ptr, info_ptr, length);
221 #endif
222
223 #ifdef PNG_READ_sPLT_SUPPORTED
224 else if (chunk_name == png_sPLT)
225 png_handle_sPLT(png_ptr, info_ptr, length);
226 #endif
227
228 #ifdef PNG_READ_tEXt_SUPPORTED
229 else if (chunk_name == png_tEXt)
230 png_handle_tEXt(png_ptr, info_ptr, length);
231 #endif
232
233 #ifdef PNG_READ_tIME_SUPPORTED
234 else if (chunk_name == png_tIME)
235 png_handle_tIME(png_ptr, info_ptr, length);
236 #endif
237
238 #ifdef PNG_READ_tRNS_SUPPORTED
239 else if (chunk_name == png_tRNS)
240 png_handle_tRNS(png_ptr, info_ptr, length);
241 #endif
242
243 #ifdef PNG_READ_zTXt_SUPPORTED
244 else if (chunk_name == png_zTXt)
245 png_handle_zTXt(png_ptr, info_ptr, length);
246 #endif
247
248 #ifdef PNG_READ_iTXt_SUPPORTED
249 else if (chunk_name == png_iTXt)
250 png_handle_iTXt(png_ptr, info_ptr, length);
251 #endif
252
253 else
254 png_handle_unknown(png_ptr, info_ptr, length,
255 PNG_HANDLE_CHUNK_AS_DEFAULT);
256 }
257 }
258 #endif /* SEQUENTIAL_READ */
259
260 /* Optional call to update the users info_ptr structure */
261 void PNGAPI
262 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
263 {
264 png_debug(1, "in png_read_update_info");
265
266 if (png_ptr != NULL)
267 {
268 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
269 {
270 png_read_start_row(png_ptr);
271
272 # ifdef PNG_READ_TRANSFORMS_SUPPORTED
273 png_read_transform_info(png_ptr, info_ptr);
274 # else
275 PNG_UNUSED(info_ptr)
276 # endif
277 }
278
279 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
280 else
281 png_app_error(png_ptr,
282 "png_read_update_info/png_start_read_image: duplicate call");
283 }
284 }
285
286 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
287 /* Initialize palette, background, etc, after transformations
288 * are set, but before any reading takes place. This allows
289 * the user to obtain a gamma-corrected palette, for example.
290 * If the user doesn't call this, we will do it ourselves.
291 */
292 void PNGAPI
293 png_start_read_image(png_structrp png_ptr)
294 {
295 png_debug(1, "in png_start_read_image");
296
297 if (png_ptr != NULL)
298 {
299 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
300 png_read_start_row(png_ptr);
301
302 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
303 else
304 png_app_error(png_ptr,
305 "png_start_read_image/png_read_update_info: duplicate call");
306 }
307 }
308 #endif /* SEQUENTIAL_READ */
309
310 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
311 #ifdef PNG_MNG_FEATURES_SUPPORTED
312 /* Undoes intrapixel differencing,
313 * NOTE: this is apparently only supported in the 'sequential' reader.
314 */
315 static void
316 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
317 {
318 png_debug(1, "in png_do_read_intrapixel");
319
320 if (
321 (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
322 {
323 int bytes_per_pixel;
324 png_uint_32 row_width = row_info->width;
325
326 if (row_info->bit_depth == 8)
327 {
328 png_bytep rp;
329 png_uint_32 i;
330
331 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
332 bytes_per_pixel = 3;
333
334 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
335 bytes_per_pixel = 4;
336
337 else
338 return;
339
340 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
341 {
342 *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
343 *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
344 }
345 }
346 else if (row_info->bit_depth == 16)
347 {
348 png_bytep rp;
349 png_uint_32 i;
350
351 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
352 bytes_per_pixel = 6;
353
354 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
355 bytes_per_pixel = 8;
356
357 else
358 return;
359
360 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
361 {
362 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
363 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
364 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
365 png_uint_32 red = (s0 + s1 + 65536) & 0xffff;
366 png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
367 *(rp ) = (png_byte)((red >> 8) & 0xff);
368 *(rp + 1) = (png_byte)(red & 0xff);
369 *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
370 *(rp + 5) = (png_byte)(blue & 0xff);
371 }
372 }
373 }
374 }
375 #endif /* MNG_FEATURES */
376
377 void PNGAPI
378 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
379 {
380 png_row_info row_info;
381
382 if (png_ptr == NULL)
383 return;
384
385 png_debug2(1, "in png_read_row (row %lu, pass %d)",
386 (unsigned long)png_ptr->row_number, png_ptr->pass);
387
388 /* png_read_start_row sets the information (in particular iwidth) for this
389 * interlace pass.
390 */
391 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
392 png_read_start_row(png_ptr);
393
394 /* 1.5.6: row_info moved out of png_struct to a local here. */
395 row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
396 row_info.color_type = png_ptr->color_type;
397 row_info.bit_depth = png_ptr->bit_depth;
398 row_info.channels = png_ptr->channels;
399 row_info.pixel_depth = png_ptr->pixel_depth;
400 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
401
402 #ifdef PNG_WARNINGS_SUPPORTED
403 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
404 {
405 /* Check for transforms that have been set but were defined out */
406 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
407 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
408 png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
409 #endif
410
411 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
412 if ((png_ptr->transformations & PNG_FILLER) != 0)
413 png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
414 #endif
415
416 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
417 !defined(PNG_READ_PACKSWAP_SUPPORTED)
418 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
419 png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
420 #endif
421
422 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
423 if ((png_ptr->transformations & PNG_PACK) != 0)
424 png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
425 #endif
426
427 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
428 if ((png_ptr->transformations & PNG_SHIFT) != 0)
429 png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
430 #endif
431
432 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
433 if ((png_ptr->transformations & PNG_BGR) != 0)
434 png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
435 #endif
436
437 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
438 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
439 png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
440 #endif
441 }
442 #endif /* WARNINGS */
443
444 #ifdef PNG_READ_INTERLACING_SUPPORTED
445 /* If interlaced and we do not need a new row, combine row and return.
446 * Notice that the pixels we have from previous rows have been transformed
447 * already; we can only combine like with like (transformed or
448 * untransformed) and, because of the libpng API for interlaced images, this
449 * means we must transform before de-interlacing.
450 */
451 if (png_ptr->interlaced != 0 &&
452 (png_ptr->transformations & PNG_INTERLACE) != 0)
453 {
454 switch (png_ptr->pass)
455 {
456 case 0:
457 if (png_ptr->row_number & 0x07)
458 {
459 if (dsp_row != NULL)
460 png_combine_row(png_ptr, dsp_row, 1/*display*/);
461 png_read_finish_row(png_ptr);
462 return;
463 }
464 break;
465
466 case 1:
467 if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
468 {
469 if (dsp_row != NULL)
470 png_combine_row(png_ptr, dsp_row, 1/*display*/);
471
472 png_read_finish_row(png_ptr);
473 return;
474 }
475 break;
476
477 case 2:
478 if ((png_ptr->row_number & 0x07) != 4)
479 {
480 if (dsp_row != NULL && (png_ptr->row_number & 4))
481 png_combine_row(png_ptr, dsp_row, 1/*display*/);
482
483 png_read_finish_row(png_ptr);
484 return;
485 }
486 break;
487
488 case 3:
489 if ((png_ptr->row_number & 3) || png_ptr->width < 3)
490 {
491 if (dsp_row != NULL)
492 png_combine_row(png_ptr, dsp_row, 1/*display*/);
493
494 png_read_finish_row(png_ptr);
495 return;
496 }
497 break;
498
499 case 4:
500 if ((png_ptr->row_number & 3) != 2)
501 {
502 if (dsp_row != NULL && (png_ptr->row_number & 2))
503 png_combine_row(png_ptr, dsp_row, 1/*display*/);
504
505 png_read_finish_row(png_ptr);
506 return;
507 }
508 break;
509
510 case 5:
511 if ((png_ptr->row_number & 1) || png_ptr->width < 2)
512 {
513 if (dsp_row != NULL)
514 png_combine_row(png_ptr, dsp_row, 1/*display*/);
515
516 png_read_finish_row(png_ptr);
517 return;
518 }
519 break;
520
521 default:
522 case 6:
523 if ((png_ptr->row_number & 1) == 0)
524 {
525 png_read_finish_row(png_ptr);
526 return;
527 }
528 break;
529 }
530 }
531 #endif
532
533 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
534 png_error(png_ptr, "Invalid attempt to read row data");
535
536 /* Fill the row with IDAT data: */
537 png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
538
539 if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
540 {
541 if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
542 png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
543 png_ptr->prev_row + 1, png_ptr->row_buf[0]);
544 else
545 png_error(png_ptr, "bad adaptive filter value");
546 }
547
548 /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
549 * 1.5.6, while the buffer really is this big in current versions of libpng
550 * it may not be in the future, so this was changed just to copy the
551 * interlaced count:
552 */
553 memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
554
555 #ifdef PNG_MNG_FEATURES_SUPPORTED
556 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
557 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
558 {
559 /* Intrapixel differencing */
560 png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
561 }
562 #endif
563
564 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
565 if (png_ptr->transformations)
566 png_do_read_transformations(png_ptr, &row_info);
567 #endif
568
569 /* The transformed pixel depth should match the depth now in row_info. */
570 if (png_ptr->transformed_pixel_depth == 0)
571 {
572 png_ptr->transformed_pixel_depth = row_info.pixel_depth;
573 if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
574 png_error(png_ptr, "sequential row overflow");
575 }
576
577 else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
578 png_error(png_ptr, "internal sequential row size calculation error");
579
580 #ifdef PNG_READ_INTERLACING_SUPPORTED
581 /* Expand interlaced rows to full size */
582 if (png_ptr->interlaced != 0 &&
583 (png_ptr->transformations & PNG_INTERLACE) != 0)
584 {
585 if (png_ptr->pass < 6)
586 png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
587 png_ptr->transformations);
588
589 if (dsp_row != NULL)
590 png_combine_row(png_ptr, dsp_row, 1/*display*/);
591
592 if (row != NULL)
593 png_combine_row(png_ptr, row, 0/*row*/);
594 }
595
596 else
597 #endif
598 {
599 if (row != NULL)
600 png_combine_row(png_ptr, row, -1/*ignored*/);
601
602 if (dsp_row != NULL)
603 png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
604 }
605 png_read_finish_row(png_ptr);
606
607 if (png_ptr->read_row_fn != NULL)
608 (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
609
610 }
611 #endif /* SEQUENTIAL_READ */
612
613 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
614 /* Read one or more rows of image data. If the image is interlaced,
615 * and png_set_interlace_handling() has been called, the rows need to
616 * contain the contents of the rows from the previous pass. If the
617 * image has alpha or transparency, and png_handle_alpha()[*] has been
618 * called, the rows contents must be initialized to the contents of the
619 * screen.
620 *
621 * "row" holds the actual image, and pixels are placed in it
622 * as they arrive. If the image is displayed after each pass, it will
623 * appear to "sparkle" in. "display_row" can be used to display a
624 * "chunky" progressive image, with finer detail added as it becomes
625 * available. If you do not want this "chunky" display, you may pass
626 * NULL for display_row. If you do not want the sparkle display, and
627 * you have not called png_handle_alpha(), you may pass NULL for rows.
628 * If you have called png_handle_alpha(), and the image has either an
629 * alpha channel or a transparency chunk, you must provide a buffer for
630 * rows. In this case, you do not have to provide a display_row buffer
631 * also, but you may. If the image is not interlaced, or if you have
632 * not called png_set_interlace_handling(), the display_row buffer will
633 * be ignored, so pass NULL to it.
634 *
635 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
636 */
637
638 void PNGAPI
639 png_read_rows(png_structrp png_ptr, png_bytepp row,
640 png_bytepp display_row, png_uint_32 num_rows)
641 {
642 png_uint_32 i;
643 png_bytepp rp;
644 png_bytepp dp;
645
646 png_debug(1, "in png_read_rows");
647
648 if (png_ptr == NULL)
649 return;
650
651 rp = row;
652 dp = display_row;
653 if (rp != NULL && dp != NULL)
654 for (i = 0; i < num_rows; i++)
655 {
656 png_bytep rptr = *rp++;
657 png_bytep dptr = *dp++;
658
659 png_read_row(png_ptr, rptr, dptr);
660 }
661
662 else if (rp != NULL)
663 for (i = 0; i < num_rows; i++)
664 {
665 png_bytep rptr = *rp;
666 png_read_row(png_ptr, rptr, NULL);
667 rp++;
668 }
669
670 else if (dp != NULL)
671 for (i = 0; i < num_rows; i++)
672 {
673 png_bytep dptr = *dp;
674 png_read_row(png_ptr, NULL, dptr);
675 dp++;
676 }
677 }
678 #endif /* SEQUENTIAL_READ */
679
680 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
681 /* Read the entire image. If the image has an alpha channel or a tRNS
682 * chunk, and you have called png_handle_alpha()[*], you will need to
683 * initialize the image to the current image that PNG will be overlaying.
684 * We set the num_rows again here, in case it was incorrectly set in
685 * png_read_start_row() by a call to png_read_update_info() or
686 * png_start_read_image() if png_set_interlace_handling() wasn't called
687 * prior to either of these functions like it should have been. You can
688 * only call this function once. If you desire to have an image for
689 * each pass of a interlaced image, use png_read_rows() instead.
690 *
691 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
692 */
693 void PNGAPI
694 png_read_image(png_structrp png_ptr, png_bytepp image)
695 {
696 png_uint_32 i, image_height;
697 int pass, j;
698 png_bytepp rp;
699
700 png_debug(1, "in png_read_image");
701
702 if (png_ptr == NULL)
703 return;
704
705 #ifdef PNG_READ_INTERLACING_SUPPORTED
706 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
707 {
708 pass = png_set_interlace_handling(png_ptr);
709 /* And make sure transforms are initialized. */
710 png_start_read_image(png_ptr);
711 }
712 else
713 {
714 if (png_ptr->interlaced != 0 &&
715 (png_ptr->transformations & PNG_INTERLACE) == 0)
716 {
717 /* Caller called png_start_read_image or png_read_update_info without
718 * first turning on the PNG_INTERLACE transform. We can fix this here,
719 * but the caller should do it!
720 */
721 png_warning(png_ptr, "Interlace handling should be turned on when "
722 "using png_read_image");
723 /* Make sure this is set correctly */
724 png_ptr->num_rows = png_ptr->height;
725 }
726
727 /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
728 * the above error case.
729 */
730 pass = png_set_interlace_handling(png_ptr);
731 }
732 #else
733 if (png_ptr->interlaced)
734 png_error(png_ptr,
735 "Cannot read interlaced image -- interlace handler disabled");
736
737 pass = 1;
738 #endif
739
740 image_height=png_ptr->height;
741
742 for (j = 0; j < pass; j++)
743 {
744 rp = image;
745 for (i = 0; i < image_height; i++)
746 {
747 png_read_row(png_ptr, *rp, NULL);
748 rp++;
749 }
750 }
751 }
752 #endif /* SEQUENTIAL_READ */
753
754 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
755 /* Read the end of the PNG file. Will not read past the end of the
756 * file, will verify the end is accurate, and will read any comments
757 * or time information at the end of the file, if info is not NULL.
758 */
759 void PNGAPI
760 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
761 {
762 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
763 int keep;
764 #endif
765
766 png_debug(1, "in png_read_end");
767
768 if (png_ptr == NULL)
769 return;
770
771 /* If png_read_end is called in the middle of reading the rows there may
772 * still be pending IDAT data and an owned zstream. Deal with this here.
773 */
774 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
775 if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
776 #endif
777 png_read_finish_IDAT(png_ptr);
778
779 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
780 /* Report invalid palette index; added at libng-1.5.10 */
781 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
782 png_ptr->num_palette_max > png_ptr->num_palette)
783 png_benign_error(png_ptr, "Read palette index exceeding num_palette");
784 #endif
785
786 do
787 {
788 png_uint_32 length = png_read_chunk_header(png_ptr);
789 png_uint_32 chunk_name = png_ptr->chunk_name;
790
791 if (chunk_name != png_IDAT)
792 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
793
794 if (chunk_name == png_IEND)
795 png_handle_IEND(png_ptr, info_ptr, length);
796
797 else if (chunk_name == png_IHDR)
798 png_handle_IHDR(png_ptr, info_ptr, length);
799
800 else if (info_ptr == NULL)
801 png_crc_finish(png_ptr, length);
802
803 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
804 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
805 {
806 if (chunk_name == png_IDAT)
807 {
808 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
809 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
810 png_benign_error(png_ptr, ".Too many IDATs found");
811 }
812 png_handle_unknown(png_ptr, info_ptr, length, keep);
813 if (chunk_name == png_PLTE)
814 png_ptr->mode |= PNG_HAVE_PLTE;
815 }
816 #endif
817
818 else if (chunk_name == png_IDAT)
819 {
820 /* Zero length IDATs are legal after the last IDAT has been
821 * read, but not after other chunks have been read. 1.6 does not
822 * always read all the deflate data; specifically it cannot be relied
823 * upon to read the Adler32 at the end. If it doesn't ignore IDAT
824 * chunks which are longer than zero as well:
825 */
826 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
827 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
828 png_benign_error(png_ptr, "..Too many IDATs found");
829
830 png_crc_finish(png_ptr, length);
831 }
832 else if (chunk_name == png_PLTE)
833 png_handle_PLTE(png_ptr, info_ptr, length);
834
835 #ifdef PNG_READ_bKGD_SUPPORTED
836 else if (chunk_name == png_bKGD)
837 png_handle_bKGD(png_ptr, info_ptr, length);
838 #endif
839
840 #ifdef PNG_READ_cHRM_SUPPORTED
841 else if (chunk_name == png_cHRM)
842 png_handle_cHRM(png_ptr, info_ptr, length);
843 #endif
844
845 #ifdef PNG_READ_gAMA_SUPPORTED
846 else if (chunk_name == png_gAMA)
847 png_handle_gAMA(png_ptr, info_ptr, length);
848 #endif
849
850 #ifdef PNG_READ_hIST_SUPPORTED
851 else if (chunk_name == png_hIST)
852 png_handle_hIST(png_ptr, info_ptr, length);
853 #endif
854
855 #ifdef PNG_READ_oFFs_SUPPORTED
856 else if (chunk_name == png_oFFs)
857 png_handle_oFFs(png_ptr, info_ptr, length);
858 #endif
859
860 #ifdef PNG_READ_pCAL_SUPPORTED
861 else if (chunk_name == png_pCAL)
862 png_handle_pCAL(png_ptr, info_ptr, length);
863 #endif
864
865 #ifdef PNG_READ_sCAL_SUPPORTED
866 else if (chunk_name == png_sCAL)
867 png_handle_sCAL(png_ptr, info_ptr, length);
868 #endif
869
870 #ifdef PNG_READ_pHYs_SUPPORTED
871 else if (chunk_name == png_pHYs)
872 png_handle_pHYs(png_ptr, info_ptr, length);
873 #endif
874
875 #ifdef PNG_READ_sBIT_SUPPORTED
876 else if (chunk_name == png_sBIT)
877 png_handle_sBIT(png_ptr, info_ptr, length);
878 #endif
879
880 #ifdef PNG_READ_sRGB_SUPPORTED
881 else if (chunk_name == png_sRGB)
882 png_handle_sRGB(png_ptr, info_ptr, length);
883 #endif
884
885 #ifdef PNG_READ_iCCP_SUPPORTED
886 else if (chunk_name == png_iCCP)
887 png_handle_iCCP(png_ptr, info_ptr, length);
888 #endif
889
890 #ifdef PNG_READ_sPLT_SUPPORTED
891 else if (chunk_name == png_sPLT)
892 png_handle_sPLT(png_ptr, info_ptr, length);
893 #endif
894
895 #ifdef PNG_READ_tEXt_SUPPORTED
896 else if (chunk_name == png_tEXt)
897 png_handle_tEXt(png_ptr, info_ptr, length);
898 #endif
899
900 #ifdef PNG_READ_tIME_SUPPORTED
901 else if (chunk_name == png_tIME)
902 png_handle_tIME(png_ptr, info_ptr, length);
903 #endif
904
905 #ifdef PNG_READ_tRNS_SUPPORTED
906 else if (chunk_name == png_tRNS)
907 png_handle_tRNS(png_ptr, info_ptr, length);
908 #endif
909
910 #ifdef PNG_READ_zTXt_SUPPORTED
911 else if (chunk_name == png_zTXt)
912 png_handle_zTXt(png_ptr, info_ptr, length);
913 #endif
914
915 #ifdef PNG_READ_iTXt_SUPPORTED
916 else if (chunk_name == png_iTXt)
917 png_handle_iTXt(png_ptr, info_ptr, length);
918 #endif
919
920 else
921 png_handle_unknown(png_ptr, info_ptr, length,
922 PNG_HANDLE_CHUNK_AS_DEFAULT);
923 } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
924 }
925 #endif /* SEQUENTIAL_READ */
926
927 /* Free all memory used in the read struct */
928 static void
929 png_read_destroy(png_structrp png_ptr)
930 {
931 png_debug(1, "in png_read_destroy");
932
933 #ifdef PNG_READ_GAMMA_SUPPORTED
934 png_destroy_gamma_table(png_ptr);
935 #endif
936
937 png_free(png_ptr, png_ptr->big_row_buf);
938 png_ptr->big_row_buf = NULL;
939 png_free(png_ptr, png_ptr->big_prev_row);
940 png_ptr->big_prev_row = NULL;
941 png_free(png_ptr, png_ptr->read_buffer);
942 png_ptr->read_buffer = NULL;
943
944 #ifdef PNG_READ_QUANTIZE_SUPPORTED
945 png_free(png_ptr, png_ptr->palette_lookup);
946 png_ptr->palette_lookup = NULL;
947 png_free(png_ptr, png_ptr->quantize_index);
948 png_ptr->quantize_index = NULL;
949 #endif
950
951 if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
952 {
953 png_zfree(png_ptr, png_ptr->palette);
954 png_ptr->palette = NULL;
955 }
956 png_ptr->free_me &= ~PNG_FREE_PLTE;
957
958 #if defined(PNG_tRNS_SUPPORTED) || \
959 defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
960 if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
961 {
962 png_free(png_ptr, png_ptr->trans_alpha);
963 png_ptr->trans_alpha = NULL;
964 }
965 png_ptr->free_me &= ~PNG_FREE_TRNS;
966 #endif
967
968 inflateEnd(&png_ptr->zstream);
969
970 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
971 png_free(png_ptr, png_ptr->save_buffer);
972 png_ptr->save_buffer = NULL;
973 #endif
974
975 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
976 defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
977 png_free(png_ptr, png_ptr->unknown_chunk.data);
978 png_ptr->unknown_chunk.data = NULL;
979 #endif
980
981 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
982 png_free(png_ptr, png_ptr->chunk_list);
983 png_ptr->chunk_list = NULL;
984 #endif
985
986 /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
987 * callbacks are still set at this point. They are required to complete the
988 * destruction of the png_struct itself.
989 */
990 }
991
992 /* Free all memory used by the read */
993 void PNGAPI
994 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
995 png_infopp end_info_ptr_ptr)
996 {
997 png_structrp png_ptr = NULL;
998
999 png_debug(1, "in png_destroy_read_struct");
1000
1001 if (png_ptr_ptr != NULL)
1002 png_ptr = *png_ptr_ptr;
1003
1004 if (png_ptr == NULL)
1005 return;
1006
1007 /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1008 * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1009 * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1010 */
1011 png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1012 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1013
1014 *png_ptr_ptr = NULL;
1015 png_read_destroy(png_ptr);
1016 png_destroy_png_struct(png_ptr);
1017 }
1018
1019 void PNGAPI
1020 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1021 {
1022 if (png_ptr == NULL)
1023 return;
1024
1025 png_ptr->read_row_fn = read_row_fn;
1026 }
1027
1028
1029 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1030 #ifdef PNG_INFO_IMAGE_SUPPORTED
1031 void PNGAPI
1032 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1033 int transforms, voidp params)
1034 {
1035 if (png_ptr == NULL || info_ptr == NULL)
1036 return;
1037
1038 /* png_read_info() gives us all of the information from the
1039 * PNG file before the first IDAT (image data chunk).
1040 */
1041 png_read_info(png_ptr, info_ptr);
1042 if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1043 png_error(png_ptr, "Image is too high to process with png_read_png()");
1044
1045 /* -------------- image transformations start here ------------------- */
1046 /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1047 * is not implemented. This will only happen in de-configured (non-default)
1048 * libpng builds. The results can be unexpected - png_read_png may return
1049 * short or mal-formed rows because the transform is skipped.
1050 */
1051
1052 /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1053 */
1054 if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1055 /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1056 * did in earlier versions, while "scale_16" is now more accurate.
1057 */
1058 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1059 png_set_scale_16(png_ptr);
1060 #else
1061 png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1062 #endif
1063
1064 /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1065 * latter by doing SCALE first. This is ok and allows apps not to check for
1066 * which is supported to get the right answer.
1067 */
1068 if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1069 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1070 png_set_strip_16(png_ptr);
1071 #else
1072 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1073 #endif
1074
1075 /* Strip alpha bytes from the input data without combining with
1076 * the background (not recommended).
1077 */
1078 if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1079 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1080 png_set_strip_alpha(png_ptr);
1081 #else
1082 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1083 #endif
1084
1085 /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1086 * byte into separate bytes (useful for paletted and grayscale images).
1087 */
1088 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1089 #ifdef PNG_READ_PACK_SUPPORTED
1090 png_set_packing(png_ptr);
1091 #else
1092 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1093 #endif
1094
1095 /* Change the order of packed pixels to least significant bit first
1096 * (not useful if you are using png_set_packing).
1097 */
1098 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1099 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1100 png_set_packswap(png_ptr);
1101 #else
1102 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1103 #endif
1104
1105 /* Expand paletted colors into true RGB triplets
1106 * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1107 * Expand paletted or RGB images with transparency to full alpha
1108 * channels so the data will be available as RGBA quartets.
1109 */
1110 if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1111 #ifdef PNG_READ_EXPAND_SUPPORTED
1112 png_set_expand(png_ptr);
1113 #else
1114 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1115 #endif
1116
1117 /* We don't handle background color or gamma transformation or quantizing.
1118 */
1119
1120 /* Invert monochrome files to have 0 as white and 1 as black
1121 */
1122 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1123 #ifdef PNG_READ_INVERT_SUPPORTED
1124 png_set_invert_mono(png_ptr);
1125 #else
1126 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1127 #endif
1128
1129 /* If you want to shift the pixel values from the range [0,255] or
1130 * [0,65535] to the original [0,7] or [0,31], or whatever range the
1131 * colors were originally in:
1132 */
1133 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1134 #ifdef PNG_READ_SHIFT_SUPPORTED
1135 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1136 png_set_shift(png_ptr, &info_ptr->sig_bit);
1137 #else
1138 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1139 #endif
1140
1141 /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1142 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1143 #ifdef PNG_READ_BGR_SUPPORTED
1144 png_set_bgr(png_ptr);
1145 #else
1146 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1147 #endif
1148
1149 /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1150 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1151 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1152 png_set_swap_alpha(png_ptr);
1153 #else
1154 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1155 #endif
1156
1157 /* Swap bytes of 16-bit files to least significant byte first */
1158 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1159 #ifdef PNG_READ_SWAP_SUPPORTED
1160 png_set_swap(png_ptr);
1161 #else
1162 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1163 #endif
1164
1165 /* Added at libpng-1.2.41 */
1166 /* Invert the alpha channel from opacity to transparency */
1167 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1168 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1169 png_set_invert_alpha(png_ptr);
1170 #else
1171 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1172 #endif
1173
1174 /* Added at libpng-1.2.41 */
1175 /* Expand grayscale image to RGB */
1176 if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1177 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1178 png_set_gray_to_rgb(png_ptr);
1179 #else
1180 png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1181 #endif
1182
1183 /* Added at libpng-1.5.4 */
1184 if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1185 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1186 png_set_expand_16(png_ptr);
1187 #else
1188 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1189 #endif
1190
1191 /* We don't handle adding filler bytes */
1192
1193 /* We use png_read_image and rely on that for interlace handling, but we also
1194 * call png_read_update_info therefore must turn on interlace handling now:
1195 */
1196 (void)png_set_interlace_handling(png_ptr);
1197
1198 /* Optional call to gamma correct and add the background to the palette
1199 * and update info structure. REQUIRED if you are expecting libpng to
1200 * update the palette for you (i.e., you selected such a transform above).
1201 */
1202 png_read_update_info(png_ptr, info_ptr);
1203
1204 /* -------------- image transformations end here ------------------- */
1205
1206 png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1207 if (info_ptr->row_pointers == NULL)
1208 {
1209 png_uint_32 iptr;
1210
1211 info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1212 info_ptr->height * (sizeof (png_bytep))));
1213
1214 for (iptr=0; iptr<info_ptr->height; iptr++)
1215 info_ptr->row_pointers[iptr] = NULL;
1216
1217 info_ptr->free_me |= PNG_FREE_ROWS;
1218
1219 for (iptr = 0; iptr < info_ptr->height; iptr++)
1220 info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1221 png_malloc(png_ptr, info_ptr->rowbytes));
1222 }
1223
1224 png_read_image(png_ptr, info_ptr->row_pointers);
1225 info_ptr->valid |= PNG_INFO_IDAT;
1226
1227 /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1228 png_read_end(png_ptr, info_ptr);
1229
1230 PNG_UNUSED(params)
1231 }
1232 #endif /* INFO_IMAGE */
1233 #endif /* SEQUENTIAL_READ */
1234
1235 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1236 /* SIMPLIFIED READ
1237 *
1238 * This code currently relies on the sequential reader, though it could easily
1239 * be made to work with the progressive one.
1240 */
1241 /* Arguments to png_image_finish_read: */
1242
1243 /* Encoding of PNG data (used by the color-map code) */
1244 # define P_NOTSET 0 /* File encoding not yet known */
1245 # define P_sRGB 1 /* 8-bit encoded to sRGB gamma */
1246 # define P_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1247 # define P_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */
1248 # define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1249
1250 /* Color-map processing: after libpng has run on the PNG image further
1251 * processing may be needed to convert the data to color-map indices.
1252 */
1253 #define PNG_CMAP_NONE 0
1254 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */
1255 #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */
1256 #define PNG_CMAP_RGB 3 /* Process RGB data */
1257 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1258
1259 /* The following document where the background is for each processing case. */
1260 #define PNG_CMAP_NONE_BACKGROUND 256
1261 #define PNG_CMAP_GA_BACKGROUND 231
1262 #define PNG_CMAP_TRANS_BACKGROUND 254
1263 #define PNG_CMAP_RGB_BACKGROUND 256
1264 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1265
1266 typedef struct
1267 {
1268 /* Arguments: */
1269 png_imagep image;
1270 png_voidp buffer;
1271 png_int_32 row_stride;
1272 png_voidp colormap;
1273 png_const_colorp background;
1274 /* Local variables: */
1275 png_voidp local_row;
1276 png_voidp first_row;
1277 ptrdiff_t row_bytes; /* step between rows */
1278 int file_encoding; /* E_ values above */
1279 png_fixed_point gamma_to_linear; /* For P_FILE, reciprocal of gamma */
1280 int colormap_processing; /* PNG_CMAP_ values above */
1281 } png_image_read_control;
1282
1283 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1284 * called, so setting up the jmp_buf is not required. This means that anything
1285 * called from here must *not* call png_malloc - it has to call png_malloc_warn
1286 * instead so that control is returned safely back to this routine.
1287 */
1288 static int
1289 png_image_read_init(png_imagep image)
1290 {
1291 if (image->opaque == NULL)
1292 {
1293 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1294 png_safe_error, png_safe_warning);
1295
1296 /* And set the rest of the structure to NULL to ensure that the various
1297 * fields are consistent.
1298 */
1299 memset(image, 0, (sizeof *image));
1300 image->version = PNG_IMAGE_VERSION;
1301
1302 if (png_ptr != NULL)
1303 {
1304 png_infop info_ptr = png_create_info_struct(png_ptr);
1305
1306 if (info_ptr != NULL)
1307 {
1308 png_controlp control = png_voidcast(png_controlp,
1309 png_malloc_warn(png_ptr, (sizeof *control)));
1310
1311 if (control != NULL)
1312 {
1313 memset(control, 0, (sizeof *control));
1314
1315 control->png_ptr = png_ptr;
1316 control->info_ptr = info_ptr;
1317 control->for_write = 0;
1318
1319 image->opaque = control;
1320 return 1;
1321 }
1322
1323 /* Error clean up */
1324 png_destroy_info_struct(png_ptr, &info_ptr);
1325 }
1326
1327 png_destroy_read_struct(&png_ptr, NULL, NULL);
1328 }
1329
1330 return png_image_error(image, "png_image_read: out of memory");
1331 }
1332
1333 return png_image_error(image, "png_image_read: opaque pointer not NULL");
1334 }
1335
1336 /* Utility to find the base format of a PNG file from a png_struct. */
1337 static png_uint_32
1338 png_image_format(png_structrp png_ptr)
1339 {
1340 png_uint_32 format = 0;
1341
1342 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1343 format |= PNG_FORMAT_FLAG_COLOR;
1344
1345 if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1346 format |= PNG_FORMAT_FLAG_ALPHA;
1347
1348 /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1349 * sets the png_struct fields; that's all we are interested in here. The
1350 * precise interaction with an app call to png_set_tRNS and PNG file reading
1351 * is unclear.
1352 */
1353 else if (png_ptr->num_trans > 0)
1354 format |= PNG_FORMAT_FLAG_ALPHA;
1355
1356 if (png_ptr->bit_depth == 16)
1357 format |= PNG_FORMAT_FLAG_LINEAR;
1358
1359 if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1360 format |= PNG_FORMAT_FLAG_COLORMAP;
1361
1362 return format;
1363 }
1364
1365 /* Is the given gamma significantly different from sRGB? The test is the same
1366 * one used in pngrtran.c when deciding whether to do gamma correction. The
1367 * arithmetic optimizes the division by using the fact that the inverse of the
1368 * file sRGB gamma is 2.2
1369 */
1370 static int
1371 png_gamma_not_sRGB(png_fixed_point g)
1372 {
1373 if (g < PNG_FP_1)
1374 {
1375 /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1376 if (g == 0)
1377 return 0;
1378
1379 return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1380 }
1381
1382 return 1;
1383 }
1384
1385 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1386 * header and fill in all the information. This is executed in a safe context,
1387 * unlike the init routine above.
1388 */
1389 static int
1390 png_image_read_header(png_voidp argument)
1391 {
1392 png_imagep image = png_voidcast(png_imagep, argument);
1393 png_structrp png_ptr = image->opaque->png_ptr;
1394 png_inforp info_ptr = image->opaque->info_ptr;
1395
1396 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1397 png_set_benign_errors(png_ptr, 1/*warn*/);
1398 #endif
1399 png_read_info(png_ptr, info_ptr);
1400
1401 /* Do this the fast way; just read directly out of png_struct. */
1402 image->width = png_ptr->width;
1403 image->height = png_ptr->height;
1404
1405 {
1406 png_uint_32 format = png_image_format(png_ptr);
1407
1408 image->format = format;
1409
1410 #ifdef PNG_COLORSPACE_SUPPORTED
1411 /* Does the colorspace match sRGB? If there is no color endpoint
1412 * (colorant) information assume yes, otherwise require the
1413 * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set. If the
1414 * colorspace has been determined to be invalid ignore it.
1415 */
1416 if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1417 & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1418 PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1419 image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1420 #endif
1421 }
1422
1423 /* We need the maximum number of entries regardless of the format the
1424 * application sets here.
1425 */
1426 {
1427 png_uint_32 cmap_entries;
1428
1429 switch (png_ptr->color_type)
1430 {
1431 case PNG_COLOR_TYPE_GRAY:
1432 cmap_entries = 1U << png_ptr->bit_depth;
1433 break;
1434
1435 case PNG_COLOR_TYPE_PALETTE:
1436 cmap_entries = (png_uint_32)png_ptr->num_palette;
1437 break;
1438
1439 default:
1440 cmap_entries = 256;
1441 break;
1442 }
1443
1444 if (cmap_entries > 256)
1445 cmap_entries = 256;
1446
1447 image->colormap_entries = cmap_entries;
1448 }
1449
1450 return 1;
1451 }
1452
1453 #ifdef PNG_STDIO_SUPPORTED
1454 int PNGAPI
1455 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1456 {
1457 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1458 {
1459 if (file != NULL)
1460 {
1461 if (png_image_read_init(image) != 0)
1462 {
1463 /* This is slightly evil, but png_init_io doesn't do anything other
1464 * than this and we haven't changed the standard IO functions so
1465 * this saves a 'safe' function.
1466 */
1467 image->opaque->png_ptr->io_ptr = file;
1468 return png_safe_execute(image, png_image_read_header, image);
1469 }
1470 }
1471
1472 else
1473 return png_image_error(image,
1474 "png_image_begin_read_from_stdio: invalid argument");
1475 }
1476
1477 else if (image != NULL)
1478 return png_image_error(image,
1479 "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1480
1481 return 0;
1482 }
1483
1484 int PNGAPI
1485 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1486 {
1487 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1488 {
1489 if (file_name != NULL)
1490 {
1491 FILE *fp = fopen(file_name, "rb");
1492
1493 if (fp != NULL)
1494 {
1495 if (png_image_read_init(image) != 0)
1496 {
1497 image->opaque->png_ptr->io_ptr = fp;
1498 image->opaque->owned_file = 1;
1499 return png_safe_execute(image, png_image_read_header, image);
1500 }
1501
1502 /* Clean up: just the opened file. */
1503 (void)fclose(fp);
1504 }
1505
1506 else
1507 return png_image_error(image, strerror(errno));
1508 }
1509
1510 else
1511 return png_image_error(image,
1512 "png_image_begin_read_from_file: invalid argument");
1513 }
1514
1515 else if (image != NULL)
1516 return png_image_error(image,
1517 "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1518
1519 return 0;
1520 }
1521 #endif /* STDIO */
1522
1523 static void PNGCBAPI
1524 png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
1525 {
1526 if (png_ptr != NULL)
1527 {
1528 png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1529 if (image != NULL)
1530 {
1531 png_controlp cp = image->opaque;
1532 if (cp != NULL)
1533 {
1534 png_const_bytep memory = cp->memory;
1535 png_size_t size = cp->size;
1536
1537 if (memory != NULL && size >= need)
1538 {
1539 memcpy(out, memory, need);
1540 cp->memory = memory + need;
1541 cp->size = size - need;
1542 return;
1543 }
1544
1545 png_error(png_ptr, "read beyond end of data");
1546 }
1547 }
1548
1549 png_error(png_ptr, "invalid memory read");
1550 }
1551 }
1552
1553 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1554 png_const_voidp memory, png_size_t size)
1555 {
1556 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1557 {
1558 if (memory != NULL && size > 0)
1559 {
1560 if (png_image_read_init(image) != 0)
1561 {
1562 /* Now set the IO functions to read from the memory buffer and
1563 * store it into io_ptr. Again do this in-place to avoid calling a
1564 * libpng function that requires error handling.
1565 */
1566 image->opaque->memory = png_voidcast(png_const_bytep, memory);
1567 image->opaque->size = size;
1568 image->opaque->png_ptr->io_ptr = image;
1569 image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1570
1571 return png_safe_execute(image, png_image_read_header, image);
1572 }
1573 }
1574
1575 else
1576 return png_image_error(image,
1577 "png_image_begin_read_from_memory: invalid argument");
1578 }
1579
1580 else if (image != NULL)
1581 return png_image_error(image,
1582 "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1583
1584 return 0;
1585 }
1586
1587 /* Utility function to skip chunks that are not used by the simplified image
1588 * read functions and an appropriate macro to call it.
1589 */
1590 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1591 static void
1592 png_image_skip_unused_chunks(png_structrp png_ptr)
1593 {
1594 /* Prepare the reader to ignore all recognized chunks whose data will not
1595 * be used, i.e., all chunks recognized by libpng except for those
1596 * involved in basic image reading:
1597 *
1598 * IHDR, PLTE, IDAT, IEND
1599 *
1600 * Or image data handling:
1601 *
1602 * tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1603 *
1604 * This provides a small performance improvement and eliminates any
1605 * potential vulnerability to security problems in the unused chunks.
1606 *
1607 * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1608 * too. This allows the simplified API to be compiled without iCCP support,
1609 * however if the support is there the chunk is still checked to detect
1610 * errors (which are unfortunately quite common.)
1611 */
1612 {
1613 static PNG_CONST png_byte chunks_to_process[] = {
1614 98, 75, 71, 68, '\0', /* bKGD */
1615 99, 72, 82, 77, '\0', /* cHRM */
1616 103, 65, 77, 65, '\0', /* gAMA */
1617 # ifdef PNG_READ_iCCP_SUPPORTED
1618 105, 67, 67, 80, '\0', /* iCCP */
1619 # endif
1620 115, 66, 73, 84, '\0', /* sBIT */
1621 115, 82, 71, 66, '\0', /* sRGB */
1622 };
1623
1624 /* Ignore unknown chunks and all other chunks except for the
1625 * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1626 */
1627 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1628 NULL, -1);
1629
1630 /* But do not ignore image data handling chunks */
1631 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1632 chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1633 }
1634 }
1635
1636 # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1637 #else
1638 # define PNG_SKIP_CHUNKS(p) ((void)0)
1639 #endif /* HANDLE_AS_UNKNOWN */
1640
1641 /* The following macro gives the exact rounded answer for all values in the
1642 * range 0..255 (it actually divides by 51.2, but the rounding still generates
1643 * the correct numbers 0..5
1644 */
1645 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1646
1647 /* Utility functions to make particular color-maps */
1648 static void
1649 set_file_encoding(png_image_read_control *display)
1650 {
1651 png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1652 if (png_gamma_significant(g) != 0)
1653 {
1654 if (png_gamma_not_sRGB(g) != 0)
1655 {
1656 display->file_encoding = P_FILE;
1657 display->gamma_to_linear = png_reciprocal(g);
1658 }
1659
1660 else
1661 display->file_encoding = P_sRGB;
1662 }
1663
1664 else
1665 display->file_encoding = P_LINEAR8;
1666 }
1667
1668 static unsigned int
1669 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1670 {
1671 if (encoding == P_FILE) /* double check */
1672 encoding = display->file_encoding;
1673
1674 if (encoding == P_NOTSET) /* must be the file encoding */
1675 {
1676 set_file_encoding(display);
1677 encoding = display->file_encoding;
1678 }
1679
1680 switch (encoding)
1681 {
1682 case P_FILE:
1683 value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1684 break;
1685
1686 case P_sRGB:
1687 value = png_sRGB_table[value];
1688 break;
1689
1690 case P_LINEAR:
1691 break;
1692
1693 case P_LINEAR8:
1694 value *= 257;
1695 break;
1696
1697 #ifdef __GNUC__
1698 default:
1699 png_error(display->image->opaque->png_ptr,
1700 "unexpected encoding (internal error)");
1701 #endif
1702 }
1703
1704 return value;
1705 }
1706
1707 static png_uint_32
1708 png_colormap_compose(png_image_read_control *display,
1709 png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1710 png_uint_32 background, int encoding)
1711 {
1712 /* The file value is composed on the background, the background has the given
1713 * encoding and so does the result, the file is encoded with P_FILE and the
1714 * file and alpha are 8-bit values. The (output) encoding will always be
1715 * P_LINEAR or P_sRGB.
1716 */
1717 png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1718 png_uint_32 b = decode_gamma(display, background, encoding);
1719
1720 /* The alpha is always an 8-bit value (it comes from the palette), the value
1721 * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1722 */
1723 f = f * alpha + b * (255-alpha);
1724
1725 if (encoding == P_LINEAR)
1726 {
1727 /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1728 * accurate, it divides by 255.00000005937181414556, with no overflow.)
1729 */
1730 f *= 257; /* Now scaled by 65535 */
1731 f += f >> 16;
1732 f = (f+32768) >> 16;
1733 }
1734
1735 else /* P_sRGB */
1736 f = PNG_sRGB_FROM_LINEAR(f);
1737
1738 return f;
1739 }
1740
1741 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1742 * be 8-bit.
1743 */
1744 static void
1745 png_create_colormap_entry(png_image_read_control *display,
1746 png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1747 png_uint_32 alpha, int encoding)
1748 {
1749 png_imagep image = display->image;
1750 const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1751 P_LINEAR : P_sRGB;
1752 const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1753 (red != green || green != blue);
1754
1755 if (ip > 255)
1756 png_error(image->opaque->png_ptr, "color-map index out of range");
1757
1758 /* Update the cache with whether the file gamma is significantly different
1759 * from sRGB.
1760 */
1761 if (encoding == P_FILE)
1762 {
1763 if (display->file_encoding == P_NOTSET)
1764 set_file_encoding(display);
1765
1766 /* Note that the cached value may be P_FILE too, but if it is then the
1767 * gamma_to_linear member has been set.
1768 */
1769 encoding = display->file_encoding;
1770 }
1771
1772 if (encoding == P_FILE)
1773 {
1774 png_fixed_point g = display->gamma_to_linear;
1775
1776 red = png_gamma_16bit_correct(red*257, g);
1777 green = png_gamma_16bit_correct(green*257, g);
1778 blue = png_gamma_16bit_correct(blue*257, g);
1779
1780 if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1781 {
1782 alpha *= 257;
1783 encoding = P_LINEAR;
1784 }
1785
1786 else
1787 {
1788 red = PNG_sRGB_FROM_LINEAR(red * 255);
1789 green = PNG_sRGB_FROM_LINEAR(green * 255);
1790 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1791 encoding = P_sRGB;
1792 }
1793 }
1794
1795 else if (encoding == P_LINEAR8)
1796 {
1797 /* This encoding occurs quite frequently in test cases because PngSuite
1798 * includes a gAMA 1.0 chunk with most images.
1799 */
1800 red *= 257;
1801 green *= 257;
1802 blue *= 257;
1803 alpha *= 257;
1804 encoding = P_LINEAR;
1805 }
1806
1807 else if (encoding == P_sRGB &&
1808 (convert_to_Y != 0 || output_encoding == P_LINEAR))
1809 {
1810 /* The values are 8-bit sRGB values, but must be converted to 16-bit
1811 * linear.
1812 */
1813 red = png_sRGB_table[red];
1814 green = png_sRGB_table[green];
1815 blue = png_sRGB_table[blue];
1816 alpha *= 257;
1817 encoding = P_LINEAR;
1818 }
1819
1820 /* This is set if the color isn't gray but the output is. */
1821 if (encoding == P_LINEAR)
1822 {
1823 if (convert_to_Y != 0)
1824 {
1825 /* NOTE: these values are copied from png_do_rgb_to_gray */
1826 png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green +
1827 (png_uint_32)2366 * blue;
1828
1829 if (output_encoding == P_LINEAR)
1830 y = (y + 16384) >> 15;
1831
1832 else
1833 {
1834 /* y is scaled by 32768, we need it scaled by 255: */
1835 y = (y + 128) >> 8;
1836 y *= 255;
1837 y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1838 alpha = PNG_DIV257(alpha);
1839 encoding = P_sRGB;
1840 }
1841
1842 blue = red = green = y;
1843 }
1844
1845 else if (output_encoding == P_sRGB)
1846 {
1847 red = PNG_sRGB_FROM_LINEAR(red * 255);
1848 green = PNG_sRGB_FROM_LINEAR(green * 255);
1849 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1850 alpha = PNG_DIV257(alpha);
1851 encoding = P_sRGB;
1852 }
1853 }
1854
1855 if (encoding != output_encoding)
1856 png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1857
1858 /* Store the value. */
1859 {
1860 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
1861 const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1862 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1863 # else
1864 # define afirst 0
1865 # endif
1866 # ifdef PNG_FORMAT_BGR_SUPPORTED
1867 const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1868 # else
1869 # define bgr 0
1870 # endif
1871
1872 if (output_encoding == P_LINEAR)
1873 {
1874 png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1875
1876 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1877
1878 /* The linear 16-bit values must be pre-multiplied by the alpha channel
1879 * value, if less than 65535 (this is, effectively, composite on black
1880 * if the alpha channel is removed.)
1881 */
1882 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1883 {
1884 case 4:
1885 entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1886 /* FALL THROUGH */
1887
1888 case 3:
1889 if (alpha < 65535)
1890 {
1891 if (alpha > 0)
1892 {
1893 blue = (blue * alpha + 32767U)/65535U;
1894 green = (green * alpha + 32767U)/65535U;
1895 red = (red * alpha + 32767U)/65535U;
1896 }
1897
1898 else
1899 red = green = blue = 0;
1900 }
1901 entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1902 entry[afirst + 1] = (png_uint_16)green;
1903 entry[afirst + bgr] = (png_uint_16)red;
1904 break;
1905
1906 case 2:
1907 entry[1 ^ afirst] = (png_uint_16)alpha;
1908 /* FALL THROUGH */
1909
1910 case 1:
1911 if (alpha < 65535)
1912 {
1913 if (alpha > 0)
1914 green = (green * alpha + 32767U)/65535U;
1915
1916 else
1917 green = 0;
1918 }
1919 entry[afirst] = (png_uint_16)green;
1920 break;
1921
1922 default:
1923 break;
1924 }
1925 }
1926
1927 else /* output encoding is P_sRGB */
1928 {
1929 png_bytep entry = png_voidcast(png_bytep, display->colormap);
1930
1931 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1932
1933 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1934 {
1935 case 4:
1936 entry[afirst ? 0 : 3] = (png_byte)alpha;
1937 case 3:
1938 entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1939 entry[afirst + 1] = (png_byte)green;
1940 entry[afirst + bgr] = (png_byte)red;
1941 break;
1942
1943 case 2:
1944 entry[1 ^ afirst] = (png_byte)alpha;
1945 case 1:
1946 entry[afirst] = (png_byte)green;
1947 break;
1948
1949 default:
1950 break;
1951 }
1952 }
1953
1954 # ifdef afirst
1955 # undef afirst
1956 # endif
1957 # ifdef bgr
1958 # undef bgr
1959 # endif
1960 }
1961 }
1962
1963 static int
1964 make_gray_file_colormap(png_image_read_control *display)
1965 {
1966 unsigned int i;
1967
1968 for (i=0; i<256; ++i)
1969 png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1970
1971 return (int)i;
1972 }
1973
1974 static int
1975 make_gray_colormap(png_image_read_control *display)
1976 {
1977 unsigned int i;
1978
1979 for (i=0; i<256; ++i)
1980 png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
1981
1982 return (int)i;
1983 }
1984 #define PNG_GRAY_COLORMAP_ENTRIES 256
1985
1986 static int
1987 make_ga_colormap(png_image_read_control *display)
1988 {
1989 unsigned int i, a;
1990
1991 /* Alpha is retained, the output will be a color-map with entries
1992 * selected by six levels of alpha. One transparent entry, 6 gray
1993 * levels for all the intermediate alpha values, leaving 230 entries
1994 * for the opaque grays. The color-map entries are the six values
1995 * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
1996 * relevant entry.
1997 *
1998 * if (alpha > 229) // opaque
1999 * {
2000 * // The 231 entries are selected to make the math below work:
2001 * base = 0;
2002 * entry = (231 * gray + 128) >> 8;
2003 * }
2004 * else if (alpha < 26) // transparent
2005 * {
2006 * base = 231;
2007 * entry = 0;
2008 * }
2009 * else // partially opaque
2010 * {
2011 * base = 226 + 6 * PNG_DIV51(alpha);
2012 * entry = PNG_DIV51(gray);
2013 * }
2014 */
2015 i = 0;
2016 while (i < 231)
2017 {
2018 unsigned int gray = (i * 256 + 115) / 231;
2019 png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2020 }
2021
2022 /* 255 is used here for the component values for consistency with the code
2023 * that undoes premultiplication in pngwrite.c.
2024 */
2025 png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2026
2027 for (a=1; a<5; ++a)
2028 {
2029 unsigned int g;
2030
2031 for (g=0; g<6; ++g)
2032 png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2033 P_sRGB);
2034 }
2035
2036 return (int)i;
2037 }
2038
2039 #define PNG_GA_COLORMAP_ENTRIES 256
2040
2041 static int
2042 make_rgb_colormap(png_image_read_control *display)
2043 {
2044 unsigned int i, r;
2045
2046 /* Build a 6x6x6 opaque RGB cube */
2047 for (i=r=0; r<6; ++r)
2048 {
2049 unsigned int g;
2050
2051 for (g=0; g<6; ++g)
2052 {
2053 unsigned int b;
2054
2055 for (b=0; b<6; ++b)
2056 png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2057 P_sRGB);
2058 }
2059 }
2060
2061 return (int)i;
2062 }
2063
2064 #define PNG_RGB_COLORMAP_ENTRIES 216
2065
2066 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2067 #define PNG_RGB_INDEX(r,g,b) \
2068 ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2069
2070 static int
2071 png_image_read_colormap(png_voidp argument)
2072 {
2073 png_image_read_control *display =
2074 png_voidcast(png_image_read_control*, argument);
2075 const png_imagep image = display->image;
2076
2077 const png_structrp png_ptr = image->opaque->png_ptr;
2078 const png_uint_32 output_format = image->format;
2079 const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2080 P_LINEAR : P_sRGB;
2081
2082 unsigned int cmap_entries;
2083 unsigned int output_processing; /* Output processing option */
2084 unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2085
2086 /* Background information; the background color and the index of this color
2087 * in the color-map if it exists (else 256).
2088 */
2089 unsigned int background_index = 256;
2090 png_uint_32 back_r, back_g, back_b;
2091
2092 /* Flags to accumulate things that need to be done to the input. */
2093 int expand_tRNS = 0;
2094
2095 /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2096 * very difficult to do, the results look awful, and it is difficult to see
2097 * what possible use it is because the application can't control the
2098 * color-map.
2099 */
2100 if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2101 png_ptr->num_trans > 0) /* alpha in input */ &&
2102 ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2103 {
2104 if (output_encoding == P_LINEAR) /* compose on black */
2105 back_b = back_g = back_r = 0;
2106
2107 else if (display->background == NULL /* no way to remove it */)
2108 png_error(png_ptr,
2109 "background color must be supplied to remove alpha/transparency");
2110
2111 /* Get a copy of the background color (this avoids repeating the checks
2112 * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the
2113 * output format.
2114 */
2115 else
2116 {
2117 back_g = display->background->green;
2118 if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2119 {
2120 back_r = display->background->red;
2121 back_b = display->background->blue;
2122 }
2123 else
2124 back_b = back_r = back_g;
2125 }
2126 }
2127
2128 else if (output_encoding == P_LINEAR)
2129 back_b = back_r = back_g = 65535;
2130
2131 else
2132 back_b = back_r = back_g = 255;
2133
2134 /* Default the input file gamma if required - this is necessary because
2135 * libpng assumes that if no gamma information is present the data is in the
2136 * output format, but the simplified API deduces the gamma from the input
2137 * format.
2138 */
2139 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2140 {
2141 /* Do this directly, not using the png_colorspace functions, to ensure
2142 * that it happens even if the colorspace is invalid (though probably if
2143 * it is the setting will be ignored) Note that the same thing can be
2144 * achieved at the application interface with png_set_gAMA.
2145 */
2146 if (png_ptr->bit_depth == 16 &&
2147 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2148 png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2149
2150 else
2151 png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2152
2153 png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2154 }
2155
2156 /* Decide what to do based on the PNG color type of the input data. The
2157 * utility function png_create_colormap_entry deals with most aspects of the
2158 * output transformations; this code works out how to produce bytes of
2159 * color-map entries from the original format.
2160 */
2161 switch (png_ptr->color_type)
2162 {
2163 case PNG_COLOR_TYPE_GRAY:
2164 if (png_ptr->bit_depth <= 8)
2165 {
2166 /* There at most 256 colors in the output, regardless of
2167 * transparency.
2168 */
2169 unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2170
2171 cmap_entries = 1U << png_ptr->bit_depth;
2172 if (cmap_entries > image->colormap_entries)
2173 png_error(png_ptr, "gray[8] color-map: too few entries");
2174
2175 step = 255 / (cmap_entries - 1);
2176 output_processing = PNG_CMAP_NONE;
2177
2178 /* If there is a tRNS chunk then this either selects a transparent
2179 * value or, if the output has no alpha, the background color.
2180 */
2181 if (png_ptr->num_trans > 0)
2182 {
2183 trans = png_ptr->trans_color.gray;
2184
2185 if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2186 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2187 }
2188
2189 /* png_create_colormap_entry just takes an RGBA and writes the
2190 * corresponding color-map entry using the format from 'image',
2191 * including the required conversion to sRGB or linear as
2192 * appropriate. The input values are always either sRGB (if the
2193 * gamma correction flag is 0) or 0..255 scaled file encoded values
2194 * (if the function must gamma correct them).
2195 */
2196 for (i=val=0; i<cmap_entries; ++i, val += step)
2197 {
2198 /* 'i' is a file value. While this will result in duplicated
2199 * entries for 8-bit non-sRGB encoded files it is necessary to
2200 * have non-gamma corrected values to do tRNS handling.
2201 */
2202 if (i != trans)
2203 png_create_colormap_entry(display, i, val, val, val, 255,
2204 P_FILE/*8-bit with file gamma*/);
2205
2206 /* Else this entry is transparent. The colors don't matter if
2207 * there is an alpha channel (back_alpha == 0), but it does no
2208 * harm to pass them in; the values are not set above so this
2209 * passes in white.
2210 *
2211 * NOTE: this preserves the full precision of the application
2212 * supplied background color when it is used.
2213 */
2214 else
2215 png_create_colormap_entry(display, i, back_r, back_g, back_b,
2216 back_alpha, output_encoding);
2217 }
2218
2219 /* We need libpng to preserve the original encoding. */
2220 data_encoding = P_FILE;
2221
2222 /* The rows from libpng, while technically gray values, are now also
2223 * color-map indices; however, they may need to be expanded to 1
2224 * byte per pixel. This is what png_set_packing does (i.e., it
2225 * unpacks the bit values into bytes.)
2226 */
2227 if (png_ptr->bit_depth < 8)
2228 png_set_packing(png_ptr);
2229 }
2230
2231 else /* bit depth is 16 */
2232 {
2233 /* The 16-bit input values can be converted directly to 8-bit gamma
2234 * encoded values; however, if a tRNS chunk is present 257 color-map
2235 * entries are required. This means that the extra entry requires
2236 * special processing; add an alpha channel, sacrifice gray level
2237 * 254 and convert transparent (alpha==0) entries to that.
2238 *
2239 * Use libpng to chop the data to 8 bits. Convert it to sRGB at the
2240 * same time to minimize quality loss. If a tRNS chunk is present
2241 * this means libpng must handle it too; otherwise it is impossible
2242 * to do the exact match on the 16-bit value.
2243 *
2244 * If the output has no alpha channel *and* the background color is
2245 * gray then it is possible to let libpng handle the substitution by
2246 * ensuring that the corresponding gray level matches the background
2247 * color exactly.
2248 */
2249 data_encoding = P_sRGB;
2250
2251 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2252 png_error(png_ptr, "gray[16] color-map: too few entries");
2253
2254 cmap_entries = (unsigned int)make_gray_colormap(display);
2255
2256 if (png_ptr->num_trans > 0)
2257 {
2258 unsigned int back_alpha;
2259
2260 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2261 back_alpha = 0;
2262
2263 else
2264 {
2265 if (back_r == back_g && back_g == back_b)
2266 {
2267 /* Background is gray; no special processing will be
2268 * required.
2269 */
2270 png_color_16 c;
2271 png_uint_32 gray = back_g;
2272
2273 if (output_encoding == P_LINEAR)
2274 {
2275 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2276
2277 /* And make sure the corresponding palette entry
2278 * matches.
2279 */
2280 png_create_colormap_entry(display, gray, back_g, back_g,
2281 back_g, 65535, P_LINEAR);
2282 }
2283
2284 /* The background passed to libpng, however, must be the
2285 * sRGB value.
2286 */
2287 c.index = 0; /*unused*/
2288 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2289
2290 /* NOTE: does this work without expanding tRNS to alpha?
2291 * It should be the color->gray case below apparently
2292 * doesn't.
2293 */
2294 png_set_background_fixed(png_ptr, &c,
2295 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2296 0/*gamma: not used*/);
2297
2298 output_processing = PNG_CMAP_NONE;
2299 break;
2300 }
2301 #ifdef __COVERITY__
2302 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2303 * here.
2304 */
2305 back_alpha = 255;
2306 #else
2307 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2308 #endif
2309 }
2310
2311 /* output_processing means that the libpng-processed row will be
2312 * 8-bit GA and it has to be processing to single byte color-map
2313 * values. Entry 254 is replaced by either a completely
2314 * transparent entry or by the background color at full
2315 * precision (and the background color is not a simple gray
2316 * level in this case.)
2317 */
2318 expand_tRNS = 1;
2319 output_processing = PNG_CMAP_TRANS;
2320 background_index = 254;
2321
2322 /* And set (overwrite) color-map entry 254 to the actual
2323 * background color at full precision.
2324 */
2325 png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2326 back_alpha, output_encoding);
2327 }
2328
2329 else
2330 output_processing = PNG_CMAP_NONE;
2331 }
2332 break;
2333
2334 case PNG_COLOR_TYPE_GRAY_ALPHA:
2335 /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum
2336 * of 65536 combinations. If, however, the alpha channel is to be
2337 * removed there are only 256 possibilities if the background is gray.
2338 * (Otherwise there is a subset of the 65536 possibilities defined by
2339 * the triangle between black, white and the background color.)
2340 *
2341 * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to
2342 * worry about tRNS matching - tRNS is ignored if there is an alpha
2343 * channel.
2344 */
2345 data_encoding = P_sRGB;
2346
2347 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2348 {
2349 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2350 png_error(png_ptr, "gray+alpha color-map: too few entries");
2351
2352 cmap_entries = (unsigned int)make_ga_colormap(display);
2353
2354 background_index = PNG_CMAP_GA_BACKGROUND;
2355 output_processing = PNG_CMAP_GA;
2356 }
2357
2358 else /* alpha is removed */
2359 {
2360 /* Alpha must be removed as the PNG data is processed when the
2361 * background is a color because the G and A channels are
2362 * independent and the vector addition (non-parallel vectors) is a
2363 * 2-D problem.
2364 *
2365 * This can be reduced to the same algorithm as above by making a
2366 * colormap containing gray levels (for the opaque grays), a
2367 * background entry (for a transparent pixel) and a set of four six
2368 * level color values, one set for each intermediate alpha value.
2369 * See the comments in make_ga_colormap for how this works in the
2370 * per-pixel processing.
2371 *
2372 * If the background is gray, however, we only need a 256 entry gray
2373 * level color map. It is sufficient to make the entry generated
2374 * for the background color be exactly the color specified.
2375 */
2376 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2377 (back_r == back_g && back_g == back_b))
2378 {
2379 /* Background is gray; no special processing will be required. */
2380 png_color_16 c;
2381 png_uint_32 gray = back_g;
2382
2383 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2384 png_error(png_ptr, "gray-alpha color-map: too few entries");
2385
2386 cmap_entries = (unsigned int)make_gray_colormap(display);
2387
2388 if (output_encoding == P_LINEAR)
2389 {
2390 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2391
2392 /* And make sure the corresponding palette entry matches. */
2393 png_create_colormap_entry(display, gray, back_g, back_g,
2394 back_g, 65535, P_LINEAR);
2395 }
2396
2397 /* The background passed to libpng, however, must be the sRGB
2398 * value.
2399 */
2400 c.index = 0; /*unused*/
2401 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2402
2403 png_set_background_fixed(png_ptr, &c,
2404 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2405 0/*gamma: not used*/);
2406
2407 output_processing = PNG_CMAP_NONE;
2408 }
2409
2410 else
2411 {
2412 png_uint_32 i, a;
2413
2414 /* This is the same as png_make_ga_colormap, above, except that
2415 * the entries are all opaque.
2416 */
2417 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2418 png_error(png_ptr, "ga-alpha color-map: too few entries");
2419
2420 i = 0;
2421 while (i < 231)
2422 {
2423 png_uint_32 gray = (i * 256 + 115) / 231;
2424 png_create_colormap_entry(display, i++, gray, gray, gray,
2425 255, P_sRGB);
2426 }
2427
2428 /* NOTE: this preserves the full precision of the application
2429 * background color.
2430 */
2431 background_index = i;
2432 png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2433 #ifdef __COVERITY__
2434 /* Coverity claims that output_encoding
2435 * cannot be 2 (P_LINEAR) here.
2436 */ 255U,
2437 #else
2438 output_encoding == P_LINEAR ? 65535U : 255U,
2439 #endif
2440 output_encoding);
2441
2442 /* For non-opaque input composite on the sRGB background - this
2443 * requires inverting the encoding for each component. The input
2444 * is still converted to the sRGB encoding because this is a
2445 * reasonable approximate to the logarithmic curve of human
2446 * visual sensitivity, at least over the narrow range which PNG
2447 * represents. Consequently 'G' is always sRGB encoded, while
2448 * 'A' is linear. We need the linear background colors.
2449 */
2450 if (output_encoding == P_sRGB) /* else already linear */
2451 {
2452 /* This may produce a value not exactly matching the
2453 * background, but that's ok because these numbers are only
2454 * used when alpha != 0
2455 */
2456 back_r = png_sRGB_table[back_r];
2457 back_g = png_sRGB_table[back_g];
2458 back_b = png_sRGB_table[back_b];
2459 }
2460
2461 for (a=1; a<5; ++a)
2462 {
2463 unsigned int g;
2464
2465 /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2466 * by an 8-bit alpha value (0..255).
2467 */
2468 png_uint_32 alpha = 51 * a;
2469 png_uint_32 back_rx = (255-alpha) * back_r;
2470 png_uint_32 back_gx = (255-alpha) * back_g;
2471 png_uint_32 back_bx = (255-alpha) * back_b;
2472
2473 for (g=0; g<6; ++g)
2474 {
2475 png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2476
2477 png_create_colormap_entry(display, i++,
2478 PNG_sRGB_FROM_LINEAR(gray + back_rx),
2479 PNG_sRGB_FROM_LINEAR(gray + back_gx),
2480 PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2481 }
2482 }
2483
2484 cmap_entries = i;
2485 output_processing = PNG_CMAP_GA;
2486 }
2487 }
2488 break;
2489
2490 case PNG_COLOR_TYPE_RGB:
2491 case PNG_COLOR_TYPE_RGB_ALPHA:
2492 /* Exclude the case where the output is gray; we can always handle this
2493 * with the cases above.
2494 */
2495 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2496 {
2497 /* The color-map will be grayscale, so we may as well convert the
2498 * input RGB values to a simple grayscale and use the grayscale
2499 * code above.
2500 *
2501 * NOTE: calling this apparently damages the recognition of the
2502 * transparent color in background color handling; call
2503 * png_set_tRNS_to_alpha before png_set_background_fixed.
2504 */
2505 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2506 -1);
2507 data_encoding = P_sRGB;
2508
2509 /* The output will now be one or two 8-bit gray or gray+alpha
2510 * channels. The more complex case arises when the input has alpha.
2511 */
2512 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2513 png_ptr->num_trans > 0) &&
2514 (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2515 {
2516 /* Both input and output have an alpha channel, so no background
2517 * processing is required; just map the GA bytes to the right
2518 * color-map entry.
2519 */
2520 expand_tRNS = 1;
2521
2522 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2523 png_error(png_ptr, "rgb[ga] color-map: too few entries");
2524
2525 cmap_entries = (unsigned int)make_ga_colormap(display);
2526 background_index = PNG_CMAP_GA_BACKGROUND;
2527 output_processing = PNG_CMAP_GA;
2528 }
2529
2530 else
2531 {
2532 /* Either the input or the output has no alpha channel, so there
2533 * will be no non-opaque pixels in the color-map; it will just be
2534 * grayscale.
2535 */
2536 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2537 png_error(png_ptr, "rgb[gray] color-map: too few entries");
2538
2539 /* Ideally this code would use libpng to do the gamma correction,
2540 * but if an input alpha channel is to be removed we will hit the
2541 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2542 * correction bug). Fix this by dropping the gamma correction in
2543 * this case and doing it in the palette; this will result in
2544 * duplicate palette entries, but that's better than the
2545 * alternative of double gamma correction.
2546 */
2547 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2548 png_ptr->num_trans > 0) &&
2549 png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2550 {
2551 cmap_entries = (unsigned int)make_gray_file_colormap(display);
2552 data_encoding = P_FILE;
2553 }
2554
2555 else
2556 cmap_entries = (unsigned int)make_gray_colormap(display);
2557
2558 /* But if the input has alpha or transparency it must be removed
2559 */
2560 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2561 png_ptr->num_trans > 0)
2562 {
2563 png_color_16 c;
2564 png_uint_32 gray = back_g;
2565
2566 /* We need to ensure that the application background exists in
2567 * the colormap and that completely transparent pixels map to
2568 * it. Achieve this simply by ensuring that the entry
2569 * selected for the background really is the background color.
2570 */
2571 if (data_encoding == P_FILE) /* from the fixup above */
2572 {
2573 /* The app supplied a gray which is in output_encoding, we
2574 * need to convert it to a value of the input (P_FILE)
2575 * encoding then set this palette entry to the required
2576 * output encoding.
2577 */
2578 if (output_encoding == P_sRGB)
2579 gray = png_sRGB_table[gray]; /* now P_LINEAR */
2580
2581 gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2582 png_ptr->colorspace.gamma)); /* now P_FILE */
2583
2584 /* And make sure the corresponding palette entry contains
2585 * exactly the required sRGB value.
2586 */
2587 png_create_colormap_entry(display, gray, back_g, back_g,
2588 back_g, 0/*unused*/, output_encoding);
2589 }
2590
2591 else if (output_encoding == P_LINEAR)
2592 {
2593 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2594
2595 /* And make sure the corresponding palette entry matches.
2596 */
2597 png_create_colormap_entry(display, gray, back_g, back_g,
2598 back_g, 0/*unused*/, P_LINEAR);
2599 }
2600
2601 /* The background passed to libpng, however, must be the
2602 * output (normally sRGB) value.
2603 */
2604 c.index = 0; /*unused*/
2605 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2606
2607 /* NOTE: the following is apparently a bug in libpng. Without
2608 * it the transparent color recognition in
2609 * png_set_background_fixed seems to go wrong.
2610 */
2611 expand_tRNS = 1;
2612 png_set_background_fixed(png_ptr, &c,
2613 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2614 0/*gamma: not used*/);
2615 }
2616
2617 output_processing = PNG_CMAP_NONE;
2618 }
2619 }
2620
2621 else /* output is color */
2622 {
2623 /* We could use png_quantize here so long as there is no transparent
2624 * color or alpha; png_quantize ignores alpha. Easier overall just
2625 * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2626 * Consequently we always want libpng to produce sRGB data.
2627 */
2628 data_encoding = P_sRGB;
2629
2630 /* Is there any transparency or alpha? */
2631 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2632 png_ptr->num_trans > 0)
2633 {
2634 /* Is there alpha in the output too? If so all four channels are
2635 * processed into a special RGB cube with alpha support.
2636 */
2637 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2638 {
2639 png_uint_32 r;
2640
2641 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2642 png_error(png_ptr, "rgb+alpha color-map: too few entries");
2643
2644 cmap_entries = (unsigned int)make_rgb_colormap(display);
2645
2646 /* Add a transparent entry. */
2647 png_create_colormap_entry(display, cmap_entries, 255, 255,
2648 255, 0, P_sRGB);
2649
2650 /* This is stored as the background index for the processing
2651 * algorithm.
2652 */
2653 background_index = cmap_entries++;
2654
2655 /* Add 27 r,g,b entries each with alpha 0.5. */
2656 for (r=0; r<256; r = (r << 1) | 0x7f)
2657 {
2658 png_uint_32 g;
2659
2660 for (g=0; g<256; g = (g << 1) | 0x7f)
2661 {
2662 png_uint_32 b;
2663
2664 /* This generates components with the values 0, 127 and
2665 * 255
2666 */
2667 for (b=0; b<256; b = (b << 1) | 0x7f)
2668 png_create_colormap_entry(display, cmap_entries++,
2669 r, g, b, 128, P_sRGB);
2670 }
2671 }
2672
2673 expand_tRNS = 1;
2674 output_processing = PNG_CMAP_RGB_ALPHA;
2675 }
2676
2677 else
2678 {
2679 /* Alpha/transparency must be removed. The background must
2680 * exist in the color map (achieved by setting adding it after
2681 * the 666 color-map). If the standard processing code will
2682 * pick up this entry automatically that's all that is
2683 * required; libpng can be called to do the background
2684 * processing.
2685 */
2686 unsigned int sample_size =
2687 PNG_IMAGE_SAMPLE_SIZE(output_format);
2688 png_uint_32 r, g, b; /* sRGB background */
2689
2690 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2691 png_error(png_ptr, "rgb-alpha color-map: too few entries");
2692
2693 cmap_entries = (unsigned int)make_rgb_colormap(display);
2694
2695 png_create_colormap_entry(display, cmap_entries, back_r,
2696 back_g, back_b, 0/*unused*/, output_encoding);
2697
2698 if (output_encoding == P_LINEAR)
2699 {
2700 r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2701 g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2702 b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2703 }
2704
2705 else
2706 {
2707 r = back_r;
2708 g = back_g;
2709 b = back_g;
2710 }
2711
2712 /* Compare the newly-created color-map entry with the one the
2713 * PNG_CMAP_RGB algorithm will use. If the two entries don't
2714 * match, add the new one and set this as the background
2715 * index.
2716 */
2717 if (memcmp((png_const_bytep)display->colormap +
2718 sample_size * cmap_entries,
2719 (png_const_bytep)display->colormap +
2720 sample_size * PNG_RGB_INDEX(r,g,b),
2721 sample_size) != 0)
2722 {
2723 /* The background color must be added. */
2724 background_index = cmap_entries++;
2725
2726 /* Add 27 r,g,b entries each with created by composing with
2727 * the background at alpha 0.5.
2728 */
2729 for (r=0; r<256; r = (r << 1) | 0x7f)
2730 {
2731 for (g=0; g<256; g = (g << 1) | 0x7f)
2732 {
2733 /* This generates components with the values 0, 127
2734 * and 255
2735 */
2736 for (b=0; b<256; b = (b << 1) | 0x7f)
2737 png_create_colormap_entry(display, cmap_entries++,
2738 png_colormap_compose(display, r, P_sRGB, 128,
2739 back_r, output_encoding),
2740 png_colormap_compose(display, g, P_sRGB, 128,
2741 back_g, output_encoding),
2742 png_colormap_compose(display, b, P_sRGB, 128,
2743 back_b, output_encoding),
2744 0/*unused*/, output_encoding);
2745 }
2746 }
2747
2748 expand_tRNS = 1;
2749 output_processing = PNG_CMAP_RGB_ALPHA;
2750 }
2751
2752 else /* background color is in the standard color-map */
2753 {
2754 png_color_16 c;
2755
2756 c.index = 0; /*unused*/
2757 c.red = (png_uint_16)back_r;
2758 c.gray = c.green = (png_uint_16)back_g;
2759 c.blue = (png_uint_16)back_b;
2760
2761 png_set_background_fixed(png_ptr, &c,
2762 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2763 0/*gamma: not used*/);
2764
2765 output_processing = PNG_CMAP_RGB;
2766 }
2767 }
2768 }
2769
2770 else /* no alpha or transparency in the input */
2771 {
2772 /* Alpha in the output is irrelevant, simply map the opaque input
2773 * pixels to the 6x6x6 color-map.
2774 */
2775 if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2776 png_error(png_ptr, "rgb color-map: too few entries");
2777
2778 cmap_entries = (unsigned int)make_rgb_colormap(display);
2779 output_processing = PNG_CMAP_RGB;
2780 }
2781 }
2782 break;
2783
2784 case PNG_COLOR_TYPE_PALETTE:
2785 /* It's already got a color-map. It may be necessary to eliminate the
2786 * tRNS entries though.
2787 */
2788 {
2789 unsigned int num_trans = png_ptr->num_trans;
2790 png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2791 png_const_colorp colormap = png_ptr->palette;
2792 const int do_background = trans != NULL &&
2793 (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2794 unsigned int i;
2795
2796 /* Just in case: */
2797 if (trans == NULL)
2798 num_trans = 0;
2799
2800 output_processing = PNG_CMAP_NONE;
2801 data_encoding = P_FILE; /* Don't change from color-map indices */
2802 cmap_entries = (unsigned int)png_ptr->num_palette;
2803 if (cmap_entries > 256)
2804 cmap_entries = 256;
2805
2806 if (cmap_entries > (unsigned int)image->colormap_entries)
2807 png_error(png_ptr, "palette color-map: too few entries");
2808
2809 for (i=0; i < cmap_entries; ++i)
2810 {
2811 if (do_background != 0 && i < num_trans && trans[i] < 255)
2812 {
2813 if (trans[i] == 0)
2814 png_create_colormap_entry(display, i, back_r, back_g,
2815 back_b, 0, output_encoding);
2816
2817 else
2818 {
2819 /* Must compose the PNG file color in the color-map entry
2820 * on the sRGB color in 'back'.
2821 */
2822 png_create_colormap_entry(display, i,
2823 png_colormap_compose(display, colormap[i].red,
2824 P_FILE, trans[i], back_r, output_encoding),
2825 png_colormap_compose(display, colormap[i].green,
2826 P_FILE, trans[i], back_g, output_encoding),
2827 png_colormap_compose(display, colormap[i].blue,
2828 P_FILE, trans[i], back_b, output_encoding),
2829 output_encoding == P_LINEAR ? trans[i] * 257U :
2830 trans[i],
2831 output_encoding);
2832 }
2833 }
2834
2835 else
2836 png_create_colormap_entry(display, i, colormap[i].red,
2837 colormap[i].green, colormap[i].blue,
2838 i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2839 }
2840
2841 /* The PNG data may have indices packed in fewer than 8 bits, it
2842 * must be expanded if so.
2843 */
2844 if (png_ptr->bit_depth < 8)
2845 png_set_packing(png_ptr);
2846 }
2847 break;
2848
2849 default:
2850 png_error(png_ptr, "invalid PNG color type");
2851 /*NOT REACHED*/
2852 }
2853
2854 /* Now deal with the output processing */
2855 if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2856 (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2857 png_set_tRNS_to_alpha(png_ptr);
2858
2859 switch (data_encoding)
2860 {
2861 case P_sRGB:
2862 /* Change to 8-bit sRGB */
2863 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2864 /* FALL THROUGH */
2865
2866 case P_FILE:
2867 if (png_ptr->bit_depth > 8)
2868 png_set_scale_16(png_ptr);
2869 break;
2870
2871 #ifdef __GNUC__
2872 default:
2873 png_error(png_ptr, "bad data option (internal error)");
2874 #endif
2875 }
2876
2877 if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2878 png_error(png_ptr, "color map overflow (BAD internal error)");
2879
2880 image->colormap_entries = cmap_entries;
2881
2882 /* Double check using the recorded background index */
2883 switch (output_processing)
2884 {
2885 case PNG_CMAP_NONE:
2886 if (background_index != PNG_CMAP_NONE_BACKGROUND)
2887 goto bad_background;
2888 break;
2889
2890 case PNG_CMAP_GA:
2891 if (background_index != PNG_CMAP_GA_BACKGROUND)
2892 goto bad_background;
2893 break;
2894
2895 case PNG_CMAP_TRANS:
2896 if (background_index >= cmap_entries ||
2897 background_index != PNG_CMAP_TRANS_BACKGROUND)
2898 goto bad_background;
2899 break;
2900
2901 case PNG_CMAP_RGB:
2902 if (background_index != PNG_CMAP_RGB_BACKGROUND)
2903 goto bad_background;
2904 break;
2905
2906 case PNG_CMAP_RGB_ALPHA:
2907 if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2908 goto bad_background;
2909 break;
2910
2911 default:
2912 png_error(png_ptr, "bad processing option (internal error)");
2913
2914 bad_background:
2915 png_error(png_ptr, "bad background index (internal error)");
2916 }
2917
2918 display->colormap_processing = (int)output_processing;
2919
2920 return 1/*ok*/;
2921 }
2922
2923 /* The final part of the color-map read called from png_image_finish_read. */
2924 static int
2925 png_image_read_and_map(png_voidp argument)
2926 {
2927 png_image_read_control *display = png_voidcast(png_image_read_control*,
2928 argument);
2929 png_imagep image = display->image;
2930 png_structrp png_ptr = image->opaque->png_ptr;
2931 int passes;
2932
2933 /* Called when the libpng data must be transformed into the color-mapped
2934 * form. There is a local row buffer in display->local and this routine must
2935 * do the interlace handling.
2936 */
2937 switch (png_ptr->interlaced)
2938 {
2939 case PNG_INTERLACE_NONE:
2940 passes = 1;
2941 break;
2942
2943 case PNG_INTERLACE_ADAM7:
2944 passes = PNG_INTERLACE_ADAM7_PASSES;
2945 break;
2946
2947 default:
2948 png_error(png_ptr, "unknown interlace type");
2949 }
2950
2951 {
2952 png_uint_32 height = image->height;
2953 png_uint_32 width = image->width;
2954 int proc = display->colormap_processing;
2955 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
2956 ptrdiff_t step_row = display->row_bytes;
2957 int pass;
2958
2959 for (pass = 0; pass < passes; ++pass)
2960 {
2961 unsigned int startx, stepx, stepy;
2962 png_uint_32 y;
2963
2964 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2965 {
2966 /* The row may be empty for a short image: */
2967 if (PNG_PASS_COLS(width, pass) == 0)
2968 continue;
2969
2970 startx = PNG_PASS_START_COL(pass);
2971 stepx = PNG_PASS_COL_OFFSET(pass);
2972 y = PNG_PASS_START_ROW(pass);
2973 stepy = PNG_PASS_ROW_OFFSET(pass);
2974 }
2975
2976 else
2977 {
2978 y = 0;
2979 startx = 0;
2980 stepx = stepy = 1;
2981 }
2982
2983 for (; y<height; y += stepy)
2984 {
2985 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
2986 png_bytep outrow = first_row + y * step_row;
2987 png_const_bytep end_row = outrow + width;
2988
2989 /* Read read the libpng data into the temporary buffer. */
2990 png_read_row(png_ptr, inrow, NULL);
2991
2992 /* Now process the row according to the processing option, note
2993 * that the caller verifies that the format of the libpng output
2994 * data is as required.
2995 */
2996 outrow += startx;
2997 switch (proc)
2998 {
2999 case PNG_CMAP_GA:
3000 for (; outrow < end_row; outrow += stepx)
3001 {
3002 /* The data is always in the PNG order */
3003 unsigned int gray = *inrow++;
3004 unsigned int alpha = *inrow++;
3005 unsigned int entry;
3006
3007 /* NOTE: this code is copied as a comment in
3008 * make_ga_colormap above. Please update the
3009 * comment if you change this code!
3010 */
3011 if (alpha > 229) /* opaque */
3012 {
3013 entry = (231 * gray + 128) >> 8;
3014 }
3015 else if (alpha < 26) /* transparent */
3016 {
3017 entry = 231;
3018 }
3019 else /* partially opaque */
3020 {
3021 entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3022 }
3023
3024 *outrow = (png_byte)entry;
3025 }
3026 break;
3027
3028 case PNG_CMAP_TRANS:
3029 for (; outrow < end_row; outrow += stepx)
3030 {
3031 png_byte gray = *inrow++;
3032 png_byte alpha = *inrow++;
3033
3034 if (alpha == 0)
3035 *outrow = PNG_CMAP_TRANS_BACKGROUND;
3036
3037 else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3038 *outrow = gray;
3039
3040 else
3041 *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3042 }
3043 break;
3044
3045 case PNG_CMAP_RGB:
3046 for (; outrow < end_row; outrow += stepx)
3047 {
3048 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3049 inrow += 3;
3050 }
3051 break;
3052
3053 case PNG_CMAP_RGB_ALPHA:
3054 for (; outrow < end_row; outrow += stepx)
3055 {
3056 unsigned int alpha = inrow[3];
3057
3058 /* Because the alpha entries only hold alpha==0.5 values
3059 * split the processing at alpha==0.25 (64) and 0.75
3060 * (196).
3061 */
3062
3063 if (alpha >= 196)
3064 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3065 inrow[2]);
3066
3067 else if (alpha < 64)
3068 *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3069
3070 else
3071 {
3072 /* Likewise there are three entries for each of r, g
3073 * and b. We could select the entry by popcount on
3074 * the top two bits on those architectures that
3075 * support it, this is what the code below does,
3076 * crudely.
3077 */
3078 unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3079
3080 /* Here are how the values map:
3081 *
3082 * 0x00 .. 0x3f -> 0
3083 * 0x40 .. 0xbf -> 1
3084 * 0xc0 .. 0xff -> 2
3085 *
3086 * So, as above with the explicit alpha checks, the
3087 * breakpoints are at 64 and 196.
3088 */
3089 if (inrow[0] & 0x80) back_i += 9; /* red */
3090 if (inrow[0] & 0x40) back_i += 9;
3091 if (inrow[0] & 0x80) back_i += 3; /* green */
3092 if (inrow[0] & 0x40) back_i += 3;
3093 if (inrow[0] & 0x80) back_i += 1; /* blue */
3094 if (inrow[0] & 0x40) back_i += 1;
3095
3096 *outrow = (png_byte)back_i;
3097 }
3098
3099 inrow += 4;
3100 }
3101 break;
3102
3103 default:
3104 break;
3105 }
3106 }
3107 }
3108 }
3109
3110 return 1;
3111 }
3112
3113 static int
3114 png_image_read_colormapped(png_voidp argument)
3115 {
3116 png_image_read_control *display = png_voidcast(png_image_read_control*,
3117 argument);
3118 png_imagep image = display->image;
3119 png_controlp control = image->opaque;
3120 png_structrp png_ptr = control->png_ptr;
3121 png_inforp info_ptr = control->info_ptr;
3122
3123 int passes = 0; /* As a flag */
3124
3125 PNG_SKIP_CHUNKS(png_ptr);
3126
3127 /* Update the 'info' structure and make sure the result is as required; first
3128 * make sure to turn on the interlace handling if it will be required
3129 * (because it can't be turned on *after* the call to png_read_update_info!)
3130 */
3131 if (display->colormap_processing == PNG_CMAP_NONE)
3132 passes = png_set_interlace_handling(png_ptr);
3133
3134 png_read_update_info(png_ptr, info_ptr);
3135
3136 /* The expected output can be deduced from the colormap_processing option. */
3137 switch (display->colormap_processing)
3138 {
3139 case PNG_CMAP_NONE:
3140 /* Output must be one channel and one byte per pixel, the output
3141 * encoding can be anything.
3142 */
3143 if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3144 info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3145 info_ptr->bit_depth == 8)
3146 break;
3147
3148 goto bad_output;
3149
3150 case PNG_CMAP_TRANS:
3151 case PNG_CMAP_GA:
3152 /* Output must be two channels and the 'G' one must be sRGB, the latter
3153 * can be checked with an exact number because it should have been set
3154 * to this number above!
3155 */
3156 if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3157 info_ptr->bit_depth == 8 &&
3158 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3159 image->colormap_entries == 256)
3160 break;
3161
3162 goto bad_output;
3163
3164 case PNG_CMAP_RGB:
3165 /* Output must be 8-bit sRGB encoded RGB */
3166 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3167 info_ptr->bit_depth == 8 &&
3168 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3169 image->colormap_entries == 216)
3170 break;
3171
3172 goto bad_output;
3173
3174 case PNG_CMAP_RGB_ALPHA:
3175 /* Output must be 8-bit sRGB encoded RGBA */
3176 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3177 info_ptr->bit_depth == 8 &&
3178 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3179 image->colormap_entries == 244 /* 216 + 1 + 27 */)
3180 break;
3181
3182 /* goto bad_output; */
3183 /* FALL THROUGH */
3184
3185 default:
3186 bad_output:
3187 png_error(png_ptr, "bad color-map processing (internal error)");
3188 }
3189
3190 /* Now read the rows. Do this here if it is possible to read directly into
3191 * the output buffer, otherwise allocate a local row buffer of the maximum
3192 * size libpng requires and call the relevant processing routine safely.
3193 */
3194 {
3195 png_voidp first_row = display->buffer;
3196 ptrdiff_t row_bytes = display->row_stride;
3197
3198 /* The following expression is designed to work correctly whether it gives
3199 * a signed or an unsigned result.
3200 */
3201 if (row_bytes < 0)
3202 {
3203 char *ptr = png_voidcast(char*, first_row);
3204 ptr += (image->height-1) * (-row_bytes);
3205 first_row = png_voidcast(png_voidp, ptr);
3206 }
3207
3208 display->first_row = first_row;
3209 display->row_bytes = row_bytes;
3210 }
3211
3212 if (passes == 0)
3213 {
3214 int result;
3215 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3216
3217 display->local_row = row;
3218 result = png_safe_execute(image, png_image_read_and_map, display);
3219 display->local_row = NULL;
3220 png_free(png_ptr, row);
3221
3222 return result;
3223 }
3224
3225 else
3226 {
3227 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3228
3229 while (--passes >= 0)
3230 {
3231 png_uint_32 y = image->height;
3232 png_bytep row = png_voidcast(png_bytep, display->first_row);
3233
3234 for (; y > 0; --y)
3235 {
3236 png_read_row(png_ptr, row, NULL);
3237 row += row_bytes;
3238 }
3239 }
3240
3241 return 1;
3242 }
3243 }
3244
3245 /* Just the row reading part of png_image_read. */