~random-stuff/libpng/libpng-1.6.x

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