Coverage Report

Created: 2025-02-15 06:13

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