Coverage Report

Created: 2026-02-14 06:26

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