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