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