Coverage Report

Created: 2026-08-14 07:18

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
54.6k
{
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
54.6k
   return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
34
54.6k
        warn_fn, NULL, NULL, NULL);
35
54.6k
}
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
54.6k
{
46
54.6k
   png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
47
54.6k
       error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
48
54.6k
#endif /* USER_MEM */
49
50
54.6k
   if (png_ptr != NULL)
51
54.6k
   {
52
54.6k
      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
54.6k
#     ifdef PNG_SEQUENTIAL_READ_SUPPORTED
58
54.6k
         png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
59
54.6k
#     endif
60
61
54.6k
#     ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
62
54.6k
         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
54.6k
#     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
54.6k
      png_set_read_fn(png_ptr, NULL, NULL);
77
54.6k
   }
78
79
54.6k
   return png_ptr;
80
54.6k
}
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
54.6k
{
95
54.6k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
96
54.6k
   int keep;
97
54.6k
#endif
98
99
54.6k
   png_debug(1, "in png_read_info");
100
101
54.6k
   if (png_ptr == NULL || info_ptr == NULL)
102
0
      return;
103
104
   /* Read and check the PNG file signature. */
105
54.6k
   png_read_sig(png_ptr, info_ptr);
106
107
54.6k
   for (;;)
108
408k
   {
109
408k
      png_uint_32 length = png_read_chunk_header(png_ptr);
110
408k
      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
408k
      if (chunk_name == png_IDAT)
116
28.8k
      {
117
28.8k
         if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
118
4
            png_chunk_error(png_ptr, "Missing IHDR before IDAT");
119
120
28.8k
         else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
121
2.32k
             (png_ptr->mode & PNG_HAVE_PLTE) == 0)
122
6
            png_chunk_error(png_ptr, "Missing PLTE before IDAT");
123
124
28.8k
         else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
125
0
            png_chunk_benign_error(png_ptr, "Too many IDATs found");
126
127
28.8k
         png_ptr->mode |= PNG_HAVE_IDAT;
128
28.8k
      }
129
130
379k
      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
408k
      if (chunk_name == png_IHDR)
137
52.8k
         png_handle_chunk(png_ptr, info_ptr, length);
138
139
355k
      else if (chunk_name == png_IEND)
140
9.98k
         png_handle_chunk(png_ptr, info_ptr, length);
141
142
345k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
143
345k
      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
345k
#endif
157
158
345k
      else if (chunk_name == png_IDAT)
159
28.8k
      {
160
28.8k
         png_ptr->idat_size = length;
161
28.8k
         break;
162
28.8k
      }
163
164
316k
      else
165
316k
         png_handle_chunk(png_ptr, info_ptr, length);
166
408k
   }
167
54.6k
}
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
28.7k
{
174
28.7k
   png_debug(1, "in png_read_update_info");
175
176
28.7k
   if (png_ptr != NULL)
177
28.7k
   {
178
28.7k
      if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
179
28.7k
      {
180
28.7k
         png_read_start_row(png_ptr);
181
182
28.7k
#        ifdef PNG_READ_TRANSFORMS_SUPPORTED
183
28.7k
            png_read_transform_info(png_ptr, info_ptr);
184
#        else
185
            PNG_UNUSED(info_ptr)
186
#        endif
187
28.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
28.7k
   }
194
28.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
3.42M
{
290
3.42M
   png_row_info row_info;
291
292
3.42M
   if (png_ptr == NULL)
293
0
      return;
294
295
3.42M
   png_debug2(1, "in png_read_row (row %lu, pass %d)",
296
3.42M
       (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
3.42M
   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
3.42M
   row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
306
3.42M
   row_info.color_type = png_ptr->color_type;
307
3.42M
   row_info.bit_depth = png_ptr->bit_depth;
308
3.42M
   row_info.channels = png_ptr->channels;
309
3.42M
   row_info.pixel_depth = png_ptr->pixel_depth;
310
3.42M
   row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
311
312
3.42M
#ifdef PNG_WARNINGS_SUPPORTED
313
3.42M
   if (png_ptr->row_number == 0 && png_ptr->pass == 0)
314
28.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
28.7k
   }
352
3.42M
#endif /* WARNINGS */
353
354
3.42M
#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
3.42M
   if (png_ptr->interlaced != 0 &&
362
3.27M
       (png_ptr->transformations & PNG_INTERLACE) != 0)
363
3.27M
   {
364
3.27M
      switch (png_ptr->pass)
365
3.27M
      {
366
655k
         case 0:
367
655k
            if (png_ptr->row_number & 0x07)
368
561k
            {
369
561k
               if (dsp_row != NULL)
370
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
371
561k
               png_read_finish_row(png_ptr);
372
561k
               return;
373
561k
            }
374
94.0k
            break;
375
376
516k
         case 1:
377
516k
            if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
378
502k
            {
379
502k
               if (dsp_row != NULL)
380
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
381
382
502k
               png_read_finish_row(png_ptr);
383
502k
               return;
384
502k
            }
385
13.4k
            break;
386
387
459k
         case 2:
388
459k
            if ((png_ptr->row_number & 0x07) != 4)
389
403k
            {
390
403k
               if (dsp_row != NULL && (png_ptr->row_number & 4))
391
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
392
393
403k
               png_read_finish_row(png_ptr);
394
403k
               return;
395
403k
            }
396
56.1k
            break;
397
398
436k
         case 3:
399
436k
            if ((png_ptr->row_number & 3) || png_ptr->width < 3)
400
418k
            {
401
418k
               if (dsp_row != NULL)
402
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
403
404
418k
               png_read_finish_row(png_ptr);
405
418k
               return;
406
418k
            }
407
18.0k
            break;
408
409
410k
         case 4:
410
410k
            if ((png_ptr->row_number & 3) != 2)
411
309k
            {
412
309k
               if (dsp_row != NULL && (png_ptr->row_number & 2))
413
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
414
415
309k
               png_read_finish_row(png_ptr);
416
309k
               return;
417
309k
            }
418
100k
            break;
419
420
399k
         case 5:
421
399k
            if ((png_ptr->row_number & 1) || png_ptr->width < 2)
422
371k
            {
423
371k
               if (dsp_row != NULL)
424
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
425
426
371k
               png_read_finish_row(png_ptr);
427
371k
               return;
428
371k
            }
429
28.1k
            break;
430
431
28.1k
         default:
432
394k
         case 6:
433
394k
            if ((png_ptr->row_number & 1) == 0)
434
202k
            {
435
202k
               png_read_finish_row(png_ptr);
436
202k
               return;
437
202k
            }
438
192k
            break;
439
3.27M
      }
440
3.27M
   }
441
652k
#endif
442
443
652k
   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
652k
   png_ptr->row_buf[0]=255; /* to force error if no data was found */
448
652k
   png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
449
450
652k
   if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
451
299k
   {
452
299k
      if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
453
299k
         png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
454
299k
             png_ptr->prev_row + 1, png_ptr->row_buf[0]);
455
358
      else
456
358
         png_error(png_ptr, "bad adaptive filter value");
457
299k
   }
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
652k
   memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
465
466
652k
#ifdef PNG_MNG_FEATURES_SUPPORTED
467
652k
   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
652k
#endif
474
475
652k
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
476
652k
   if (png_ptr->transformations
477
1.46k
#     ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
478
1.46k
         || png_ptr->num_palette_max >= 0
479
652k
#     endif
480
652k
      )
481
643k
      png_do_read_transformations(png_ptr, &row_info);
482
652k
#endif
483
484
   /* The transformed pixel depth should match the depth now in row_info. */
485
652k
   if (png_ptr->transformed_pixel_depth == 0)
486
23.4k
   {
487
23.4k
      png_ptr->transformed_pixel_depth = row_info.pixel_depth;
488
23.4k
      if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
489
0
         png_error(png_ptr, "sequential row overflow");
490
23.4k
   }
491
492
629k
   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
652k
#ifdef PNG_READ_INTERLACING_SUPPORTED
496
   /* Expand interlaced rows to full size */
497
652k
   if (png_ptr->interlaced != 0 &&
498
500k
      (png_ptr->transformations & PNG_INTERLACE) != 0)
499
497k
   {
500
497k
      if (png_ptr->pass < 6)
501
305k
         png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
502
305k
             png_ptr->transformations);
503
504
497k
      if (dsp_row != NULL)
505
0
         png_combine_row(png_ptr, dsp_row, 1/*display*/);
506
507
497k
      if (row != NULL)
508
497k
         png_combine_row(png_ptr, row, 0/*row*/);
509
497k
   }
510
511
154k
   else
512
154k
#endif
513
154k
   {
514
154k
      if (row != NULL)
515
145k
         png_combine_row(png_ptr, row, -1/*ignored*/);
516
517
154k
      if (dsp_row != NULL)
518
0
         png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
519
154k
   }
520
652k
   png_read_finish_row(png_ptr);
521
522
652k
   if (png_ptr->read_row_fn != NULL)
523
0
      (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
524
652k
}
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.26k
          (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.7k
   for (j = 0; j < pass; j++)
657
7.49k
   {
658
7.49k
      rp = image;
659
202k
      for (i = 0; i < image_height; i++)
660
194k
      {
661
194k
         png_read_row(png_ptr, *rp, NULL);
662
194k
         rp++;
663
194k
      }
664
7.49k
   }
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
8.94k
{
676
8.94k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
677
8.94k
   int keep;
678
8.94k
#endif
679
680
8.94k
   png_debug(1, "in png_read_end");
681
682
8.94k
   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
8.94k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
689
8.94k
   if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
690
8.94k
#endif
691
8.94k
      png_read_finish_IDAT(png_ptr);
692
693
8.94k
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
694
   /* Report invalid palette index; added at libpng-1.5.10 */
695
8.94k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
696
437
       png_ptr->num_palette_max >= png_ptr->num_palette)
697
1
      png_benign_error(png_ptr, "Read palette index exceeding num_palette");
698
8.94k
#endif
699
700
8.94k
   do
701
14.5k
   {
702
14.5k
      png_uint_32 length = png_read_chunk_header(png_ptr);
703
14.5k
      png_uint_32 chunk_name = png_ptr->chunk_name;
704
705
14.5k
      if (chunk_name != png_IDAT)
706
11.8k
      {
707
         /* These flags must be set consistently for all non-IDAT chunks,
708
          * including the unknown chunks.
709
          */
710
11.8k
         png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT | PNG_AFTER_IDAT;
711
11.8k
      }
712
713
14.5k
      if (chunk_name == png_IEND)
714
8.72k
         png_handle_chunk(png_ptr, info_ptr, length);
715
716
5.82k
      else if (chunk_name == png_IHDR)
717
4
         png_handle_chunk(png_ptr, info_ptr, length);
718
719
5.81k
      else if (info_ptr == NULL)
720
0
         png_crc_finish(png_ptr, length);
721
722
5.81k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
723
5.81k
      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
5.81k
#endif
736
737
5.81k
      else if (chunk_name == png_IDAT)
738
2.65k
      {
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
2.65k
         if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
746
2.65k
             || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
747
877
            png_benign_error(png_ptr, "..Too many IDATs found");
748
749
2.65k
         png_crc_finish(png_ptr, length);
750
2.65k
      }
751
752
3.16k
      else
753
3.16k
         png_handle_chunk(png_ptr, info_ptr, length);
754
14.5k
   } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
755
8.94k
}
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
54.6k
{
762
54.6k
   png_debug(1, "in png_read_destroy");
763
764
54.6k
#ifdef PNG_READ_GAMMA_SUPPORTED
765
54.6k
   png_destroy_gamma_table(png_ptr);
766
54.6k
#endif
767
768
54.6k
   png_free(png_ptr, png_ptr->big_row_buf);
769
54.6k
   png_ptr->big_row_buf = NULL;
770
54.6k
   png_free(png_ptr, png_ptr->big_prev_row);
771
54.6k
   png_ptr->big_prev_row = NULL;
772
54.6k
   png_free(png_ptr, png_ptr->read_buffer);
773
54.6k
   png_ptr->read_buffer = NULL;
774
775
54.6k
#ifdef PNG_READ_QUANTIZE_SUPPORTED
776
54.6k
   png_free(png_ptr, png_ptr->palette_lookup);
777
54.6k
   png_ptr->palette_lookup = NULL;
778
54.6k
   png_free(png_ptr, png_ptr->quantize_index);
779
54.6k
   png_ptr->quantize_index = NULL;
780
54.6k
#endif
781
782
   /* png_ptr->palette is always independently allocated (not aliased
783
    * with info_ptr->palette), so free it unconditionally.
784
    */
785
54.6k
   png_free(png_ptr, png_ptr->palette);
786
54.6k
   png_ptr->palette = NULL;
787
788
54.6k
#if defined(PNG_tRNS_SUPPORTED) || \
789
54.6k
    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
54.6k
   png_free(png_ptr, png_ptr->trans_alpha);
794
54.6k
   png_ptr->trans_alpha = NULL;
795
54.6k
#endif
796
797
54.6k
   inflateEnd(&png_ptr->zstream);
798
799
54.6k
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
800
54.6k
   png_free(png_ptr, png_ptr->save_buffer);
801
54.6k
   png_ptr->save_buffer = NULL;
802
54.6k
#endif
803
804
54.6k
#if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
805
54.6k
   defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
806
54.6k
   png_free(png_ptr, png_ptr->unknown_chunk.data);
807
54.6k
   png_ptr->unknown_chunk.data = NULL;
808
54.6k
#endif
809
810
54.6k
#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
811
54.6k
   png_free(png_ptr, png_ptr->chunk_list);
812
54.6k
   png_ptr->chunk_list = NULL;
813
54.6k
#endif
814
815
54.6k
#if defined(PNG_READ_EXPAND_SUPPORTED) && \
816
54.6k
    (defined(PNG_ARM_NEON_IMPLEMENTATION) || \
817
54.6k
     defined(PNG_RISCV_RVV_IMPLEMENTATION))
818
54.6k
   png_free(png_ptr, png_ptr->riffled_palette);
819
54.6k
   png_ptr->riffled_palette = NULL;
820
54.6k
#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
54.6k
}
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
80.8k
{
833
80.8k
   png_structrp png_ptr = NULL;
834
835
80.8k
   png_debug(1, "in png_destroy_read_struct");
836
837
80.8k
   if (png_ptr_ptr != NULL)
838
80.8k
      png_ptr = *png_ptr_ptr;
839
840
80.8k
   if (png_ptr == NULL)
841
26.2k
      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
54.6k
   png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
848
54.6k
   png_destroy_info_struct(png_ptr, info_ptr_ptr);
849
850
54.6k
   *png_ptr_ptr = NULL;
851
54.6k
   png_read_destroy(png_ptr);
852
54.6k
   png_destroy_png_struct(png_ptr);
853
54.6k
}
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.90k
{
871
9.90k
   png_debug(1, "in png_read_png");
872
873
9.90k
   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.90k
   png_read_info(png_ptr, info_ptr);
880
9.90k
   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.90k
   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.58k
#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
897
2.58k
      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.90k
   if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
907
2.61k
#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
908
2.61k
      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.90k
   if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
917
2.45k
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
918
2.45k
      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.90k
   if ((transforms & PNG_TRANSFORM_PACKING) != 0)
927
2.54k
#ifdef PNG_READ_PACK_SUPPORTED
928
2.54k
      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.90k
   if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
937
3.04k
#ifdef PNG_READ_PACKSWAP_SUPPORTED
938
3.04k
      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.90k
   if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
949
2.38k
#ifdef PNG_READ_EXPAND_SUPPORTED
950
2.38k
      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.90k
   if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
961
2.86k
#ifdef PNG_READ_INVERT_SUPPORTED
962
2.86k
      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.90k
   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
135
         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.90k
   if ((transforms & PNG_TRANSFORM_BGR) != 0)
981
2.62k
#ifdef PNG_READ_BGR_SUPPORTED
982
2.62k
      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.90k
   if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
989
2.86k
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
990
2.86k
      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.90k
   if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
997
2.99k
#ifdef PNG_READ_SWAP_SUPPORTED
998
2.99k
      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.90k
   if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1006
2.99k
#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1007
2.99k
      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.90k
   if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1015
2.54k
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1016
2.54k
      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.90k
   if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1023
2.53k
#ifdef PNG_READ_EXPAND_16_SUPPORTED
1024
2.53k
      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.90k
   (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.90k
   png_read_update_info(png_ptr, info_ptr);
1041
1042
   /* -------------- image transformations end here ------------------- */
1043
1044
9.90k
   png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1045
9.90k
   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
592k
      for (iptr=0; iptr<info_ptr->height; iptr++)
1053
588k
         info_ptr->row_pointers[iptr] = NULL;
1054
1055
4.20k
      info_ptr->free_me |= PNG_FREE_ROWS;
1056
1057
592k
      for (iptr = 0; iptr < info_ptr->height; iptr++)
1058
588k
         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.90k
   png_read_image(png_ptr, info_ptr->row_pointers);
1063
9.90k
   info_ptr->valid |= PNG_INFO_IDAT;
1064
1065
   /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1066
9.90k
   png_read_end(png_ptr, info_ptr);
1067
1068
9.90k
   PNG_UNUSED(params)
1069
9.90k
}
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
49.6k
#  define P_NOTSET  0 /* File encoding not yet known */
1083
598k
#  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
1084
659k
#  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1085
382k
#  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
1086
147k
#  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.30k
#define PNG_CMAP_NONE      0
1092
1.57k
#define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
1093
394
#define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
1094
1.69k
#define PNG_CMAP_RGB       3 /* Process RGB data */
1095
618
#define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1096
1097
/* The following document where the background is for each processing case. */
1098
748
#define PNG_CMAP_NONE_BACKGROUND      256
1099
176
#define PNG_CMAP_GA_BACKGROUND        231
1100
949k
#define PNG_CMAP_TRANS_BACKGROUND     254
1101
135
#define PNG_CMAP_RGB_BACKGROUND       256
1102
93.1k
#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
18.5k
{
1130
18.5k
   if (image->opaque == NULL)
1131
18.5k
   {
1132
18.5k
      png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1133
18.5k
          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
18.5k
      memset(image, 0, (sizeof *image));
1139
18.5k
      image->version = PNG_IMAGE_VERSION;
1140
1141
18.5k
      if (png_ptr != NULL)
1142
18.5k
      {
1143
18.5k
         png_infop info_ptr = png_create_info_struct(png_ptr);
1144
1145
18.5k
         if (info_ptr != NULL)
1146
18.5k
         {
1147
18.5k
            png_controlp control = png_voidcast(png_controlp,
1148
18.5k
                png_malloc_warn(png_ptr, (sizeof *control)));
1149
1150
18.5k
            if (control != NULL)
1151
18.5k
            {
1152
18.5k
               memset(control, 0, (sizeof *control));
1153
1154
18.5k
               control->png_ptr = png_ptr;
1155
18.5k
               control->info_ptr = info_ptr;
1156
18.5k
               control->for_write = 0;
1157
1158
18.5k
               image->opaque = control;
1159
18.5k
               return 1;
1160
18.5k
            }
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
18.5k
   }
1171
1172
0
   return png_image_error(image, "png_image_read: opaque pointer not NULL");
1173
18.5k
}
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
25.5k
{
1179
25.5k
   png_uint_32 format = 0;
1180
1181
25.5k
   if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1182
14.4k
      format |= PNG_FORMAT_FLAG_COLOR;
1183
1184
25.5k
   if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1185
4.48k
      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
21.0k
   else if (png_ptr->num_trans > 0)
1193
2.10k
      format |= PNG_FORMAT_FLAG_ALPHA;
1194
1195
25.5k
   if (png_ptr->bit_depth == 16)
1196
5.81k
      format |= PNG_FORMAT_FLAG_LINEAR;
1197
1198
25.5k
   if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1199
1.75k
      format |= PNG_FORMAT_FLAG_COLORMAP;
1200
1201
25.5k
   return format;
1202
25.5k
}
1203
1204
static int
1205
chromaticities_match_sRGB(const png_xy *xy)
1206
4.19k
{
1207
4.19k
#  define sRGB_TOLERANCE 1000
1208
4.19k
   static const png_xy sRGB_xy = /* From ITU-R BT.709-3 */
1209
4.19k
   {
1210
      /* color      x       y */
1211
4.19k
      /* red   */ 64000, 33000,
1212
4.19k
      /* green */ 30000, 60000,
1213
4.19k
      /* blue  */ 15000,  6000,
1214
4.19k
      /* white */ 31270, 32900
1215
4.19k
   };
1216
1217
4.19k
   if (PNG_OUT_OF_RANGE(xy->whitex, sRGB_xy.whitex,sRGB_TOLERANCE) ||
1218
3.06k
       PNG_OUT_OF_RANGE(xy->whitey, sRGB_xy.whitey,sRGB_TOLERANCE) ||
1219
2.63k
       PNG_OUT_OF_RANGE(xy->redx,   sRGB_xy.redx,  sRGB_TOLERANCE) ||
1220
2.16k
       PNG_OUT_OF_RANGE(xy->redy,   sRGB_xy.redy,  sRGB_TOLERANCE) ||
1221
1.72k
       PNG_OUT_OF_RANGE(xy->greenx, sRGB_xy.greenx,sRGB_TOLERANCE) ||
1222
1.27k
       PNG_OUT_OF_RANGE(xy->greeny, sRGB_xy.greeny,sRGB_TOLERANCE) ||
1223
829
       PNG_OUT_OF_RANGE(xy->bluex,  sRGB_xy.bluex, sRGB_TOLERANCE) ||
1224
554
       PNG_OUT_OF_RANGE(xy->bluey,  sRGB_xy.bluey, sRGB_TOLERANCE))
1225
4.12k
      return 0;
1226
70
   return 1;
1227
4.19k
}
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
650
{
1237
   /* 1.6.47: use the same sanity checks as used in pngrtran.c */
1238
650
   if (g < PNG_LIB_GAMMA_MIN || g > PNG_LIB_GAMMA_MAX)
1239
60
      return 0; /* Includes the uninitialized value 0 */
1240
1241
590
   return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1242
650
}
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
7.59k
{
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
7.59k
   if (png_has_chunk(png_ptr, cICP) || png_has_chunk(png_ptr, mDCV))
1261
2.11k
      return !chromaticities_match_sRGB(&png_ptr->chromaticities);
1262
1263
   /* If the image is marked as sRGB then it is... */
1264
5.48k
   if (png_has_chunk(png_ptr, sRGB))
1265
6
      return 0;
1266
1267
   /* Last stop: cHRM, must check: */
1268
5.48k
   if (png_has_chunk(png_ptr, cHRM))
1269
2.08k
      return !chromaticities_match_sRGB(&png_ptr->chromaticities);
1270
1271
   /* Else default to sRGB */
1272
3.40k
   return 0;
1273
5.48k
}
1274
1275
static int
1276
png_image_read_header(png_voidp argument)
1277
18.5k
{
1278
18.5k
   png_imagep image = png_voidcast(png_imagep, argument);
1279
18.5k
   png_structrp png_ptr = image->opaque->png_ptr;
1280
18.5k
   png_inforp info_ptr = image->opaque->info_ptr;
1281
1282
18.5k
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
1283
18.5k
   png_set_benign_errors(png_ptr, 1/*warn*/);
1284
18.5k
#endif
1285
18.5k
   png_read_info(png_ptr, info_ptr);
1286
1287
   /* Do this the fast way; just read directly out of png_struct. */
1288
18.5k
   image->width = png_ptr->width;
1289
18.5k
   image->height = png_ptr->height;
1290
1291
18.5k
   {
1292
18.5k
      png_uint_32 format = png_image_format(png_ptr);
1293
1294
18.5k
      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
18.5k
      if ((format & PNG_FORMAT_FLAG_COLOR) != 0 &&
1301
7.59k
          png_image_is_not_sRGB(png_ptr))
1302
4.12k
         image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1303
18.5k
   }
1304
1305
   /* We need the maximum number of entries regardless of the format the
1306
    * application sets here.
1307
    */
1308
18.5k
   {
1309
18.5k
      png_uint_32 cmap_entries;
1310
1311
18.5k
      switch (png_ptr->color_type)
1312
18.5k
      {
1313
5.16k
         case PNG_COLOR_TYPE_GRAY:
1314
5.16k
            cmap_entries = 1U << png_ptr->bit_depth;
1315
5.16k
            break;
1316
1317
1.01k
         case PNG_COLOR_TYPE_PALETTE:
1318
1.01k
            cmap_entries = (png_uint_32)png_ptr->num_palette;
1319
1.01k
            break;
1320
1321
7.13k
         default:
1322
7.13k
            cmap_entries = 256;
1323
7.13k
            break;
1324
18.5k
      }
1325
1326
13.3k
      if (cmap_entries > 256)
1327
769
         cmap_entries = 256;
1328
1329
13.3k
      image->colormap_entries = cmap_entries;
1330
13.3k
   }
1331
1332
0
   return 1;
1333
18.5k
}
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
573k
{
1408
573k
   if (png_ptr != NULL)
1409
573k
   {
1410
573k
      png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1411
573k
      if (image != NULL)
1412
573k
      {
1413
573k
         png_controlp cp = image->opaque;
1414
573k
         if (cp != NULL)
1415
573k
         {
1416
573k
            png_const_bytep memory = cp->memory;
1417
573k
            size_t size = cp->size;
1418
1419
573k
            if (memory != NULL && size >= need)
1420
568k
            {
1421
568k
               memcpy(out, memory, need);
1422
568k
               cp->memory = memory + need;
1423
568k
               cp->size = size - need;
1424
568k
               return;
1425
568k
            }
1426
1427
5.31k
            png_error(png_ptr, "read beyond end of data");
1428
573k
         }
1429
573k
      }
1430
1431
0
      png_error(png_ptr, "invalid memory read");
1432
573k
   }
1433
573k
}
1434
1435
int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1436
    png_const_voidp memory, size_t size)
1437
18.5k
{
1438
18.5k
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
1439
18.5k
   {
1440
18.5k
      if (memory != NULL && size > 0)
1441
18.5k
      {
1442
18.5k
         if (png_image_read_init(image) != 0)
1443
18.5k
         {
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
18.5k
            image->opaque->memory = png_voidcast(png_const_bytep, memory);
1449
18.5k
            image->opaque->size = size;
1450
18.5k
            image->opaque->png_ptr->io_ptr = image;
1451
18.5k
            image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1452
1453
18.5k
            return png_safe_execute(image, png_image_read_header, image);
1454
18.5k
         }
1455
18.5k
      }
1456
1457
0
      else
1458
0
         return png_image_error(image,
1459
0
             "png_image_begin_read_from_memory: invalid argument");
1460
18.5k
   }
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
18.5k
}
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
13.2k
{
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
13.2k
   {
1493
13.2k
         static const png_byte chunks_to_process[] = {
1494
13.2k
            98,  75,  71,  68, '\0',  /* bKGD */
1495
13.2k
            99,  72,  82,  77, '\0',  /* cHRM */
1496
13.2k
            99,  73,  67,  80, '\0',  /* cICP */
1497
13.2k
           103,  65,  77,  65, '\0',  /* gAMA */
1498
13.2k
           109,  68,  67,  86, '\0',  /* mDCV */
1499
13.2k
           115,  66,  73,  84, '\0',  /* sBIT */
1500
13.2k
           115,  82,  71,  66, '\0',  /* sRGB */
1501
13.2k
         };
1502
1503
       /* Ignore unknown chunks and all other chunks except for the
1504
        * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1505
        */
1506
13.2k
       png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1507
13.2k
           NULL, -1);
1508
1509
       /* But do not ignore image data handling chunks */
1510
13.2k
       png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1511
13.2k
           chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1512
13.2k
   }
1513
13.2k
}
1514
1515
13.2k
#  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
924k
#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
536
{
1530
536
   png_structrp png_ptr = display->image->opaque->png_ptr;
1531
536
   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
536
   if (g == 0)
1537
0
      png_error(png_ptr, "internal: default gamma not set");
1538
1539
536
   if (png_gamma_significant(g) != 0)
1540
472
   {
1541
472
      if (png_gamma_not_sRGB(g) != 0)
1542
102
      {
1543
102
         display->file_encoding = P_FILE;
1544
102
         display->gamma_to_linear = png_reciprocal(g);
1545
102
      }
1546
1547
370
      else
1548
370
         display->file_encoding = P_sRGB;
1549
472
   }
1550
1551
64
   else
1552
64
      display->file_encoding = P_LINEAR8;
1553
536
}
1554
1555
static unsigned int
1556
decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1557
13.8k
{
1558
13.8k
   if (encoding == P_FILE) /* double check */
1559
6.13k
      encoding = display->file_encoding;
1560
1561
13.8k
   if (encoding == P_NOTSET) /* must be the file encoding */
1562
89
   {
1563
89
      set_file_encoding(display);
1564
89
      encoding = display->file_encoding;
1565
89
   }
1566
1567
13.8k
   switch (encoding)
1568
13.8k
   {
1569
1.08k
      case P_FILE:
1570
1.08k
         value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1571
1.08k
         break;
1572
1573
7.45k
      case P_sRGB:
1574
7.45k
         value = png_sRGB_table[value];
1575
7.45k
         break;
1576
1577
4.38k
      case P_LINEAR:
1578
4.38k
         break;
1579
1580
969
      case P_LINEAR8:
1581
969
         value *= 257;
1582
969
         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
13.8k
#endif
1589
13.8k
   }
1590
1591
13.8k
   return value;
1592
13.8k
}
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
6.94k
{
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
6.94k
   png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1605
6.94k
   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
6.94k
   f = f * alpha + b * (255-alpha);
1611
1612
6.94k
   if (encoding == P_LINEAR)
1613
4.38k
   {
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.38k
      f *= 257; /* Now scaled by 65535 */
1618
4.38k
      f += f >> 16;
1619
4.38k
      f = (f+32768) >> 16;
1620
4.38k
   }
1621
1622
2.56k
   else /* P_sRGB */
1623
2.56k
      f = PNG_sRGB_FROM_LINEAR(f);
1624
1625
6.94k
   return f;
1626
6.94k
}
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
162k
{
1636
162k
   png_imagep image = display->image;
1637
162k
   int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1638
81.6k
       P_LINEAR : P_sRGB;
1639
162k
   int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1640
95.9k
       (red != green || green != blue);
1641
1642
162k
   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
162k
   if (encoding == P_FILE)
1649
34.7k
   {
1650
34.7k
      if (display->file_encoding == P_NOTSET)
1651
447
         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
34.7k
      encoding = display->file_encoding;
1657
34.7k
   }
1658
1659
162k
   if (encoding == P_FILE)
1660
15.6k
   {
1661
15.6k
      png_fixed_point g = display->gamma_to_linear;
1662
1663
15.6k
      red = png_gamma_16bit_correct(red*257, g);
1664
15.6k
      green = png_gamma_16bit_correct(green*257, g);
1665
15.6k
      blue = png_gamma_16bit_correct(blue*257, g);
1666
1667
15.6k
      if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1668
1.74k
      {
1669
1.74k
         alpha *= 257;
1670
1.74k
         encoding = P_LINEAR;
1671
1.74k
      }
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
15.6k
   }
1681
1682
146k
   else if (encoding == P_LINEAR8)
1683
12.3k
   {
1684
      /* This encoding occurs quite frequently in test cases because PngSuite
1685
       * includes a gAMA 1.0 chunk with most images.
1686
       */
1687
12.3k
      red *= 257;
1688
12.3k
      green *= 257;
1689
12.3k
      blue *= 257;
1690
12.3k
      alpha *= 257;
1691
12.3k
      encoding = P_LINEAR;
1692
12.3k
   }
1693
1694
134k
   else if (encoding == P_sRGB &&
1695
132k
       (convert_to_Y  != 0 || output_encoding == P_LINEAR))
1696
75.3k
   {
1697
      /* The values are 8-bit sRGB values, but must be converted to 16-bit
1698
       * linear.
1699
       */
1700
75.3k
      red = png_sRGB_table[red];
1701
75.3k
      green = png_sRGB_table[green];
1702
75.3k
      blue = png_sRGB_table[blue];
1703
75.3k
      alpha *= 257;
1704
75.3k
      encoding = P_LINEAR;
1705
75.3k
   }
1706
1707
   /* This is set if the color isn't gray but the output is. */
1708
162k
   if (encoding == P_LINEAR)
1709
91.6k
   {
1710
91.6k
      if (convert_to_Y != 0)
1711
3.26k
      {
1712
         /* NOTE: these values are copied from png_do_rgb_to_gray */
1713
3.26k
         png_uint_32 y = (png_uint_32)6968 * red  + (png_uint_32)23434 * green +
1714
3.26k
            (png_uint_32)2366 * blue;
1715
1716
3.26k
         if (output_encoding == P_LINEAR)
1717
2.12k
            y = (y + 16384) >> 15;
1718
1719
1.14k
         else
1720
1.14k
         {
1721
            /* y is scaled by 32768, we need it scaled by 255: */
1722
1.14k
            y = (y + 128) >> 8;
1723
1.14k
            y *= 255;
1724
1.14k
            y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1725
1.14k
            alpha = PNG_DIV257(alpha);
1726
1.14k
            encoding = P_sRGB;
1727
1.14k
         }
1728
1729
3.26k
         blue = red = green = y;
1730
3.26k
      }
1731
1732
88.3k
      else if (output_encoding == P_sRGB)
1733
9.54k
      {
1734
9.54k
         red = PNG_sRGB_FROM_LINEAR(red * 255);
1735
9.54k
         green = PNG_sRGB_FROM_LINEAR(green * 255);
1736
9.54k
         blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1737
9.54k
         alpha = PNG_DIV257(alpha);
1738
9.54k
         encoding = P_sRGB;
1739
9.54k
      }
1740
91.6k
   }
1741
1742
162k
   if (encoding != output_encoding)
1743
0
      png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1744
1745
   /* Store the value. */
1746
162k
   {
1747
162k
#     ifdef PNG_FORMAT_AFIRST_SUPPORTED
1748
162k
         int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1749
112k
            (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1750
#     else
1751
#        define afirst 0
1752
#     endif
1753
162k
#     ifdef PNG_FORMAT_BGR_SUPPORTED
1754
162k
         int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1755
#     else
1756
#        define bgr 0
1757
#     endif
1758
1759
162k
      if (output_encoding == P_LINEAR)
1760
80.9k
      {
1761
80.9k
         png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1762
1763
80.9k
         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
80.9k
         switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1770
80.9k
         {
1771
12.5k
            case 4:
1772
12.5k
               entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1773
               /* FALLTHROUGH */
1774
1775
51.1k
            case 3:
1776
51.1k
               if (alpha < 65535)
1777
1.51k
               {
1778
1.51k
                  if (alpha > 0)
1779
1.14k
                  {
1780
1.14k
                     blue = (blue * alpha + 32767U)/65535U;
1781
1.14k
                     green = (green * alpha + 32767U)/65535U;
1782
1.14k
                     red = (red * alpha + 32767U)/65535U;
1783
1.14k
                  }
1784
1785
367
                  else
1786
367
                     red = green = blue = 0;
1787
1.51k
               }
1788
51.1k
               entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1789
51.1k
               entry[afirst + 1] = (png_uint_16)green;
1790
51.1k
               entry[afirst + bgr] = (png_uint_16)red;
1791
51.1k
               break;
1792
1793
13.2k
            case 2:
1794
13.2k
               entry[1 ^ afirst] = (png_uint_16)alpha;
1795
               /* FALLTHROUGH */
1796
1797
29.8k
            case 1:
1798
29.8k
               if (alpha < 65535)
1799
2.30k
               {
1800
2.30k
                  if (alpha > 0)
1801
1.76k
                     green = (green * alpha + 32767U)/65535U;
1802
1803
543
                  else
1804
543
                     green = 0;
1805
2.30k
               }
1806
29.8k
               entry[afirst] = (png_uint_16)green;
1807
29.8k
               break;
1808
1809
0
            default:
1810
0
               break;
1811
80.9k
         }
1812
80.9k
      }
1813
1814
81.6k
      else /* output encoding is P_sRGB */
1815
81.6k
      {
1816
81.6k
         png_bytep entry = png_voidcast(png_bytep, display->colormap);
1817
1818
81.6k
         entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1819
1820
81.6k
         switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1821
81.6k
         {
1822
6.06k
            case 4:
1823
6.06k
               entry[afirst ? 0 : 3] = (png_byte)alpha;
1824
               /* FALLTHROUGH */
1825
15.5k
            case 3:
1826
15.5k
               entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1827
15.5k
               entry[afirst + 1] = (png_byte)green;
1828
15.5k
               entry[afirst + bgr] = (png_byte)red;
1829
15.5k
               break;
1830
1831
14.5k
            case 2:
1832
14.5k
               entry[1 ^ afirst] = (png_byte)alpha;
1833
               /* FALLTHROUGH */
1834
66.0k
            case 1:
1835
66.0k
               entry[afirst] = (png_byte)green;
1836
66.0k
               break;
1837
1838
0
            default:
1839
0
               break;
1840
81.6k
         }
1841
81.6k
      }
1842
1843
#     ifdef afirst
1844
#        undef afirst
1845
#     endif
1846
#     ifdef bgr
1847
#        undef bgr
1848
#     endif
1849
162k
   }
1850
162k
}
1851
1852
static int
1853
make_gray_file_colormap(png_image_read_control *display)
1854
104
{
1855
104
   unsigned int i;
1856
1857
26.7k
   for (i=0; i<256; ++i)
1858
26.6k
      png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1859
1860
104
   return (int)i;
1861
104
}
1862
1863
static int
1864
make_gray_colormap(png_image_read_control *display)
1865
237
{
1866
237
   unsigned int i;
1867
1868
60.9k
   for (i=0; i<256; ++i)
1869
60.6k
      png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
1870
1871
237
   return (int)i;
1872
237
}
1873
341
#define PNG_GRAY_COLORMAP_ENTRIES 256
1874
1875
static int
1876
make_ga_colormap(png_image_read_control *display)
1877
82
{
1878
82
   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
82
   i = 0;
1905
19.0k
   while (i < 231)
1906
18.9k
   {
1907
18.9k
      unsigned int gray = (i * 256 + 115) / 231;
1908
18.9k
      png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
1909
18.9k
   }
1910
1911
   /* 255 is used here for the component values for consistency with the code
1912
    * that undoes premultiplication in pngwrite.c.
1913
    */
1914
82
   png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
1915
1916
410
   for (a=1; a<5; ++a)
1917
328
   {
1918
328
      unsigned int g;
1919
1920
2.29k
      for (g=0; g<6; ++g)
1921
1.96k
         png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
1922
1.96k
             P_sRGB);
1923
328
   }
1924
1925
82
   return (int)i;
1926
82
}
1927
1928
94
#define PNG_GA_COLORMAP_ENTRIES 256
1929
1930
static int
1931
make_rgb_colormap(png_image_read_control *display)
1932
180
{
1933
180
   unsigned int i, r;
1934
1935
   /* Build a 6x6x6 opaque RGB cube */
1936
1.26k
   for (i=r=0; r<6; ++r)
1937
1.08k
   {
1938
1.08k
      unsigned int g;
1939
1940
7.56k
      for (g=0; g<6; ++g)
1941
6.48k
      {
1942
6.48k
         unsigned int b;
1943
1944
45.3k
         for (b=0; b<6; ++b)
1945
38.8k
            png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
1946
38.8k
                P_sRGB);
1947
6.48k
      }
1948
1.08k
   }
1949
1950
180
   return (int)i;
1951
180
}
1952
1953
180
#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
302k
   ((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.05k
{
1962
1.05k
   png_image_read_control *display =
1963
1.05k
      png_voidcast(png_image_read_control*, argument);
1964
1.05k
   png_imagep image = display->image;
1965
1966
1.05k
   png_structrp png_ptr = image->opaque->png_ptr;
1967
1.05k
   png_uint_32 output_format = image->format;
1968
1.05k
   int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1969
552
      P_LINEAR : P_sRGB;
1970
1971
1.05k
   unsigned int cmap_entries;
1972
1.05k
   unsigned int output_processing;        /* Output processing option */
1973
1.05k
   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.05k
   unsigned int background_index = 256;
1979
1.05k
   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.05k
   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.05k
   if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
1990
678
         png_ptr->num_trans > 0) /* alpha in input */ &&
1991
686
      ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
1992
524
   {
1993
524
      if (output_encoding == P_LINEAR) /* compose on black */
1994
290
         back_b = back_g = back_r = 0;
1995
1996
234
      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
234
      else
2005
234
      {
2006
234
         back_g = display->background->green;
2007
234
         if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2008
42
         {
2009
42
            back_r = display->background->red;
2010
42
            back_b = display->background->blue;
2011
42
         }
2012
192
         else
2013
192
            back_b = back_r = back_g;
2014
234
      }
2015
524
   }
2016
2017
533
   else if (output_encoding == P_LINEAR)
2018
262
      back_b = back_r = back_g = 65535;
2019
2020
271
   else
2021
271
      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.05k
   if (png_ptr->bit_depth == 16 &&
2033
330
      (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2034
330
      png_ptr->default_gamma = PNG_GAMMA_LINEAR;
2035
2036
727
   else
2037
727
      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.05k
   switch (png_ptr->color_type)
2045
1.05k
   {
2046
255
      case PNG_COLOR_TYPE_GRAY:
2047
255
         if (png_ptr->bit_depth <= 8)
2048
170
         {
2049
            /* There at most 256 colors in the output, regardless of
2050
             * transparency.
2051
             */
2052
170
            unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2053
2054
170
            cmap_entries = 1U << png_ptr->bit_depth;
2055
170
            if (cmap_entries > image->colormap_entries)
2056
0
               png_error(png_ptr, "gray[8] color-map: too few entries");
2057
2058
170
            step = 255 / (cmap_entries - 1);
2059
170
            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
170
            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.05k
            for (i=val=0; i<cmap_entries; ++i, val += step)
2080
3.88k
            {
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.88k
               if (i != trans)
2086
3.86k
                  png_create_colormap_entry(display, i, val, val, val, 255,
2087
3.86k
                      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
20
               else
2098
20
                  png_create_colormap_entry(display, i, back_r, back_g, back_b,
2099
20
                      back_alpha, output_encoding);
2100
3.88k
            }
2101
2102
            /* We need libpng to preserve the original encoding. */
2103
170
            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
170
            if (png_ptr->bit_depth < 8)
2111
159
               png_set_packing(png_ptr);
2112
170
         }
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
55
            {
2141
55
               unsigned int back_alpha;
2142
2143
55
               if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2144
29
                  back_alpha = 0;
2145
2146
26
               else
2147
26
               {
2148
26
                  if (back_r == back_g && back_g == back_b)
2149
20
                  {
2150
                     /* Background is gray; no special processing will be
2151
                      * required.
2152
                      */
2153
20
                     png_color_16 c;
2154
20
                     png_uint_32 gray = back_g;
2155
2156
20
                     if (output_encoding == P_LINEAR)
2157
15
                     {
2158
15
                        gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2159
2160
                        /* And make sure the corresponding palette entry
2161
                         * matches.
2162
                         */
2163
15
                        png_create_colormap_entry(display, gray, back_g, back_g,
2164
15
                            back_g, 65535, P_LINEAR);
2165
15
                     }
2166
2167
                     /* The background passed to libpng, however, must be the
2168
                      * sRGB value.
2169
                      */
2170
20
                     c.index = 0; /*unused*/
2171
20
                     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
20
                     png_set_background_fixed(png_ptr, &c,
2178
20
                         PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2179
20
                         0/*gamma: not used*/);
2180
2181
20
                     output_processing = PNG_CMAP_NONE;
2182
20
                     break;
2183
20
                  }
2184
#ifdef __COVERITY__
2185
                 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2186
                  * here.
2187
                  */
2188
                  back_alpha = 255;
2189
#else
2190
6
                  back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2191
6
#endif
2192
6
               }
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
35
               expand_tRNS = 1;
2202
35
               output_processing = PNG_CMAP_TRANS;
2203
35
               background_index = 254;
2204
2205
               /* And set (overwrite) color-map entry 254 to the actual
2206
                * background color at full precision.
2207
                */
2208
35
               png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2209
35
                   back_alpha, output_encoding);
2210
35
            }
2211
2212
30
            else
2213
30
               output_processing = PNG_CMAP_NONE;
2214
85
         }
2215
235
         break;
2216
2217
235
      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
95
         data_encoding = P_sRGB;
2229
2230
95
         if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2231
38
         {
2232
38
            if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2233
0
               png_error(png_ptr, "gray+alpha color-map: too few entries");
2234
2235
38
            cmap_entries = (unsigned int)make_ga_colormap(display);
2236
2237
38
            background_index = PNG_CMAP_GA_BACKGROUND;
2238
38
            output_processing = PNG_CMAP_GA;
2239
38
         }
2240
2241
57
         else /* alpha is removed */
2242
57
         {
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
57
            if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2260
37
               (back_r == back_g && back_g == back_b))
2261
45
            {
2262
               /* Background is gray; no special processing will be required. */
2263
45
               png_color_16 c;
2264
45
               png_uint_32 gray = back_g;
2265
2266
45
               if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2267
0
                  png_error(png_ptr, "gray-alpha color-map: too few entries");
2268
2269
45
               cmap_entries = (unsigned int)make_gray_colormap(display);
2270
2271
45
               if (output_encoding == P_LINEAR)
2272
27
               {
2273
27
                  gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2274
2275
                  /* And make sure the corresponding palette entry matches. */
2276
27
                  png_create_colormap_entry(display, gray, back_g, back_g,
2277
27
                      back_g, 65535, P_LINEAR);
2278
27
               }
2279
2280
               /* The background passed to libpng, however, must be the sRGB
2281
                * value.
2282
                */
2283
45
               c.index = 0; /*unused*/
2284
45
               c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2285
2286
45
               png_set_background_fixed(png_ptr, &c,
2287
45
                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2288
45
                   0/*gamma: not used*/);
2289
2290
45
               output_processing = PNG_CMAP_NONE;
2291
45
            }
2292
2293
12
            else
2294
12
            {
2295
12
               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
12
               if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2301
0
                  png_error(png_ptr, "ga-alpha color-map: too few entries");
2302
2303
12
               i = 0;
2304
2.78k
               while (i < 231)
2305
2.77k
               {
2306
2.77k
                  png_uint_32 gray = (i * 256 + 115) / 231;
2307
2.77k
                  png_create_colormap_entry(display, i++, gray, gray, gray,
2308
2.77k
                      255, P_sRGB);
2309
2.77k
               }
2310
2311
               /* NOTE: this preserves the full precision of the application
2312
                * background color.
2313
                */
2314
12
               background_index = i;
2315
12
               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
12
                    output_encoding == P_LINEAR ? 65535U : 255U,
2322
12
#endif
2323
12
                    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
12
               if (output_encoding == P_sRGB) /* else already linear */
2334
12
               {
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
12
                  back_r = png_sRGB_table[back_r];
2340
12
                  back_g = png_sRGB_table[back_g];
2341
12
                  back_b = png_sRGB_table[back_b];
2342
12
               }
2343
2344
60
               for (a=1; a<5; ++a)
2345
48
               {
2346
48
                  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
48
                  png_uint_32 alpha = 51 * a;
2352
48
                  png_uint_32 back_rx = (255-alpha) * back_r;
2353
48
                  png_uint_32 back_gx = (255-alpha) * back_g;
2354
48
                  png_uint_32 back_bx = (255-alpha) * back_b;
2355
2356
336
                  for (g=0; g<6; ++g)
2357
288
                  {
2358
288
                     png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2359
2360
288
                     png_create_colormap_entry(display, i++,
2361
288
                         PNG_sRGB_FROM_LINEAR(gray + back_rx),
2362
288
                         PNG_sRGB_FROM_LINEAR(gray + back_gx),
2363
288
                         PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2364
288
                  }
2365
48
               }
2366
2367
12
               cmap_entries = i;
2368
12
               output_processing = PNG_CMAP_GA;
2369
12
            }
2370
57
         }
2371
95
         break;
2372
2373
151
      case PNG_COLOR_TYPE_RGB:
2374
435
      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
435
         if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2379
255
         {
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
255
            png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2389
255
                -1);
2390
255
            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
255
            if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2396
36
               png_ptr->num_trans > 0) &&
2397
222
               (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2398
44
            {
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
44
               expand_tRNS = 1;
2404
2405
44
               if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2406
0
                  png_error(png_ptr, "rgb[ga] color-map: too few entries");
2407
2408
44
               cmap_entries = (unsigned int)make_ga_colormap(display);
2409
44
               background_index = PNG_CMAP_GA_BACKGROUND;
2410
44
               output_processing = PNG_CMAP_GA;
2411
44
            }
2412
2413
211
            else
2414
211
            {
2415
211
               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
211
               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
211
               if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2436
35
                  png_ptr->num_trans > 0) &&
2437
178
                  png_gamma_not_sRGB(gamma) != 0)
2438
104
               {
2439
104
                  cmap_entries = (unsigned int)make_gray_file_colormap(display);
2440
104
                  data_encoding = P_FILE;
2441
104
               }
2442
2443
107
               else
2444
107
                  cmap_entries = (unsigned int)make_gray_colormap(display);
2445
2446
               /* But if the input has alpha or transparency it must be removed
2447
                */
2448
211
               if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2449
35
                  png_ptr->num_trans > 0)
2450
178
               {
2451
178
                  png_color_16 c;
2452
178
                  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
178
                  if (data_encoding == P_FILE) /* from the fixup above */
2460
104
                  {
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
104
                     if (output_encoding == P_sRGB)
2467
89
                        gray = png_sRGB_table[gray]; /* now P_LINEAR */
2468
2469
104
                     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
104
                     png_create_colormap_entry(display, gray, back_g, back_g,
2476
104
                         back_g, 0/*unused*/, output_encoding);
2477
104
                  }
2478
2479
74
                  else if (output_encoding == P_LINEAR)
2480
14
                  {
2481
14
                     gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2482
2483
                     /* And make sure the corresponding palette entry matches.
2484
                      */
2485
14
                     png_create_colormap_entry(display, gray, back_g, back_g,
2486
14
                        back_g, 0/*unused*/, P_LINEAR);
2487
14
                  }
2488
2489
                  /* The background passed to libpng, however, must be the
2490
                   * output (normally sRGB) value.
2491
                   */
2492
178
                  c.index = 0; /*unused*/
2493
178
                  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
178
                  expand_tRNS = 1;
2500
178
                  png_set_background_fixed(png_ptr, &c,
2501
178
                      PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2502
178
                      0/*gamma: not used*/);
2503
178
               }
2504
2505
211
               output_processing = PNG_CMAP_NONE;
2506
211
            }
2507
255
         }
2508
2509
180
         else /* output is color */
2510
180
         {
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
180
            data_encoding = P_sRGB;
2517
2518
            /* Is there any transparency or alpha? */
2519
180
            if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2520
115
               png_ptr->num_trans > 0)
2521
171
            {
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
171
               if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2526
35
               {
2527
35
                  png_uint_32 r;
2528
2529
35
                  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
35
                  cmap_entries = (unsigned int)make_rgb_colormap(display);
2533
2534
                  /* Add a transparent entry. */
2535
35
                  png_create_colormap_entry(display, cmap_entries, 255, 255,
2536
35
                      255, 0, P_sRGB);
2537
2538
                  /* This is stored as the background index for the processing
2539
                   * algorithm.
2540
                   */
2541
35
                  background_index = cmap_entries++;
2542
2543
                  /* Add 27 r,g,b entries each with alpha 0.5. */
2544
140
                  for (r=0; r<256; r = (r << 1) | 0x7f)
2545
105
                  {
2546
105
                     png_uint_32 g;
2547
2548
420
                     for (g=0; g<256; g = (g << 1) | 0x7f)
2549
315
                     {
2550
315
                        png_uint_32 b;
2551
2552
                        /* This generates components with the values 0, 127 and
2553
                         * 255
2554
                         */
2555
1.26k
                        for (b=0; b<256; b = (b << 1) | 0x7f)
2556
945
                           png_create_colormap_entry(display, cmap_entries++,
2557
945
                               r, g, b, 128, P_sRGB);
2558
315
                     }
2559
105
                  }
2560
2561
35
                  expand_tRNS = 1;
2562
35
                  output_processing = PNG_CMAP_RGB_ALPHA;
2563
35
               }
2564
2565
136
               else
2566
136
               {
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
136
                  unsigned int sample_size =
2575
136
                     PNG_IMAGE_SAMPLE_SIZE(output_format);
2576
136
                  png_uint_32 r, g, b; /* sRGB background */
2577
2578
136
                  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
136
                  cmap_entries = (unsigned int)make_rgb_colormap(display);
2582
2583
136
                  png_create_colormap_entry(display, cmap_entries, back_r,
2584
136
                      back_g, back_b, 0/*unused*/, output_encoding);
2585
2586
136
                  if (output_encoding == P_LINEAR)
2587
126
                  {
2588
126
                     r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2589
126
                     g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2590
126
                     b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2591
126
                  }
2592
2593
10
                  else
2594
10
                  {
2595
10
                     r = back_r;
2596
10
                     g = back_g;
2597
10
                     b = back_b;
2598
10
                  }
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
136
                  if (memcmp((png_const_bytep)display->colormap +
2606
136
                      sample_size * cmap_entries,
2607
136
                      (png_const_bytep)display->colormap +
2608
136
                          sample_size * PNG_RGB_INDEX(r,g,b),
2609
136
                     sample_size) != 0)
2610
10
                  {
2611
                     /* The background color must be added. */
2612
10
                     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
40
                     for (r=0; r<256; r = (r << 1) | 0x7f)
2618
30
                     {
2619
120
                        for (g=0; g<256; g = (g << 1) | 0x7f)
2620
90
                        {
2621
                           /* This generates components with the values 0, 127
2622
                            * and 255
2623
                            */
2624
360
                           for (b=0; b<256; b = (b << 1) | 0x7f)
2625
270
                              png_create_colormap_entry(display, cmap_entries++,
2626
270
                                  png_colormap_compose(display, r, P_sRGB, 128,
2627
270
                                      back_r, output_encoding),
2628
270
                                  png_colormap_compose(display, g, P_sRGB, 128,
2629
270
                                      back_g, output_encoding),
2630
270
                                  png_colormap_compose(display, b, P_sRGB, 128,
2631
270
                                      back_b, output_encoding),
2632
270
                                  0/*unused*/, output_encoding);
2633
90
                        }
2634
30
                     }
2635
2636
10
                     expand_tRNS = 1;
2637
10
                     output_processing = PNG_CMAP_RGB_ALPHA;
2638
10
                  }
2639
2640
126
                  else /* background color is in the standard color-map */
2641
126
                  {
2642
126
                     png_color_16 c;
2643
2644
126
                     c.index = 0; /*unused*/
2645
126
                     c.red = (png_uint_16)back_r;
2646
126
                     c.gray = c.green = (png_uint_16)back_g;
2647
126
                     c.blue = (png_uint_16)back_b;
2648
2649
126
                     png_set_background_fixed(png_ptr, &c,
2650
126
                         PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2651
126
                         0/*gamma: not used*/);
2652
2653
126
                     output_processing = PNG_CMAP_RGB;
2654
126
                  }
2655
136
               }
2656
171
            }
2657
2658
9
            else /* no alpha or transparency in the input */
2659
9
            {
2660
               /* Alpha in the output is irrelevant, simply map the opaque input
2661
                * pixels to the 6x6x6 color-map.
2662
                */
2663
9
               if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2664
0
                  png_error(png_ptr, "rgb color-map: too few entries");
2665
2666
9
               cmap_entries = (unsigned int)make_rgb_colormap(display);
2667
9
               output_processing = PNG_CMAP_RGB;
2668
9
            }
2669
180
         }
2670
435
         break;
2671
2672
435
      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
272
         {
2677
272
            unsigned int num_trans = png_ptr->num_trans;
2678
272
            png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2679
272
            png_const_colorp colormap = png_ptr->palette;
2680
272
            int do_background = trans != NULL &&
2681
121
               (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2682
272
            unsigned int i;
2683
2684
            /* Just in case: */
2685
272
            if (trans == NULL)
2686
151
               num_trans = 0;
2687
2688
272
            output_processing = PNG_CMAP_NONE;
2689
272
            data_encoding = P_FILE; /* Don't change from color-map indices */
2690
272
            cmap_entries = (unsigned int)png_ptr->num_palette;
2691
272
            if (cmap_entries > 256)
2692
0
               cmap_entries = 256;
2693
2694
272
            if (cmap_entries > (unsigned int)image->colormap_entries)
2695
0
               png_error(png_ptr, "palette color-map: too few entries");
2696
2697
7.18k
            for (i=0; i < cmap_entries; ++i)
2698
6.91k
            {
2699
6.91k
               if (do_background != 0 && i < num_trans && trans[i] < 255)
2700
2.67k
               {
2701
2.67k
                  if (trans[i] == 0)
2702
627
                     png_create_colormap_entry(display, i, back_r, back_g,
2703
627
                         back_b, 0, output_encoding);
2704
2705
2.04k
                  else
2706
2.04k
                  {
2707
                     /* Must compose the PNG file color in the color-map entry
2708
                      * on the sRGB color in 'back'.
2709
                      */
2710
2.04k
                     png_create_colormap_entry(display, i,
2711
2.04k
                         png_colormap_compose(display, colormap[i].red,
2712
2.04k
                             P_FILE, trans[i], back_r, output_encoding),
2713
2.04k
                         png_colormap_compose(display, colormap[i].green,
2714
2.04k
                             P_FILE, trans[i], back_g, output_encoding),
2715
2.04k
                         png_colormap_compose(display, colormap[i].blue,
2716
2.04k
                             P_FILE, trans[i], back_b, output_encoding),
2717
2.04k
                         output_encoding == P_LINEAR ? trans[i] * 257U :
2718
2.04k
                             trans[i],
2719
2.04k
                         output_encoding);
2720
2.04k
                  }
2721
2.67k
               }
2722
2723
4.24k
               else
2724
4.24k
                  png_create_colormap_entry(display, i, colormap[i].red,
2725
4.24k
                      colormap[i].green, colormap[i].blue,
2726
4.24k
                      i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2727
6.91k
            }
2728
2729
            /* The PNG data may have indices packed in fewer than 8 bits, it
2730
             * must be expanded if so.
2731
             */
2732
272
            if (png_ptr->bit_depth < 8)
2733
106
               png_set_packing(png_ptr);
2734
272
         }
2735
0
         break;
2736
2737
0
      default:
2738
0
         png_error(png_ptr, "invalid PNG color type");
2739
         /*NOT REACHED*/
2740
1.05k
   }
2741
2742
   /* Now deal with the output processing */
2743
1.05k
   if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2744
39
       (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2745
39
      png_set_tRNS_to_alpha(png_ptr);
2746
2747
1.05k
   switch (data_encoding)
2748
1.05k
   {
2749
511
      case P_sRGB:
2750
         /* Change to 8-bit sRGB */
2751
511
         png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2752
         /* FALLTHROUGH */
2753
2754
1.05k
      case P_FILE:
2755
1.05k
         if (png_ptr->bit_depth > 8)
2756
330
            png_set_scale_16(png_ptr);
2757
1.05k
         break;
2758
2759
0
#ifdef __GNUC__
2760
0
      default:
2761
0
         png_error(png_ptr, "bad data option (internal error)");
2762
1.05k
#endif
2763
1.05k
   }
2764
2765
1.05k
   if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2766
0
      png_error(png_ptr, "color map overflow (BAD internal error)");
2767
2768
1.05k
   image->colormap_entries = cmap_entries;
2769
2770
   /* Double check using the recorded background index */
2771
1.05k
   switch (output_processing)
2772
1.05k
   {
2773
748
      case PNG_CMAP_NONE:
2774
748
         if (background_index != PNG_CMAP_NONE_BACKGROUND)
2775
0
            goto bad_background;
2776
748
         break;
2777
2778
748
      case PNG_CMAP_GA:
2779
94
         if (background_index != PNG_CMAP_GA_BACKGROUND)
2780
0
            goto bad_background;
2781
94
         break;
2782
2783
94
      case PNG_CMAP_TRANS:
2784
35
         if (background_index >= cmap_entries ||
2785
35
            background_index != PNG_CMAP_TRANS_BACKGROUND)
2786
0
            goto bad_background;
2787
35
         break;
2788
2789
135
      case PNG_CMAP_RGB:
2790
135
         if (background_index != PNG_CMAP_RGB_BACKGROUND)
2791
0
            goto bad_background;
2792
135
         break;
2793
2794
135
      case PNG_CMAP_RGB_ALPHA:
2795
45
         if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2796
0
            goto bad_background;
2797
45
         break;
2798
2799
45
      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.05k
   }
2805
2806
1.05k
   display->colormap_processing = (int)output_processing;
2807
2808
1.05k
   return 1/*ok*/;
2809
1.05k
}
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
309
{
2815
309
   png_image_read_control *display = png_voidcast(png_image_read_control*,
2816
309
       argument);
2817
309
   png_imagep image = display->image;
2818
309
   png_structrp png_ptr = image->opaque->png_ptr;
2819
309
   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
309
   switch (png_ptr->interlaced)
2826
309
   {
2827
127
      case PNG_INTERLACE_NONE:
2828
127
         passes = 1;
2829
127
         break;
2830
2831
182
      case PNG_INTERLACE_ADAM7:
2832
182
         passes = PNG_INTERLACE_ADAM7_PASSES;
2833
182
         break;
2834
2835
0
      default:
2836
0
         png_error(png_ptr, "unknown interlace type");
2837
309
   }
2838
2839
309
   {
2840
309
      png_uint_32 height = image->height;
2841
309
      png_uint_32 width = image->width;
2842
309
      int proc = display->colormap_processing;
2843
309
      png_bytep first_row = png_voidcast(png_bytep, display->first_row);
2844
309
      ptrdiff_t row_step = display->row_step;
2845
309
      int pass;
2846
2847
650
      for (pass = 0; pass < passes; ++pass)
2848
608
      {
2849
608
         unsigned int startx, stepx, stepy;
2850
608
         png_uint_32 y;
2851
2852
608
         if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2853
481
         {
2854
            /* The row may be empty for a short image: */
2855
481
            if (PNG_PASS_COLS(width, pass) == 0)
2856
38
               continue;
2857
2858
443
            startx = PNG_PASS_START_COL(pass);
2859
443
            stepx = PNG_PASS_COL_OFFSET(pass);
2860
443
            y = PNG_PASS_START_ROW(pass);
2861
443
            stepy = PNG_PASS_ROW_OFFSET(pass);
2862
443
         }
2863
2864
127
         else
2865
127
         {
2866
127
            y = 0;
2867
127
            startx = 0;
2868
127
            stepx = stepy = 1;
2869
127
         }
2870
2871
3.88k
         for (; y<height; y += stepy)
2872
3.58k
         {
2873
3.58k
            png_bytep inrow = png_voidcast(png_bytep, display->local_row);
2874
3.58k
            png_bytep outrow = first_row + y * row_step;
2875
3.58k
            png_const_bytep row_end = outrow + width;
2876
2877
            /* Read the libpng data into the temporary buffer. */
2878
3.58k
            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.58k
            outrow += startx;
2885
3.58k
            switch (proc)
2886
3.58k
            {
2887
1.25k
               case PNG_CMAP_GA:
2888
15.9k
                  for (; outrow < row_end; outrow += stepx)
2889
14.6k
                  {
2890
                     /* The data is always in the PNG order */
2891
14.6k
                     unsigned int gray = *inrow++;
2892
14.6k
                     unsigned int alpha = *inrow++;
2893
14.6k
                     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
14.6k
                     if (alpha > 229) /* opaque */
2900
1.12k
                     {
2901
1.12k
                        entry = (231 * gray + 128) >> 8;
2902
1.12k
                     }
2903
13.5k
                     else if (alpha < 26) /* transparent */
2904
4.98k
                     {
2905
4.98k
                        entry = 231;
2906
4.98k
                     }
2907
8.56k
                     else /* partially opaque */
2908
8.56k
                     {
2909
8.56k
                        entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
2910
8.56k
                     }
2911
2912
14.6k
                     *outrow = (png_byte)entry;
2913
14.6k
                  }
2914
1.25k
                  break;
2915
2916
289
               case PNG_CMAP_TRANS:
2917
946k
                  for (; outrow < row_end; outrow += stepx)
2918
946k
                  {
2919
946k
                     png_byte gray = *inrow++;
2920
946k
                     png_byte alpha = *inrow++;
2921
2922
946k
                     if (alpha == 0)
2923
189k
                        *outrow = PNG_CMAP_TRANS_BACKGROUND;
2924
2925
756k
                     else if (gray != PNG_CMAP_TRANS_BACKGROUND)
2926
752k
                        *outrow = gray;
2927
2928
3.88k
                     else
2929
3.88k
                        *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
2930
946k
                  }
2931
289
                  break;
2932
2933
1.28k
               case PNG_CMAP_RGB:
2934
277k
                  for (; outrow < row_end; outrow += stepx)
2935
276k
                  {
2936
276k
                     *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
2937
276k
                     inrow += 3;
2938
276k
                  }
2939
1.28k
                  break;
2940
2941
483
               case PNG_CMAP_RGB_ALPHA:
2942
119k
                  for (; outrow < row_end; outrow += stepx)
2943
119k
                  {
2944
119k
                     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
119k
                     if (alpha >= 196)
2952
25.9k
                        *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
2953
119k
                            inrow[2]);
2954
2955
93.1k
                     else if (alpha < 64)
2956
30.1k
                        *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
2957
2958
63.0k
                     else
2959
63.0k
                     {
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
63.0k
                        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
63.0k
                        if (inrow[0] & 0x80) back_i += 9; /* red */
2978
63.0k
                        if (inrow[0] & 0x40) back_i += 9;
2979
63.0k
                        if (inrow[1] & 0x80) back_i += 3; /* green */
2980
63.0k
                        if (inrow[1] & 0x40) back_i += 3;
2981
63.0k
                        if (inrow[2] & 0x80) back_i += 1; /* blue */
2982
63.0k
                        if (inrow[2] & 0x40) back_i += 1;
2983
2984
63.0k
                        *outrow = (png_byte)back_i;
2985
63.0k
                     }
2986
2987
119k
                     inrow += 4;
2988
119k
                  }
2989
483
                  break;
2990
2991
0
               default:
2992
0
                  break;
2993
3.58k
            }
2994
3.58k
         }
2995
570
      }
2996
309
   }
2997
2998
42
   return 1;
2999
309
}
3000
3001
static int
3002
png_image_read_colormapped(png_voidp argument)
3003
1.05k
{
3004
1.05k
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3005
1.05k
       argument);
3006
1.05k
   png_imagep image = display->image;
3007
1.05k
   png_controlp control = image->opaque;
3008
1.05k
   png_structrp png_ptr = control->png_ptr;
3009
1.05k
   png_inforp info_ptr = control->info_ptr;
3010
3011
1.05k
   int passes = 0; /* As a flag */
3012
3013
1.05k
   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.05k
   if (display->colormap_processing == PNG_CMAP_NONE)
3020
748
      passes = png_set_interlace_handling(png_ptr);
3021
3022
1.05k
   png_read_update_info(png_ptr, info_ptr);
3023
3024
   /* The expected output can be deduced from the colormap_processing option. */
3025
1.05k
   switch (display->colormap_processing)
3026
1.05k
   {
3027
748
      case PNG_CMAP_NONE:
3028
         /* Output must be one channel and one byte per pixel, the output
3029
          * encoding can be anything.
3030
          */
3031
748
         if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3032
476
            info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3033
748
            info_ptr->bit_depth == 8)
3034
748
            break;
3035
3036
0
         goto bad_output;
3037
3038
35
      case PNG_CMAP_TRANS:
3039
129
      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
129
         if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3045
129
            info_ptr->bit_depth == 8 &&
3046
129
            png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3047
129
            image->colormap_entries == 256)
3048
129
            break;
3049
3050
0
         goto bad_output;
3051
3052
135
      case PNG_CMAP_RGB:
3053
         /* Output must be 8-bit sRGB encoded RGB */
3054
135
         if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3055
135
            info_ptr->bit_depth == 8 &&
3056
135
            png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3057
135
            image->colormap_entries == 216)
3058
135
            break;
3059
3060
0
         goto bad_output;
3061
3062
45
      case PNG_CMAP_RGB_ALPHA:
3063
         /* Output must be 8-bit sRGB encoded RGBA */
3064
45
         if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3065
45
            info_ptr->bit_depth == 8 &&
3066
45
            png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3067
45
            image->colormap_entries == 244 /* 216 + 1 + 27 */)
3068
45
            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.05k
   }
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.05k
   {
3082
1.05k
      png_voidp first_row = display->buffer;
3083
1.05k
      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.05k
      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.05k
      display->first_row = first_row;
3096
1.05k
      display->row_step = row_step;
3097
1.05k
   }
3098
3099
1.05k
   if (passes == 0)
3100
309
   {
3101
309
      int result;
3102
309
      png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3103
3104
309
      display->local_row = row;
3105
309
      result = png_safe_execute(image, png_image_read_and_map, display);
3106
309
      display->local_row = NULL;
3107
309
      png_free(png_ptr, row);
3108
3109
309
      return result;
3110
309
   }
3111
3112
748
   else
3113
748
   {
3114
748
      ptrdiff_t row_step = display->row_step;
3115
3116
2.06k
      while (--passes >= 0)
3117
1.32k
      {
3118
1.32k
         png_uint_32 y = image->height;
3119
1.32k
         png_bytep row = png_voidcast(png_bytep, display->first_row);
3120
3121
20.1k
         for (; y > 0; --y)
3122
18.8k
         {
3123
18.8k
            png_read_row(png_ptr, row, NULL);
3124
18.8k
            row += row_step;
3125
18.8k
         }
3126
1.32k
      }
3127
3128
748
      return 1;
3129
748
   }
3130
1.05k
}
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.29k
{
3136
1.29k
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3137
1.29k
       argument);
3138
1.29k
   png_imagep image = display->image;
3139
1.29k
   png_structrp png_ptr = image->opaque->png_ptr;
3140
1.29k
   png_inforp info_ptr = image->opaque->info_ptr;
3141
1.29k
   png_bytep local_row = png_voidcast(png_bytep, display->local_row);
3142
1.29k
   png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3143
1.29k
   ptrdiff_t row_step = display->row_step;
3144
1.29k
   size_t row_bytes = png_get_rowbytes(png_ptr, info_ptr);
3145
1.29k
   int passes;
3146
3147
   /* Handle interlacing. */
3148
1.29k
   switch (png_ptr->interlaced)
3149
1.29k
   {
3150
0
      case PNG_INTERLACE_NONE:
3151
0
         passes = 1;
3152
0
         break;
3153
3154
1.29k
      case PNG_INTERLACE_ADAM7:
3155
1.29k
         passes = PNG_INTERLACE_ADAM7_PASSES;
3156
1.29k
         break;
3157
3158
0
      default:
3159
0
         png_error(png_ptr, "unknown interlace type");
3160
1.29k
   }
3161
3162
   /* Read each pass using local_row as intermediate buffer. */
3163
8.06k
   while (--passes >= 0)
3164
6.76k
   {
3165
6.76k
      png_uint_32 y = image->height;
3166
6.76k
      png_bytep output_row = first_row;
3167
3168
84.0k
      for (; y > 0; --y)
3169
77.2k
      {
3170
         /* Read into local_row (gets transformed 8-bit data). */
3171
77.2k
         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
77.2k
         memcpy(output_row, local_row, row_bytes);
3180
77.2k
         output_row += row_step;
3181
77.2k
      }
3182
6.76k
   }
3183
3184
1.29k
   return 1;
3185
1.29k
}
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
588
{
3343
588
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3344
588
       argument);
3345
588
   png_imagep image = display->image;
3346
588
   png_structrp png_ptr = image->opaque->png_ptr;
3347
588
   png_inforp info_ptr = image->opaque->info_ptr;
3348
588
   png_uint_32 height = image->height;
3349
588
   png_uint_32 width = image->width;
3350
588
   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
588
   if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3358
0
      png_error(png_ptr, "lost rgb to gray");
3359
3360
588
   if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3361
12
      png_error(png_ptr, "unexpected compose");
3362
3363
576
   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
576
   if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3368
480
      (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3369
0
      png_error(png_ptr, "unexpected 8-bit transformation");
3370
3371
576
   switch (png_ptr->interlaced)
3372
576
   {
3373
248
      case PNG_INTERLACE_NONE:
3374
248
         passes = 1;
3375
248
         break;
3376
3377
328
      case PNG_INTERLACE_ADAM7:
3378
328
         passes = PNG_INTERLACE_ADAM7_PASSES;
3379
328
         break;
3380
3381
0
      default:
3382
0
         png_error(png_ptr, "unknown interlace type");
3383
576
   }
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
576
   switch (info_ptr->bit_depth)
3391
576
   {
3392
480
      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
480
         {
3399
480
            png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3400
480
            ptrdiff_t row_step = display->row_step;
3401
3402
1.04k
            for (pass = 0; pass < passes; ++pass)
3403
565
            {
3404
565
               unsigned int startx, stepx, stepy;
3405
565
               png_uint_32 y;
3406
3407
565
               if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3408
351
               {
3409
                  /* The row may be empty for a short image: */
3410
351
                  if (PNG_PASS_COLS(width, pass) == 0)
3411
17
                     continue;
3412
3413
334
                  startx = PNG_PASS_START_COL(pass);
3414
334
                  stepx = PNG_PASS_COL_OFFSET(pass);
3415
334
                  y = PNG_PASS_START_ROW(pass);
3416
334
                  stepy = PNG_PASS_ROW_OFFSET(pass);
3417
334
               }
3418
3419
214
               else
3420
214
               {
3421
214
                  y = 0;
3422
214
                  startx = 0;
3423
214
                  stepx = stepy = 1;
3424
214
               }
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
415k
                     for (; outrow < row_end; outrow += stepx)
3486
414k
                     {
3487
414k
                        png_byte alpha = inrow[1];
3488
3489
414k
                        if (alpha > 0) /* else use background */
3490
214k
                        {
3491
214k
                           png_uint_32 component = inrow[0];
3492
3493
214k
                           if (alpha < 255) /* else just use component */
3494
200k
                           {
3495
200k
                              component = png_sRGB_table[component] * alpha;
3496
200k
                              component += background * (255-alpha);
3497
200k
                              component = PNG_sRGB_FROM_LINEAR(component);
3498
200k
                           }
3499
3500
214k
                           outrow[0] = (png_byte)component;
3501
214k
                        }
3502
3503
200k
                        else
3504
200k
                           outrow[0] = background8;
3505
3506
414k
                        inrow += 2; /* gray and alpha channel */
3507
414k
                     }
3508
1.48k
                  }
3509
548
               }
3510
548
            }
3511
480
         }
3512
480
         break;
3513
3514
96
      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
96
         {
3520
96
            png_uint_16p first_row = png_voidcast(png_uint_16p,
3521
96
                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
96
            ptrdiff_t row_step = display->row_step / 2;
3526
96
            unsigned int preserve_alpha = (image->format &
3527
96
                PNG_FORMAT_FLAG_ALPHA) != 0;
3528
96
            unsigned int outchannels = 1U+preserve_alpha;
3529
96
            int swap_alpha = 0;
3530
3531
96
#           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3532
96
               if (preserve_alpha != 0 &&
3533
30
                   (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3534
24
                  swap_alpha = 1;
3535
96
#           endif
3536
3537
288
            for (pass = 0; pass < passes; ++pass)
3538
192
            {
3539
192
               unsigned int startx, stepx, stepy;
3540
192
               png_uint_32 y;
3541
3542
               /* The 'x' start and step are adjusted to output components here.
3543
                */
3544
192
               if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3545
158
               {
3546
                  /* The row may be empty for a short image: */
3547
158
                  if (PNG_PASS_COLS(width, pass) == 0)
3548
23
                     continue;
3549
3550
135
                  startx = PNG_PASS_START_COL(pass) * outchannels;
3551
135
                  stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3552
135
                  y = PNG_PASS_START_ROW(pass);
3553
135
                  stepy = PNG_PASS_ROW_OFFSET(pass);
3554
135
               }
3555
3556
34
               else
3557
34
               {
3558
34
                  y = 0;
3559
34
                  startx = 0;
3560
34
                  stepx = outchannels;
3561
34
                  stepy = 1;
3562
34
               }
3563
3564
791
               for (; y<height; y += stepy)
3565
622
               {
3566
622
                  png_const_uint_16p inrow;
3567
622
                  png_uint_16p outrow = first_row + y * row_step;
3568
622
                  png_uint_16p row_end = outrow + width * outchannels;
3569
3570
                  /* Read the row, which is packed: */
3571
622
                  png_read_row(png_ptr, png_voidcast(png_bytep,
3572
622
                      display->local_row), NULL);
3573
622
                  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
622
                  outrow += startx;
3578
516k
                  for (; outrow < row_end; outrow += stepx)
3579
515k
                  {
3580
515k
                     png_uint_32 component = inrow[0];
3581
515k
                     png_uint_16 alpha = inrow[1];
3582
3583
515k
                     if (alpha > 0) /* else 0 */
3584
351k
                     {
3585
351k
                        if (alpha < 65535) /* else just use component */
3586
226k
                        {
3587
226k
                           component *= alpha;
3588
226k
                           component += 32767;
3589
226k
                           component /= 65535;
3590
226k
                        }
3591
351k
                     }
3592
3593
164k
                     else
3594
164k
                        component = 0;
3595
3596
515k
                     outrow[swap_alpha] = (png_uint_16)component;
3597
515k
                     if (preserve_alpha != 0)
3598
516
                        outrow[1 ^ swap_alpha] = alpha;
3599
3600
515k
                     inrow += 2; /* components and alpha channel */
3601
515k
                  }
3602
622
               }
3603
169
            }
3604
96
         }
3605
96
         break;
3606
3607
0
#ifdef __GNUC__
3608
0
      default:
3609
0
         png_error(png_ptr, "unexpected bit depth");
3610
576
#endif
3611
576
   }
3612
3613
20
   return 1;
3614
576
}
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
12.2k
{
3620
12.2k
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3621
12.2k
       argument);
3622
12.2k
   png_imagep image = display->image;
3623
12.2k
   png_structrp png_ptr = image->opaque->png_ptr;
3624
12.2k
   png_inforp info_ptr = image->opaque->info_ptr;
3625
3626
12.2k
   png_uint_32 format = image->format;
3627
12.2k
   int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3628
12.2k
   int do_local_compose = 0;
3629
12.2k
   int do_local_background = 0; /* to avoid double gamma correction bug */
3630
12.2k
   int do_local_scale = 0; /* for interlaced 16-to-8 bit conversion */
3631
12.2k
   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
12.2k
   png_set_expand(png_ptr);
3638
3639
   /* Now check the format to see if it was modified. */
3640
12.2k
   {
3641
12.2k
      png_uint_32 base_format = png_image_format(png_ptr) &
3642
12.2k
         ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3643
12.2k
      png_uint_32 change = format ^ base_format;
3644
12.2k
      png_fixed_point output_gamma;
3645
12.2k
      int mode; /* alpha mode */
3646
3647
      /* Do this first so that we have a record if rgb to gray is happening. */
3648
12.2k
      if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3649
6.19k
      {
3650
         /* gray<->color transformation required. */
3651
6.19k
         if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3652
5.16k
            png_set_gray_to_rgb(png_ptr);
3653
3654
1.03k
         else
3655
1.03k
         {
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.03k
            if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3670
694
               do_local_background = 1/*maybe*/;
3671
3672
1.03k
            png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3673
1.03k
                PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3674
1.03k
         }
3675
3676
6.19k
         change &= ~PNG_FORMAT_FLAG_COLOR;
3677
6.19k
      }
3678
3679
      /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3680
       */
3681
12.2k
      {
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
12.2k
         png_fixed_point input_gamma_default;
3689
3690
12.2k
         if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3691
2.74k
             (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3692
2.74k
            input_gamma_default = PNG_GAMMA_LINEAR;
3693
9.51k
         else
3694
9.51k
            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
12.2k
         png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3700
12.2k
      }
3701
3702
12.2k
      if (linear != 0)
3703
718
      {
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
718
         if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3708
424
            mode = PNG_ALPHA_STANDARD; /* associated alpha */
3709
3710
294
         else
3711
294
            mode = PNG_ALPHA_PNG;
3712
3713
718
         output_gamma = PNG_GAMMA_LINEAR;
3714
718
      }
3715
3716
11.5k
      else
3717
11.5k
      {
3718
11.5k
         mode = PNG_ALPHA_PNG;
3719
11.5k
         output_gamma = PNG_DEFAULT_sRGB;
3720
11.5k
      }
3721
3722
12.2k
      if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
3723
386
      {
3724
386
         mode = PNG_ALPHA_OPTIMIZED;
3725
386
         change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3726
386
      }
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
12.2k
      if (do_local_background != 0)
3735
694
      {
3736
694
         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
694
         if (png_muldiv(&gtest, output_gamma,
3744
694
                  png_resolve_file_gamma(png_ptr), PNG_FP_1) != 0 &&
3745
694
             png_gamma_significant(gtest) == 0)
3746
54
            do_local_background = 0;
3747
3748
640
         else if (mode == PNG_ALPHA_STANDARD)
3749
90
         {
3750
90
            do_local_background = 2/*required*/;
3751
90
            mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3752
90
         }
3753
3754
         /* else leave as 1 for the checks below */
3755
694
      }
3756
3757
      /* If the bit-depth changes then handle that here. */
3758
12.2k
      if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3759
3.10k
      {
3760
3.10k
         if (linear != 0 /*16-bit output*/)
3761
542
            png_set_expand_16(png_ptr);
3762
3763
2.56k
         else /* 8-bit output */
3764
2.56k
         {
3765
2.56k
            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.56k
            if (png_ptr->interlaced != 0)
3771
1.37k
               do_local_scale = 1;
3772
2.56k
         }
3773
3774
3.10k
         change &= ~PNG_FORMAT_FLAG_LINEAR;
3775
3.10k
      }
3776
3777
      /* Now the background/alpha channel changes. */
3778
12.2k
      if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3779
9.66k
      {
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
9.66k
         if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3785
781
         {
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
781
            if (do_local_background != 0)
3792
565
               do_local_background = 2/*required*/;
3793
3794
            /* 16-bit output: just remove the channel */
3795
216
            else if (linear != 0) /* compose on black (well, pre-multiply) */
3796
144
               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
781
         }
3831
3832
8.88k
         else /* output needs an alpha channel */
3833
8.88k
         {
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
8.88k
            png_uint_32 filler; /* opaque filler */
3840
8.88k
            int where;
3841
3842
8.88k
            if (linear != 0)
3843
146
               filler = 65535;
3844
3845
8.73k
            else
3846
8.73k
               filler = 255;
3847
3848
8.88k
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
3849
8.88k
            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3850
140
            {
3851
140
               where = PNG_FILLER_BEFORE;
3852
140
               change &= ~PNG_FORMAT_FLAG_AFIRST;
3853
140
            }
3854
3855
8.74k
            else
3856
8.74k
#endif
3857
8.74k
            where = PNG_FILLER_AFTER;
3858
3859
8.88k
            png_set_add_alpha(png_ptr, filler, where);
3860
8.88k
         }
3861
3862
         /* This stops the (irrelevant) call to swap_alpha below. */
3863
9.66k
         change &= ~PNG_FORMAT_FLAG_ALPHA;
3864
9.66k
      }
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
12.2k
      png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3871
3872
12.2k
#     ifdef PNG_FORMAT_BGR_SUPPORTED
3873
12.2k
         if ((change & PNG_FORMAT_FLAG_BGR) != 0)
3874
841
         {
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
841
            if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3879
408
               png_set_bgr(png_ptr);
3880
3881
433
            else
3882
433
               format &= ~PNG_FORMAT_FLAG_BGR;
3883
3884
841
            change &= ~PNG_FORMAT_FLAG_BGR;
3885
841
         }
3886
12.2k
#     endif
3887
3888
12.2k
#     ifdef PNG_FORMAT_AFIRST_SUPPORTED
3889
12.2k
         if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
3890
626
         {
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
626
            if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
3897
229
            {
3898
               /* Disable this if doing a local background,
3899
                * TODO: remove this when local background is no longer required.
3900
                */
3901
229
               if (do_local_background != 2)
3902
205
                  png_set_swap_alpha(png_ptr);
3903
229
            }
3904
3905
397
            else
3906
397
               format &= ~PNG_FORMAT_FLAG_AFIRST;
3907
3908
626
            change &= ~PNG_FORMAT_FLAG_AFIRST;
3909
626
         }
3910
12.2k
#     endif
3911
3912
      /* If the *output* is 16-bit then we need to check for a byte-swap on this
3913
       * architecture.
3914
       */
3915
12.2k
      if (linear != 0)
3916
718
      {
3917
718
         png_uint_16 le = 0x0001;
3918
3919
718
         if ((*(png_const_bytep) & le) != 0)
3920
718
            png_set_swap(png_ptr);
3921
718
      }
3922
3923
      /* If change is not now 0 some transformation is missing - error out. */
3924
12.2k
      if (change != 0)
3925
86
         png_error(png_ptr, "png_read_image: unsupported transformation");
3926
12.2k
   }
3927
3928
12.1k
   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
12.1k
   if (do_local_compose == 0 && do_local_background != 2)
3937
11.5k
      passes = png_set_interlace_handling(png_ptr);
3938
3939
12.1k
   png_read_update_info(png_ptr, info_ptr);
3940
3941
12.1k
   {
3942
12.1k
      png_uint_32 info_format = 0;
3943
3944
12.1k
      if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3945
10.9k
         info_format |= PNG_FORMAT_FLAG_COLOR;
3946
3947
12.1k
      if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
3948
11.5k
      {
3949
         /* do_local_compose removes this channel below. */
3950
11.5k
         if (do_local_compose == 0)
3951
11.5k
         {
3952
            /* do_local_background does the same if required. */
3953
11.5k
            if (do_local_background != 2 ||
3954
588
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3955
11.0k
               info_format |= PNG_FORMAT_FLAG_ALPHA;
3956
11.5k
         }
3957
11.5k
      }
3958
3959
590
      else if (do_local_compose != 0) /* internal error */
3960
0
         png_error(png_ptr, "png_image_read: alpha channel lost");
3961
3962
12.1k
      if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
3963
350
         info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3964
350
      }
3965
3966
12.1k
      if (info_ptr->bit_depth == 16)
3967
679
         info_format |= PNG_FORMAT_FLAG_LINEAR;
3968
3969
12.1k
#ifdef PNG_FORMAT_BGR_SUPPORTED
3970
12.1k
      if ((png_ptr->transformations & PNG_BGR) != 0)
3971
390
         info_format |= PNG_FORMAT_FLAG_BGR;
3972
12.1k
#endif
3973
3974
12.1k
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
3975
12.1k
         if (do_local_background == 2)
3976
588
         {
3977
588
            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3978
24
               info_format |= PNG_FORMAT_FLAG_AFIRST;
3979
588
         }
3980
3981
12.1k
         if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
3982
11.9k
            ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
3983
8.86k
            (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
12.1k
#     endif
3991
3992
      /* This is actually an internal error. */
3993
12.1k
      if (info_format != format)
3994
0
         png_error(png_ptr, "png_read_image: invalid transformations");
3995
12.1k
   }
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
12.1k
   {
4003
12.1k
      png_voidp first_row = display->buffer;
4004
12.1k
      ptrdiff_t row_step = display->row_stride;
4005
4006
12.1k
      if (linear != 0)
4007
679
         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
12.1k
      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
12.1k
      display->first_row = first_row;
4020
12.1k
      display->row_step = row_step;
4021
12.1k
   }
4022
4023
12.1k
   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
12.1k
   else if (do_local_background == 2)
4037
588
   {
4038
588
      int result;
4039
588
      png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4040
4041
588
      display->local_row = row;
4042
588
      result = png_safe_execute(image, png_image_read_background, display);
4043
588
      display->local_row = NULL;
4044
588
      png_free(png_ptr, row);
4045
4046
588
      return result;
4047
588
   }
4048
4049
11.5k
   else if (do_local_scale != 0)
4050
1.29k
   {
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.29k
      int result;
4057
1.29k
      png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4058
4059
1.29k
      display->local_row = row;
4060
1.29k
      result = png_safe_execute(image, png_image_read_direct_scaled, display);
4061
1.29k
      display->local_row = NULL;
4062
1.29k
      png_free(png_ptr, row);
4063
4064
1.29k
      return result;
4065
1.29k
   }
4066
4067
10.2k
   else
4068
10.2k
   {
4069
10.2k
      ptrdiff_t row_step = display->row_step;
4070
4071
45.9k
      while (--passes >= 0)
4072
35.7k
      {
4073
35.7k
         png_uint_32 y = image->height;
4074
35.7k
         png_bytep row = png_voidcast(png_bytep, display->first_row);
4075
4076
1.53M
         for (; y > 0; --y)
4077
1.49M
         {
4078
1.49M
            png_read_row(png_ptr, row, NULL);
4079
1.49M
            row += row_step;
4080
1.49M
         }
4081
35.7k
      }
4082
4083
10.2k
      return 1;
4084
10.2k
   }
4085
12.1k
}
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
13.3k
{
4091
13.3k
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
4092
13.3k
   {
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
13.3k
      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
13.3k
      if (image->width <= 0x7fffffffU/channels) /* no overflow */
4106
13.3k
      {
4107
13.3k
         png_uint_32 check;
4108
13.3k
         png_uint_32 png_row_stride = image->width * channels;
4109
4110
13.3k
         if (row_stride == 0)
4111
13.3k
            row_stride = (png_int_32)/*SAFE*/png_row_stride;
4112
4113
13.3k
         if (row_stride < 0)
4114
0
            check = -(png_uint_32)row_stride;
4115
4116
13.3k
         else
4117
13.3k
            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
13.3k
         if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4124
13.3k
         {
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
13.3k
            if (image->height <=
4142
13.3k
                0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4143
13.3k
            {
4144
13.3k
               if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4145
1.05k
                  (image->colormap_entries > 0 && colormap != NULL))
4146
13.3k
               {
4147
13.3k
                  int result;
4148
13.3k
                  png_image_read_control display;
4149
4150
13.3k
                  memset(&display, 0, (sizeof display));
4151
13.3k
                  display.image = image;
4152
13.3k
                  display.buffer = buffer;
4153
13.3k
                  display.row_stride = row_stride;
4154
13.3k
                  display.colormap = colormap;
4155
13.3k
                  display.background = background;
4156
13.3k
                  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
13.3k
                  if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4162
1.05k
                     result =
4163
1.05k
                         png_safe_execute(image,
4164
1.05k
                             png_image_read_colormap, &display) &&
4165
1.05k
                             png_safe_execute(image,
4166
1.05k
                             png_image_read_colormapped, &display);
4167
4168
12.2k
                  else
4169
12.2k
                     result =
4170
12.2k
                        png_safe_execute(image,
4171
12.2k
                            png_image_read_direct, &display);
4172
4173
13.3k
                  png_image_free(image);
4174
13.3k
                  return result;
4175
13.3k
               }
4176
4177
0
               else
4178
0
                  return png_image_error(image,
4179
0
                      "png_image_finish_read[color-map]: no color-map");
4180
13.3k
            }
4181
4182
0
            else
4183
0
               return png_image_error(image,
4184
0
                   "png_image_finish_read: image too large");
4185
13.3k
         }
4186
4187
0
         else
4188
0
            return png_image_error(image,
4189
0
                "png_image_finish_read: invalid argument");
4190
13.3k
      }
4191
4192
0
      else
4193
0
         return png_image_error(image,
4194
0
             "png_image_finish_read: row_stride too large");
4195
13.3k
   }
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
13.3k
}
4203
4204
#endif /* SIMPLIFIED_READ */
4205
#endif /* READ */