Coverage Report

Created: 2018-09-25 14:53

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