Coverage Report

Created: 2025-10-12 07:48

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-2025 Cosmin Truta
4
 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
5
 * Copyright (c) 1996-1997 Andreas Dilger
6
 * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
7
 *
8
 * This code is released under the libpng license.
9
 * For conditions of distribution and use, see the disclaimer
10
 * and license in png.h
11
 *
12
 * This file contains routines that an application calls directly to
13
 * read a PNG file or stream.
14
 */
15
16
#include "pngpriv.h"
17
#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
18
#  include <errno.h>
19
#endif
20
21
#ifdef PNG_READ_SUPPORTED
22
23
/* Create a PNG structure for reading, and allocate any memory needed. */
24
PNG_FUNCTION(png_structp,
25
png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
26
    png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
27
0
{
28
#ifndef PNG_USER_MEM_SUPPORTED
29
   png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
30
        error_fn, warn_fn, NULL, NULL, NULL);
31
#else
32
0
   return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
33
0
        warn_fn, NULL, NULL, NULL);
34
0
}
35
36
/* Alternate create PNG structure for reading, and allocate any memory
37
 * needed.
38
 */
39
PNG_FUNCTION(png_structp,
40
png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
41
    png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
42
    png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
43
87.5k
{
44
87.5k
   png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
45
87.5k
       error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
46
87.5k
#endif /* USER_MEM */
47
48
87.5k
   if (png_ptr != NULL)
49
87.5k
   {
50
87.5k
      png_ptr->mode = PNG_IS_READ_STRUCT;
51
52
      /* Added in libpng-1.6.0; this can be used to detect a read structure if
53
       * required (it will be zero in a write structure.)
54
       */
55
87.5k
#     ifdef PNG_SEQUENTIAL_READ_SUPPORTED
56
87.5k
         png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
57
87.5k
#     endif
58
59
87.5k
#     ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
60
87.5k
         png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
61
62
         /* In stable builds only warn if an application error can be completely
63
          * handled.
64
          */
65
#        if PNG_RELEASE_BUILD
66
            png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
67
#        endif
68
87.5k
#     endif
69
70
87.5k
#     ifdef PNG_TARGET_CODE_IMPLEMENTATION /* target specific code */
71
         /* Current support is read-only so this happens here, not in the
72
          * general creation.  It could easily be moved.
73
          */
74
87.5k
         png_target_init(png_ptr);
75
87.5k
         if (png_ptr->target_state != 0U)
76
87.5k
            png_set_option(png_ptr, PNG_TARGET_SPECIFIC_CODE, 1);
77
87.5k
#     endif
78
79
      /* TODO: delay this, it can be done in png_init_io (if the app doesn't
80
       * do it itself) avoiding setting the default function if it is not
81
       * required.
82
       */
83
87.5k
      png_set_read_fn(png_ptr, NULL, NULL);
84
87.5k
   }
85
86
87.5k
   return png_ptr;
87
87.5k
}
88
89
90
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
91
/* Read the information before the actual image data.  This has been
92
 * changed in v0.90 to allow reading a file that already has the magic
93
 * bytes read from the stream.  You can tell libpng how many bytes have
94
 * been read from the beginning of the stream (up to the maximum of 8)
95
 * via png_set_sig_bytes(), and we will only check the remaining bytes
96
 * here.  The application can then have access to the signature bytes we
97
 * read if it is determined that this isn't a valid PNG file.
98
 */
99
void
100
png_read_info(png_structrp png_ptr, png_inforp info_ptr)
101
87.5k
{
102
87.5k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
103
87.5k
   int keep;
104
87.5k
#endif
105
106
87.5k
   png_debug(1, "in png_read_info");
107
108
87.5k
   if (png_ptr == NULL || info_ptr == NULL)
109
0
      return;
110
111
   /* Read and check the PNG file signature. */
112
87.5k
   png_read_sig(png_ptr, info_ptr);
113
114
87.5k
   for (;;)
115
618k
   {
116
618k
      png_uint_32 length = png_read_chunk_header(png_ptr);
117
618k
      png_uint_32 chunk_name = png_ptr->chunk_name;
118
119
      /* IDAT logic needs to happen here to simplify getting the two flags
120
       * right.
121
       */
122
618k
      if (chunk_name == png_IDAT)
123
46.5k
      {
124
46.5k
         if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
125
16
            png_chunk_error(png_ptr, "Missing IHDR before IDAT");
126
127
46.5k
         else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
128
1.47k
             (png_ptr->mode & PNG_HAVE_PLTE) == 0)
129
10
            png_chunk_error(png_ptr, "Missing PLTE before IDAT");
130
131
46.5k
         else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
132
0
            png_chunk_benign_error(png_ptr, "Too many IDATs found");
133
134
46.5k
         png_ptr->mode |= PNG_HAVE_IDAT;
135
46.5k
      }
136
137
572k
      else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
138
0
      {
139
0
         png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
140
0
         png_ptr->mode |= PNG_AFTER_IDAT;
141
0
      }
142
143
618k
      if (chunk_name == png_IHDR)
144
71.0k
         png_handle_chunk(png_ptr, info_ptr, length);
145
146
547k
      else if (chunk_name == png_IEND)
147
92
         png_handle_chunk(png_ptr, info_ptr, length);
148
149
547k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
150
547k
      else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
151
167k
      {
152
167k
         png_handle_unknown(png_ptr, info_ptr, length, keep);
153
154
167k
         if (chunk_name == png_PLTE)
155
0
            png_ptr->mode |= PNG_HAVE_PLTE;
156
157
167k
         else if (chunk_name == png_IDAT)
158
0
         {
159
0
            png_ptr->idat_size = 0; /* It has been consumed */
160
0
            break;
161
0
         }
162
167k
      }
163
379k
#endif
164
165
379k
      else if (chunk_name == png_IDAT)
166
46.5k
      {
167
46.5k
#ifdef PNG_READ_APNG_SUPPORTED
168
46.5k
         png_have_info(png_ptr, info_ptr);
169
46.5k
#endif
170
46.5k
         png_ptr->idat_size = length;
171
46.5k
         break;
172
46.5k
      }
173
174
333k
#ifdef PNG_READ_APNG_SUPPORTED
175
333k
      else if (chunk_name == png_acTL)
176
0
         png_handle_acTL(png_ptr, info_ptr, length);
177
178
333k
      else if (chunk_name == png_fcTL)
179
0
         png_handle_fcTL(png_ptr, info_ptr, length);
180
181
333k
      else if (chunk_name == png_fdAT)
182
0
         png_handle_fdAT(png_ptr, info_ptr, length);
183
333k
#endif
184
185
333k
      else
186
333k
         png_handle_chunk(png_ptr, info_ptr, length);
187
618k
   }
188
87.5k
}
189
#endif /* SEQUENTIAL_READ */
190
191
#ifdef PNG_READ_APNG_SUPPORTED
192
void PNGAPI
193
png_read_frame_head(png_structp png_ptr, png_infop info_ptr)
194
0
{
195
0
   png_byte have_chunk_after_DAT; /* after IDAT or after fdAT */
196
197
0
   png_debug(1, "Reading frame head");
198
199
0
   if (!(png_ptr->mode & PNG_HAVE_acTL))
200
0
      png_error(png_ptr, "Cannot read APNG frame: missing acTL");
201
202
   /* Do nothing for the main IDAT. */
203
0
   if (png_ptr->num_frames_read == 0)
204
0
      return;
205
206
0
   png_read_reset(png_ptr);
207
0
   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
208
0
   png_ptr->mode &= ~PNG_HAVE_fcTL;
209
210
0
   have_chunk_after_DAT = 0;
211
0
   for (;;)
212
0
   {
213
0
      png_uint_32 length = png_read_chunk_header(png_ptr);
214
215
0
      if (png_ptr->chunk_name == png_IDAT)
216
0
      {
217
         /* Discard trailing IDATs for the first frame. */
218
0
         if (have_chunk_after_DAT || png_ptr->num_frames_read > 1)
219
0
            png_error(png_ptr, "Misplaced IDAT in APNG stream");
220
0
         png_crc_finish(png_ptr, length);
221
0
      }
222
0
      else if (png_ptr->chunk_name == png_fcTL)
223
0
      {
224
0
         png_handle_fcTL(png_ptr, info_ptr, length);
225
0
         have_chunk_after_DAT = 1;
226
0
      }
227
0
      else if (png_ptr->chunk_name == png_fdAT)
228
0
      {
229
0
         png_ensure_sequence_number(png_ptr, length);
230
231
         /* Discard trailing fdATs for all frames except the first. */
232
0
         if (!have_chunk_after_DAT && png_ptr->num_frames_read > 1)
233
0
         {
234
0
            png_crc_finish(png_ptr, length - 4);
235
0
         }
236
0
         else if (png_ptr->mode & PNG_HAVE_fcTL)
237
0
         {
238
0
            png_ptr->idat_size = length - 4;
239
0
            png_ptr->mode |= PNG_HAVE_IDAT;
240
0
            break;
241
0
         }
242
0
         else
243
0
         {
244
0
            png_error(png_ptr, "Misplaced fdAT in APNG stream");
245
0
         }
246
0
      }
247
0
      else
248
0
      {
249
0
         png_warning(png_ptr, "Ignoring unexpected chunk in APNG sequence");
250
0
         png_crc_finish(png_ptr, length);
251
0
      }
252
0
   }
253
0
}
254
#endif /* PNG_READ_APNG_SUPPORTED */
255
256
/* Optional call to update the users info_ptr structure */
257
void
258
png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
259
46.5k
{
260
46.5k
   png_debug(1, "in png_read_update_info");
261
262
46.5k
   if (png_ptr != NULL)
263
46.5k
   {
264
46.5k
      if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
265
46.5k
      {
266
46.5k
         png_read_start_row(png_ptr);
267
268
46.5k
#        ifdef PNG_READ_TRANSFORMS_SUPPORTED
269
46.5k
            png_read_transform_info(png_ptr, info_ptr);
270
#        else
271
            PNG_UNUSED(info_ptr)
272
#        endif
273
46.5k
      }
274
275
      /* New in 1.6.0 this avoids the bug of doing the initializations twice */
276
0
      else
277
0
         png_app_error(png_ptr,
278
0
             "png_read_update_info/png_start_read_image: duplicate call");
279
46.5k
   }
280
46.5k
}
281
282
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
283
/* Initialize palette, background, etc, after transformations
284
 * are set, but before any reading takes place.  This allows
285
 * the user to obtain a gamma-corrected palette, for example.
286
 * If the user doesn't call this, we will do it ourselves.
287
 */
288
void
289
png_start_read_image(png_structrp png_ptr)
290
0
{
291
0
   png_debug(1, "in png_start_read_image");
292
293
0
   if (png_ptr != NULL)
294
0
   {
295
0
      if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
296
0
         png_read_start_row(png_ptr);
297
298
      /* New in 1.6.0 this avoids the bug of doing the initializations twice */
299
0
      else
300
0
         png_app_error(png_ptr,
301
0
             "png_start_read_image/png_read_update_info: duplicate call");
302
0
   }
303
0
}
304
#endif /* SEQUENTIAL_READ */
305
306
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
307
#ifdef PNG_MNG_FEATURES_SUPPORTED
308
/* Undoes intrapixel differencing,
309
 * NOTE: this is apparently only supported in the 'sequential' reader.
310
 */
311
static void
312
png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
313
0
{
314
0
   png_debug(1, "in png_do_read_intrapixel");
315
316
0
   if (
317
0
       (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
318
0
   {
319
0
      int bytes_per_pixel;
320
0
      png_uint_32 row_width = row_info->width;
321
322
0
      if (row_info->bit_depth == 8)
323
0
      {
324
0
         png_bytep rp;
325
0
         png_uint_32 i;
326
327
0
         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
328
0
            bytes_per_pixel = 3;
329
330
0
         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
331
0
            bytes_per_pixel = 4;
332
333
0
         else
334
0
            return;
335
336
0
         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
337
0
         {
338
0
            *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
339
0
            *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
340
0
         }
341
0
      }
342
0
      else if (row_info->bit_depth == 16)
343
0
      {
344
0
         png_bytep rp;
345
0
         png_uint_32 i;
346
347
0
         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
348
0
            bytes_per_pixel = 6;
349
350
0
         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
351
0
            bytes_per_pixel = 8;
352
353
0
         else
354
0
            return;
355
356
0
         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
357
0
         {
358
0
            png_uint_32 s0   = (png_uint_32)(*(rp    ) << 8) | *(rp + 1);
359
0
            png_uint_32 s1   = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
360
0
            png_uint_32 s2   = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
361
0
            png_uint_32 red  = (s0 + s1 + 65536) & 0xffff;
362
0
            png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
363
0
            *(rp    ) = (png_byte)((red >> 8) & 0xff);
364
0
            *(rp + 1) = (png_byte)(red & 0xff);
365
0
            *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
366
0
            *(rp + 5) = (png_byte)(blue & 0xff);
367
0
         }
368
0
      }
369
0
   }
370
0
}
371
#endif /* MNG_FEATURES */
372
373
void
374
png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
375
3.01M
{
376
3.01M
   png_row_info row_info;
377
378
3.01M
   if (png_ptr == NULL)
379
0
      return;
380
381
3.01M
   png_debug2(1, "in png_read_row (row %lu, pass %d)",
382
3.01M
       (unsigned long)png_ptr->row_number, png_ptr->pass);
383
384
   /* png_read_start_row sets the information (in particular iwidth) for this
385
    * interlace pass.
386
    */
387
3.01M
   if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
388
0
      png_read_start_row(png_ptr);
389
390
   /* 1.5.6: row_info moved out of png_struct to a local here. */
391
3.01M
   row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
392
3.01M
   row_info.color_type = png_ptr->color_type;
393
3.01M
   row_info.bit_depth = png_ptr->bit_depth;
394
3.01M
   row_info.channels = png_ptr->channels;
395
3.01M
   row_info.pixel_depth = png_ptr->pixel_depth;
396
3.01M
   row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
397
398
3.01M
#ifdef PNG_WARNINGS_SUPPORTED
399
3.01M
   if (png_ptr->row_number == 0 && png_ptr->pass == 0)
400
45.7k
   {
401
   /* Check for transforms that have been set but were defined out */
402
#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
403
   if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
404
      png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
405
#endif
406
407
#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
408
   if ((png_ptr->transformations & PNG_FILLER) != 0)
409
      png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
410
#endif
411
412
#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
413
    !defined(PNG_READ_PACKSWAP_SUPPORTED)
414
   if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
415
      png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
416
#endif
417
418
#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
419
   if ((png_ptr->transformations & PNG_PACK) != 0)
420
      png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
421
#endif
422
423
#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
424
   if ((png_ptr->transformations & PNG_SHIFT) != 0)
425
      png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
426
#endif
427
428
#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
429
   if ((png_ptr->transformations & PNG_BGR) != 0)
430
      png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
431
#endif
432
433
#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
434
   if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
435
      png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
436
#endif
437
45.7k
   }
438
3.01M
#endif /* WARNINGS */
439
440
3.01M
#ifdef PNG_READ_INTERLACING_SUPPORTED
441
   /* If interlaced and we do not need a new row, combine row and return.
442
    * Notice that the pixels we have from previous rows have been transformed
443
    * already; we can only combine like with like (transformed or
444
    * untransformed) and, because of the libpng API for interlaced images, this
445
    * means we must transform before de-interlacing.
446
    */
447
3.01M
   if (png_ptr->interlaced != 0 &&
448
2.52M
       (png_ptr->transformations & PNG_INTERLACE) != 0)
449
2.52M
   {
450
2.52M
      switch (png_ptr->pass)
451
2.52M
      {
452
547k
         case 0:
453
547k
            if (png_ptr->row_number & 0x07)
454
459k
            {
455
459k
               if (dsp_row != NULL)
456
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
457
459k
               png_read_finish_row(png_ptr);
458
459k
               return;
459
459k
            }
460
88.6k
            break;
461
462
481k
         case 1:
463
481k
            if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
464
442k
            {
465
442k
               if (dsp_row != NULL)
466
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
467
468
442k
               png_read_finish_row(png_ptr);
469
442k
               return;
470
442k
            }
471
39.4k
            break;
472
473
411k
         case 2:
474
411k
            if ((png_ptr->row_number & 0x07) != 4)
475
362k
            {
476
362k
               if (dsp_row != NULL && (png_ptr->row_number & 4))
477
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
478
479
362k
               png_read_finish_row(png_ptr);
480
362k
               return;
481
362k
            }
482
48.9k
            break;
483
484
360k
         case 3:
485
360k
            if ((png_ptr->row_number & 3) || png_ptr->width < 3)
486
299k
            {
487
299k
               if (dsp_row != NULL)
488
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
489
490
299k
               png_read_finish_row(png_ptr);
491
299k
               return;
492
299k
            }
493
60.9k
            break;
494
495
298k
         case 4:
496
298k
            if ((png_ptr->row_number & 3) != 2)
497
229k
            {
498
229k
               if (dsp_row != NULL && (png_ptr->row_number & 2))
499
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
500
501
229k
               png_read_finish_row(png_ptr);
502
229k
               return;
503
229k
            }
504
69.6k
            break;
505
506
256k
         case 5:
507
256k
            if ((png_ptr->row_number & 1) || png_ptr->width < 2)
508
173k
            {
509
173k
               if (dsp_row != NULL)
510
0
                  png_combine_row(png_ptr, dsp_row, 1/*display*/);
511
512
173k
               png_read_finish_row(png_ptr);
513
173k
               return;
514
173k
            }
515
82.9k
            break;
516
517
82.9k
         default:
518
168k
         case 6:
519
168k
            if ((png_ptr->row_number & 1) == 0)
520
94.1k
            {
521
94.1k
               png_read_finish_row(png_ptr);
522
94.1k
               return;
523
94.1k
            }
524
73.8k
            break;
525
2.52M
      }
526
2.52M
   }
527
952k
#endif
528
529
952k
   if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
530
0
      png_error(png_ptr, "Invalid attempt to read row data");
531
532
   /* Fill the row with IDAT data: */
533
952k
   png_ptr->row_buf[0]=255; /* to force error if no data was found */
534
952k
   png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
535
536
952k
   if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
537
433k
   {
538
433k
      if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
539
432k
         png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
540
432k
             png_ptr->prev_row + 1, png_ptr->row_buf[0]);
541
750
      else
542
750
         png_error(png_ptr, "bad adaptive filter value");
543
433k
   }
544
545
   /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
546
    * 1.5.6, while the buffer really is this big in current versions of libpng
547
    * it may not be in the future, so this was changed just to copy the
548
    * interlaced count:
549
    */
550
951k
   memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
551
552
951k
#ifdef PNG_MNG_FEATURES_SUPPORTED
553
951k
   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
554
32.6k
       (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
555
0
   {
556
      /* Intrapixel differencing */
557
0
      png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
558
0
   }
559
951k
#endif
560
561
951k
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
562
951k
   if (png_ptr->transformations
563
285k
#     ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
564
285k
         || png_ptr->num_palette_max >= 0
565
951k
#     endif
566
951k
      )
567
657k
      png_do_read_transformations(png_ptr, &row_info);
568
951k
#endif
569
570
   /* The transformed pixel depth should match the depth now in row_info. */
571
951k
   if (png_ptr->transformed_pixel_depth == 0)
572
41.8k
   {
573
41.8k
      png_ptr->transformed_pixel_depth = row_info.pixel_depth;
574
41.8k
      if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
575
0
         png_error(png_ptr, "sequential row overflow");
576
41.8k
   }
577
578
909k
   else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
579
0
      png_error(png_ptr, "internal sequential row size calculation error");
580
581
951k
#ifdef PNG_READ_INTERLACING_SUPPORTED
582
   /* Expand interlaced rows to full size */
583
951k
   if (png_ptr->interlaced != 0 &&
584
460k
      (png_ptr->transformations & PNG_INTERLACE) != 0)
585
460k
   {
586
460k
      if (png_ptr->pass < 6)
587
387k
         png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
588
387k
             png_ptr->transformations);
589
590
460k
      if (dsp_row != NULL)
591
0
         png_combine_row(png_ptr, dsp_row, 1/*display*/);
592
593
460k
      if (row != NULL)
594
460k
         png_combine_row(png_ptr, row, 0/*row*/);
595
460k
   }
596
597
490k
   else
598
490k
#endif
599
490k
   {
600
490k
      if (row != NULL)
601
482k
         png_combine_row(png_ptr, row, -1/*ignored*/);
602
603
490k
      if (dsp_row != NULL)
604
0
         png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
605
490k
   }
606
951k
   png_read_finish_row(png_ptr);
607
608
951k
   if (png_ptr->read_row_fn != NULL)
609
0
      (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
610
611
951k
}
612
#endif /* SEQUENTIAL_READ */
613
614
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
615
/* Read one or more rows of image data.  If the image is interlaced,
616
 * and png_set_interlace_handling() has been called, the rows need to
617
 * contain the contents of the rows from the previous pass.  If the
618
 * image has alpha or transparency, and png_handle_alpha()[*] has been
619
 * called, the rows contents must be initialized to the contents of the
620
 * screen.
621
 *
622
 * "row" holds the actual image, and pixels are placed in it
623
 * as they arrive.  If the image is displayed after each pass, it will
624
 * appear to "sparkle" in.  "display_row" can be used to display a
625
 * "chunky" progressive image, with finer detail added as it becomes
626
 * available.  If you do not want this "chunky" display, you may pass
627
 * NULL for display_row.  If you do not want the sparkle display, and
628
 * you have not called png_handle_alpha(), you may pass NULL for rows.
629
 * If you have called png_handle_alpha(), and the image has either an
630
 * alpha channel or a transparency chunk, you must provide a buffer for
631
 * rows.  In this case, you do not have to provide a display_row buffer
632
 * also, but you may.  If the image is not interlaced, or if you have
633
 * not called png_set_interlace_handling(), the display_row buffer will
634
 * be ignored, so pass NULL to it.
635
 *
636
 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
637
 */
638
639
void
640
png_read_rows(png_structrp png_ptr, png_bytepp row,
641
    png_bytepp display_row, png_uint_32 num_rows)
642
0
{
643
0
   png_uint_32 i;
644
0
   png_bytepp rp;
645
0
   png_bytepp dp;
646
647
0
   png_debug(1, "in png_read_rows");
648
649
0
   if (png_ptr == NULL)
650
0
      return;
651
652
0
   rp = row;
653
0
   dp = display_row;
654
0
   if (rp != NULL && dp != NULL)
655
0
      for (i = 0; i < num_rows; i++)
656
0
      {
657
0
         png_bytep rptr = *rp++;
658
0
         png_bytep dptr = *dp++;
659
660
0
         png_read_row(png_ptr, rptr, dptr);
661
0
      }
662
663
0
   else if (rp != NULL)
664
0
      for (i = 0; i < num_rows; i++)
665
0
      {
666
0
         png_bytep rptr = *rp;
667
0
         png_read_row(png_ptr, rptr, NULL);
668
0
         rp++;
669
0
      }
670
671
0
   else if (dp != NULL)
672
0
      for (i = 0; i < num_rows; i++)
673
0
      {
674
0
         png_bytep dptr = *dp;
675
0
         png_read_row(png_ptr, NULL, dptr);
676
0
         dp++;
677
0
      }
678
0
}
679
#endif /* SEQUENTIAL_READ */
680
681
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
682
/* Read the entire image.  If the image has an alpha channel or a tRNS
683
 * chunk, and you have called png_handle_alpha()[*], you will need to
684
 * initialize the image to the current image that PNG will be overlaying.
685
 * We set the num_rows again here, in case it was incorrectly set in
686
 * png_read_start_row() by a call to png_read_update_info() or
687
 * png_start_read_image() if png_set_interlace_handling() wasn't called
688
 * prior to either of these functions like it should have been.  You can
689
 * only call this function once.  If you desire to have an image for
690
 * each pass of a interlaced image, use png_read_rows() instead.
691
 *
692
 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
693
 */
694
void
695
png_read_image(png_structrp png_ptr, png_bytepp image)
696
0
{
697
0
   png_uint_32 i, image_height;
698
0
   int pass, j;
699
0
   png_bytepp rp;
700
701
0
   png_debug(1, "in png_read_image");
702
703
0
   if (png_ptr == NULL)
704
0
      return;
705
706
0
#ifdef PNG_READ_INTERLACING_SUPPORTED
707
0
   if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
708
0
   {
709
0
      pass = png_set_interlace_handling(png_ptr);
710
      /* And make sure transforms are initialized. */
711
0
      png_start_read_image(png_ptr);
712
0
   }
713
0
   else
714
0
   {
715
0
      if (png_ptr->interlaced != 0 &&
716
0
          (png_ptr->transformations & PNG_INTERLACE) == 0)
717
0
      {
718
         /* Caller called png_start_read_image or png_read_update_info without
719
          * first turning on the PNG_INTERLACE transform.  We can fix this here,
720
          * but the caller should do it!
721
          */
722
0
         png_warning(png_ptr, "Interlace handling should be turned on when "
723
0
             "using png_read_image");
724
         /* Make sure this is set correctly */
725
0
         png_ptr->num_rows = png_ptr->height;
726
0
      }
727
728
      /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
729
       * the above error case.
730
       */
731
0
      pass = png_set_interlace_handling(png_ptr);
732
0
   }
733
#else
734
   if (png_ptr->interlaced)
735
      png_error(png_ptr,
736
          "Cannot read interlaced image -- interlace handler disabled");
737
738
   pass = 1;
739
#endif
740
741
0
   image_height=png_ptr->height;
742
743
0
   for (j = 0; j < pass; j++)
744
0
   {
745
0
      rp = image;
746
0
      for (i = 0; i < image_height; i++)
747
0
      {
748
0
         png_read_row(png_ptr, *rp, NULL);
749
0
         rp++;
750
0
      }
751
0
   }
752
0
}
753
#endif /* SEQUENTIAL_READ */
754
755
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
756
/* Read the end of the PNG file.  Will not read past the end of the
757
 * file, will verify the end is accurate, and will read any comments
758
 * or time information at the end of the file, if info is not NULL.
759
 */
760
void
761
png_read_end(png_structrp png_ptr, png_inforp info_ptr)
762
34.9k
{
763
34.9k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
764
34.9k
   int keep;
765
34.9k
#endif
766
767
34.9k
   png_debug(1, "in png_read_end");
768
769
34.9k
   if (png_ptr == NULL)
770
0
      return;
771
772
   /* If png_read_end is called in the middle of reading the rows there may
773
    * still be pending IDAT data and an owned zstream.  Deal with this here.
774
    */
775
34.9k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
776
34.9k
   if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
777
34.9k
#endif
778
34.9k
      png_read_finish_IDAT(png_ptr);
779
780
34.9k
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
781
   /* Report invalid palette index; added at libng-1.5.10 */
782
34.9k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
783
1.01k
       png_ptr->num_palette_max >= png_ptr->num_palette)
784
0
      png_benign_error(png_ptr, "Read palette index exceeding num_palette");
785
34.9k
#endif
786
787
34.9k
   do
788
86.2k
   {
789
86.2k
      png_uint_32 length = png_read_chunk_header(png_ptr);
790
86.2k
      png_uint_32 chunk_name = png_ptr->chunk_name;
791
792
86.2k
      if (chunk_name != png_IDAT)
793
78.7k
      {
794
         /* These flags must be set consistently for all non-IDAT chunks,
795
          * including the unknown chunks.
796
          */
797
78.7k
         png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT | PNG_AFTER_IDAT;
798
78.7k
      }
799
800
86.2k
      if (chunk_name == png_IEND)
801
33.6k
         png_handle_chunk(png_ptr, info_ptr, length);
802
803
52.5k
      else if (chunk_name == png_IHDR)
804
11
         png_handle_chunk(png_ptr, info_ptr, length);
805
806
52.5k
      else if (info_ptr == NULL)
807
0
         png_crc_finish(png_ptr, length);
808
809
52.5k
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
810
52.5k
      else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
811
7.01k
      {
812
7.01k
         if (chunk_name == png_IDAT)
813
0
         {
814
0
            if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
815
0
                || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
816
0
               png_benign_error(png_ptr, ".Too many IDATs found");
817
0
         }
818
7.01k
         png_handle_unknown(png_ptr, info_ptr, length, keep);
819
7.01k
         if (chunk_name == png_PLTE)
820
0
            png_ptr->mode |= PNG_HAVE_PLTE;
821
7.01k
      }
822
45.5k
#endif
823
824
45.5k
      else if (chunk_name == png_IDAT)
825
7.15k
      {
826
         /* Zero length IDATs are legal after the last IDAT has been
827
          * read, but not after other chunks have been read.  1.6 does not
828
          * always read all the deflate data; specifically it cannot be relied
829
          * upon to read the Adler32 at the end.  If it doesn't ignore IDAT
830
          * chunks which are longer than zero as well:
831
          */
832
7.15k
         if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
833
7.15k
             || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
834
2.19k
            png_benign_error(png_ptr, "..Too many IDATs found");
835
836
7.15k
         png_crc_finish(png_ptr, length);
837
7.15k
      }
838
839
38.4k
      else
840
38.4k
         png_handle_chunk(png_ptr, info_ptr, length);
841
86.2k
   } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
842
34.9k
}
843
#endif /* SEQUENTIAL_READ */
844
845
/* Free all memory used in the read struct */
846
static void
847
png_read_destroy(png_structrp png_ptr)
848
87.5k
{
849
87.5k
   png_debug(1, "in png_read_destroy");
850
851
87.5k
#ifdef PNG_READ_GAMMA_SUPPORTED
852
87.5k
   png_destroy_gamma_table(png_ptr);
853
87.5k
#endif
854
855
87.5k
   png_free(png_ptr, png_ptr->big_row_buf);
856
87.5k
   png_ptr->big_row_buf = NULL;
857
87.5k
   png_free(png_ptr, png_ptr->big_prev_row);
858
87.5k
   png_ptr->big_prev_row = NULL;
859
87.5k
   png_free(png_ptr, png_ptr->read_buffer);
860
87.5k
   png_ptr->read_buffer = NULL;
861
862
87.5k
#ifdef PNG_READ_QUANTIZE_SUPPORTED
863
87.5k
   png_free(png_ptr, png_ptr->palette_lookup);
864
87.5k
   png_ptr->palette_lookup = NULL;
865
87.5k
   png_free(png_ptr, png_ptr->quantize_index);
866
87.5k
   png_ptr->quantize_index = NULL;
867
87.5k
#endif
868
869
87.5k
   if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
870
0
   {
871
0
      png_zfree(png_ptr, png_ptr->palette);
872
0
      png_ptr->palette = NULL;
873
0
   }
874
87.5k
   png_ptr->free_me &= ~PNG_FREE_PLTE;
875
876
87.5k
#if defined(PNG_tRNS_SUPPORTED) || \
877
87.5k
    defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
878
87.5k
   if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
879
0
   {
880
0
      png_free(png_ptr, png_ptr->trans_alpha);
881
0
      png_ptr->trans_alpha = NULL;
882
0
   }
883
87.5k
   png_ptr->free_me &= ~PNG_FREE_TRNS;
884
87.5k
#endif
885
886
87.5k
   inflateEnd(&png_ptr->zstream);
887
888
87.5k
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
889
87.5k
   png_free(png_ptr, png_ptr->save_buffer);
890
87.5k
   png_ptr->save_buffer = NULL;
891
87.5k
#endif
892
893
87.5k
#if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
894
87.5k
   defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
895
87.5k
   png_free(png_ptr, png_ptr->unknown_chunk.data);
896
87.5k
   png_ptr->unknown_chunk.data = NULL;
897
87.5k
#endif
898
899
87.5k
#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
900
87.5k
   png_free(png_ptr, png_ptr->chunk_list);
901
87.5k
   png_ptr->chunk_list = NULL;
902
87.5k
#endif
903
904
#ifdef PNG_TARGET_STORES_DATA
905
   if (png_ptr->target_data != NULL)
906
      png_target_free_data(png_ptr);
907
   png_ptr->target_data = NULL;
908
#endif
909
910
   /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
911
    * callbacks are still set at this point.  They are required to complete the
912
    * destruction of the png_struct itself.
913
    */
914
87.5k
}
915
916
/* Free all memory used by the read */
917
void
918
png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
919
    png_infopp end_info_ptr_ptr)
920
87.5k
{
921
87.5k
   png_structrp png_ptr = NULL;
922
923
87.5k
   png_debug(1, "in png_destroy_read_struct");
924
925
87.5k
   if (png_ptr_ptr != NULL)
926
87.5k
      png_ptr = *png_ptr_ptr;
927
928
87.5k
   if (png_ptr == NULL)
929
0
      return;
930
931
   /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
932
    * behavior.  Prior to 1.6.0 libpng did extra 'info' destruction in this API.
933
    * The extra was, apparently, unnecessary yet this hides memory leak bugs.
934
    */
935
87.5k
   png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
936
87.5k
   png_destroy_info_struct(png_ptr, info_ptr_ptr);
937
938
87.5k
   *png_ptr_ptr = NULL;
939
87.5k
   png_read_destroy(png_ptr);
940
87.5k
   png_destroy_png_struct(png_ptr);
941
87.5k
}
942
943
void
944
png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
945
0
{
946
0
   if (png_ptr == NULL)
947
0
      return;
948
949
0
   png_ptr->read_row_fn = read_row_fn;
950
0
}
951
952
953
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
954
#ifdef PNG_INFO_IMAGE_SUPPORTED
955
void
956
png_read_png(png_structrp png_ptr, png_inforp info_ptr,
957
    int transforms, voidp params)
958
0
{
959
0
   png_debug(1, "in png_read_png");
960
961
0
   if (png_ptr == NULL || info_ptr == NULL)
962
0
      return;
963
964
   /* png_read_info() gives us all of the information from the
965
    * PNG file before the first IDAT (image data chunk).
966
    */
967
0
   png_read_info(png_ptr, info_ptr);
968
0
   if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
969
0
      png_error(png_ptr, "Image is too high to process with png_read_png()");
970
971
   /* -------------- image transformations start here ------------------- */
972
   /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
973
    * is not implemented.  This will only happen in de-configured (non-default)
974
    * libpng builds.  The results can be unexpected - png_read_png may return
975
    * short or mal-formed rows because the transform is skipped.
976
    */
977
978
   /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
979
    */
980
0
   if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
981
      /* Added at libpng-1.5.4. "strip_16" produces the same result that it
982
       * did in earlier versions, while "scale_16" is now more accurate.
983
       */
984
0
#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
985
0
      png_set_scale_16(png_ptr);
986
#else
987
      png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
988
#endif
989
990
   /* If both SCALE and STRIP are required pngrtran will effectively cancel the
991
    * latter by doing SCALE first.  This is ok and allows apps not to check for
992
    * which is supported to get the right answer.
993
    */
994
0
   if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
995
0
#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
996
0
      png_set_strip_16(png_ptr);
997
#else
998
      png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
999
#endif
1000
1001
   /* Strip alpha bytes from the input data without combining with
1002
    * the background (not recommended).
1003
    */
1004
0
   if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1005
0
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1006
0
      png_set_strip_alpha(png_ptr);
1007
#else
1008
      png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1009
#endif
1010
1011
   /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1012
    * byte into separate bytes (useful for paletted and grayscale images).
1013
    */
1014
0
   if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1015
0
#ifdef PNG_READ_PACK_SUPPORTED
1016
0
      png_set_packing(png_ptr);
1017
#else
1018
      png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1019
#endif
1020
1021
   /* Change the order of packed pixels to least significant bit first
1022
    * (not useful if you are using png_set_packing).
1023
    */
1024
0
   if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1025
0
#ifdef PNG_READ_PACKSWAP_SUPPORTED
1026
0
      png_set_packswap(png_ptr);
1027
#else
1028
      png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1029
#endif
1030
1031
   /* Expand paletted colors into true RGB triplets
1032
    * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1033
    * Expand paletted or RGB images with transparency to full alpha
1034
    * channels so the data will be available as RGBA quartets.
1035
    */
1036
0
   if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1037
0
#ifdef PNG_READ_EXPAND_SUPPORTED
1038
0
      png_set_expand(png_ptr);
1039
#else
1040
      png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1041
#endif
1042
1043
   /* We don't handle background color or gamma transformation or quantizing.
1044
    */
1045
1046
   /* Invert monochrome files to have 0 as white and 1 as black
1047
    */
1048
0
   if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1049
0
#ifdef PNG_READ_INVERT_SUPPORTED
1050
0
      png_set_invert_mono(png_ptr);
1051
#else
1052
      png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1053
#endif
1054
1055
   /* If you want to shift the pixel values from the range [0,255] or
1056
    * [0,65535] to the original [0,7] or [0,31], or whatever range the
1057
    * colors were originally in:
1058
    */
1059
0
   if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1060
0
#ifdef PNG_READ_SHIFT_SUPPORTED
1061
0
      if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1062
0
         png_set_shift(png_ptr, &info_ptr->sig_bit);
1063
#else
1064
      png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1065
#endif
1066
1067
   /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1068
0
   if ((transforms & PNG_TRANSFORM_BGR) != 0)
1069
0
#ifdef PNG_READ_BGR_SUPPORTED
1070
0
      png_set_bgr(png_ptr);
1071
#else
1072
      png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1073
#endif
1074
1075
   /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1076
0
   if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1077
0
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1078
0
      png_set_swap_alpha(png_ptr);
1079
#else
1080
      png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1081
#endif
1082
1083
   /* Swap bytes of 16-bit files to least significant byte first */
1084
0
   if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1085
0
#ifdef PNG_READ_SWAP_SUPPORTED
1086
0
      png_set_swap(png_ptr);
1087
#else
1088
      png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1089
#endif
1090
1091
/* Added at libpng-1.2.41 */
1092
   /* Invert the alpha channel from opacity to transparency */
1093
0
   if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1094
0
#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1095
0
      png_set_invert_alpha(png_ptr);
1096
#else
1097
      png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1098
#endif
1099
1100
/* Added at libpng-1.2.41 */
1101
   /* Expand grayscale image to RGB */
1102
0
   if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1103
0
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1104
0
      png_set_gray_to_rgb(png_ptr);
1105
#else
1106
      png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1107
#endif
1108
1109
/* Added at libpng-1.5.4 */
1110
0
   if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1111
0
#ifdef PNG_READ_EXPAND_16_SUPPORTED
1112
0
      png_set_expand_16(png_ptr);
1113
#else
1114
      png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1115
#endif
1116
1117
   /* We don't handle adding filler bytes */
1118
1119
   /* We use png_read_image and rely on that for interlace handling, but we also
1120
    * call png_read_update_info therefore must turn on interlace handling now:
1121
    */
1122
0
   (void)png_set_interlace_handling(png_ptr);
1123
1124
   /* Optional call to gamma correct and add the background to the palette
1125
    * and update info structure.  REQUIRED if you are expecting libpng to
1126
    * update the palette for you (i.e., you selected such a transform above).
1127
    */
1128
0
   png_read_update_info(png_ptr, info_ptr);
1129
1130
   /* -------------- image transformations end here ------------------- */
1131
1132
0
   png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1133
0
   if (info_ptr->row_pointers == NULL)
1134
0
   {
1135
0
      png_uint_32 iptr;
1136
1137
0
      info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1138
0
          info_ptr->height * (sizeof (png_bytep))));
1139
1140
0
      for (iptr=0; iptr<info_ptr->height; iptr++)
1141
0
         info_ptr->row_pointers[iptr] = NULL;
1142
1143
0
      info_ptr->free_me |= PNG_FREE_ROWS;
1144
1145
0
      for (iptr = 0; iptr < info_ptr->height; iptr++)
1146
0
         info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1147
0
             png_malloc(png_ptr, info_ptr->rowbytes));
1148
0
   }
1149
1150
0
   png_read_image(png_ptr, info_ptr->row_pointers);
1151
0
   info_ptr->valid |= PNG_INFO_IDAT;
1152
1153
   /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1154
0
   png_read_end(png_ptr, info_ptr);
1155
1156
0
   PNG_UNUSED(params)
1157
0
}
1158
#endif /* INFO_IMAGE */
1159
#endif /* SEQUENTIAL_READ */
1160
1161
#ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1162
/* SIMPLIFIED READ
1163
 *
1164
 * This code currently relies on the sequential reader, though it could easily
1165
 * be made to work with the progressive one.
1166
 */
1167
/* Arguments to png_image_finish_read: */
1168
1169
/* Encoding of PNG data (used by the color-map code) */
1170
0
#  define P_NOTSET  0 /* File encoding not yet known */
1171
0
#  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
1172
0
#  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1173
0
#  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
1174
0
#  define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1175
1176
/* Color-map processing: after libpng has run on the PNG image further
1177
 * processing may be needed to convert the data to color-map indices.
1178
 */
1179
0
#define PNG_CMAP_NONE      0
1180
0
#define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
1181
0
#define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
1182
0
#define PNG_CMAP_RGB       3 /* Process RGB data */
1183
0
#define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1184
1185
/* The following document where the background is for each processing case. */
1186
0
#define PNG_CMAP_NONE_BACKGROUND      256
1187
0
#define PNG_CMAP_GA_BACKGROUND        231
1188
0
#define PNG_CMAP_TRANS_BACKGROUND     254
1189
0
#define PNG_CMAP_RGB_BACKGROUND       256
1190
0
#define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1191
1192
typedef struct
1193
{
1194
   /* Arguments: */
1195
   png_imagep image;
1196
   png_voidp  buffer;
1197
   png_int_32 row_stride;
1198
   png_voidp  colormap;
1199
   png_const_colorp background;
1200
   /* Local variables: */
1201
   png_voidp       local_row;
1202
   png_voidp       first_row;
1203
   ptrdiff_t       row_bytes;           /* 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_imagep image)
1216
0
{
1217
0
   if (image->opaque == NULL)
1218
0
   {
1219
0
      png_structp 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_infop info_ptr = png_create_info_struct(png_ptr);
1231
1232
0
         if (info_ptr != NULL)
1233
0
         {
1234
0
            png_controlp control = png_voidcast(png_controlp,
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_structrp 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(png_const_structrp 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 occured 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(png_voidp argument)
1364
0
{
1365
0
   png_imagep image = png_voidcast(png_imagep, argument);
1366
0
   png_structrp png_ptr = image->opaque->png_ptr;
1367
0
   png_inforp 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_imagep 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_imagep 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_structp png_ptr, png_bytep out, size_t need)
1494
0
{
1495
0
   if (png_ptr != NULL)
1496
0
   {
1497
0
      png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1498
0
      if (image != NULL)
1499
0
      {
1500
0
         png_controlp cp = image->opaque;
1501
0
         if (cp != NULL)
1502
0
         {
1503
0
            png_const_bytep 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_imagep image,
1523
    png_const_voidp 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(png_const_bytep, 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_structrp 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_structrp 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_imagep 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_16p entry = png_voidcast(png_uint_16p, 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_bytep entry = png_voidcast(png_bytep, 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(png_voidp argument)
2048
0
{
2049
0
   png_image_read_control *display =
2050
0
      png_voidcast(png_image_read_control*, argument);
2051
0
   png_imagep image = display->image;
2052
2053
0
   png_structrp 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_g;
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((png_const_bytep)display->colormap +
2693
0
                      sample_size * cmap_entries,
2694
0
                      (png_const_bytep)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
            png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2766
0
            png_const_colorp 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(png_voidp argument)
2901
0
{
2902
0
   png_image_read_control *display = png_voidcast(png_image_read_control*,
2903
0
       argument);
2904
0
   png_imagep image = display->image;
2905
0
   png_structrp 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_bytep    first_row = png_voidcast(png_bytep, display->first_row);
2931
0
      ptrdiff_t    step_row = display->row_bytes;
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_bytep inrow = png_voidcast(png_bytep, display->local_row);
2961
0
            png_bytep outrow = first_row + y * step_row;
2962
0
            png_const_bytep end_row = outrow + width;
2963
2964
            /* Read 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 < end_row; 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 < end_row; 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 < end_row; 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 < end_row; 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[0] & 0x80) back_i += 3; /* green */
3067
0
                        if (inrow[0] & 0x40) back_i += 3;
3068
0
                        if (inrow[0] & 0x80) back_i += 1; /* blue */
3069
0
                        if (inrow[0] & 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(png_voidp argument)
3090
0
{
3091
0
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3092
0
       argument);
3093
0
   png_imagep image = display->image;
3094
0
   png_controlp control = image->opaque;
3095
0
   png_structrp png_ptr = control->png_ptr;
3096
0
   png_inforp 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
      png_voidp first_row = display->buffer;
3170
0
      ptrdiff_t row_bytes = display->row_stride;
3171
3172
      /* The following expression is designed to work correctly whether it gives
3173
       * a signed or an unsigned result.
3174
       */
3175
0
      if (row_bytes < 0)
3176
0
      {
3177
0
         char *ptr = png_voidcast(char*, first_row);
3178
0
         ptr += (image->height-1) * (-row_bytes);
3179
0
         first_row = png_voidcast(png_voidp, ptr);
3180
0
      }
3181
3182
0
      display->first_row = first_row;
3183
0
      display->row_bytes = row_bytes;
3184
0
   }
3185
3186
0
   if (passes == 0)
3187
0
   {
3188
0
      int result;
3189
0
      png_voidp 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
      png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3202
3203
0
      while (--passes >= 0)
3204
0
      {
3205
0
         png_uint_32      y = image->height;
3206
0
         png_bytep        row = png_voidcast(png_bytep, 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_bytes;
3212
0
         }
3213
0
      }
3214
3215
0
      return 1;
3216
0
   }
3217
0
}
3218
3219
/* Just the row reading part of png_image_read. */
3220
static int
3221
png_image_read_composite(png_voidp argument)
3222
0
{
3223
0
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3224
0
       argument);
3225
0
   png_imagep image = display->image;
3226
0
   png_structrp png_ptr = image->opaque->png_ptr;
3227
0
   int passes;
3228
3229
0
   switch (png_ptr->interlaced)
3230
0
   {
3231
0
      case PNG_INTERLACE_NONE:
3232
0
         passes = 1;
3233
0
         break;
3234
3235
0
      case PNG_INTERLACE_ADAM7:
3236
0
         passes = PNG_INTERLACE_ADAM7_PASSES;
3237
0
         break;
3238
3239
0
      default:
3240
0
         png_error(png_ptr, "unknown interlace type");
3241
0
   }
3242
3243
0
   {
3244
0
      png_uint_32  height = image->height;
3245
0
      png_uint_32  width = image->width;
3246
0
      ptrdiff_t    step_row = display->row_bytes;
3247
0
      unsigned int channels =
3248
0
          (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3249
0
      int pass;
3250
3251
0
      for (pass = 0; pass < passes; ++pass)
3252
0
      {
3253
0
         unsigned int     startx, stepx, stepy;
3254
0
         png_uint_32      y;
3255
3256
0
         if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3257
0
         {
3258
            /* The row may be empty for a short image: */
3259
0
            if (PNG_PASS_COLS(width, pass) == 0)
3260
0
               continue;
3261
3262
0
            startx = PNG_PASS_START_COL(pass) * channels;
3263
0
            stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3264
0
            y = PNG_PASS_START_ROW(pass);
3265
0
            stepy = PNG_PASS_ROW_OFFSET(pass);
3266
0
         }
3267
3268
0
         else
3269
0
         {
3270
0
            y = 0;
3271
0
            startx = 0;
3272
0
            stepx = channels;
3273
0
            stepy = 1;
3274
0
         }
3275
3276
0
         for (; y<height; y += stepy)
3277
0
         {
3278
0
            png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3279
0
            png_bytep outrow;
3280
0
            png_const_bytep end_row;
3281
3282
            /* Read the row, which is packed: */
3283
0
            png_read_row(png_ptr, inrow, NULL);
3284
3285
0
            outrow = png_voidcast(png_bytep, display->first_row);
3286
0
            outrow += y * step_row;
3287
0
            end_row = outrow + width * channels;
3288
3289
            /* Now do the composition on each pixel in this row. */
3290
0
            outrow += startx;
3291
0
            for (; outrow < end_row; outrow += stepx)
3292
0
            {
3293
0
               png_byte alpha = inrow[channels];
3294
3295
0
               if (alpha > 0) /* else no change to the output */
3296
0
               {
3297
0
                  unsigned int c;
3298
3299
0
                  for (c=0; c<channels; ++c)
3300
0
                  {
3301
0
                     png_uint_32 component = inrow[c];
3302
3303
0
                     if (alpha < 255) /* else just use component */
3304
0
                     {
3305
                        /* This is PNG_OPTIMIZED_ALPHA, the component value
3306
                         * is a linear 8-bit value.  Combine this with the
3307
                         * current outrow[c] value which is sRGB encoded.
3308
                         * Arithmetic here is 16-bits to preserve the output
3309
                         * values correctly.
3310
                         */
3311
0
                        component *= 257*255; /* =65535 */
3312
0
                        component += (255-alpha)*png_sRGB_table[outrow[c]];
3313
3314
                        /* So 'component' is scaled by 255*65535 and is
3315
                         * therefore appropriate for the sRGB to linear
3316
                         * conversion table.
3317
                         */
3318
0
                        component = PNG_sRGB_FROM_LINEAR(component);
3319
0
                     }
3320
3321
0
                     outrow[c] = (png_byte)component;
3322
0
                  }
3323
0
               }
3324
3325
0
               inrow += channels+1; /* components and alpha channel */
3326
0
            }
3327
0
         }
3328
0
      }
3329
0
   }
3330
3331
0
   return 1;
3332
0
}
3333
3334
/* The do_local_background case; called when all the following transforms are to
3335
 * be done:
3336
 *
3337
 * PNG_RGB_TO_GRAY
3338
 * PNG_COMPOSITE
3339
 * PNG_GAMMA
3340
 *
3341
 * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3342
 * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3343
 * correction.  The fix-up is to prevent the PNG_COMPOSITE operation from
3344
 * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3345
 * row and handles the removal or pre-multiplication of the alpha channel.
3346
 */
3347
static int
3348
png_image_read_background(png_voidp argument)
3349
0
{
3350
0
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3351
0
       argument);
3352
0
   png_imagep image = display->image;
3353
0
   png_structrp png_ptr = image->opaque->png_ptr;
3354
0
   png_inforp info_ptr = image->opaque->info_ptr;
3355
0
   png_uint_32 height = image->height;
3356
0
   png_uint_32 width = image->width;
3357
0
   int pass, passes;
3358
3359
   /* Double check the convoluted logic below.  We expect to get here with
3360
    * libpng doing rgb to gray and gamma correction but background processing
3361
    * left to the png_image_read_background function.  The rows libpng produce
3362
    * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3363
    */
3364
0
   if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3365
0
      png_error(png_ptr, "lost rgb to gray");
3366
3367
0
   if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3368
0
      png_error(png_ptr, "unexpected compose");
3369
3370
0
   if (png_get_channels(png_ptr, info_ptr) != 2)
3371
0
      png_error(png_ptr, "lost/gained channels");
3372
3373
   /* Expect the 8-bit case to always remove the alpha channel */
3374
0
   if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3375
0
      (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3376
0
      png_error(png_ptr, "unexpected 8-bit transformation");
3377
3378
0
   switch (png_ptr->interlaced)
3379
0
   {
3380
0
      case PNG_INTERLACE_NONE:
3381
0
         passes = 1;
3382
0
         break;
3383
3384
0
      case PNG_INTERLACE_ADAM7:
3385
0
         passes = PNG_INTERLACE_ADAM7_PASSES;
3386
0
         break;
3387
3388
0
      default:
3389
0
         png_error(png_ptr, "unknown interlace type");
3390
0
   }
3391
3392
   /* Use direct access to info_ptr here because otherwise the simplified API
3393
    * would require PNG_EASY_ACCESS_SUPPORTED (just for this.)  Note this is
3394
    * checking the value after libpng expansions, not the original value in the
3395
    * PNG.
3396
    */
3397
0
   switch (info_ptr->bit_depth)
3398
0
   {
3399
0
      case 8:
3400
         /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3401
          * to be removed by composing on a background: either the row if
3402
          * display->background is NULL or display->background->green if not.
3403
          * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3404
          */
3405
0
         {
3406
0
            png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3407
0
            ptrdiff_t step_row = display->row_bytes;
3408
3409
0
            for (pass = 0; pass < passes; ++pass)
3410
0
            {
3411
0
               unsigned int     startx, stepx, stepy;
3412
0
               png_uint_32      y;
3413
3414
0
               if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3415
0
               {
3416
                  /* The row may be empty for a short image: */
3417
0
                  if (PNG_PASS_COLS(width, pass) == 0)
3418
0
                     continue;
3419
3420
0
                  startx = PNG_PASS_START_COL(pass);
3421
0
                  stepx = PNG_PASS_COL_OFFSET(pass);
3422
0
                  y = PNG_PASS_START_ROW(pass);
3423
0
                  stepy = PNG_PASS_ROW_OFFSET(pass);
3424
0
               }
3425
3426
0
               else
3427
0
               {
3428
0
                  y = 0;
3429
0
                  startx = 0;
3430
0
                  stepx = stepy = 1;
3431
0
               }
3432
3433
0
               if (display->background == NULL)
3434
0
               {
3435
0
                  for (; y<height; y += stepy)
3436
0
                  {
3437
0
                     png_bytep inrow = png_voidcast(png_bytep,
3438
0
                         display->local_row);
3439
0
                     png_bytep outrow = first_row + y * step_row;
3440
0
                     png_const_bytep end_row = outrow + width;
3441
3442
                     /* Read the row, which is packed: */
3443
0
                     png_read_row(png_ptr, inrow, NULL);
3444
3445
                     /* Now do the composition on each pixel in this row. */
3446
0
                     outrow += startx;
3447
0
                     for (; outrow < end_row; outrow += stepx)
3448
0
                     {
3449
0
                        png_byte alpha = inrow[1];
3450
3451
0
                        if (alpha > 0) /* else no change to the output */
3452
0
                        {
3453
0
                           png_uint_32 component = inrow[0];
3454
3455
0
                           if (alpha < 255) /* else just use component */
3456
0
                           {
3457
                              /* Since PNG_OPTIMIZED_ALPHA was not set it is
3458
                               * necessary to invert the sRGB transfer
3459
                               * function and multiply the alpha out.
3460
                               */
3461
0
                              component = png_sRGB_table[component] * alpha;
3462
0
                              component += png_sRGB_table[outrow[0]] *
3463
0
                                 (255-alpha);
3464
0
                              component = PNG_sRGB_FROM_LINEAR(component);
3465
0
                           }
3466
3467
0
                           outrow[0] = (png_byte)component;
3468
0
                        }
3469
3470
0
                        inrow += 2; /* gray and alpha channel */
3471
0
                     }
3472
0
                  }
3473
0
               }
3474
3475
0
               else /* constant background value */
3476
0
               {
3477
0
                  png_byte background8 = display->background->green;
3478
0
                  png_uint_16 background = png_sRGB_table[background8];
3479
3480
0
                  for (; y<height; y += stepy)
3481
0
                  {
3482
0
                     png_bytep inrow = png_voidcast(png_bytep,
3483
0
                         display->local_row);
3484
0
                     png_bytep outrow = first_row + y * step_row;
3485
0
                     png_const_bytep end_row = outrow + width;
3486
3487
                     /* Read the row, which is packed: */
3488
0
                     png_read_row(png_ptr, inrow, NULL);
3489
3490
                     /* Now do the composition on each pixel in this row. */
3491
0
                     outrow += startx;
3492
0
                     for (; outrow < end_row; outrow += stepx)
3493
0
                     {
3494
0
                        png_byte alpha = inrow[1];
3495
3496
0
                        if (alpha > 0) /* else use background */
3497
0
                        {
3498
0
                           png_uint_32 component = inrow[0];
3499
3500
0
                           if (alpha < 255) /* else just use component */
3501
0
                           {
3502
0
                              component = png_sRGB_table[component] * alpha;
3503
0
                              component += background * (255-alpha);
3504
0
                              component = PNG_sRGB_FROM_LINEAR(component);
3505
0
                           }
3506
3507
0
                           outrow[0] = (png_byte)component;
3508
0
                        }
3509
3510
0
                        else
3511
0
                           outrow[0] = background8;
3512
3513
0
                        inrow += 2; /* gray and alpha channel */
3514
0
                     }
3515
0
                  }
3516
0
               }
3517
0
            }
3518
0
         }
3519
0
         break;
3520
3521
0
      case 16:
3522
         /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3523
          * still be done and, maybe, the alpha channel removed.  This code also
3524
          * handles the alpha-first option.
3525
          */
3526
0
         {
3527
0
            png_uint_16p first_row = png_voidcast(png_uint_16p,
3528
0
                display->first_row);
3529
            /* The division by two is safe because the caller passed in a
3530
             * stride which was multiplied by 2 (below) to get row_bytes.
3531
             */
3532
0
            ptrdiff_t    step_row = display->row_bytes / 2;
3533
0
            unsigned int preserve_alpha = (image->format &
3534
0
                PNG_FORMAT_FLAG_ALPHA) != 0;
3535
0
            unsigned int outchannels = 1U+preserve_alpha;
3536
0
            int swap_alpha = 0;
3537
3538
0
#           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3539
0
               if (preserve_alpha != 0 &&
3540
0
                   (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3541
0
                  swap_alpha = 1;
3542
0
#           endif
3543
3544
0
            for (pass = 0; pass < passes; ++pass)
3545
0
            {
3546
0
               unsigned int     startx, stepx, stepy;
3547
0
               png_uint_32      y;
3548
3549
               /* The 'x' start and step are adjusted to output components here.
3550
                */
3551
0
               if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3552
0
               {
3553
                  /* The row may be empty for a short image: */
3554
0
                  if (PNG_PASS_COLS(width, pass) == 0)
3555
0
                     continue;
3556
3557
0
                  startx = PNG_PASS_START_COL(pass) * outchannels;
3558
0
                  stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3559
0
                  y = PNG_PASS_START_ROW(pass);
3560
0
                  stepy = PNG_PASS_ROW_OFFSET(pass);
3561
0
               }
3562
3563
0
               else
3564
0
               {
3565
0
                  y = 0;
3566
0
                  startx = 0;
3567
0
                  stepx = outchannels;
3568
0
                  stepy = 1;
3569
0
               }
3570
3571
0
               for (; y<height; y += stepy)
3572
0
               {
3573
0
                  png_const_uint_16p inrow;
3574
0
                  png_uint_16p outrow = first_row + y*step_row;
3575
0
                  png_uint_16p end_row = outrow + width * outchannels;
3576
3577
                  /* Read the row, which is packed: */
3578
0
                  png_read_row(png_ptr, png_voidcast(png_bytep,
3579
0
                      display->local_row), NULL);
3580
0
                  inrow = png_voidcast(png_const_uint_16p, display->local_row);
3581
3582
                  /* Now do the pre-multiplication on each pixel in this row.
3583
                   */
3584
0
                  outrow += startx;
3585
0
                  for (; outrow < end_row; outrow += stepx)
3586
0
                  {
3587
0
                     png_uint_32 component = inrow[0];
3588
0
                     png_uint_16 alpha = inrow[1];
3589
3590
0
                     if (alpha > 0) /* else 0 */
3591
0
                     {
3592
0
                        if (alpha < 65535) /* else just use component */
3593
0
                        {
3594
0
                           component *= alpha;
3595
0
                           component += 32767;
3596
0
                           component /= 65535;
3597
0
                        }
3598
0
                     }
3599
3600
0
                     else
3601
0
                        component = 0;
3602
3603
0
                     outrow[swap_alpha] = (png_uint_16)component;
3604
0
                     if (preserve_alpha != 0)
3605
0
                        outrow[1 ^ swap_alpha] = alpha;
3606
3607
0
                     inrow += 2; /* components and alpha channel */
3608
0
                  }
3609
0
               }
3610
0
            }
3611
0
         }
3612
0
         break;
3613
3614
0
#ifdef __GNUC__
3615
0
      default:
3616
0
         png_error(png_ptr, "unexpected bit depth");
3617
0
#endif
3618
0
   }
3619
3620
0
   return 1;
3621
0
}
3622
3623
/* The guts of png_image_finish_read as a png_safe_execute callback. */
3624
static int
3625
png_image_read_direct(png_voidp argument)
3626
0
{
3627
0
   png_image_read_control *display = png_voidcast(png_image_read_control*,
3628
0
       argument);
3629
0
   png_imagep image = display->image;
3630
0
   png_structrp png_ptr = image->opaque->png_ptr;
3631
0
   png_inforp info_ptr = image->opaque->info_ptr;
3632
3633
0
   png_uint_32 format = image->format;
3634
0
   int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3635
0
   int do_local_compose = 0;
3636
0
   int do_local_background = 0; /* to avoid double gamma correction bug */
3637
0
   int passes = 0;
3638
3639
   /* Add transforms to ensure the correct output format is produced then check
3640
    * that the required implementation support is there.  Always expand; always
3641
    * need 8 bits minimum, no palette and expanded tRNS.
3642
    */
3643
0
   png_set_expand(png_ptr);
3644
3645
   /* Now check the format to see if it was modified. */
3646
0
   {
3647
0
      png_uint_32 base_format = png_image_format(png_ptr) &
3648
0
         ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3649
0
      png_uint_32 change = format ^ base_format;
3650
0
      png_fixed_point output_gamma;
3651
0
      int mode; /* alpha mode */
3652
3653
      /* Do this first so that we have a record if rgb to gray is happening. */
3654
0
      if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3655
0
      {
3656
         /* gray<->color transformation required. */
3657
0
         if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3658
0
            png_set_gray_to_rgb(png_ptr);
3659
3660
0
         else
3661
0
         {
3662
            /* libpng can't do both rgb to gray and
3663
             * background/pre-multiplication if there is also significant gamma
3664
             * correction, because both operations require linear colors and
3665
             * the code only supports one transform doing the gamma correction.
3666
             * Handle this by doing the pre-multiplication or background
3667
             * operation in this code, if necessary.
3668
             *
3669
             * TODO: fix this by rewriting pngrtran.c (!)
3670
             *
3671
             * For the moment (given that fixing this in pngrtran.c is an
3672
             * enormous change) 'do_local_background' is used to indicate that
3673
             * the problem exists.
3674
             */
3675
0
            if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3676
0
               do_local_background = 1/*maybe*/;
3677
3678
0
            png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3679
0
                PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3680
0
         }
3681
3682
0
         change &= ~PNG_FORMAT_FLAG_COLOR;
3683
0
      }
3684
3685
      /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3686
       */
3687
0
      {
3688
         /* This is safe but should no longer be necessary as
3689
          * png_ptr->default_gamma should have been set after the
3690
          * info-before-IDAT was read in png_image_read_header.
3691
          *
3692
          * TODO: 1.8: remove this and see what happens.
3693
          */
3694
0
         png_fixed_point input_gamma_default;
3695
3696
0
         if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3697
0
             (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3698
0
            input_gamma_default = PNG_GAMMA_LINEAR;
3699
0
         else
3700
0
            input_gamma_default = PNG_DEFAULT_sRGB;
3701
3702
         /* Call png_set_alpha_mode to set the default for the input gamma; the
3703
          * output gamma is set by a second call below.
3704
          */
3705
0
         png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3706
0
      }
3707
3708
0
      if (linear != 0)
3709
0
      {
3710
         /* If there *is* an alpha channel in the input it must be multiplied
3711
          * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3712
          */
3713
0
         if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3714
0
            mode = PNG_ALPHA_STANDARD; /* associated alpha */
3715
3716
0
         else
3717
0
            mode = PNG_ALPHA_PNG;
3718
3719
0
         output_gamma = PNG_GAMMA_LINEAR;
3720
0
      }
3721
3722
0
      else
3723
0
      {
3724
0
         mode = PNG_ALPHA_PNG;
3725
0
         output_gamma = PNG_DEFAULT_sRGB;
3726
0
      }
3727
3728
0
      if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
3729
0
      {
3730
0
         mode = PNG_ALPHA_OPTIMIZED;
3731
0
         change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3732
0
      }
3733
3734
      /* If 'do_local_background' is set check for the presence of gamma
3735
       * correction; this is part of the work-round for the libpng bug
3736
       * described above.
3737
       *
3738
       * TODO: fix libpng and remove this.
3739
       */
3740
0
      if (do_local_background != 0)
3741
0
      {
3742
0
         png_fixed_point gtest;
3743
3744
         /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3745
          * gamma correction, the screen gamma hasn't been set on png_struct
3746
          * yet; it's set below.  png_struct::gamma, however, is set to the
3747
          * final value.
3748
          */
3749
0
         if (png_muldiv(&gtest, output_gamma,
3750
0
                  png_resolve_file_gamma(png_ptr), PNG_FP_1) != 0 &&
3751
0
             png_gamma_significant(gtest) == 0)
3752
0
            do_local_background = 0;
3753
3754
0
         else if (mode == PNG_ALPHA_STANDARD)
3755
0
         {
3756
0
            do_local_background = 2/*required*/;
3757
0
            mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3758
0
         }
3759
3760
         /* else leave as 1 for the checks below */
3761
0
      }
3762
3763
      /* If the bit-depth changes then handle that here. */
3764
0
      if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3765
0
      {
3766
0
         if (linear != 0 /*16-bit output*/)
3767
0
            png_set_expand_16(png_ptr);
3768
3769
0
         else /* 8-bit output */
3770
0
            png_set_scale_16(png_ptr);
3771
3772
0
         change &= ~PNG_FORMAT_FLAG_LINEAR;
3773
0
      }
3774
3775
      /* Now the background/alpha channel changes. */
3776
0
      if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3777
0
      {
3778
         /* Removing an alpha channel requires composition for the 8-bit
3779
          * formats; for the 16-bit it is already done, above, by the
3780
          * pre-multiplication and the channel just needs to be stripped.
3781
          */
3782
0
         if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3783
0
         {
3784
            /* If RGB->gray is happening the alpha channel must be left and the
3785
             * operation completed locally.
3786
             *
3787
             * TODO: fix libpng and remove this.
3788
             */
3789
0
            if (do_local_background != 0)
3790
0
               do_local_background = 2/*required*/;
3791
3792
            /* 16-bit output: just remove the channel */
3793
0
            else if (linear != 0) /* compose on black (well, pre-multiply) */
3794
0
               png_set_strip_alpha(png_ptr);
3795
3796
            /* 8-bit output: do an appropriate compose */
3797
0
            else if (display->background != NULL)
3798
0
            {
3799
0
               png_color_16 c;
3800
3801
0
               c.index = 0; /*unused*/
3802
0
               c.red = display->background->red;
3803
0
               c.green = display->background->green;
3804
0
               c.blue = display->background->blue;
3805
0
               c.gray = display->background->green;
3806
3807
               /* This is always an 8-bit sRGB value, using the 'green' channel
3808
                * for gray is much better than calculating the luminance here;
3809
                * we can get off-by-one errors in that calculation relative to
3810
                * the app expectations and that will show up in transparent
3811
                * pixels.
3812
                */
3813
0
               png_set_background_fixed(png_ptr, &c,
3814
0
                   PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3815
0
                   0/*gamma: not used*/);
3816
0
            }
3817
3818
0
            else /* compose on row: implemented below. */
3819
0
            {
3820
0
               do_local_compose = 1;
3821
               /* This leaves the alpha channel in the output, so it has to be
3822
                * removed by the code below.  Set the encoding to the 'OPTIMIZE'
3823
                * one so the code only has to hack on the pixels that require
3824
                * composition.
3825
                */
3826
0
               mode = PNG_ALPHA_OPTIMIZED;
3827
0
            }
3828
0
         }
3829
3830
0
         else /* output needs an alpha channel */
3831
0
         {
3832
            /* This is tricky because it happens before the swap operation has
3833
             * been accomplished; however, the swap does *not* swap the added
3834
             * alpha channel (weird API), so it must be added in the correct
3835
             * place.
3836
             */
3837
0
            png_uint_32 filler; /* opaque filler */
3838
0
            int where;
3839
3840
0
            if (linear != 0)
3841
0
               filler = 65535;
3842
3843
0
            else
3844
0
               filler = 255;
3845
3846
0
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
3847
0
            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3848
0
            {
3849
0
               where = PNG_FILLER_BEFORE;
3850
0
               change &= ~PNG_FORMAT_FLAG_AFIRST;
3851
0
            }
3852
3853
0
            else
3854
0
#endif
3855
0
            where = PNG_FILLER_AFTER;
3856
3857
0
            png_set_add_alpha(png_ptr, filler, where);
3858
0
         }
3859
3860
         /* This stops the (irrelevant) call to swap_alpha below. */
3861
0
         change &= ~PNG_FORMAT_FLAG_ALPHA;
3862
0
      }
3863
3864
      /* Now set the alpha mode correctly; this is always done, even if there is
3865
       * no alpha channel in either the input or the output because it correctly
3866
       * sets the output gamma.
3867
       */
3868
0
      png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3869
3870
0
#     ifdef PNG_FORMAT_BGR_SUPPORTED
3871
0
         if ((change & PNG_FORMAT_FLAG_BGR) != 0)
3872
0
         {
3873
            /* Check only the output format; PNG is never BGR; don't do this if
3874
             * the output is gray, but fix up the 'format' value in that case.
3875
             */
3876
0
            if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3877
0
               png_set_bgr(png_ptr);
3878
3879
0
            else
3880
0
               format &= ~PNG_FORMAT_FLAG_BGR;
3881
3882
0
            change &= ~PNG_FORMAT_FLAG_BGR;
3883
0
         }
3884
0
#     endif
3885
3886
0
#     ifdef PNG_FORMAT_AFIRST_SUPPORTED
3887
0
         if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
3888
0
         {
3889
            /* Only relevant if there is an alpha channel - it's particularly
3890
             * important to handle this correctly because do_local_compose may
3891
             * be set above and then libpng will keep the alpha channel for this
3892
             * code to remove.
3893
             */
3894
0
            if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
3895
0
            {
3896
               /* Disable this if doing a local background,
3897
                * TODO: remove this when local background is no longer required.
3898
                */
3899
0
               if (do_local_background != 2)
3900
0
                  png_set_swap_alpha(png_ptr);
3901
0
            }
3902
3903
0
            else
3904
0
               format &= ~PNG_FORMAT_FLAG_AFIRST;
3905
3906
0
            change &= ~PNG_FORMAT_FLAG_AFIRST;
3907
0
         }
3908
0
#     endif
3909
3910
      /* If the *output* is 16-bit then we need to check for a byte-swap on this
3911
       * architecture.
3912
       */
3913
0
      if (linear != 0)
3914
0
      {
3915
0
         png_uint_16 le = 0x0001;
3916
3917
0
         if ((*(png_const_bytep) & le) != 0)
3918
0
            png_set_swap(png_ptr);
3919
0
      }
3920
3921
      /* If change is not now 0 some transformation is missing - error out. */
3922
0
      if (change != 0)
3923
0
         png_error(png_ptr, "png_read_image: unsupported transformation");
3924
0
   }
3925
3926
0
   PNG_SKIP_CHUNKS(png_ptr);
3927
3928
   /* Update the 'info' structure and make sure the result is as required; first
3929
    * make sure to turn on the interlace handling if it will be required
3930
    * (because it can't be turned on *after* the call to png_read_update_info!)
3931
    *
3932
    * TODO: remove the do_local_background fixup below.
3933
    */
3934
0
   if (do_local_compose == 0 && do_local_background != 2)
3935
0
      passes = png_set_interlace_handling(png_ptr);
3936
3937
0
   png_read_update_info(png_ptr, info_ptr);
3938
3939
0
   {
3940
0
      png_uint_32 info_format = 0;
3941
3942
0
      if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3943
0
         info_format |= PNG_FORMAT_FLAG_COLOR;
3944
3945
0
      if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
3946
0
      {
3947
         /* do_local_compose removes this channel below. */
3948
0
         if (do_local_compose == 0)
3949
0
         {
3950
            /* do_local_background does the same if required. */
3951
0
            if (do_local_background != 2 ||
3952
0
               (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3953
0
               info_format |= PNG_FORMAT_FLAG_ALPHA;
3954
0
         }
3955
0
      }
3956
3957
0
      else if (do_local_compose != 0) /* internal error */
3958
0
         png_error(png_ptr, "png_image_read: alpha channel lost");
3959
3960
0
      if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
3961
0
         info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3962
0
      }
3963
3964
0
      if (info_ptr->bit_depth == 16)
3965
0
         info_format |= PNG_FORMAT_FLAG_LINEAR;
3966
3967
0
#ifdef PNG_FORMAT_BGR_SUPPORTED
3968
0
      if ((png_ptr->transformations & PNG_BGR) != 0)
3969
0
         info_format |= PNG_FORMAT_FLAG_BGR;
3970
0
#endif
3971
3972
0
#ifdef PNG_FORMAT_AFIRST_SUPPORTED
3973
0
         if (do_local_background == 2)
3974
0
         {
3975
0
            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3976
0
               info_format |= PNG_FORMAT_FLAG_AFIRST;
3977
0
         }
3978
3979
0
         if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
3980
0
            ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
3981
0
            (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
3982
0
         {
3983
0
            if (do_local_background == 2)
3984
0
               png_error(png_ptr, "unexpected alpha swap transformation");
3985
3986
0
            info_format |= PNG_FORMAT_FLAG_AFIRST;
3987
0
         }
3988
0
#     endif
3989
3990
      /* This is actually an internal error. */
3991
0
      if (info_format != format)
3992
0
         png_error(png_ptr, "png_read_image: invalid transformations");
3993
0
   }
3994
3995
   /* Now read the rows.  If do_local_compose is set then it is necessary to use
3996
    * a local row buffer.  The output will be GA, RGBA or BGRA and must be
3997
    * converted to G, RGB or BGR as appropriate.  The 'local_row' member of the
3998
    * display acts as a flag.
3999
    */
4000
0
   {
4001
0
      png_voidp first_row = display->buffer;
4002
0
      ptrdiff_t row_bytes = display->row_stride;
4003
4004
0
      if (linear != 0)
4005
0
         row_bytes *= 2;
4006
4007
      /* The following expression is designed to work correctly whether it gives
4008
       * a signed or an unsigned result.
4009
       */
4010
0
      if (row_bytes < 0)
4011
0
      {
4012
0
         char *ptr = png_voidcast(char*, first_row);
4013
0
         ptr += (image->height-1) * (-row_bytes);
4014
0
         first_row = png_voidcast(png_voidp, ptr);
4015
0
      }
4016
4017
0
      display->first_row = first_row;
4018
0
      display->row_bytes = row_bytes;
4019
0
   }
4020
4021
0
   if (do_local_compose != 0)
4022
0
   {
4023
0
      int result;
4024
0
      png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4025
4026
0
      display->local_row = row;
4027
0
      result = png_safe_execute(image, png_image_read_composite, display);
4028
0
      display->local_row = NULL;
4029
0
      png_free(png_ptr, row);
4030
4031
0
      return result;
4032
0
   }
4033
4034
0
   else if (do_local_background == 2)
4035
0
   {
4036
0
      int result;
4037
0
      png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4038
4039
0
      display->local_row = row;
4040
0
      result = png_safe_execute(image, png_image_read_background, display);
4041
0
      display->local_row = NULL;
4042
0
      png_free(png_ptr, row);
4043
4044
0
      return result;
4045
0
   }
4046
4047
0
   else
4048
0
   {
4049
0
      png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4050
4051
0
      while (--passes >= 0)
4052
0
      {
4053
0
         png_uint_32      y = image->height;
4054
0
         png_bytep        row = png_voidcast(png_bytep, display->first_row);
4055
4056
0
         for (; y > 0; --y)
4057
0
         {
4058
0
            png_read_row(png_ptr, row, NULL);
4059
0
            row += row_bytes;
4060
0
         }
4061
0
      }
4062
4063
0
      return 1;
4064
0
   }
4065
0
}
4066
4067
int
4068
png_image_finish_read(png_imagep image, png_const_colorp background,
4069
    void *buffer, png_int_32 row_stride, void *colormap)
4070
0
{
4071
0
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
4072
0
   {
4073
      /* Check for row_stride overflow.  This check is not performed on the
4074
       * original PNG format because it may not occur in the output PNG format
4075
       * and libpng deals with the issues of reading the original.
4076
       */
4077
0
      unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4078
4079
      /* The following checks just the 'row_stride' calculation to ensure it
4080
       * fits in a signed 32-bit value.  Because channels/components can be
4081
       * either 1 or 2 bytes in size the length of a row can still overflow 32
4082
       * bits; this is just to verify that the 'row_stride' argument can be
4083
       * represented.
4084
       */
4085
0
      if (image->width <= 0x7fffffffU/channels) /* no overflow */
4086
0
      {
4087
0
         png_uint_32 check;
4088
0
         png_uint_32 png_row_stride = image->width * channels;
4089
4090
0
         if (row_stride == 0)
4091
0
            row_stride = (png_int_32)/*SAFE*/png_row_stride;
4092
4093
0
         if (row_stride < 0)
4094
0
            check = (png_uint_32)(-row_stride);
4095
4096
0
         else
4097
0
            check = (png_uint_32)row_stride;
4098
4099
         /* This verifies 'check', the absolute value of the actual stride
4100
          * passed in and detects overflow in the application calculation (i.e.
4101
          * if the app did actually pass in a non-zero 'row_stride'.
4102
          */
4103
0
         if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4104
0
         {
4105
            /* Now check for overflow of the image buffer calculation; this
4106
             * limits the whole image size to 32 bits for API compatibility with
4107
             * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4108
             *
4109
             * The PNG_IMAGE_BUFFER_SIZE macro is:
4110
             *
4111
             *    (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4112
             *
4113
             * And the component size is always 1 or 2, so make sure that the
4114
             * number of *bytes* that the application is saying are available
4115
             * does actually fit into a 32-bit number.
4116
             *
4117
             * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4118
             * will be changed to use png_alloc_size_t; bigger images can be
4119
             * accommodated on 64-bit systems.
4120
             */
4121
0
            if (image->height <=
4122
0
                0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4123
0
            {
4124
0
               if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4125
0
                  (image->colormap_entries > 0 && colormap != NULL))
4126
0
               {
4127
0
                  int result;
4128
0
                  png_image_read_control display;
4129
4130
0
                  memset(&display, 0, (sizeof display));
4131
0
                  display.image = image;
4132
0
                  display.buffer = buffer;
4133
0
                  display.row_stride = row_stride;
4134
0
                  display.colormap = colormap;
4135
0
                  display.background = background;
4136
0
                  display.local_row = NULL;
4137
4138
                  /* Choose the correct 'end' routine; for the color-map case
4139
                   * all the setup has already been done.
4140
                   */
4141
0
                  if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4142
0
                     result =
4143
0
                         png_safe_execute(image,
4144
0
                             png_image_read_colormap, &display) &&
4145
0
                             png_safe_execute(image,
4146
0
                             png_image_read_colormapped, &display);
4147
4148
0
                  else
4149
0
                     result =
4150
0
                        png_safe_execute(image,
4151
0
                            png_image_read_direct, &display);
4152
4153
0
                  png_image_free(image);
4154
0
                  return result;
4155
0
               }
4156
4157
0
               else
4158
0
                  return png_image_error(image,
4159
0
                      "png_image_finish_read[color-map]: no color-map");
4160
0
            }
4161
4162
0
            else
4163
0
               return png_image_error(image,
4164
0
                   "png_image_finish_read: image too large");
4165
0
         }
4166
4167
0
         else
4168
0
            return png_image_error(image,
4169
0
                "png_image_finish_read: invalid argument");
4170
0
      }
4171
4172
0
      else
4173
0
         return png_image_error(image,
4174
0
             "png_image_finish_read: row_stride too large");
4175
0
   }
4176
4177
0
   else if (image != NULL)
4178
0
      return png_image_error(image,
4179
0
          "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4180
4181
0
   return 0;
4182
0
}
4183
4184
#endif /* SIMPLIFIED_READ */
4185
#endif /* READ */