Coverage Report

Created: 2025-07-23 06:34

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