1 
2 /* pngread.c - read a PNG file
3  *
4  * Last changed in libpng 1.6.9 [February 6, 2014]
5  * Copyright (c) 1998-2014 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 /* PNG_USER_MEM_SUPPORTED */
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_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
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
png_read_info(png_structrp png_ptr,png_inforp info_ptr)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))
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))
121             png_chunk_error(png_ptr, "Missing PLTE before IDAT");
122 
123          else if (png_ptr->mode & PNG_AFTER_IDAT)
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)
130          png_ptr->mode |= PNG_AFTER_IDAT;
131 
132       /* This should be a binary subdivision search or a hash for
133        * matching the chunk name rather than a linear search.
134        */
135       if (chunk_name == png_IHDR)
136          png_handle_IHDR(png_ptr, info_ptr, length);
137 
138       else if (chunk_name == png_IEND)
139          png_handle_IEND(png_ptr, info_ptr, length);
140 
141 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
142       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
143       {
144          png_handle_unknown(png_ptr, info_ptr, length, keep);
145 
146          if (chunk_name == png_PLTE)
147             png_ptr->mode |= PNG_HAVE_PLTE;
148 
149          else if (chunk_name == png_IDAT)
150          {
151             png_ptr->idat_size = 0; /* It has been consumed */
152             break;
153          }
154       }
155 #endif
156       else if (chunk_name == png_PLTE)
157          png_handle_PLTE(png_ptr, info_ptr, length);
158 
159       else if (chunk_name == png_IDAT)
160       {
161          png_ptr->idat_size = length;
162          break;
163       }
164 
165 #ifdef PNG_READ_bKGD_SUPPORTED
166       else if (chunk_name == png_bKGD)
167          png_handle_bKGD(png_ptr, info_ptr, length);
168 #endif
169 
170 #ifdef PNG_READ_cHRM_SUPPORTED
171       else if (chunk_name == png_cHRM)
172          png_handle_cHRM(png_ptr, info_ptr, length);
173 #endif
174 
175 #ifdef PNG_READ_gAMA_SUPPORTED
176       else if (chunk_name == png_gAMA)
177          png_handle_gAMA(png_ptr, info_ptr, length);
178 #endif
179 
180 #ifdef PNG_READ_hIST_SUPPORTED
181       else if (chunk_name == png_hIST)
182          png_handle_hIST(png_ptr, info_ptr, length);
183 #endif
184 
185 #ifdef PNG_READ_oFFs_SUPPORTED
186       else if (chunk_name == png_oFFs)
187          png_handle_oFFs(png_ptr, info_ptr, length);
188 #endif
189 
190 #ifdef PNG_READ_pCAL_SUPPORTED
191       else if (chunk_name == png_pCAL)
192          png_handle_pCAL(png_ptr, info_ptr, length);
193 #endif
194 
195 #ifdef PNG_READ_sCAL_SUPPORTED
196       else if (chunk_name == png_sCAL)
197          png_handle_sCAL(png_ptr, info_ptr, length);
198 #endif
199 
200 #ifdef PNG_READ_pHYs_SUPPORTED
201       else if (chunk_name == png_pHYs)
202          png_handle_pHYs(png_ptr, info_ptr, length);
203 #endif
204 
205 #ifdef PNG_READ_sBIT_SUPPORTED
206       else if (chunk_name == png_sBIT)
207          png_handle_sBIT(png_ptr, info_ptr, length);
208 #endif
209 
210 #ifdef PNG_READ_sRGB_SUPPORTED
211       else if (chunk_name == png_sRGB)
212          png_handle_sRGB(png_ptr, info_ptr, length);
213 #endif
214 
215 #ifdef PNG_READ_iCCP_SUPPORTED
216       else if (chunk_name == png_iCCP)
217          png_handle_iCCP(png_ptr, info_ptr, length);
218 #endif
219 
220 #ifdef PNG_READ_sPLT_SUPPORTED
221       else if (chunk_name == png_sPLT)
222          png_handle_sPLT(png_ptr, info_ptr, length);
223 #endif
224 
225 #ifdef PNG_READ_tEXt_SUPPORTED
226       else if (chunk_name == png_tEXt)
227          png_handle_tEXt(png_ptr, info_ptr, length);
228 #endif
229 
230 #ifdef PNG_READ_tIME_SUPPORTED
231       else if (chunk_name == png_tIME)
232          png_handle_tIME(png_ptr, info_ptr, length);
233 #endif
234 
235 #ifdef PNG_READ_tRNS_SUPPORTED
236       else if (chunk_name == png_tRNS)
237          png_handle_tRNS(png_ptr, info_ptr, length);
238 #endif
239 
240 #ifdef PNG_READ_zTXt_SUPPORTED
241       else if (chunk_name == png_zTXt)
242          png_handle_zTXt(png_ptr, info_ptr, length);
243 #endif
244 
245 #ifdef PNG_READ_iTXt_SUPPORTED
246       else if (chunk_name == png_iTXt)
247          png_handle_iTXt(png_ptr, info_ptr, length);
248 #endif
249 
250       else
251          png_handle_unknown(png_ptr, info_ptr, length,
252             PNG_HANDLE_CHUNK_AS_DEFAULT);
253    }
254 }
255 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
256 
257 /* Optional call to update the users info_ptr structure */
258 void PNGAPI
png_read_update_info(png_structrp png_ptr,png_inforp info_ptr)259 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
260 {
261    png_debug(1, "in png_read_update_info");
262 
263    if (png_ptr != NULL)
264    {
265       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
266       {
267          png_read_start_row(png_ptr);
268 
269 #        ifdef PNG_READ_TRANSFORMS_SUPPORTED
270             png_read_transform_info(png_ptr, info_ptr);
271 #        else
272             PNG_UNUSED(info_ptr)
273 #        endif
274       }
275 
276       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
277       else
278          png_app_error(png_ptr,
279             "png_read_update_info/png_start_read_image: duplicate call");
280    }
281 }
282 
283 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
284 /* Initialize palette, background, etc, after transformations
285  * are set, but before any reading takes place.  This allows
286  * the user to obtain a gamma-corrected palette, for example.
287  * If the user doesn't call this, we will do it ourselves.
288  */
289 void PNGAPI
png_start_read_image(png_structrp png_ptr)290 png_start_read_image(png_structrp png_ptr)
291 {
292    png_debug(1, "in png_start_read_image");
293 
294    if (png_ptr != NULL)
295    {
296       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
297          png_read_start_row(png_ptr);
298 
299       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
300       else
301          png_app_error(png_ptr,
302             "png_start_read_image/png_read_update_info: duplicate call");
303    }
304 }
305 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
306 
307 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
308 #ifdef PNG_MNG_FEATURES_SUPPORTED
309 /* Undoes intrapixel differencing,
310  * NOTE: this is apparently only supported in the 'sequential' reader.
311  */
312 static void
png_do_read_intrapixel(png_row_infop row_info,png_bytep row)313 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
314 {
315    png_debug(1, "in png_do_read_intrapixel");
316 
317    if (
318        (row_info->color_type & PNG_COLOR_MASK_COLOR))
319    {
320       int bytes_per_pixel;
321       png_uint_32 row_width = row_info->width;
322 
323       if (row_info->bit_depth == 8)
324       {
325          png_bytep rp;
326          png_uint_32 i;
327 
328          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
329             bytes_per_pixel = 3;
330 
331          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
332             bytes_per_pixel = 4;
333 
334          else
335             return;
336 
337          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
338          {
339             *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
340             *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
341          }
342       }
343       else if (row_info->bit_depth == 16)
344       {
345          png_bytep rp;
346          png_uint_32 i;
347 
348          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
349             bytes_per_pixel = 6;
350 
351          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
352             bytes_per_pixel = 8;
353 
354          else
355             return;
356 
357          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
358          {
359             png_uint_32 s0   = (*(rp    ) << 8) | *(rp + 1);
360             png_uint_32 s1   = (*(rp + 2) << 8) | *(rp + 3);
361             png_uint_32 s2   = (*(rp + 4) << 8) | *(rp + 5);
362             png_uint_32 red  = (s0 + s1 + 65536) & 0xffff;
363             png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
364             *(rp    ) = (png_byte)((red >> 8) & 0xff);
365             *(rp + 1) = (png_byte)(red & 0xff);
366             *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
367             *(rp + 5) = (png_byte)(blue & 0xff);
368          }
369       }
370    }
371 }
372 #endif /* PNG_MNG_FEATURES_SUPPORTED */
373 
374 void PNGAPI
png_read_row(png_structrp png_ptr,png_bytep row,png_bytep dsp_row)375 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
376 {
377    png_row_info row_info;
378 
379    if (png_ptr == NULL)
380       return;
381 
382    png_debug2(1, "in png_read_row (row %lu, pass %d)",
383        (unsigned long)png_ptr->row_number, png_ptr->pass);
384 
385    /* png_read_start_row sets the information (in particular iwidth) for this
386     * interlace pass.
387     */
388    if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
389       png_read_start_row(png_ptr);
390 
391    /* 1.5.6: row_info moved out of png_struct to a local here. */
392    row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
393    row_info.color_type = png_ptr->color_type;
394    row_info.bit_depth = png_ptr->bit_depth;
395    row_info.channels = png_ptr->channels;
396    row_info.pixel_depth = png_ptr->pixel_depth;
397    row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
398 
399    if (png_ptr->row_number == 0 && png_ptr->pass == 0)
400    {
401    /* Check for transforms that have been set but were defined out */
402 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
403    if (png_ptr->transformations & PNG_INVERT_MONO)
404       png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
405 #endif
406 
407 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
408    if (png_ptr->transformations & PNG_FILLER)
409       png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
410 #endif
411 
412 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
413     !defined(PNG_READ_PACKSWAP_SUPPORTED)
414    if (png_ptr->transformations & PNG_PACKSWAP)
415       png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
416 #endif
417 
418 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
419    if (png_ptr->transformations & PNG_PACK)
420       png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
421 #endif
422 
423 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
424    if (png_ptr->transformations & PNG_SHIFT)
425       png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
426 #endif
427 
428 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
429    if (png_ptr->transformations & PNG_BGR)
430       png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
431 #endif
432 
433 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
434    if (png_ptr->transformations & PNG_SWAP_BYTES)
435       png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
436 #endif
437    }
438 
439 #ifdef PNG_READ_INTERLACING_SUPPORTED
440    /* If interlaced and we do not need a new row, combine row and return.
441     * Notice that the pixels we have from previous rows have been transformed
442     * already; we can only combine like with like (transformed or
443     * untransformed) and, because of the libpng API for interlaced images, this
444     * means we must transform before de-interlacing.
445     */
446    if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
447    {
448       switch (png_ptr->pass)
449       {
450          case 0:
451             if (png_ptr->row_number & 0x07)
452             {
453                if (dsp_row != NULL)
454                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
455                png_read_finish_row(png_ptr);
456                return;
457             }
458             break;
459 
460          case 1:
461             if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
462             {
463                if (dsp_row != NULL)
464                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
465 
466                png_read_finish_row(png_ptr);
467                return;
468             }
469             break;
470 
471          case 2:
472             if ((png_ptr->row_number & 0x07) != 4)
473             {
474                if (dsp_row != NULL && (png_ptr->row_number & 4))
475                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
476 
477                png_read_finish_row(png_ptr);
478                return;
479             }
480             break;
481 
482          case 3:
483             if ((png_ptr->row_number & 3) || png_ptr->width < 3)
484             {
485                if (dsp_row != NULL)
486                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
487 
488                png_read_finish_row(png_ptr);
489                return;
490             }
491             break;
492 
493          case 4:
494             if ((png_ptr->row_number & 3) != 2)
495             {
496                if (dsp_row != NULL && (png_ptr->row_number & 2))
497                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
498 
499                png_read_finish_row(png_ptr);
500                return;
501             }
502             break;
503 
504          case 5:
505             if ((png_ptr->row_number & 1) || png_ptr->width < 2)
506             {
507                if (dsp_row != NULL)
508                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
509 
510                png_read_finish_row(png_ptr);
511                return;
512             }
513             break;
514 
515          default:
516          case 6:
517             if (!(png_ptr->row_number & 1))
518             {
519                png_read_finish_row(png_ptr);
520                return;
521             }
522             break;
523       }
524    }
525 #endif
526 
527    if (!(png_ptr->mode & PNG_HAVE_IDAT))
528       png_error(png_ptr, "Invalid attempt to read row data");
529 
530    /* Fill the row with IDAT data: */
531    png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
532 
533    if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
534    {
535       if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
536          png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
537             png_ptr->prev_row + 1, png_ptr->row_buf[0]);
538       else
539          png_error(png_ptr, "bad adaptive filter value");
540    }
541 
542    /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
543     * 1.5.6, while the buffer really is this big in current versions of libpng
544     * it may not be in the future, so this was changed just to copy the
545     * interlaced count:
546     */
547    memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
548 
549 #ifdef PNG_MNG_FEATURES_SUPPORTED
550    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
551        (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
552    {
553       /* Intrapixel differencing */
554       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
555    }
556 #endif
557 
558 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
559    if (png_ptr->transformations)
560       png_do_read_transformations(png_ptr, &row_info);
561 #endif
562 
563    /* The transformed pixel depth should match the depth now in row_info. */
564    if (png_ptr->transformed_pixel_depth == 0)
565    {
566       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
567       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
568          png_error(png_ptr, "sequential row overflow");
569    }
570 
571    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
572       png_error(png_ptr, "internal sequential row size calculation error");
573 
574 #ifdef PNG_READ_INTERLACING_SUPPORTED
575    /* Blow up interlaced rows to full size */
576    if (png_ptr->interlaced &&
577       (png_ptr->transformations & PNG_INTERLACE))
578    {
579       if (png_ptr->pass < 6)
580          png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
581             png_ptr->transformations);
582 
583       if (dsp_row != NULL)
584          png_combine_row(png_ptr, dsp_row, 1/*display*/);
585 
586       if (row != NULL)
587          png_combine_row(png_ptr, row, 0/*row*/);
588    }
589 
590    else
591 #endif
592    {
593       if (row != NULL)
594          png_combine_row(png_ptr, row, -1/*ignored*/);
595 
596       if (dsp_row != NULL)
597          png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
598    }
599    png_read_finish_row(png_ptr);
600 
601    if (png_ptr->read_row_fn != NULL)
602       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
603 
604 }
605 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
606 
607 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
608 /* Read one or more rows of image data.  If the image is interlaced,
609  * and png_set_interlace_handling() has been called, the rows need to
610  * contain the contents of the rows from the previous pass.  If the
611  * image has alpha or transparency, and png_handle_alpha()[*] has been
612  * called, the rows contents must be initialized to the contents of the
613  * screen.
614  *
615  * "row" holds the actual image, and pixels are placed in it
616  * as they arrive.  If the image is displayed after each pass, it will
617  * appear to "sparkle" in.  "display_row" can be used to display a
618  * "chunky" progressive image, with finer detail added as it becomes
619  * available.  If you do not want this "chunky" display, you may pass
620  * NULL for display_row.  If you do not want the sparkle display, and
621  * you have not called png_handle_alpha(), you may pass NULL for rows.
622  * If you have called png_handle_alpha(), and the image has either an
623  * alpha channel or a transparency chunk, you must provide a buffer for
624  * rows.  In this case, you do not have to provide a display_row buffer
625  * also, but you may.  If the image is not interlaced, or if you have
626  * not called png_set_interlace_handling(), the display_row buffer will
627  * be ignored, so pass NULL to it.
628  *
629  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
630  */
631 
632 void PNGAPI
png_read_rows(png_structrp png_ptr,png_bytepp row,png_bytepp display_row,png_uint_32 num_rows)633 png_read_rows(png_structrp png_ptr, png_bytepp row,
634     png_bytepp display_row, png_uint_32 num_rows)
635 {
636    png_uint_32 i;
637    png_bytepp rp;
638    png_bytepp dp;
639 
640    png_debug(1, "in png_read_rows");
641 
642    if (png_ptr == NULL)
643       return;
644 
645    rp = row;
646    dp = display_row;
647    if (rp != NULL && dp != NULL)
648       for (i = 0; i < num_rows; i++)
649       {
650          png_bytep rptr = *rp++;
651          png_bytep dptr = *dp++;
652 
653          png_read_row(png_ptr, rptr, dptr);
654       }
655 
656    else if (rp != NULL)
657       for (i = 0; i < num_rows; i++)
658       {
659          png_bytep rptr = *rp;
660          png_read_row(png_ptr, rptr, NULL);
661          rp++;
662       }
663 
664    else if (dp != NULL)
665       for (i = 0; i < num_rows; i++)
666       {
667          png_bytep dptr = *dp;
668          png_read_row(png_ptr, NULL, dptr);
669          dp++;
670       }
671 }
672 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
673 
674 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
675 /* Read the entire image.  If the image has an alpha channel or a tRNS
676  * chunk, and you have called png_handle_alpha()[*], you will need to
677  * initialize the image to the current image that PNG will be overlaying.
678  * We set the num_rows again here, in case it was incorrectly set in
679  * png_read_start_row() by a call to png_read_update_info() or
680  * png_start_read_image() if png_set_interlace_handling() wasn't called
681  * prior to either of these functions like it should have been.  You can
682  * only call this function once.  If you desire to have an image for
683  * each pass of a interlaced image, use png_read_rows() instead.
684  *
685  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
686  */
687 void PNGAPI
png_read_image(png_structrp png_ptr,png_bytepp image)688 png_read_image(png_structrp png_ptr, png_bytepp image)
689 {
690    png_uint_32 i, image_height;
691    int pass, j;
692    png_bytepp rp;
693 
694    png_debug(1, "in png_read_image");
695 
696    if (png_ptr == NULL)
697       return;
698 
699 #ifdef PNG_READ_INTERLACING_SUPPORTED
700    if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
701    {
702       pass = png_set_interlace_handling(png_ptr);
703       /* And make sure transforms are initialized. */
704       png_start_read_image(png_ptr);
705    }
706    else
707    {
708       if (png_ptr->interlaced && !(png_ptr->transformations & PNG_INTERLACE))
709       {
710          /* Caller called png_start_read_image or png_read_update_info without
711           * first turning on the PNG_INTERLACE transform.  We can fix this here,
712           * but the caller should do it!
713           */
714          png_warning(png_ptr, "Interlace handling should be turned on when "
715             "using png_read_image");
716          /* Make sure this is set correctly */
717          png_ptr->num_rows = png_ptr->height;
718       }
719 
720       /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
721        * the above error case.
722        */
723       pass = png_set_interlace_handling(png_ptr);
724    }
725 #else
726    if (png_ptr->interlaced)
727       png_error(png_ptr,
728           "Cannot read interlaced image -- interlace handler disabled");
729 
730    pass = 1;
731 #endif
732 
733    image_height=png_ptr->height;
734 
735    for (j = 0; j < pass; j++)
736    {
737       rp = image;
738       for (i = 0; i < image_height; i++)
739       {
740          png_read_row(png_ptr, *rp, NULL);
741          rp++;
742       }
743    }
744 }
745 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
746 
747 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
748 /* Read the end of the PNG file.  Will not read past the end of the
749  * file, will verify the end is accurate, and will read any comments
750  * or time information at the end of the file, if info is not NULL.
751  */
752 void PNGAPI
png_read_end(png_structrp png_ptr,png_inforp info_ptr)753 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
754 {
755 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
756    int keep;
757 #endif
758 
759    png_debug(1, "in png_read_end");
760 
761    if (png_ptr == NULL)
762       return;
763 
764    /* If png_read_end is called in the middle of reading the rows there may
765     * still be pending IDAT data and an owned zstream.  Deal with this here.
766     */
767 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
768    if (!png_chunk_unknown_handling(png_ptr, png_IDAT))
769 #endif
770       png_read_finish_IDAT(png_ptr);
771 
772 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
773    /* Report invalid palette index; added at libng-1.5.10 */
774    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
775       png_ptr->num_palette_max > png_ptr->num_palette)
776      png_benign_error(png_ptr, "Read palette index exceeding num_palette");
777 #endif
778 
779    do
780    {
781       png_uint_32 length = png_read_chunk_header(png_ptr);
782       png_uint_32 chunk_name = png_ptr->chunk_name;
783 
784       if (chunk_name == png_IHDR)
785          png_handle_IHDR(png_ptr, info_ptr, length);
786 
787       else if (chunk_name == png_IEND)
788          png_handle_IEND(png_ptr, info_ptr, length);
789 
790 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
791       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
792       {
793          if (chunk_name == png_IDAT)
794          {
795             if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
796                png_benign_error(png_ptr, "Too many IDATs found");
797          }
798          png_handle_unknown(png_ptr, info_ptr, length, keep);
799          if (chunk_name == png_PLTE)
800             png_ptr->mode |= PNG_HAVE_PLTE;
801       }
802 #endif
803 
804       else if (chunk_name == png_IDAT)
805       {
806          /* Zero length IDATs are legal after the last IDAT has been
807           * read, but not after other chunks have been read.
808           */
809          if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
810             png_benign_error(png_ptr, "Too many IDATs found");
811 
812          png_crc_finish(png_ptr, length);
813       }
814       else if (chunk_name == png_PLTE)
815          png_handle_PLTE(png_ptr, info_ptr, length);
816 
817 #ifdef PNG_READ_bKGD_SUPPORTED
818       else if (chunk_name == png_bKGD)
819          png_handle_bKGD(png_ptr, info_ptr, length);
820 #endif
821 
822 #ifdef PNG_READ_cHRM_SUPPORTED
823       else if (chunk_name == png_cHRM)
824          png_handle_cHRM(png_ptr, info_ptr, length);
825 #endif
826 
827 #ifdef PNG_READ_gAMA_SUPPORTED
828       else if (chunk_name == png_gAMA)
829          png_handle_gAMA(png_ptr, info_ptr, length);
830 #endif
831 
832 #ifdef PNG_READ_hIST_SUPPORTED
833       else if (chunk_name == png_hIST)
834          png_handle_hIST(png_ptr, info_ptr, length);
835 #endif
836 
837 #ifdef PNG_READ_oFFs_SUPPORTED
838       else if (chunk_name == png_oFFs)
839          png_handle_oFFs(png_ptr, info_ptr, length);
840 #endif
841 
842 #ifdef PNG_READ_pCAL_SUPPORTED
843       else if (chunk_name == png_pCAL)
844          png_handle_pCAL(png_ptr, info_ptr, length);
845 #endif
846 
847 #ifdef PNG_READ_sCAL_SUPPORTED
848       else if (chunk_name == png_sCAL)
849          png_handle_sCAL(png_ptr, info_ptr, length);
850 #endif
851 
852 #ifdef PNG_READ_pHYs_SUPPORTED
853       else if (chunk_name == png_pHYs)
854          png_handle_pHYs(png_ptr, info_ptr, length);
855 #endif
856 
857 #ifdef PNG_READ_sBIT_SUPPORTED
858       else if (chunk_name == png_sBIT)
859          png_handle_sBIT(png_ptr, info_ptr, length);
860 #endif
861 
862 #ifdef PNG_READ_sRGB_SUPPORTED
863       else if (chunk_name == png_sRGB)
864          png_handle_sRGB(png_ptr, info_ptr, length);
865 #endif
866 
867 #ifdef PNG_READ_iCCP_SUPPORTED
868       else if (chunk_name == png_iCCP)
869          png_handle_iCCP(png_ptr, info_ptr, length);
870 #endif
871 
872 #ifdef PNG_READ_sPLT_SUPPORTED
873       else if (chunk_name == png_sPLT)
874          png_handle_sPLT(png_ptr, info_ptr, length);
875 #endif
876 
877 #ifdef PNG_READ_tEXt_SUPPORTED
878       else if (chunk_name == png_tEXt)
879          png_handle_tEXt(png_ptr, info_ptr, length);
880 #endif
881 
882 #ifdef PNG_READ_tIME_SUPPORTED
883       else if (chunk_name == png_tIME)
884          png_handle_tIME(png_ptr, info_ptr, length);
885 #endif
886 
887 #ifdef PNG_READ_tRNS_SUPPORTED
888       else if (chunk_name == png_tRNS)
889          png_handle_tRNS(png_ptr, info_ptr, length);
890 #endif
891 
892 #ifdef PNG_READ_zTXt_SUPPORTED
893       else if (chunk_name == png_zTXt)
894          png_handle_zTXt(png_ptr, info_ptr, length);
895 #endif
896 
897 #ifdef PNG_READ_iTXt_SUPPORTED
898       else if (chunk_name == png_iTXt)
899          png_handle_iTXt(png_ptr, info_ptr, length);
900 #endif
901 
902       else
903          png_handle_unknown(png_ptr, info_ptr, length,
904             PNG_HANDLE_CHUNK_AS_DEFAULT);
905    } while (!(png_ptr->mode & PNG_HAVE_IEND));
906 }
907 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
908 
909 /* Free all memory used in the read struct */
910 static void
png_read_destroy(png_structrp png_ptr)911 png_read_destroy(png_structrp png_ptr)
912 {
913    png_debug(1, "in png_read_destroy");
914 
915 #ifdef PNG_READ_GAMMA_SUPPORTED
916    png_destroy_gamma_table(png_ptr);
917 #endif
918 
919    png_free(png_ptr, png_ptr->big_row_buf);
920    png_free(png_ptr, png_ptr->big_prev_row);
921    png_free(png_ptr, png_ptr->read_buffer);
922 
923 #ifdef PNG_READ_QUANTIZE_SUPPORTED
924    png_free(png_ptr, png_ptr->palette_lookup);
925    png_free(png_ptr, png_ptr->quantize_index);
926 #endif
927 
928    if (png_ptr->free_me & PNG_FREE_PLTE)
929       png_zfree(png_ptr, png_ptr->palette);
930    png_ptr->free_me &= ~PNG_FREE_PLTE;
931 
932 #if defined(PNG_tRNS_SUPPORTED) || \
933     defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
934    if (png_ptr->free_me & PNG_FREE_TRNS)
935       png_free(png_ptr, png_ptr->trans_alpha);
936    png_ptr->free_me &= ~PNG_FREE_TRNS;
937 #endif
938 
939    inflateEnd(&png_ptr->zstream);
940 
941 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
942    png_free(png_ptr, png_ptr->save_buffer);
943 #endif
944 
945 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) &&\
946    defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
947    png_free(png_ptr, png_ptr->unknown_chunk.data);
948 #endif
949 
950 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
951    png_free(png_ptr, png_ptr->chunk_list);
952 #endif
953 
954    /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
955     * callbacks are still set at this point.  They are required to complete the
956     * destruction of the png_struct itself.
957     */
958 }
959 
960 /* Free all memory used by the read */
961 void PNGAPI
png_destroy_read_struct(png_structpp png_ptr_ptr,png_infopp info_ptr_ptr,png_infopp end_info_ptr_ptr)962 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
963     png_infopp end_info_ptr_ptr)
964 {
965    png_structrp png_ptr = NULL;
966 
967    png_debug(1, "in png_destroy_read_struct");
968 
969    if (png_ptr_ptr != NULL)
970       png_ptr = *png_ptr_ptr;
971 
972    if (png_ptr == NULL)
973       return;
974 
975    /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
976     * behavior.  Prior to 1.6.0 libpng did extra 'info' destruction in this API.
977     * The extra was, apparently, unnecessary yet this hides memory leak bugs.
978     */
979    png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
980    png_destroy_info_struct(png_ptr, info_ptr_ptr);
981 
982    *png_ptr_ptr = NULL;
983    png_read_destroy(png_ptr);
984    png_destroy_png_struct(png_ptr);
985 }
986 
987 void PNGAPI
png_set_read_status_fn(png_structrp png_ptr,png_read_status_ptr read_row_fn)988 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
989 {
990    if (png_ptr == NULL)
991       return;
992 
993    png_ptr->read_row_fn = read_row_fn;
994 }
995 
996 
997 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
998 #ifdef PNG_INFO_IMAGE_SUPPORTED
999 void PNGAPI
png_read_png(png_structrp png_ptr,png_inforp info_ptr,int transforms,voidp params)1000 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1001                            int transforms,
1002                            voidp params)
1003 {
1004    int row;
1005 
1006    if (png_ptr == NULL || info_ptr == NULL)
1007       return;
1008 
1009    /* png_read_info() gives us all of the information from the
1010     * PNG file before the first IDAT (image data chunk).
1011     */
1012    png_read_info(png_ptr, info_ptr);
1013    if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1014       png_error(png_ptr, "Image is too high to process with png_read_png()");
1015 
1016    /* -------------- image transformations start here ------------------- */
1017 
1018 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1019    /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1020     */
1021    if (transforms & PNG_TRANSFORM_SCALE_16)
1022    {
1023      /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1024       * did in earlier versions, while "scale_16" is now more accurate.
1025       */
1026       png_set_scale_16(png_ptr);
1027    }
1028 #endif
1029 
1030 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1031    /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1032     * latter by doing SCALE first.  This is ok and allows apps not to check for
1033     * which is supported to get the right answer.
1034     */
1035    if (transforms & PNG_TRANSFORM_STRIP_16)
1036       png_set_strip_16(png_ptr);
1037 #endif
1038 
1039 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1040    /* Strip alpha bytes from the input data without combining with
1041     * the background (not recommended).
1042     */
1043    if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
1044       png_set_strip_alpha(png_ptr);
1045 #endif
1046 
1047 #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
1048    /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1049     * byte into separate bytes (useful for paletted and grayscale images).
1050     */
1051    if (transforms & PNG_TRANSFORM_PACKING)
1052       png_set_packing(png_ptr);
1053 #endif
1054 
1055 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1056    /* Change the order of packed pixels to least significant bit first
1057     * (not useful if you are using png_set_packing).
1058     */
1059    if (transforms & PNG_TRANSFORM_PACKSWAP)
1060       png_set_packswap(png_ptr);
1061 #endif
1062 
1063 #ifdef PNG_READ_EXPAND_SUPPORTED
1064    /* Expand paletted colors into true RGB triplets
1065     * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1066     * Expand paletted or RGB images with transparency to full alpha
1067     * channels so the data will be available as RGBA quartets.
1068     */
1069    if (transforms & PNG_TRANSFORM_EXPAND)
1070       if ((png_ptr->bit_depth < 8) ||
1071           (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
1072           (info_ptr->valid & PNG_INFO_tRNS))
1073          png_set_expand(png_ptr);
1074 #endif
1075 
1076    /* We don't handle background color or gamma transformation or quantizing.
1077     */
1078 
1079 #ifdef PNG_READ_INVERT_SUPPORTED
1080    /* Invert monochrome files to have 0 as white and 1 as black
1081     */
1082    if (transforms & PNG_TRANSFORM_INVERT_MONO)
1083       png_set_invert_mono(png_ptr);
1084 #endif
1085 
1086 #ifdef PNG_READ_SHIFT_SUPPORTED
1087    /* If you want to shift the pixel values from the range [0,255] or
1088     * [0,65535] to the original [0,7] or [0,31], or whatever range the
1089     * colors were originally in:
1090     */
1091    if ((transforms & PNG_TRANSFORM_SHIFT) && (info_ptr->valid & PNG_INFO_sBIT))
1092       png_set_shift(png_ptr, &info_ptr->sig_bit);
1093 #endif
1094 
1095 #ifdef PNG_READ_BGR_SUPPORTED
1096    /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1097    if (transforms & PNG_TRANSFORM_BGR)
1098       png_set_bgr(png_ptr);
1099 #endif
1100 
1101 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1102    /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1103    if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
1104       png_set_swap_alpha(png_ptr);
1105 #endif
1106 
1107 #ifdef PNG_READ_SWAP_SUPPORTED
1108    /* Swap bytes of 16-bit files to least significant byte first */
1109    if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
1110       png_set_swap(png_ptr);
1111 #endif
1112 
1113 /* Added at libpng-1.2.41 */
1114 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1115    /* Invert the alpha channel from opacity to transparency */
1116    if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
1117       png_set_invert_alpha(png_ptr);
1118 #endif
1119 
1120 /* Added at libpng-1.2.41 */
1121 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1122    /* Expand grayscale image to RGB */
1123    if (transforms & PNG_TRANSFORM_GRAY_TO_RGB)
1124       png_set_gray_to_rgb(png_ptr);
1125 #endif
1126 
1127 /* Added at libpng-1.5.4 */
1128 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1129    if (transforms & PNG_TRANSFORM_EXPAND_16)
1130       png_set_expand_16(png_ptr);
1131 #endif
1132 
1133    /* We don't handle adding filler bytes */
1134 
1135    /* We use png_read_image and rely on that for interlace handling, but we also
1136     * call png_read_update_info therefore must turn on interlace handling now:
1137     */
1138    (void)png_set_interlace_handling(png_ptr);
1139 
1140    /* Optional call to gamma correct and add the background to the palette
1141     * and update info structure.  REQUIRED if you are expecting libpng to
1142     * update the palette for you (i.e., you selected such a transform above).
1143     */
1144    png_read_update_info(png_ptr, info_ptr);
1145 
1146    /* -------------- image transformations end here ------------------- */
1147 
1148    png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1149    if (info_ptr->row_pointers == NULL)
1150    {
1151       png_uint_32 iptr;
1152 
1153       info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
1154           info_ptr->height * (sizeof (png_bytep)));
1155       for (iptr=0; iptr<info_ptr->height; iptr++)
1156          info_ptr->row_pointers[iptr] = NULL;
1157 
1158       info_ptr->free_me |= PNG_FREE_ROWS;
1159 
1160       for (row = 0; row < (int)info_ptr->height; row++)
1161          info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
1162             png_get_rowbytes(png_ptr, info_ptr));
1163    }
1164 
1165    png_read_image(png_ptr, info_ptr->row_pointers);
1166    info_ptr->valid |= PNG_INFO_IDAT;
1167 
1168    /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1169    png_read_end(png_ptr, info_ptr);
1170 
1171    PNG_UNUSED(transforms)   /* Quiet compiler warnings */
1172    PNG_UNUSED(params)
1173 
1174 }
1175 #endif /* PNG_INFO_IMAGE_SUPPORTED */
1176 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
1177 
1178 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1179 /* SIMPLIFIED READ
1180  *
1181  * This code currently relies on the sequential reader, though it could easily
1182  * be made to work with the progressive one.
1183  */
1184 /* Arguments to png_image_finish_read: */
1185 
1186 /* Encoding of PNG data (used by the color-map code) */
1187 #  define P_NOTSET  0 /* File encoding not yet known */
1188 #  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
1189 #  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1190 #  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
1191 #  define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1192 
1193 /* Color-map processing: after libpng has run on the PNG image further
1194  * processing may be needed to conver the data to color-map indicies.
1195  */
1196 #define PNG_CMAP_NONE      0
1197 #define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
1198 #define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
1199 #define PNG_CMAP_RGB       3 /* Process RGB data */
1200 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1201 
1202 /* The following document where the background is for each processing case. */
1203 #define PNG_CMAP_NONE_BACKGROUND      256
1204 #define PNG_CMAP_GA_BACKGROUND        231
1205 #define PNG_CMAP_TRANS_BACKGROUND     254
1206 #define PNG_CMAP_RGB_BACKGROUND       256
1207 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1208 
1209 typedef struct
1210 {
1211    /* Arguments: */
1212    png_imagep image;
1213    png_voidp  buffer;
1214    png_int_32 row_stride;
1215    png_voidp  colormap;
1216    png_const_colorp background;
1217    /* Local variables: */
1218    png_voidp       local_row;
1219    png_voidp       first_row;
1220    ptrdiff_t       row_bytes;           /* step between rows */
1221    int             file_encoding;       /* E_ values above */
1222    png_fixed_point gamma_to_linear;     /* For P_FILE, reciprocal of gamma */
1223    int             colormap_processing; /* PNG_CMAP_ values above */
1224 } png_image_read_control;
1225 
1226 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1227  * called, so setting up the jmp_buf is not required.  This means that anything
1228  * called from here must *not* call png_malloc - it has to call png_malloc_warn
1229  * instead so that control is returned safely back to this routine.
1230  */
1231 static int
png_image_read_init(png_imagep image)1232 png_image_read_init(png_imagep image)
1233 {
1234    if (image->opaque == NULL)
1235    {
1236       png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1237           png_safe_error, png_safe_warning);
1238 
1239       /* And set the rest of the structure to NULL to ensure that the various
1240        * fields are consistent.
1241        */
1242       memset(image, 0, (sizeof *image));
1243       image->version = PNG_IMAGE_VERSION;
1244 
1245       if (png_ptr != NULL)
1246       {
1247          png_infop info_ptr = png_create_info_struct(png_ptr);
1248 
1249          if (info_ptr != NULL)
1250          {
1251             png_controlp control = png_voidcast(png_controlp,
1252                png_malloc_warn(png_ptr, (sizeof *control)));
1253 
1254             if (control != NULL)
1255             {
1256                memset(control, 0, (sizeof *control));
1257 
1258                control->png_ptr = png_ptr;
1259                control->info_ptr = info_ptr;
1260                control->for_write = 0;
1261 
1262                image->opaque = control;
1263                return 1;
1264             }
1265 
1266             /* Error clean up */
1267             png_destroy_info_struct(png_ptr, &info_ptr);
1268          }
1269 
1270          png_destroy_read_struct(&png_ptr, NULL, NULL);
1271       }
1272 
1273       return png_image_error(image, "png_image_read: out of memory");
1274    }
1275 
1276    return png_image_error(image, "png_image_read: opaque pointer not NULL");
1277 }
1278 
1279 /* Utility to find the base format of a PNG file from a png_struct. */
1280 static png_uint_32
png_image_format(png_structrp png_ptr)1281 png_image_format(png_structrp png_ptr)
1282 {
1283    png_uint_32 format = 0;
1284 
1285    if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
1286       format |= PNG_FORMAT_FLAG_COLOR;
1287 
1288    if (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)
1289       format |= PNG_FORMAT_FLAG_ALPHA;
1290 
1291    /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1292     * sets the png_struct fields; that's all we are interested in here.  The
1293     * precise interaction with an app call to png_set_tRNS and PNG file reading
1294     * is unclear.
1295     */
1296    else if (png_ptr->num_trans > 0)
1297       format |= PNG_FORMAT_FLAG_ALPHA;
1298 
1299    if (png_ptr->bit_depth == 16)
1300       format |= PNG_FORMAT_FLAG_LINEAR;
1301 
1302    if (png_ptr->color_type & PNG_COLOR_MASK_PALETTE)
1303       format |= PNG_FORMAT_FLAG_COLORMAP;
1304 
1305    return format;
1306 }
1307 
1308 /* Is the given gamma significantly different from sRGB?  The test is the same
1309  * one used in pngrtran.c when deciding whether to do gamma correction.  The
1310  * arithmetic optimizes the division by using the fact that the inverse of the
1311  * file sRGB gamma is 2.2
1312  */
1313 static int
png_gamma_not_sRGB(png_fixed_point g)1314 png_gamma_not_sRGB(png_fixed_point g)
1315 {
1316    if (g < PNG_FP_1)
1317    {
1318       /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1319       if (g == 0)
1320          return 0;
1321 
1322       return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1323    }
1324 
1325    return 1;
1326 }
1327 
1328 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1329  * header and fill in all the information.  This is executed in a safe context,
1330  * unlike the init routine above.
1331  */
1332 static int
png_image_read_header(png_voidp argument)1333 png_image_read_header(png_voidp argument)
1334 {
1335    png_imagep image = png_voidcast(png_imagep, argument);
1336    png_structrp png_ptr = image->opaque->png_ptr;
1337    png_inforp info_ptr = image->opaque->info_ptr;
1338 
1339    png_set_benign_errors(png_ptr, 1/*warn*/);
1340    png_read_info(png_ptr, info_ptr);
1341 
1342    /* Do this the fast way; just read directly out of png_struct. */
1343    image->width = png_ptr->width;
1344    image->height = png_ptr->height;
1345 
1346    {
1347       png_uint_32 format = png_image_format(png_ptr);
1348 
1349       image->format = format;
1350 
1351 #ifdef PNG_COLORSPACE_SUPPORTED
1352       /* Does the colorspace match sRGB?  If there is no color endpoint
1353        * (colorant) information assume yes, otherwise require the
1354        * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set.  If the
1355        * colorspace has been determined to be invalid ignore it.
1356        */
1357       if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1358          & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1359             PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1360          image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1361 #endif
1362    }
1363 
1364    /* We need the maximum number of entries regardless of the format the
1365     * application sets here.
1366     */
1367    {
1368       png_uint_32 cmap_entries;
1369 
1370       switch (png_ptr->color_type)
1371       {
1372          case PNG_COLOR_TYPE_GRAY:
1373             cmap_entries = 1U << png_ptr->bit_depth;
1374             break;
1375 
1376          case PNG_COLOR_TYPE_PALETTE:
1377             cmap_entries = png_ptr->num_palette;
1378             break;
1379 
1380          default:
1381             cmap_entries = 256;
1382             break;
1383       }
1384 
1385       if (cmap_entries > 256)
1386          cmap_entries = 256;
1387 
1388       image->colormap_entries = cmap_entries;
1389    }
1390 
1391    return 1;
1392 }
1393 
1394 #ifdef PNG_STDIO_SUPPORTED
1395 int PNGAPI
png_image_begin_read_from_stdio(png_imagep image,FILE * file)1396 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1397 {
1398    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1399    {
1400       if (file != NULL)
1401       {
1402          if (png_image_read_init(image))
1403          {
1404             /* This is slightly evil, but png_init_io doesn't do anything other
1405              * than this and we haven't changed the standard IO functions so
1406              * this saves a 'safe' function.
1407              */
1408             image->opaque->png_ptr->io_ptr = file;
1409             return png_safe_execute(image, png_image_read_header, image);
1410          }
1411       }
1412 
1413       else
1414          return png_image_error(image,
1415             "png_image_begin_read_from_stdio: invalid argument");
1416    }
1417 
1418    else if (image != NULL)
1419       return png_image_error(image,
1420          "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1421 
1422    return 0;
1423 }
1424 
1425 int PNGAPI
png_image_begin_read_from_file(png_imagep image,const char * file_name)1426 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1427 {
1428    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1429    {
1430       if (file_name != NULL)
1431       {
1432          FILE *fp = fopen(file_name, "rb");
1433 
1434          if (fp != NULL)
1435          {
1436             if (png_image_read_init(image))
1437             {
1438                image->opaque->png_ptr->io_ptr = fp;
1439                image->opaque->owned_file = 1;
1440                return png_safe_execute(image, png_image_read_header, image);
1441             }
1442 
1443             /* Clean up: just the opened file. */
1444             (void)fclose(fp);
1445          }
1446 
1447          else
1448             return png_image_error(image, strerror(errno));
1449       }
1450 
1451       else
1452          return png_image_error(image,
1453             "png_image_begin_read_from_file: invalid argument");
1454    }
1455 
1456    else if (image != NULL)
1457       return png_image_error(image,
1458          "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1459 
1460    return 0;
1461 }
1462 #endif /* PNG_STDIO_SUPPORTED */
1463 
1464 static void PNGCBAPI
png_image_memory_read(png_structp png_ptr,png_bytep out,png_size_t need)1465 png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
1466 {
1467    if (png_ptr != NULL)
1468    {
1469       png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1470       if (image != NULL)
1471       {
1472          png_controlp cp = image->opaque;
1473          if (cp != NULL)
1474          {
1475             png_const_bytep memory = cp->memory;
1476             png_size_t size = cp->size;
1477 
1478             if (memory != NULL && size >= need)
1479             {
1480                memcpy(out, memory, need);
1481                cp->memory = memory + need;
1482                cp->size = size - need;
1483                return;
1484             }
1485 
1486             png_error(png_ptr, "read beyond end of data");
1487          }
1488       }
1489 
1490       png_error(png_ptr, "invalid memory read");
1491    }
1492 }
1493 
png_image_begin_read_from_memory(png_imagep image,png_const_voidp memory,png_size_t size)1494 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1495    png_const_voidp memory, png_size_t size)
1496 {
1497    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1498    {
1499       if (memory != NULL && size > 0)
1500       {
1501          if (png_image_read_init(image))
1502          {
1503             /* Now set the IO functions to read from the memory buffer and
1504              * store it into io_ptr.  Again do this in-place to avoid calling a
1505              * libpng function that requires error handling.
1506              */
1507             image->opaque->memory = png_voidcast(png_const_bytep, memory);
1508             image->opaque->size = size;
1509             image->opaque->png_ptr->io_ptr = image;
1510             image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1511 
1512             return png_safe_execute(image, png_image_read_header, image);
1513          }
1514       }
1515 
1516       else
1517          return png_image_error(image,
1518             "png_image_begin_read_from_memory: invalid argument");
1519    }
1520 
1521    else if (image != NULL)
1522       return png_image_error(image,
1523          "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1524 
1525    return 0;
1526 }
1527 
1528 /* Utility function to skip chunks that are not used by the simplified image
1529  * read functions and an appropriate macro to call it.
1530  */
1531 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1532 static void
png_image_skip_unused_chunks(png_structrp png_ptr)1533 png_image_skip_unused_chunks(png_structrp png_ptr)
1534 {
1535    /* Prepare the reader to ignore all recognized chunks whose data will not
1536     * be used, i.e., all chunks recognized by libpng except for those
1537     * involved in basic image reading:
1538     *
1539     *    IHDR, PLTE, IDAT, IEND
1540     *
1541     * Or image data handling:
1542     *
1543     *    tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1544     *
1545     * This provides a small performance improvement and eliminates any
1546     * potential vulnerability to security problems in the unused chunks.
1547     *
1548     * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1549     * too.  This allows the simplified API to be compiled without iCCP support,
1550     * however if the support is there the chunk is still checked to detect
1551     * errors (which are unfortunately quite common.)
1552     */
1553    {
1554          static PNG_CONST png_byte chunks_to_process[] = {
1555             98,  75,  71,  68, '\0',  /* bKGD */
1556             99,  72,  82,  77, '\0',  /* cHRM */
1557            103,  65,  77,  65, '\0',  /* gAMA */
1558 #        ifdef PNG_READ_iCCP_SUPPORTED
1559            105,  67,  67,  80, '\0',  /* iCCP */
1560 #        endif
1561            115,  66,  73,  84, '\0',  /* sBIT */
1562            115,  82,  71,  66, '\0',  /* sRGB */
1563            };
1564 
1565        /* Ignore unknown chunks and all other chunks except for the
1566         * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1567         */
1568        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1569          NULL, -1);
1570 
1571        /* But do not ignore image data handling chunks */
1572        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1573          chunks_to_process, (sizeof chunks_to_process)/5);
1574     }
1575 }
1576 
1577 #  define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1578 #else
1579 #  define PNG_SKIP_CHUNKS(p) ((void)0)
1580 #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */
1581 
1582 /* The following macro gives the exact rounded answer for all values in the
1583  * range 0..255 (it actually divides by 51.2, but the rounding still generates
1584  * the correct numbers 0..5
1585  */
1586 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1587 
1588 /* Utility functions to make particular color-maps */
1589 static void
set_file_encoding(png_image_read_control * display)1590 set_file_encoding(png_image_read_control *display)
1591 {
1592    png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1593    if (png_gamma_significant(g))
1594    {
1595       if (png_gamma_not_sRGB(g))
1596       {
1597          display->file_encoding = P_FILE;
1598          display->gamma_to_linear = png_reciprocal(g);
1599       }
1600 
1601       else
1602          display->file_encoding = P_sRGB;
1603    }
1604 
1605    else
1606       display->file_encoding = P_LINEAR8;
1607 }
1608 
1609 static unsigned int
decode_gamma(png_image_read_control * display,png_uint_32 value,int encoding)1610 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1611 {
1612    if (encoding == P_FILE) /* double check */
1613       encoding = display->file_encoding;
1614 
1615    if (encoding == P_NOTSET) /* must be the file encoding */
1616    {
1617       set_file_encoding(display);
1618       encoding = display->file_encoding;
1619    }
1620 
1621    switch (encoding)
1622    {
1623       case P_FILE:
1624          value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1625          break;
1626 
1627       case P_sRGB:
1628          value = png_sRGB_table[value];
1629          break;
1630 
1631       case P_LINEAR:
1632          break;
1633 
1634       case P_LINEAR8:
1635          value *= 257;
1636          break;
1637 
1638       default:
1639          png_error(display->image->opaque->png_ptr,
1640             "unexpected encoding (internal error)");
1641          break;
1642    }
1643 
1644    return value;
1645 }
1646 
1647 static png_uint_32
png_colormap_compose(png_image_read_control * display,png_uint_32 foreground,int foreground_encoding,png_uint_32 alpha,png_uint_32 background,int encoding)1648 png_colormap_compose(png_image_read_control *display,
1649    png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1650    png_uint_32 background, int encoding)
1651 {
1652    /* The file value is composed on the background, the background has the given
1653     * encoding and so does the result, the file is encoded with P_FILE and the
1654     * file and alpha are 8-bit values.  The (output) encoding will always be
1655     * P_LINEAR or P_sRGB.
1656     */
1657    png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1658    png_uint_32 b = decode_gamma(display, background, encoding);
1659 
1660    /* The alpha is always an 8-bit value (it comes from the palette), the value
1661     * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1662     */
1663    f = f * alpha + b * (255-alpha);
1664 
1665    if (encoding == P_LINEAR)
1666    {
1667       /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1668        * accurate, it divides by 255.00000005937181414556, with no overflow.)
1669        */
1670       f *= 257; /* Now scaled by 65535 */
1671       f += f >> 16;
1672       f = (f+32768) >> 16;
1673    }
1674 
1675    else /* P_sRGB */
1676       f = PNG_sRGB_FROM_LINEAR(f);
1677 
1678    return f;
1679 }
1680 
1681 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1682  * be 8-bit.
1683  */
1684 static void
png_create_colormap_entry(png_image_read_control * display,png_uint_32 ip,png_uint_32 red,png_uint_32 green,png_uint_32 blue,png_uint_32 alpha,int encoding)1685 png_create_colormap_entry(png_image_read_control *display,
1686    png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1687    png_uint_32 alpha, int encoding)
1688 {
1689    png_imagep image = display->image;
1690    const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) ?
1691       P_LINEAR : P_sRGB;
1692    const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1693       (red != green || green != blue);
1694 
1695    if (ip > 255)
1696       png_error(image->opaque->png_ptr, "color-map index out of range");
1697 
1698    /* Update the cache with whether the file gamma is significantly different
1699     * from sRGB.
1700     */
1701    if (encoding == P_FILE)
1702    {
1703       if (display->file_encoding == P_NOTSET)
1704          set_file_encoding(display);
1705 
1706       /* Note that the cached value may be P_FILE too, but if it is then the
1707        * gamma_to_linear member has been set.
1708        */
1709       encoding = display->file_encoding;
1710    }
1711 
1712    if (encoding == P_FILE)
1713    {
1714       png_fixed_point g = display->gamma_to_linear;
1715 
1716       red = png_gamma_16bit_correct(red*257, g);
1717       green = png_gamma_16bit_correct(green*257, g);
1718       blue = png_gamma_16bit_correct(blue*257, g);
1719 
1720       if (convert_to_Y || output_encoding == P_LINEAR)
1721       {
1722          alpha *= 257;
1723          encoding = P_LINEAR;
1724       }
1725 
1726       else
1727       {
1728          red = PNG_sRGB_FROM_LINEAR(red * 255);
1729          green = PNG_sRGB_FROM_LINEAR(green * 255);
1730          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1731          encoding = P_sRGB;
1732       }
1733    }
1734 
1735    else if (encoding == P_LINEAR8)
1736    {
1737       /* This encoding occurs quite frequently in test cases because PngSuite
1738        * includes a gAMA 1.0 chunk with most images.
1739        */
1740       red *= 257;
1741       green *= 257;
1742       blue *= 257;
1743       alpha *= 257;
1744       encoding = P_LINEAR;
1745    }
1746 
1747    else if (encoding == P_sRGB && (convert_to_Y || output_encoding == P_LINEAR))
1748    {
1749       /* The values are 8-bit sRGB values, but must be converted to 16-bit
1750        * linear.
1751        */
1752       red = png_sRGB_table[red];
1753       green = png_sRGB_table[green];
1754       blue = png_sRGB_table[blue];
1755       alpha *= 257;
1756       encoding = P_LINEAR;
1757    }
1758 
1759    /* This is set if the color isn't gray but the output is. */
1760    if (encoding == P_LINEAR)
1761    {
1762       if (convert_to_Y)
1763       {
1764          /* NOTE: these values are copied from png_do_rgb_to_gray */
1765          png_uint_32 y = (png_uint_32)6968 * red  + (png_uint_32)23434 * green +
1766             (png_uint_32)2366 * blue;
1767 
1768          if (output_encoding == P_LINEAR)
1769             y = (y + 16384) >> 15;
1770 
1771          else
1772          {
1773             /* y is scaled by 32768, we need it scaled by 255: */
1774             y = (y + 128) >> 8;
1775             y *= 255;
1776             y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1777             encoding = P_sRGB;
1778          }
1779 
1780          blue = red = green = y;
1781       }
1782 
1783       else if (output_encoding == P_sRGB)
1784       {
1785          red = PNG_sRGB_FROM_LINEAR(red * 255);
1786          green = PNG_sRGB_FROM_LINEAR(green * 255);
1787          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1788          alpha = PNG_DIV257(alpha);
1789          encoding = P_sRGB;
1790       }
1791    }
1792 
1793    if (encoding != output_encoding)
1794       png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1795 
1796    /* Store the value. */
1797    {
1798 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
1799          const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1800             (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1801 #     else
1802 #        define afirst 0
1803 #     endif
1804 #     ifdef PNG_FORMAT_BGR_SUPPORTED
1805          const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) ? 2 : 0;
1806 #     else
1807 #        define bgr 0
1808 #     endif
1809 
1810       if (output_encoding == P_LINEAR)
1811       {
1812          png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1813 
1814          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1815 
1816          /* The linear 16-bit values must be pre-multiplied by the alpha channel
1817           * value, if less than 65535 (this is, effectively, composite on black
1818           * if the alpha channel is removed.)
1819           */
1820          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1821          {
1822             case 4:
1823                entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1824                /* FALL THROUGH */
1825 
1826             case 3:
1827                if (alpha < 65535)
1828                {
1829                   if (alpha > 0)
1830                   {
1831                      blue = (blue * alpha + 32767U)/65535U;
1832                      green = (green * alpha + 32767U)/65535U;
1833                      red = (red * alpha + 32767U)/65535U;
1834                   }
1835 
1836                   else
1837                      red = green = blue = 0;
1838                }
1839                entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1840                entry[afirst + 1] = (png_uint_16)green;
1841                entry[afirst + bgr] = (png_uint_16)red;
1842                break;
1843 
1844             case 2:
1845                entry[1 ^ afirst] = (png_uint_16)alpha;
1846                /* FALL THROUGH */
1847 
1848             case 1:
1849                if (alpha < 65535)
1850                {
1851                   if (alpha > 0)
1852                      green = (green * alpha + 32767U)/65535U;
1853 
1854                   else
1855                      green = 0;
1856                }
1857                entry[afirst] = (png_uint_16)green;
1858                break;
1859 
1860             default:
1861                break;
1862          }
1863       }
1864 
1865       else /* output encoding is P_sRGB */
1866       {
1867          png_bytep entry = png_voidcast(png_bytep, display->colormap);
1868 
1869          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1870 
1871          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1872          {
1873             case 4:
1874                entry[afirst ? 0 : 3] = (png_byte)alpha;
1875             case 3:
1876                entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1877                entry[afirst + 1] = (png_byte)green;
1878                entry[afirst + bgr] = (png_byte)red;
1879                break;
1880 
1881             case 2:
1882                entry[1 ^ afirst] = (png_byte)alpha;
1883             case 1:
1884                entry[afirst] = (png_byte)green;
1885                break;
1886 
1887             default:
1888                break;
1889          }
1890       }
1891 
1892 #     ifdef afirst
1893 #        undef afirst
1894 #     endif
1895 #     ifdef bgr
1896 #        undef bgr
1897 #     endif
1898    }
1899 }
1900 
1901 static int
make_gray_file_colormap(png_image_read_control * display)1902 make_gray_file_colormap(png_image_read_control *display)
1903 {
1904    unsigned int i;
1905 
1906    for (i=0; i<256; ++i)
1907       png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1908 
1909    return i;
1910 }
1911 
1912 static int
make_gray_colormap(png_image_read_control * display)1913 make_gray_colormap(png_image_read_control *display)
1914 {
1915    unsigned int i;
1916 
1917    for (i=0; i<256; ++i)
1918       png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
1919 
1920    return i;
1921 }
1922 #define PNG_GRAY_COLORMAP_ENTRIES 256
1923 
1924 static int
make_ga_colormap(png_image_read_control * display)1925 make_ga_colormap(png_image_read_control *display)
1926 {
1927    unsigned int i, a;
1928 
1929    /* Alpha is retained, the output will be a color-map with entries
1930     * selected by six levels of alpha.  One transparent entry, 6 gray
1931     * levels for all the intermediate alpha values, leaving 230 entries
1932     * for the opaque grays.  The color-map entries are the six values
1933     * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
1934     * relevant entry.
1935     *
1936     * if (alpha > 229) // opaque
1937     * {
1938     *    // The 231 entries are selected to make the math below work:
1939     *    base = 0;
1940     *    entry = (231 * gray + 128) >> 8;
1941     * }
1942     * else if (alpha < 26) // transparent
1943     * {
1944     *    base = 231;
1945     *    entry = 0;
1946     * }
1947     * else // partially opaque
1948     * {
1949     *    base = 226 + 6 * PNG_DIV51(alpha);
1950     *    entry = PNG_DIV51(gray);
1951     * }
1952     */
1953    i = 0;
1954    while (i < 231)
1955    {
1956       unsigned int gray = (i * 256 + 115) / 231;
1957       png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
1958    }
1959 
1960    /* 255 is used here for the component values for consistency with the code
1961     * that undoes premultiplication in pngwrite.c.
1962     */
1963    png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
1964 
1965    for (a=1; a<5; ++a)
1966    {
1967       unsigned int g;
1968 
1969       for (g=0; g<6; ++g)
1970          png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
1971             P_sRGB);
1972    }
1973 
1974    return i;
1975 }
1976 
1977 #define PNG_GA_COLORMAP_ENTRIES 256
1978 
1979 static int
make_rgb_colormap(png_image_read_control * display)1980 make_rgb_colormap(png_image_read_control *display)
1981 {
1982    unsigned int i, r;
1983 
1984    /* Build a 6x6x6 opaque RGB cube */
1985    for (i=r=0; r<6; ++r)
1986    {
1987       unsigned int g;
1988 
1989       for (g=0; g<6; ++g)
1990       {
1991          unsigned int b;
1992 
1993          for (b=0; b<6; ++b)
1994             png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
1995                P_sRGB);
1996       }
1997    }
1998 
1999    return i;
2000 }
2001 
2002 #define PNG_RGB_COLORMAP_ENTRIES 216
2003 
2004 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2005 #define PNG_RGB_INDEX(r,g,b) \
2006    ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2007 
2008 static int
png_image_read_colormap(png_voidp argument)2009 png_image_read_colormap(png_voidp argument)
2010 {
2011    png_image_read_control *display =
2012       png_voidcast(png_image_read_control*, argument);
2013    const png_imagep image = display->image;
2014 
2015    const png_structrp png_ptr = image->opaque->png_ptr;
2016    const png_uint_32 output_format = image->format;
2017    const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) ?
2018       P_LINEAR : P_sRGB;
2019 
2020    unsigned int cmap_entries;
2021    unsigned int output_processing;        /* Output processing option */
2022    unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2023 
2024    /* Background information; the background color and the index of this color
2025     * in the color-map if it exists (else 256).
2026     */
2027    unsigned int background_index = 256;
2028    png_uint_32 back_r, back_g, back_b;
2029 
2030    /* Flags to accumulate things that need to be done to the input. */
2031    int expand_tRNS = 0;
2032 
2033    /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2034     * very difficult to do, the results look awful, and it is difficult to see
2035     * what possible use it is because the application can't control the
2036     * color-map.
2037     */
2038    if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2039          png_ptr->num_trans > 0) /* alpha in input */ &&
2040       ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2041    {
2042       if (output_encoding == P_LINEAR) /* compose on black */
2043          back_b = back_g = back_r = 0;
2044 
2045       else if (display->background == NULL /* no way to remove it */)
2046          png_error(png_ptr,
2047             "a background color must be supplied to remove alpha/transparency");
2048 
2049       /* Get a copy of the background color (this avoids repeating the checks
2050        * below.)  The encoding is 8-bit sRGB or 16-bit linear, depending on the
2051        * output format.
2052        */
2053       else
2054       {
2055          back_g = display->background->green;
2056          if (output_format & PNG_FORMAT_FLAG_COLOR)
2057          {
2058             back_r = display->background->red;
2059             back_b = display->background->blue;
2060          }
2061          else
2062             back_b = back_r = back_g;
2063       }
2064    }
2065 
2066    else if (output_encoding == P_LINEAR)
2067       back_b = back_r = back_g = 65535;
2068 
2069    else
2070       back_b = back_r = back_g = 255;
2071 
2072    /* Default the input file gamma if required - this is necessary because
2073     * libpng assumes that if no gamma information is present the data is in the
2074     * output format, but the simplified API deduces the gamma from the input
2075     * format.
2076     */
2077    if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2078    {
2079       /* Do this directly, not using the png_colorspace functions, to ensure
2080        * that it happens even if the colorspace is invalid (though probably if
2081        * it is the setting will be ignored)  Note that the same thing can be
2082        * achieved at the application interface with png_set_gAMA.
2083        */
2084       if (png_ptr->bit_depth == 16 &&
2085          (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2086          png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2087 
2088       else
2089          png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2090 
2091       png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2092    }
2093 
2094    /* Decide what to do based on the PNG color type of the input data.  The
2095     * utility function png_create_colormap_entry deals with most aspects of the
2096     * output transformations; this code works out how to produce bytes of
2097     * color-map entries from the original format.
2098     */
2099    switch (png_ptr->color_type)
2100    {
2101       case PNG_COLOR_TYPE_GRAY:
2102          if (png_ptr->bit_depth <= 8)
2103          {
2104             /* There at most 256 colors in the output, regardless of
2105              * transparency.
2106              */
2107             unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2108 
2109             cmap_entries = 1U << png_ptr->bit_depth;
2110             if (cmap_entries > image->colormap_entries)
2111                png_error(png_ptr, "gray[8] color-map: too few entries");
2112 
2113             step = 255 / (cmap_entries - 1);
2114             output_processing = PNG_CMAP_NONE;
2115 
2116             /* If there is a tRNS chunk then this either selects a transparent
2117              * value or, if the output has no alpha, the background color.
2118              */
2119             if (png_ptr->num_trans > 0)
2120             {
2121                trans = png_ptr->trans_color.gray;
2122 
2123                if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2124                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2125             }
2126 
2127             /* png_create_colormap_entry just takes an RGBA and writes the
2128              * corresponding color-map entry using the format from 'image',
2129              * including the required conversion to sRGB or linear as
2130              * appropriate.  The input values are always either sRGB (if the
2131              * gamma correction flag is 0) or 0..255 scaled file encoded values
2132              * (if the function must gamma correct them).
2133              */
2134             for (i=val=0; i<cmap_entries; ++i, val += step)
2135             {
2136                /* 'i' is a file value.  While this will result in duplicated
2137                 * entries for 8-bit non-sRGB encoded files it is necessary to
2138                 * have non-gamma corrected values to do tRNS handling.
2139                 */
2140                if (i != trans)
2141                   png_create_colormap_entry(display, i, val, val, val, 255,
2142                      P_FILE/*8-bit with file gamma*/);
2143 
2144                /* Else this entry is transparent.  The colors don't matter if
2145                 * there is an alpha channel (back_alpha == 0), but it does no
2146                 * harm to pass them in; the values are not set above so this
2147                 * passes in white.
2148                 *
2149                 * NOTE: this preserves the full precision of the application
2150                 * supplied background color when it is used.
2151                 */
2152                else
2153                   png_create_colormap_entry(display, i, back_r, back_g, back_b,
2154                      back_alpha, output_encoding);
2155             }
2156 
2157             /* We need libpng to preserve the original encoding. */
2158             data_encoding = P_FILE;
2159 
2160             /* The rows from libpng, while technically gray values, are now also
2161              * color-map indicies; however, they may need to be expanded to 1
2162              * byte per pixel.  This is what png_set_packing does (i.e., it
2163              * unpacks the bit values into bytes.)
2164              */
2165             if (png_ptr->bit_depth < 8)
2166                png_set_packing(png_ptr);
2167          }
2168 
2169          else /* bit depth is 16 */
2170          {
2171             /* The 16-bit input values can be converted directly to 8-bit gamma
2172              * encoded values; however, if a tRNS chunk is present 257 color-map
2173              * entries are required.  This means that the extra entry requires
2174              * special processing; add an alpha channel, sacrifice gray level
2175              * 254 and convert transparent (alpha==0) entries to that.
2176              *
2177              * Use libpng to chop the data to 8 bits.  Convert it to sRGB at the
2178              * same time to minimize quality loss.  If a tRNS chunk is present
2179              * this means libpng must handle it too; otherwise it is impossible
2180              * to do the exact match on the 16-bit value.
2181              *
2182              * If the output has no alpha channel *and* the background color is
2183              * gray then it is possible to let libpng handle the substitution by
2184              * ensuring that the corresponding gray level matches the background
2185              * color exactly.
2186              */
2187             data_encoding = P_sRGB;
2188 
2189             if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2190                png_error(png_ptr, "gray[16] color-map: too few entries");
2191 
2192             cmap_entries = make_gray_colormap(display);
2193 
2194             if (png_ptr->num_trans > 0)
2195             {
2196                unsigned int back_alpha;
2197 
2198                if (output_format & PNG_FORMAT_FLAG_ALPHA)
2199                   back_alpha = 0;
2200 
2201                else
2202                {
2203                   if (back_r == back_g && back_g == back_b)
2204                   {
2205                      /* Background is gray; no special processing will be
2206                       * required.
2207                       */
2208                      png_color_16 c;
2209                      png_uint_32 gray = back_g;
2210 
2211                      if (output_encoding == P_LINEAR)
2212                      {
2213                         gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2214 
2215                         /* And make sure the corresponding palette entry
2216                          * matches.
2217                          */
2218                         png_create_colormap_entry(display, gray, back_g, back_g,
2219                            back_g, 65535, P_LINEAR);
2220                      }
2221 
2222                      /* The background passed to libpng, however, must be the
2223                       * sRGB value.
2224                       */
2225                      c.index = 0; /*unused*/
2226                      c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2227 
2228                      /* NOTE: does this work without expanding tRNS to alpha?
2229                       * It should be the color->gray case below apparently
2230                       * doesn't.
2231                       */
2232                      png_set_background_fixed(png_ptr, &c,
2233                         PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2234                         0/*gamma: not used*/);
2235 
2236                      output_processing = PNG_CMAP_NONE;
2237                      break;
2238                   }
2239 
2240                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2241                }
2242 
2243                /* output_processing means that the libpng-processed row will be
2244                 * 8-bit GA and it has to be processing to single byte color-map
2245                 * values.  Entry 254 is replaced by either a completely
2246                 * transparent entry or by the background color at full
2247                 * precision (and the background color is not a simple gray leve
2248                 * in this case.)
2249                 */
2250                expand_tRNS = 1;
2251                output_processing = PNG_CMAP_TRANS;
2252                background_index = 254;
2253 
2254                /* And set (overwrite) color-map entry 254 to the actual
2255                 * background color at full precision.
2256                 */
2257                png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2258                   back_alpha, output_encoding);
2259             }
2260 
2261             else
2262                output_processing = PNG_CMAP_NONE;
2263          }
2264          break;
2265 
2266       case PNG_COLOR_TYPE_GRAY_ALPHA:
2267          /* 8-bit or 16-bit PNG with two channels - gray and alpha.  A minimum
2268           * of 65536 combinations.  If, however, the alpha channel is to be
2269           * removed there are only 256 possibilities if the background is gray.
2270           * (Otherwise there is a subset of the 65536 possibilities defined by
2271           * the triangle between black, white and the background color.)
2272           *
2273           * Reduce 16-bit files to 8-bit and sRGB encode the result.  No need to
2274           * worry about tRNS matching - tRNS is ignored if there is an alpha
2275           * channel.
2276           */
2277          data_encoding = P_sRGB;
2278 
2279          if (output_format & PNG_FORMAT_FLAG_ALPHA)
2280          {
2281             if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2282                png_error(png_ptr, "gray+alpha color-map: too few entries");
2283 
2284             cmap_entries = make_ga_colormap(display);
2285 
2286             background_index = PNG_CMAP_GA_BACKGROUND;
2287             output_processing = PNG_CMAP_GA;
2288          }
2289 
2290          else /* alpha is removed */
2291          {
2292             /* Alpha must be removed as the PNG data is processed when the
2293              * background is a color because the G and A channels are
2294              * independent and the vector addition (non-parallel vectors) is a
2295              * 2-D problem.
2296              *
2297              * This can be reduced to the same algorithm as above by making a
2298              * colormap containing gray levels (for the opaque grays), a
2299              * background entry (for a transparent pixel) and a set of four six
2300              * level color values, one set for each intermediate alpha value.
2301              * See the comments in make_ga_colormap for how this works in the
2302              * per-pixel processing.
2303              *
2304              * If the background is gray, however, we only need a 256 entry gray
2305              * level color map.  It is sufficient to make the entry generated
2306              * for the background color be exactly the color specified.
2307              */
2308             if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2309                (back_r == back_g && back_g == back_b))
2310             {
2311                /* Background is gray; no special processing will be required. */
2312                png_color_16 c;
2313                png_uint_32 gray = back_g;
2314 
2315                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2316                   png_error(png_ptr, "gray-alpha color-map: too few entries");
2317 
2318                cmap_entries = make_gray_colormap(display);
2319 
2320                if (output_encoding == P_LINEAR)
2321                {
2322                   gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2323 
2324                   /* And make sure the corresponding palette entry matches. */
2325                   png_create_colormap_entry(display, gray, back_g, back_g,
2326                      back_g, 65535, P_LINEAR);
2327                }
2328 
2329                /* The background passed to libpng, however, must be the sRGB
2330                 * value.
2331                 */
2332                c.index = 0; /*unused*/
2333                c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2334 
2335                png_set_background_fixed(png_ptr, &c,
2336                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2337                   0/*gamma: not used*/);
2338 
2339                output_processing = PNG_CMAP_NONE;
2340             }
2341 
2342             else
2343             {
2344                png_uint_32 i, a;
2345 
2346                /* This is the same as png_make_ga_colormap, above, except that
2347                 * the entries are all opaque.
2348                 */
2349                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2350                   png_error(png_ptr, "ga-alpha color-map: too few entries");
2351 
2352                i = 0;
2353                while (i < 231)
2354                {
2355                   png_uint_32 gray = (i * 256 + 115) / 231;
2356                   png_create_colormap_entry(display, i++, gray, gray, gray,
2357                      255, P_sRGB);
2358                }
2359 
2360                /* NOTE: this preserves the full precision of the application
2361                 * background color.
2362                 */
2363                background_index = i;
2364                png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2365                   output_encoding == P_LINEAR ? 65535U : 255U, output_encoding);
2366 
2367                /* For non-opaque input composite on the sRGB background - this
2368                 * requires inverting the encoding for each component.  The input
2369                 * is still converted to the sRGB encoding because this is a
2370                 * reasonable approximate to the logarithmic curve of human
2371                 * visual sensitivity, at least over the narrow range which PNG
2372                 * represents.  Consequently 'G' is always sRGB encoded, while
2373                 * 'A' is linear.  We need the linear background colors.
2374                 */
2375                if (output_encoding == P_sRGB) /* else already linear */
2376                {
2377                   /* This may produce a value not exactly matching the
2378                    * background, but that's ok because these numbers are only
2379                    * used when alpha != 0
2380                    */
2381                   back_r = png_sRGB_table[back_r];
2382                   back_g = png_sRGB_table[back_g];
2383                   back_b = png_sRGB_table[back_b];
2384                }
2385 
2386                for (a=1; a<5; ++a)
2387                {
2388                   unsigned int g;
2389 
2390                   /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2391                    * by an 8-bit alpha value (0..255).
2392                    */
2393                   png_uint_32 alpha = 51 * a;
2394                   png_uint_32 back_rx = (255-alpha) * back_r;
2395                   png_uint_32 back_gx = (255-alpha) * back_g;
2396                   png_uint_32 back_bx = (255-alpha) * back_b;
2397 
2398                   for (g=0; g<6; ++g)
2399                   {
2400                      png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2401 
2402                      png_create_colormap_entry(display, i++,
2403                         PNG_sRGB_FROM_LINEAR(gray + back_rx),
2404                         PNG_sRGB_FROM_LINEAR(gray + back_gx),
2405                         PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2406                   }
2407                }
2408 
2409                cmap_entries = i;
2410                output_processing = PNG_CMAP_GA;
2411             }
2412          }
2413          break;
2414 
2415       case PNG_COLOR_TYPE_RGB:
2416       case PNG_COLOR_TYPE_RGB_ALPHA:
2417          /* Exclude the case where the output is gray; we can always handle this
2418           * with the cases above.
2419           */
2420          if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2421          {
2422             /* The color-map will be grayscale, so we may as well convert the
2423              * input RGB values to a simple grayscale and use the grayscale
2424              * code above.
2425              *
2426              * NOTE: calling this apparently damages the recognition of the
2427              * transparent color in background color handling; call
2428              * png_set_tRNS_to_alpha before png_set_background_fixed.
2429              */
2430             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2431                -1);
2432             data_encoding = P_sRGB;
2433 
2434             /* The output will now be one or two 8-bit gray or gray+alpha
2435              * channels.  The more complex case arises when the input has alpha.
2436              */
2437             if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2438                png_ptr->num_trans > 0) &&
2439                (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2440             {
2441                /* Both input and output have an alpha channel, so no background
2442                 * processing is required; just map the GA bytes to the right
2443                 * color-map entry.
2444                 */
2445                expand_tRNS = 1;
2446 
2447                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2448                   png_error(png_ptr, "rgb[ga] color-map: too few entries");
2449 
2450                cmap_entries = make_ga_colormap(display);
2451                background_index = PNG_CMAP_GA_BACKGROUND;
2452                output_processing = PNG_CMAP_GA;
2453             }
2454 
2455             else
2456             {
2457                /* Either the input or the output has no alpha channel, so there
2458                 * will be no non-opaque pixels in the color-map; it will just be
2459                 * grayscale.
2460                 */
2461                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2462                   png_error(png_ptr, "rgb[gray] color-map: too few entries");
2463 
2464                /* Ideally this code would use libpng to do the gamma correction,
2465                 * but if an input alpha channel is to be removed we will hit the
2466                 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2467                 * correction bug).  Fix this by dropping the gamma correction in
2468                 * this case and doing it in the palette; this will result in
2469                 * duplicate palette entries, but that's better than the
2470                 * alternative of double gamma correction.
2471                 */
2472                if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2473                   png_ptr->num_trans > 0) &&
2474                   png_gamma_not_sRGB(png_ptr->colorspace.gamma))
2475                {
2476                   cmap_entries = make_gray_file_colormap(display);
2477                   data_encoding = P_FILE;
2478                }
2479 
2480                else
2481                   cmap_entries = make_gray_colormap(display);
2482 
2483                /* But if the input has alpha or transparency it must be removed
2484                 */
2485                if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2486                   png_ptr->num_trans > 0)
2487                {
2488                   png_color_16 c;
2489                   png_uint_32 gray = back_g;
2490 
2491                   /* We need to ensure that the application background exists in
2492                    * the colormap and that completely transparent pixels map to
2493                    * it.  Achieve this simply by ensuring that the entry
2494                    * selected for the background really is the background color.
2495                    */
2496                   if (data_encoding == P_FILE) /* from the fixup above */
2497                   {
2498                      /* The app supplied a gray which is in output_encoding, we
2499                       * need to convert it to a value of the input (P_FILE)
2500                       * encoding then set this palette entry to the required
2501                       * output encoding.
2502                       */
2503                      if (output_encoding == P_sRGB)
2504                         gray = png_sRGB_table[gray]; /* now P_LINEAR */
2505 
2506                      gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2507                         png_ptr->colorspace.gamma)); /* now P_FILE */
2508 
2509                      /* And make sure the corresponding palette entry contains
2510                       * exactly the required sRGB value.
2511                       */
2512                      png_create_colormap_entry(display, gray, back_g, back_g,
2513                         back_g, 0/*unused*/, output_encoding);
2514                   }
2515 
2516                   else if (output_encoding == P_LINEAR)
2517                   {
2518                      gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2519 
2520                      /* And make sure the corresponding palette entry matches.
2521                       */
2522                      png_create_colormap_entry(display, gray, back_g, back_g,
2523                         back_g, 0/*unused*/, P_LINEAR);
2524                   }
2525 
2526                   /* The background passed to libpng, however, must be the
2527                    * output (normally sRGB) value.
2528                    */
2529                   c.index = 0; /*unused*/
2530                   c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2531 
2532                   /* NOTE: the following is apparently a bug in libpng. Without
2533                    * it the transparent color recognition in
2534                    * png_set_background_fixed seems to go wrong.
2535                    */
2536                   expand_tRNS = 1;
2537                   png_set_background_fixed(png_ptr, &c,
2538                      PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2539                      0/*gamma: not used*/);
2540                }
2541 
2542                output_processing = PNG_CMAP_NONE;
2543             }
2544          }
2545 
2546          else /* output is color */
2547          {
2548             /* We could use png_quantize here so long as there is no transparent
2549              * color or alpha; png_quantize ignores alpha.  Easier overall just
2550              * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2551              * Consequently we always want libpng to produce sRGB data.
2552              */
2553             data_encoding = P_sRGB;
2554 
2555             /* Is there any transparency or alpha? */
2556             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2557                png_ptr->num_trans > 0)
2558             {
2559                /* Is there alpha in the output too?  If so all four channels are
2560                 * processed into a special RGB cube with alpha support.
2561                 */
2562                if (output_format & PNG_FORMAT_FLAG_ALPHA)
2563                {
2564                   png_uint_32 r;
2565 
2566                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2567                      png_error(png_ptr, "rgb+alpha color-map: too few entries");
2568 
2569                   cmap_entries = make_rgb_colormap(display);
2570 
2571                   /* Add a transparent entry. */
2572                   png_create_colormap_entry(display, cmap_entries, 255, 255,
2573                      255, 0, P_sRGB);
2574 
2575                   /* This is stored as the background index for the processing
2576                    * algorithm.
2577                    */
2578                   background_index = cmap_entries++;
2579 
2580                   /* Add 27 r,g,b entries each with alpha 0.5. */
2581                   for (r=0; r<256; r = (r << 1) | 0x7f)
2582                   {
2583                      png_uint_32 g;
2584 
2585                      for (g=0; g<256; g = (g << 1) | 0x7f)
2586                      {
2587                         png_uint_32 b;
2588 
2589                         /* This generates components with the values 0, 127 and
2590                          * 255
2591                          */
2592                         for (b=0; b<256; b = (b << 1) | 0x7f)
2593                            png_create_colormap_entry(display, cmap_entries++,
2594                               r, g, b, 128, P_sRGB);
2595                      }
2596                   }
2597 
2598                   expand_tRNS = 1;
2599                   output_processing = PNG_CMAP_RGB_ALPHA;
2600                }
2601 
2602                else
2603                {
2604                   /* Alpha/transparency must be removed.  The background must
2605                    * exist in the color map (achieved by setting adding it after
2606                    * the 666 color-map).  If the standard processing code will
2607                    * pick up this entry automatically that's all that is
2608                    * required; libpng can be called to do the background
2609                    * processing.
2610                    */
2611                   unsigned int sample_size =
2612                      PNG_IMAGE_SAMPLE_SIZE(output_format);
2613                   png_uint_32 r, g, b; /* sRGB background */
2614 
2615                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2616                      png_error(png_ptr, "rgb-alpha color-map: too few entries");
2617 
2618                   cmap_entries = make_rgb_colormap(display);
2619 
2620                   png_create_colormap_entry(display, cmap_entries, back_r,
2621                         back_g, back_b, 0/*unused*/, output_encoding);
2622 
2623                   if (output_encoding == P_LINEAR)
2624                   {
2625                      r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2626                      g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2627                      b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2628                   }
2629 
2630                   else
2631                   {
2632                      r = back_r;
2633                      g = back_g;
2634                      b = back_g;
2635                   }
2636 
2637                   /* Compare the newly-created color-map entry with the one the
2638                    * PNG_CMAP_RGB algorithm will use.  If the two entries don't
2639                    * match, add the new one and set this as the background
2640                    * index.
2641                    */
2642                   if (memcmp((png_const_bytep)display->colormap +
2643                         sample_size * cmap_entries,
2644                      (png_const_bytep)display->colormap +
2645                         sample_size * PNG_RGB_INDEX(r,g,b),
2646                      sample_size) != 0)
2647                   {
2648                      /* The background color must be added. */
2649                      background_index = cmap_entries++;
2650 
2651                      /* Add 27 r,g,b entries each with created by composing with
2652                       * the background at alpha 0.5.
2653                       */
2654                      for (r=0; r<256; r = (r << 1) | 0x7f)
2655                      {
2656                         for (g=0; g<256; g = (g << 1) | 0x7f)
2657                         {
2658                            /* This generates components with the values 0, 127
2659                             * and 255
2660                             */
2661                            for (b=0; b<256; b = (b << 1) | 0x7f)
2662                               png_create_colormap_entry(display, cmap_entries++,
2663                                  png_colormap_compose(display, r, P_sRGB, 128,
2664                                     back_r, output_encoding),
2665                                  png_colormap_compose(display, g, P_sRGB, 128,
2666                                     back_g, output_encoding),
2667                                  png_colormap_compose(display, b, P_sRGB, 128,
2668                                     back_b, output_encoding),
2669                                  0/*unused*/, output_encoding);
2670                         }
2671                      }
2672 
2673                      expand_tRNS = 1;
2674                      output_processing = PNG_CMAP_RGB_ALPHA;
2675                   }
2676 
2677                   else /* background color is in the standard color-map */
2678                   {
2679                      png_color_16 c;
2680 
2681                      c.index = 0; /*unused*/
2682                      c.red = (png_uint_16)back_r;
2683                      c.gray = c.green = (png_uint_16)back_g;
2684                      c.blue = (png_uint_16)back_b;
2685 
2686                      png_set_background_fixed(png_ptr, &c,
2687                         PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2688                         0/*gamma: not used*/);
2689 
2690                      output_processing = PNG_CMAP_RGB;
2691                   }
2692                }
2693             }
2694 
2695             else /* no alpha or transparency in the input */
2696             {
2697                /* Alpha in the output is irrelevant, simply map the opaque input
2698                 * pixels to the 6x6x6 color-map.
2699                 */
2700                if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2701                   png_error(png_ptr, "rgb color-map: too few entries");
2702 
2703                cmap_entries = make_rgb_colormap(display);
2704                output_processing = PNG_CMAP_RGB;
2705             }
2706          }
2707          break;
2708 
2709       case PNG_COLOR_TYPE_PALETTE:
2710          /* It's already got a color-map.  It may be necessary to eliminate the
2711           * tRNS entries though.
2712           */
2713          {
2714             unsigned int num_trans = png_ptr->num_trans;
2715             png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2716             png_const_colorp colormap = png_ptr->palette;
2717             const int do_background = trans != NULL &&
2718                (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2719             unsigned int i;
2720 
2721             /* Just in case: */
2722             if (trans == NULL)
2723                num_trans = 0;
2724 
2725             output_processing = PNG_CMAP_NONE;
2726             data_encoding = P_FILE; /* Don't change from color-map indicies */
2727             cmap_entries = png_ptr->num_palette;
2728             if (cmap_entries > 256)
2729                cmap_entries = 256;
2730 
2731             if (cmap_entries > image->colormap_entries)
2732                png_error(png_ptr, "palette color-map: too few entries");
2733 
2734             for (i=0; i < cmap_entries; ++i)
2735             {
2736                if (do_background && i < num_trans && trans[i] < 255)
2737                {
2738                   if (trans[i] == 0)
2739                      png_create_colormap_entry(display, i, back_r, back_g,
2740                         back_b, 0, output_encoding);
2741 
2742                   else
2743                   {
2744                      /* Must compose the PNG file color in the color-map entry
2745                       * on the sRGB color in 'back'.
2746                       */
2747                      png_create_colormap_entry(display, i,
2748                         png_colormap_compose(display, colormap[i].red, P_FILE,
2749                            trans[i], back_r, output_encoding),
2750                         png_colormap_compose(display, colormap[i].green, P_FILE,
2751                            trans[i], back_g, output_encoding),
2752                         png_colormap_compose(display, colormap[i].blue, P_FILE,
2753                            trans[i], back_b, output_encoding),
2754                         output_encoding == P_LINEAR ? trans[i] * 257U :
2755                            trans[i],
2756                         output_encoding);
2757                   }
2758                }
2759 
2760                else
2761                   png_create_colormap_entry(display, i, colormap[i].red,
2762                      colormap[i].green, colormap[i].blue,
2763                      i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2764             }
2765 
2766             /* The PNG data may have indicies packed in fewer than 8 bits, it
2767              * must be expanded if so.
2768              */
2769             if (png_ptr->bit_depth < 8)
2770                png_set_packing(png_ptr);
2771          }
2772          break;
2773 
2774       default:
2775          png_error(png_ptr, "invalid PNG color type");
2776          /*NOT REACHED*/
2777          break;
2778    }
2779 
2780    /* Now deal with the output processing */
2781    if (expand_tRNS && png_ptr->num_trans > 0 &&
2782       (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2783       png_set_tRNS_to_alpha(png_ptr);
2784 
2785    switch (data_encoding)
2786    {
2787       default:
2788          png_error(png_ptr, "bad data option (internal error)");
2789          break;
2790 
2791       case P_sRGB:
2792          /* Change to 8-bit sRGB */
2793          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2794          /* FALL THROUGH */
2795 
2796       case P_FILE:
2797          if (png_ptr->bit_depth > 8)
2798             png_set_scale_16(png_ptr);
2799          break;
2800    }
2801 
2802    if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2803       png_error(png_ptr, "color map overflow (BAD internal error)");
2804 
2805    image->colormap_entries = cmap_entries;
2806 
2807    /* Double check using the recorded background index */
2808    switch (output_processing)
2809    {
2810       case PNG_CMAP_NONE:
2811          if (background_index != PNG_CMAP_NONE_BACKGROUND)
2812             goto bad_background;
2813          break;
2814 
2815       case PNG_CMAP_GA:
2816          if (background_index != PNG_CMAP_GA_BACKGROUND)
2817             goto bad_background;
2818          break;
2819 
2820       case PNG_CMAP_TRANS:
2821          if (background_index >= cmap_entries ||
2822             background_index != PNG_CMAP_TRANS_BACKGROUND)
2823             goto bad_background;
2824          break;
2825 
2826       case PNG_CMAP_RGB:
2827          if (background_index != PNG_CMAP_RGB_BACKGROUND)
2828             goto bad_background;
2829          break;
2830 
2831       case PNG_CMAP_RGB_ALPHA:
2832          if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2833             goto bad_background;
2834          break;
2835 
2836       default:
2837          png_error(png_ptr, "bad processing option (internal error)");
2838 
2839       bad_background:
2840          png_error(png_ptr, "bad background index (internal error)");
2841    }
2842 
2843    display->colormap_processing = output_processing;
2844 
2845    return 1/*ok*/;
2846 }
2847 
2848 /* The final part of the color-map read called from png_image_finish_read. */
2849 static int
png_image_read_and_map(png_voidp argument)2850 png_image_read_and_map(png_voidp argument)
2851 {
2852    png_image_read_control *display = png_voidcast(png_image_read_control*,
2853       argument);
2854    png_imagep image = display->image;
2855    png_structrp png_ptr = image->opaque->png_ptr;
2856    int passes;
2857 
2858    /* Called when the libpng data must be transformed into the color-mapped
2859     * form.  There is a local row buffer in display->local and this routine must
2860     * do the interlace handling.
2861     */
2862    switch (png_ptr->interlaced)
2863    {
2864       case PNG_INTERLACE_NONE:
2865          passes = 1;
2866          break;
2867 
2868       case PNG_INTERLACE_ADAM7:
2869          passes = PNG_INTERLACE_ADAM7_PASSES;
2870          break;
2871 
2872       default:
2873          png_error(png_ptr, "unknown interlace type");
2874    }
2875 
2876    {
2877       png_uint_32  height = image->height;
2878       png_uint_32  width = image->width;
2879       int          proc = display->colormap_processing;
2880       png_bytep    first_row = png_voidcast(png_bytep, display->first_row);
2881       ptrdiff_t    step_row = display->row_bytes;
2882       int pass;
2883 
2884       for (pass = 0; pass < passes; ++pass)
2885       {
2886          unsigned int     startx, stepx, stepy;
2887          png_uint_32      y;
2888 
2889          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2890          {
2891             /* The row may be empty for a short image: */
2892             if (PNG_PASS_COLS(width, pass) == 0)
2893                continue;
2894 
2895             startx = PNG_PASS_START_COL(pass);
2896             stepx = PNG_PASS_COL_OFFSET(pass);
2897             y = PNG_PASS_START_ROW(pass);
2898             stepy = PNG_PASS_ROW_OFFSET(pass);
2899          }
2900 
2901          else
2902          {
2903             y = 0;
2904             startx = 0;
2905             stepx = stepy = 1;
2906          }
2907 
2908          for (; y<height; y += stepy)
2909          {
2910             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
2911             png_bytep outrow = first_row + y * step_row;
2912             png_const_bytep end_row = outrow + width;
2913 
2914             /* Read read the libpng data into the temporary buffer. */
2915             png_read_row(png_ptr, inrow, NULL);
2916 
2917             /* Now process the row according to the processing option, note
2918              * that the caller verifies that the format of the libpng output
2919              * data is as required.
2920              */
2921             outrow += startx;
2922             switch (proc)
2923             {
2924                case PNG_CMAP_GA:
2925                   for (; outrow < end_row; outrow += stepx)
2926                   {
2927                      /* The data is always in the PNG order */
2928                      unsigned int gray = *inrow++;
2929                      unsigned int alpha = *inrow++;
2930                      unsigned int entry;
2931 
2932                      /* NOTE: this code is copied as a comment in
2933                       * make_ga_colormap above.  Please update the
2934                       * comment if you change this code!
2935                       */
2936                      if (alpha > 229) /* opaque */
2937                      {
2938                         entry = (231 * gray + 128) >> 8;
2939                      }
2940                      else if (alpha < 26) /* transparent */
2941                      {
2942                         entry = 231;
2943                      }
2944                      else /* partially opaque */
2945                      {
2946                         entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
2947                      }
2948 
2949                      *outrow = (png_byte)entry;
2950                   }
2951                   break;
2952 
2953                case PNG_CMAP_TRANS:
2954                   for (; outrow < end_row; outrow += stepx)
2955                   {
2956                      png_byte gray = *inrow++;
2957                      png_byte alpha = *inrow++;
2958 
2959                      if (alpha == 0)
2960                         *outrow = PNG_CMAP_TRANS_BACKGROUND;
2961 
2962                      else if (gray != PNG_CMAP_TRANS_BACKGROUND)
2963                         *outrow = gray;
2964 
2965                      else
2966                         *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
2967                   }
2968                   break;
2969 
2970                case PNG_CMAP_RGB:
2971                   for (; outrow < end_row; outrow += stepx)
2972                   {
2973                      *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
2974                      inrow += 3;
2975                   }
2976                   break;
2977 
2978                case PNG_CMAP_RGB_ALPHA:
2979                   for (; outrow < end_row; outrow += stepx)
2980                   {
2981                      unsigned int alpha = inrow[3];
2982 
2983                      /* Because the alpha entries only hold alpha==0.5 values
2984                       * split the processing at alpha==0.25 (64) and 0.75
2985                       * (196).
2986                       */
2987 
2988                      if (alpha >= 196)
2989                         *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
2990                            inrow[2]);
2991 
2992                      else if (alpha < 64)
2993                         *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
2994 
2995                      else
2996                      {
2997                         /* Likewise there are three entries for each of r, g
2998                          * and b.  We could select the entry by popcount on
2999                          * the top two bits on those architectures that
3000                          * support it, this is what the code below does,
3001                          * crudely.
3002                          */
3003                         unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3004 
3005                         /* Here are how the values map:
3006                          *
3007                          * 0x00 .. 0x3f -> 0
3008                          * 0x40 .. 0xbf -> 1
3009                          * 0xc0 .. 0xff -> 2
3010                          *
3011                          * So, as above with the explicit alpha checks, the
3012                          * breakpoints are at 64 and 196.
3013                          */
3014                         if (inrow[0] & 0x80) back_i += 9; /* red */
3015                         if (inrow[0] & 0x40) back_i += 9;
3016                         if (inrow[0] & 0x80) back_i += 3; /* green */
3017                         if (inrow[0] & 0x40) back_i += 3;
3018                         if (inrow[0] & 0x80) back_i += 1; /* blue */
3019                         if (inrow[0] & 0x40) back_i += 1;
3020 
3021                         *outrow = (png_byte)back_i;
3022                      }
3023 
3024                      inrow += 4;
3025                   }
3026                   break;
3027 
3028                default:
3029                   break;
3030             }
3031          }
3032       }
3033    }
3034 
3035    return 1;
3036 }
3037 
3038 static int
png_image_read_colormapped(png_voidp argument)3039 png_image_read_colormapped(png_voidp argument)
3040 {
3041    png_image_read_control *display = png_voidcast(png_image_read_control*,
3042       argument);
3043    png_imagep image = display->image;
3044    png_controlp control = image->opaque;
3045    png_structrp png_ptr = control->png_ptr;
3046    png_inforp info_ptr = control->info_ptr;
3047 
3048    int passes = 0; /* As a flag */
3049 
3050    PNG_SKIP_CHUNKS(png_ptr);
3051 
3052    /* Update the 'info' structure and make sure the result is as required; first
3053     * make sure to turn on the interlace handling if it will be required
3054     * (because it can't be turned on *after* the call to png_read_update_info!)
3055     */
3056    if (display->colormap_processing == PNG_CMAP_NONE)
3057       passes = png_set_interlace_handling(png_ptr);
3058 
3059    png_read_update_info(png_ptr, info_ptr);
3060 
3061    /* The expected output can be deduced from the colormap_processing option. */
3062    switch (display->colormap_processing)
3063    {
3064       case PNG_CMAP_NONE:
3065          /* Output must be one channel and one byte per pixel, the output
3066           * encoding can be anything.
3067           */
3068          if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3069             info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3070             info_ptr->bit_depth == 8)
3071             break;
3072 
3073          goto bad_output;
3074 
3075       case PNG_CMAP_TRANS:
3076       case PNG_CMAP_GA:
3077          /* Output must be two channels and the 'G' one must be sRGB, the latter
3078           * can be checked with an exact number because it should have been set
3079           * to this number above!
3080           */
3081          if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3082             info_ptr->bit_depth == 8 &&
3083             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3084             image->colormap_entries == 256)
3085             break;
3086 
3087          goto bad_output;
3088 
3089       case PNG_CMAP_RGB:
3090          /* Output must be 8-bit sRGB encoded RGB */
3091          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3092             info_ptr->bit_depth == 8 &&
3093             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3094             image->colormap_entries == 216)
3095             break;
3096 
3097          goto bad_output;
3098 
3099       case PNG_CMAP_RGB_ALPHA:
3100          /* Output must be 8-bit sRGB encoded RGBA */
3101          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3102             info_ptr->bit_depth == 8 &&
3103             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3104             image->colormap_entries == 244 /* 216 + 1 + 27 */)
3105             break;
3106 
3107          /* goto bad_output; */
3108          /* FALL THROUGH */
3109 
3110       default:
3111       bad_output:
3112          png_error(png_ptr, "bad color-map processing (internal error)");
3113    }
3114 
3115    /* Now read the rows.  Do this here if it is possible to read directly into
3116     * the output buffer, otherwise allocate a local row buffer of the maximum
3117     * size libpng requires and call the relevant processing routine safely.
3118     */
3119    {
3120       png_voidp first_row = display->buffer;
3121       ptrdiff_t row_bytes = display->row_stride;
3122 
3123       /* The following expression is designed to work correctly whether it gives
3124        * a signed or an unsigned result.
3125        */
3126       if (row_bytes < 0)
3127       {
3128          char *ptr = png_voidcast(char*, first_row);
3129          ptr += (image->height-1) * (-row_bytes);
3130          first_row = png_voidcast(png_voidp, ptr);
3131       }
3132 
3133       display->first_row = first_row;
3134       display->row_bytes = row_bytes;
3135    }
3136 
3137    if (passes == 0)
3138    {
3139       int result;
3140       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3141 
3142       display->local_row = row;
3143       result = png_safe_execute(image, png_image_read_and_map, display);
3144       display->local_row = NULL;
3145       png_free(png_ptr, row);
3146 
3147       return result;
3148    }
3149 
3150    else
3151    {
3152       png_alloc_size_t row_bytes = display->row_bytes;
3153 
3154       while (--passes >= 0)
3155       {
3156          png_uint_32      y = image->height;
3157          png_bytep        row = png_voidcast(png_bytep, display->first_row);
3158 
3159          while (y-- > 0)
3160          {
3161             png_read_row(png_ptr, row, NULL);
3162             row += row_bytes;
3163          }
3164       }
3165 
3166       return 1;
3167    }
3168 }
3169 
3170 /* Just the row reading part of png_image_read. */
3171 static int
png_image_read_composite(png_voidp argument)3172 png_image_read_composite(png_voidp argument)
3173 {
3174    png_image_read_control *display = png_voidcast(png_image_read_control*,
3175       argument);
3176    png_imagep image = display->image;
3177    png_structrp png_ptr = image->opaque->png_ptr;
3178    int passes;
3179 
3180    switch (png_ptr->interlaced)
3181    {
3182       case PNG_INTERLACE_NONE:
3183          passes = 1;
3184          break;
3185 
3186       case PNG_INTERLACE_ADAM7:
3187          passes = PNG_INTERLACE_ADAM7_PASSES;
3188          break;
3189 
3190       default:
3191          png_error(png_ptr, "unknown interlace type");
3192    }
3193 
3194    {
3195       png_uint_32  height = image->height;
3196       png_uint_32  width = image->width;
3197       ptrdiff_t    step_row = display->row_bytes;
3198       unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) ? 3 : 1;
3199       int pass;
3200 
3201       for (pass = 0; pass < passes; ++pass)
3202       {
3203          unsigned int     startx, stepx, stepy;
3204          png_uint_32      y;
3205 
3206          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3207          {
3208             /* The row may be empty for a short image: */
3209             if (PNG_PASS_COLS(width, pass) == 0)
3210                continue;
3211 
3212             startx = PNG_PASS_START_COL(pass) * channels;
3213             stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3214             y = PNG_PASS_START_ROW(pass);
3215             stepy = PNG_PASS_ROW_OFFSET(pass);
3216          }
3217 
3218          else
3219          {
3220             y = 0;
3221             startx = 0;
3222             stepx = channels;
3223             stepy = 1;
3224          }
3225 
3226          for (; y<height; y += stepy)
3227          {
3228             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3229             png_bytep outrow;
3230             png_const_bytep end_row;
3231 
3232             /* Read the row, which is packed: */
3233             png_read_row(png_ptr, inrow, NULL);
3234 
3235             outrow = png_voidcast(png_bytep, display->first_row);
3236             outrow += y * step_row;
3237             end_row = outrow + width * channels;
3238 
3239             /* Now do the composition on each pixel in this row. */
3240             outrow += startx;
3241             for (; outrow < end_row; outrow += stepx)
3242             {
3243                png_byte alpha = inrow[channels];
3244 
3245                if (alpha > 0) /* else no change to the output */
3246                {
3247                   unsigned int c;
3248 
3249                   for (c=0; c<channels; ++c)
3250                   {
3251                      png_uint_32 component = inrow[c];
3252 
3253                      if (alpha < 255) /* else just use component */
3254                      {
3255                         /* This is PNG_OPTIMIZED_ALPHA, the component value
3256                          * is a linear 8-bit value.  Combine this with the
3257                          * current outrow[c] value which is sRGB encoded.
3258                          * Arithmetic here is 16-bits to preserve the output
3259                          * values correctly.
3260                          */
3261                         component *= 257*255; /* =65535 */
3262                         component += (255-alpha)*png_sRGB_table[outrow[c]];
3263 
3264                         /* So 'component' is scaled by 255*65535 and is
3265                          * therefore appropriate for the sRGB to linear
3266                          * conversion table.
3267                          */
3268                         component = PNG_sRGB_FROM_LINEAR(component);
3269                      }
3270 
3271                      outrow[c] = (png_byte)component;
3272                   }
3273                }
3274 
3275                inrow += channels+1; /* components and alpha channel */
3276             }
3277          }
3278       }
3279    }
3280 
3281    return 1;
3282 }
3283 
3284 /* The do_local_background case; called when all the following transforms are to
3285  * be done:
3286  *
3287  * PNG_RGB_TO_GRAY
3288  * PNG_COMPOSITE
3289  * PNG_GAMMA
3290  *
3291  * This is a work-round for the fact that both the PNG_RGB_TO_GRAY and
3292  * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3293  * correction.  The fix-up is to prevent the PNG_COMPOSITE operation happening
3294  * inside libpng, so this routine sees an 8 or 16-bit gray+alpha row and handles
3295  * the removal or pre-multiplication of the alpha channel.
3296  */
3297 static int
png_image_read_background(png_voidp argument)3298 png_image_read_background(png_voidp argument)
3299 {
3300    png_image_read_control *display = png_voidcast(png_image_read_control*,
3301       argument);
3302    png_imagep image = display->image;
3303    png_structrp png_ptr = image->opaque->png_ptr;
3304    png_inforp info_ptr = image->opaque->info_ptr;
3305    png_uint_32 height = image->height;
3306    png_uint_32 width = image->width;
3307    int pass, passes;
3308 
3309    /* Double check the convoluted logic below.  We expect to get here with
3310     * libpng doing rgb to gray and gamma correction but background processing
3311     * left to the png_image_read_background function.  The rows libpng produce
3312     * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3313     */
3314    if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3315       png_error(png_ptr, "lost rgb to gray");
3316 
3317    if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3318       png_error(png_ptr, "unexpected compose");
3319 
3320    if (png_get_channels(png_ptr, info_ptr) != 2)
3321       png_error(png_ptr, "lost/gained channels");
3322 
3323    /* Expect the 8-bit case to always remove the alpha channel */
3324    if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3325       (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3326       png_error(png_ptr, "unexpected 8-bit transformation");
3327 
3328    switch (png_ptr->interlaced)
3329    {
3330       case PNG_INTERLACE_NONE:
3331          passes = 1;
3332          break;
3333 
3334       case PNG_INTERLACE_ADAM7:
3335          passes = PNG_INTERLACE_ADAM7_PASSES;
3336          break;
3337 
3338       default:
3339          png_error(png_ptr, "unknown interlace type");
3340    }
3341 
3342    /* Use direct access to info_ptr here because otherwise the simplified API
3343     * would require PNG_EASY_ACCESS_SUPPORTED (just for this.)  Note this is
3344     * checking the value after libpng expansions, not the original value in the
3345     * PNG.
3346     */
3347    switch (info_ptr->bit_depth)
3348    {
3349       default:
3350          png_error(png_ptr, "unexpected bit depth");
3351          break;
3352 
3353       case 8:
3354          /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3355           * to be removed by composing on a background: either the row if
3356           * display->background is NULL or display->background->green if not.
3357           * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3358           */
3359          {
3360             png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3361             ptrdiff_t step_row = display->row_bytes;
3362 
3363             for (pass = 0; pass < passes; ++pass)
3364             {
3365                png_bytep        row = png_voidcast(png_bytep,
3366                                                    display->first_row);
3367                unsigned int     startx, stepx, stepy;
3368                png_uint_32      y;
3369 
3370                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3371                {
3372                   /* The row may be empty for a short image: */
3373                   if (PNG_PASS_COLS(width, pass) == 0)
3374                      continue;
3375 
3376                   startx = PNG_PASS_START_COL(pass);
3377                   stepx = PNG_PASS_COL_OFFSET(pass);
3378                   y = PNG_PASS_START_ROW(pass);
3379                   stepy = PNG_PASS_ROW_OFFSET(pass);
3380                }
3381 
3382                else
3383                {
3384                   y = 0;
3385                   startx = 0;
3386                   stepx = stepy = 1;
3387                }
3388 
3389                if (display->background == NULL)
3390                {
3391                   for (; y<height; y += stepy)
3392                   {
3393                      png_bytep inrow = png_voidcast(png_bytep,
3394                         display->local_row);
3395                      png_bytep outrow = first_row + y * step_row;
3396                      png_const_bytep end_row = outrow + width;
3397 
3398                      /* Read the row, which is packed: */
3399                      png_read_row(png_ptr, inrow, NULL);
3400 
3401                      /* Now do the composition on each pixel in this row. */
3402                      outrow += startx;
3403                      for (; outrow < end_row; outrow += stepx)
3404                      {
3405                         png_byte alpha = inrow[1];
3406 
3407                         if (alpha > 0) /* else no change to the output */
3408                         {
3409                            png_uint_32 component = inrow[0];
3410 
3411                            if (alpha < 255) /* else just use component */
3412                            {
3413                               /* Since PNG_OPTIMIZED_ALPHA was not set it is
3414                                * necessary to invert the sRGB transfer
3415                                * function and multiply the alpha out.
3416                                */
3417                               component = png_sRGB_table[component] * alpha;
3418                               component += png_sRGB_table[outrow[0]] *
3419                                  (255-alpha);
3420                               component = PNG_sRGB_FROM_LINEAR(component);
3421                            }
3422 
3423                            outrow[0] = (png_byte)component;
3424                         }
3425 
3426                         inrow += 2; /* gray and alpha channel */
3427                      }
3428                   }
3429                }
3430 
3431                else /* constant background value */
3432                {
3433                   png_byte background8 = display->background->green;
3434                   png_uint_16 background = png_sRGB_table[background8];
3435 
3436                   for (; y<height; y += stepy)
3437                   {
3438                      png_bytep inrow = png_voidcast(png_bytep,
3439                         display->local_row);
3440                      png_bytep outrow = first_row + y * step_row;
3441                      png_const_bytep end_row = outrow + width;
3442 
3443                      /* Read the row, which is packed: */
3444                      png_read_row(png_ptr, inrow, NULL);
3445 
3446                      /* Now do the composition on each pixel in this row. */
3447                      outrow += startx;
3448                      for (; outrow < end_row; outrow += stepx)
3449                      {
3450                         png_byte alpha = inrow[1];
3451 
3452                         if (alpha > 0) /* else use background */
3453                         {
3454                            png_uint_32 component = inrow[0];
3455 
3456                            if (alpha < 255) /* else just use component */
3457                            {
3458                               component = png_sRGB_table[component] * alpha;
3459                               component += background * (255-alpha);
3460                               component = PNG_sRGB_FROM_LINEAR(component);
3461                            }
3462 
3463                            outrow[0] = (png_byte)component;
3464                         }
3465 
3466                         else
3467                            outrow[0] = background8;
3468 
3469                         inrow += 2; /* gray and alpha channel */
3470                      }
3471 
3472                      row += display->row_bytes;
3473                   }
3474                }
3475             }
3476          }
3477          break;
3478 
3479       case 16:
3480          /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3481           * still be done and, maybe, the alpha channel removed.  This code also
3482           * handles the alpha-first option.
3483           */
3484          {
3485             png_uint_16p first_row = png_voidcast(png_uint_16p,
3486                display->first_row);
3487             /* The division by two is safe because the caller passed in a
3488              * stride which was multiplied by 2 (below) to get row_bytes.
3489              */
3490             ptrdiff_t    step_row = display->row_bytes / 2;
3491             int preserve_alpha = (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
3492             unsigned int outchannels = 1+preserve_alpha;
3493             int swap_alpha = 0;
3494 
3495 #           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3496                if (preserve_alpha && (image->format & PNG_FORMAT_FLAG_AFIRST))
3497                   swap_alpha = 1;
3498 #           endif
3499 
3500             for (pass = 0; pass < passes; ++pass)
3501             {
3502                unsigned int     startx, stepx, stepy;
3503                png_uint_32      y;
3504 
3505                /* The 'x' start and step are adjusted to output components here.
3506                 */
3507                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3508                {
3509                   /* The row may be empty for a short image: */
3510                   if (PNG_PASS_COLS(width, pass) == 0)
3511                      continue;
3512 
3513                   startx = PNG_PASS_START_COL(pass) * outchannels;
3514                   stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3515                   y = PNG_PASS_START_ROW(pass);
3516                   stepy = PNG_PASS_ROW_OFFSET(pass);
3517                }
3518 
3519                else
3520                {
3521                   y = 0;
3522                   startx = 0;
3523                   stepx = outchannels;
3524                   stepy = 1;
3525                }
3526 
3527                for (; y<height; y += stepy)
3528                {
3529                   png_const_uint_16p inrow;
3530                   png_uint_16p outrow = first_row + y*step_row;
3531                   png_uint_16p end_row = outrow + width * outchannels;
3532 
3533                   /* Read the row, which is packed: */
3534                   png_read_row(png_ptr, png_voidcast(png_bytep,
3535                      display->local_row), NULL);
3536                   inrow = png_voidcast(png_const_uint_16p, display->local_row);
3537 
3538                   /* Now do the pre-multiplication on each pixel in this row.
3539                    */
3540                   outrow += startx;
3541                   for (; outrow < end_row; outrow += stepx)
3542                   {
3543                      png_uint_32 component = inrow[0];
3544                      png_uint_16 alpha = inrow[1];
3545 
3546                      if (alpha > 0) /* else 0 */
3547                      {
3548                         if (alpha < 65535) /* else just use component */
3549                         {
3550                            component *= alpha;
3551                            component += 32767;
3552                            component /= 65535;
3553                         }
3554                      }
3555 
3556                      else
3557                         component = 0;
3558 
3559                      outrow[swap_alpha] = (png_uint_16)component;
3560                      if (preserve_alpha)
3561                         outrow[1 ^ swap_alpha] = alpha;
3562 
3563                      inrow += 2; /* components and alpha channel */
3564                   }
3565                }
3566             }
3567          }
3568          break;
3569    }
3570 
3571    return 1;
3572 }
3573 
3574 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3575 static int
png_image_read_direct(png_voidp argument)3576 png_image_read_direct(png_voidp argument)
3577 {
3578    png_image_read_control *display = png_voidcast(png_image_read_control*,
3579       argument);
3580    png_imagep image = display->image;
3581    png_structrp png_ptr = image->opaque->png_ptr;
3582    png_inforp info_ptr = image->opaque->info_ptr;
3583 
3584    png_uint_32 format = image->format;
3585    int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3586    int do_local_compose = 0;
3587    int do_local_background = 0; /* to avoid double gamma correction bug */
3588    int passes = 0;
3589 
3590    /* Add transforms to ensure the correct output format is produced then check
3591     * that the required implementation support is there.  Always expand; always
3592     * need 8 bits minimum, no palette and expanded tRNS.
3593     */
3594    png_set_expand(png_ptr);
3595 
3596    /* Now check the format to see if it was modified. */
3597    {
3598       png_uint_32 base_format = png_image_format(png_ptr) &
3599          ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3600       png_uint_32 change = format ^ base_format;
3601       png_fixed_point output_gamma;
3602       int mode; /* alpha mode */
3603 
3604       /* Do this first so that we have a record if rgb to gray is happening. */
3605       if (change & PNG_FORMAT_FLAG_COLOR)
3606       {
3607          /* gray<->color transformation required. */
3608          if (format & PNG_FORMAT_FLAG_COLOR)
3609             png_set_gray_to_rgb(png_ptr);
3610 
3611          else
3612          {
3613             /* libpng can't do both rgb to gray and
3614              * background/pre-multiplication if there is also significant gamma
3615              * correction, because both operations require linear colors and
3616              * the code only supports one transform doing the gamma correction.
3617              * Handle this by doing the pre-multiplication or background
3618              * operation in this code, if necessary.
3619              *
3620              * TODO: fix this by rewriting pngrtran.c (!)
3621              *
3622              * For the moment (given that fixing this in pngrtran.c is an
3623              * enormous change) 'do_local_background' is used to indicate that
3624              * the problem exists.
3625              */
3626             if (base_format & PNG_FORMAT_FLAG_ALPHA)
3627                do_local_background = 1/*maybe*/;
3628 
3629             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3630                PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3631          }
3632 
3633          change &= ~PNG_FORMAT_FLAG_COLOR;
3634       }
3635 
3636       /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3637        */
3638       {
3639          png_fixed_point input_gamma_default;
3640 
3641          if ((base_format & PNG_FORMAT_FLAG_LINEAR) &&
3642             (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3643             input_gamma_default = PNG_GAMMA_LINEAR;
3644          else
3645             input_gamma_default = PNG_DEFAULT_sRGB;
3646 
3647          /* Call png_set_alpha_mode to set the default for the input gamma; the
3648           * output gamma is set by a second call below.
3649           */
3650          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3651       }
3652 
3653       if (linear)
3654       {
3655          /* If there *is* an alpha channel in the input it must be multiplied
3656           * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3657           */
3658          if (base_format & PNG_FORMAT_FLAG_ALPHA)
3659             mode = PNG_ALPHA_STANDARD; /* associated alpha */
3660 
3661          else
3662             mode = PNG_ALPHA_PNG;
3663 
3664          output_gamma = PNG_GAMMA_LINEAR;
3665       }
3666 
3667       else
3668       {
3669          mode = PNG_ALPHA_PNG;
3670          output_gamma = PNG_DEFAULT_sRGB;
3671       }
3672 
3673       /* If 'do_local_background' is set check for the presence of gamma
3674        * correction; this is part of the work-round for the libpng bug
3675        * described above.
3676        *
3677        * TODO: fix libpng and remove this.
3678        */
3679       if (do_local_background)
3680       {
3681          png_fixed_point gtest;
3682 
3683          /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3684           * gamma correction, the screen gamma hasn't been set on png_struct
3685           * yet; it's set below.  png_struct::gamma, however, is set to the
3686           * final value.
3687           */
3688          if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma,
3689                PNG_FP_1) && !png_gamma_significant(gtest))
3690             do_local_background = 0;
3691 
3692          else if (mode == PNG_ALPHA_STANDARD)
3693          {
3694             do_local_background = 2/*required*/;
3695             mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3696          }
3697 
3698          /* else leave as 1 for the checks below */
3699       }
3700 
3701       /* If the bit-depth changes then handle that here. */
3702       if (change & PNG_FORMAT_FLAG_LINEAR)
3703       {
3704          if (linear /*16-bit output*/)
3705             png_set_expand_16(png_ptr);
3706 
3707          else /* 8-bit output */
3708             png_set_scale_16(png_ptr);
3709 
3710          change &= ~PNG_FORMAT_FLAG_LINEAR;
3711       }
3712 
3713       /* Now the background/alpha channel changes. */
3714       if (change & PNG_FORMAT_FLAG_ALPHA)
3715       {
3716          /* Removing an alpha channel requires composition for the 8-bit
3717           * formats; for the 16-bit it is already done, above, by the
3718           * pre-multiplication and the channel just needs to be stripped.
3719           */
3720          if (base_format & PNG_FORMAT_FLAG_ALPHA)
3721          {
3722             /* If RGB->gray is happening the alpha channel must be left and the
3723              * operation completed locally.
3724              *
3725              * TODO: fix libpng and remove this.
3726              */
3727             if (do_local_background)
3728                do_local_background = 2/*required*/;
3729 
3730             /* 16-bit output: just remove the channel */
3731             else if (linear) /* compose on black (well, pre-multiply) */
3732                png_set_strip_alpha(png_ptr);
3733 
3734             /* 8-bit output: do an appropriate compose */
3735             else if (display->background != NULL)
3736             {
3737                png_color_16 c;
3738 
3739                c.index = 0; /*unused*/
3740                c.red = display->background->red;
3741                c.green = display->background->green;
3742                c.blue = display->background->blue;
3743                c.gray = display->background->green;
3744 
3745                /* This is always an 8-bit sRGB value, using the 'green' channel
3746                 * for gray is much better than calculating the luminance here;
3747                 * we can get off-by-one errors in that calculation relative to
3748                 * the app expectations and that will show up in transparent
3749                 * pixels.
3750                 */
3751                png_set_background_fixed(png_ptr, &c,
3752                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3753                   0/*gamma: not used*/);
3754             }
3755 
3756             else /* compose on row: implemented below. */
3757             {
3758                do_local_compose = 1;
3759                /* This leaves the alpha channel in the output, so it has to be
3760                 * removed by the code below.  Set the encoding to the 'OPTIMIZE'
3761                 * one so the code only has to hack on the pixels that require
3762                 * composition.
3763                 */
3764                mode = PNG_ALPHA_OPTIMIZED;
3765             }
3766          }
3767 
3768          else /* output needs an alpha channel */
3769          {
3770             /* This is tricky because it happens before the swap operation has
3771              * been accomplished; however, the swap does *not* swap the added
3772              * alpha channel (weird API), so it must be added in the correct
3773              * place.
3774              */
3775             png_uint_32 filler; /* opaque filler */
3776             int where;
3777 
3778             if (linear)
3779                filler = 65535;
3780 
3781             else
3782                filler = 255;
3783 
3784 #           ifdef PNG_FORMAT_AFIRST_SUPPORTED
3785                if (format & PNG_FORMAT_FLAG_AFIRST)
3786                {
3787                   where = PNG_FILLER_BEFORE;
3788                   change &= ~PNG_FORMAT_FLAG_AFIRST;
3789                }
3790 
3791                else
3792 #           endif
3793                where = PNG_FILLER_AFTER;
3794 
3795             png_set_add_alpha(png_ptr, filler, where);
3796          }
3797 
3798          /* This stops the (irrelevant) call to swap_alpha below. */
3799          change &= ~PNG_FORMAT_FLAG_ALPHA;
3800       }
3801 
3802       /* Now set the alpha mode correctly; this is always done, even if there is
3803        * no alpha channel in either the input or the output because it correctly
3804        * sets the output gamma.
3805        */
3806       png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3807 
3808 #     ifdef PNG_FORMAT_BGR_SUPPORTED
3809          if (change & PNG_FORMAT_FLAG_BGR)
3810          {
3811             /* Check only the output format; PNG is never BGR; don't do this if
3812              * the output is gray, but fix up the 'format' value in that case.
3813              */
3814             if (format & PNG_FORMAT_FLAG_COLOR)
3815                png_set_bgr(png_ptr);
3816 
3817             else
3818                format &= ~PNG_FORMAT_FLAG_BGR;
3819 
3820             change &= ~PNG_FORMAT_FLAG_BGR;
3821          }
3822 #     endif
3823 
3824 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
3825          if (change & PNG_FORMAT_FLAG_AFIRST)
3826          {
3827             /* Only relevant if there is an alpha channel - it's particularly
3828              * important to handle this correctly because do_local_compose may
3829              * be set above and then libpng will keep the alpha channel for this
3830              * code to remove.
3831              */
3832             if (format & PNG_FORMAT_FLAG_ALPHA)
3833             {
3834                /* Disable this if doing a local background,
3835                 * TODO: remove this when local background is no longer required.
3836                 */
3837                if (do_local_background != 2)
3838                   png_set_swap_alpha(png_ptr);
3839             }
3840 
3841             else
3842                format &= ~PNG_FORMAT_FLAG_AFIRST;
3843 
3844             change &= ~PNG_FORMAT_FLAG_AFIRST;
3845          }
3846 #     endif
3847 
3848       /* If the *output* is 16-bit then we need to check for a byte-swap on this
3849        * architecture.
3850        */
3851       if (linear)
3852       {
3853          PNG_CONST png_uint_16 le = 0x0001;
3854 
3855          if (*(png_const_bytep)&le)
3856             png_set_swap(png_ptr);
3857       }
3858 
3859       /* If change is not now 0 some transformation is missing - error out. */
3860       if (change)
3861          png_error(png_ptr, "png_read_image: unsupported transformation");
3862    }
3863 
3864    PNG_SKIP_CHUNKS(png_ptr);
3865 
3866    /* Update the 'info' structure and make sure the result is as required; first
3867     * make sure to turn on the interlace handling if it will be required
3868     * (because it can't be turned on *after* the call to png_read_update_info!)
3869     *
3870     * TODO: remove the do_local_background fixup below.
3871     */
3872    if (!do_local_compose && do_local_background != 2)
3873       passes = png_set_interlace_handling(png_ptr);
3874 
3875    png_read_update_info(png_ptr, info_ptr);
3876 
3877    {
3878       png_uint_32 info_format = 0;
3879 
3880       if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
3881          info_format |= PNG_FORMAT_FLAG_COLOR;
3882 
3883       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
3884       {
3885          /* do_local_compose removes this channel below. */
3886          if (!do_local_compose)
3887          {
3888             /* do_local_background does the same if required. */
3889             if (do_local_background != 2 ||
3890                (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3891                info_format |= PNG_FORMAT_FLAG_ALPHA;
3892          }
3893       }
3894 
3895       else if (do_local_compose) /* internal error */
3896          png_error(png_ptr, "png_image_read: alpha channel lost");
3897 
3898       if (info_ptr->bit_depth == 16)
3899          info_format |= PNG_FORMAT_FLAG_LINEAR;
3900 
3901 #     ifdef PNG_FORMAT_BGR_SUPPORTED
3902          if (png_ptr->transformations & PNG_BGR)
3903             info_format |= PNG_FORMAT_FLAG_BGR;
3904 #     endif
3905 
3906 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
3907          if (do_local_background == 2)
3908          {
3909             if (format & PNG_FORMAT_FLAG_AFIRST)
3910                info_format |= PNG_FORMAT_FLAG_AFIRST;
3911          }
3912 
3913          if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
3914             ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
3915             (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
3916          {
3917             if (do_local_background == 2)
3918                png_error(png_ptr, "unexpected alpha swap transformation");
3919 
3920             info_format |= PNG_FORMAT_FLAG_AFIRST;
3921          }
3922 #     endif
3923 
3924       /* This is actually an internal error. */
3925       if (info_format != format)
3926          png_error(png_ptr, "png_read_image: invalid transformations");
3927    }
3928 
3929    /* Now read the rows.  If do_local_compose is set then it is necessary to use
3930     * a local row buffer.  The output will be GA, RGBA or BGRA and must be
3931     * converted to G, RGB or BGR as appropriate.  The 'local_row' member of the
3932     * display acts as a flag.
3933     */
3934    {
3935       png_voidp first_row = display->buffer;
3936       ptrdiff_t row_bytes = display->row_stride;
3937 
3938       if (linear)
3939          row_bytes *= 2;
3940 
3941       /* The following expression is designed to work correctly whether it gives
3942        * a signed or an unsigned result.
3943        */
3944       if (row_bytes < 0)
3945       {
3946          char *ptr = png_voidcast(char*, first_row);
3947          ptr += (image->height-1) * (-row_bytes);
3948          first_row = png_voidcast(png_voidp, ptr);
3949       }
3950 
3951       display->first_row = first_row;
3952       display->row_bytes = row_bytes;
3953    }
3954 
3955    if (do_local_compose)
3956    {
3957       int result;
3958       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3959 
3960       display->local_row = row;
3961       result = png_safe_execute(image, png_image_read_composite, display);
3962       display->local_row = NULL;
3963       png_free(png_ptr, row);
3964 
3965       return result;
3966    }
3967 
3968    else if (do_local_background == 2)
3969    {
3970       int result;
3971       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3972 
3973       display->local_row = row;
3974       result = png_safe_execute(image, png_image_read_background, display);
3975       display->local_row = NULL;
3976       png_free(png_ptr, row);
3977 
3978       return result;
3979    }
3980 
3981    else
3982    {
3983       png_alloc_size_t row_bytes = display->row_bytes;
3984 
3985       while (--passes >= 0)
3986       {
3987          png_uint_32      y = image->height;
3988          png_bytep        row = png_voidcast(png_bytep, display->first_row);
3989 
3990          while (y-- > 0)
3991          {
3992             png_read_row(png_ptr, row, NULL);
3993             row += row_bytes;
3994          }
3995       }
3996 
3997       return 1;
3998    }
3999 }
4000 
4001 int PNGAPI
png_image_finish_read(png_imagep image,png_const_colorp background,void * buffer,png_int_32 row_stride,void * colormap)4002 png_image_finish_read(png_imagep image, png_const_colorp background,
4003    void *buffer, png_int_32 row_stride, void *colormap)
4004 {
4005    if (image != NULL && image->version == PNG_IMAGE_VERSION)
4006    {
4007       png_uint_32 check;
4008 
4009       if (row_stride == 0)
4010          row_stride = PNG_IMAGE_ROW_STRIDE(*image);
4011 
4012       if (row_stride < 0)
4013          check = -row_stride;
4014 
4015       else
4016          check = row_stride;
4017 
4018       if (image->opaque != NULL && buffer != NULL &&
4019          check >= PNG_IMAGE_ROW_STRIDE(*image))
4020       {
4021          if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4022             (image->colormap_entries > 0 && colormap != NULL))
4023          {
4024             int result;
4025             png_image_read_control display;
4026 
4027             memset(&display, 0, (sizeof display));
4028             display.image = image;
4029             display.buffer = buffer;
4030             display.row_stride = row_stride;
4031             display.colormap = colormap;
4032             display.background = background;
4033             display.local_row = NULL;
4034 
4035             /* Choose the correct 'end' routine; for the color-map case all the
4036              * setup has already been done.
4037              */
4038             if (image->format & PNG_FORMAT_FLAG_COLORMAP)
4039                result =
4040                   png_safe_execute(image, png_image_read_colormap, &display) &&
4041                   png_safe_execute(image, png_image_read_colormapped, &display);
4042 
4043             else
4044                result =
4045                   png_safe_execute(image, png_image_read_direct, &display);
4046 
4047             png_image_free(image);
4048             return result;
4049          }
4050 
4051          else
4052             return png_image_error(image,
4053                "png_image_finish_read[color-map]: no color-map");
4054       }
4055 
4056       else
4057          return png_image_error(image,
4058             "png_image_finish_read: invalid argument");
4059    }
4060 
4061    else if (image != NULL)
4062       return png_image_error(image,
4063          "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4064 
4065    return 0;
4066 }
4067 
4068 #endif /* PNG_SIMPLIFIED_READ_SUPPORTED */
4069 #endif /* PNG_READ_SUPPORTED */
4070