Coverage Report

Created: 2026-06-30 06:15

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