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