Coverage Report

Created: 2021-08-22 09:07

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