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