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