Coverage Report

Created: 2026-03-31 06:35

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