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