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