[DEVENUM]
[reactos.git] / reactos / dll / 3rdparty / libpng / png.c
1
2 /* png.c - location for general purpose libpng functions
3 *
4 * Last changed in libpng 1.5.14 [January 24, 2013]
5 * Copyright (c) 1998-2013 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
14 #include "pngpriv.h"
15
16 /* Generate a compiler error if there is an old png.h in the search path. */
17 typedef png_libpng_version_1_5_14 Your_png_h_is_not_version_1_5_14;
18
19 /* Tells libpng that we have already handled the first "num_bytes" bytes
20 * of the PNG file signature. If the PNG data is embedded into another
21 * stream we can set num_bytes = 8 so that libpng will not attempt to read
22 * or write any of the magic bytes before it starts on the IHDR.
23 */
24
25 #ifdef PNG_READ_SUPPORTED
26 void PNGAPI
27 png_set_sig_bytes(png_structp png_ptr, int num_bytes)
28 {
29 png_debug(1, "in png_set_sig_bytes");
30
31 if (png_ptr == NULL)
32 return;
33
34 if (num_bytes > 8)
35 png_error(png_ptr, "Too many bytes for PNG signature");
36
37 png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
38 }
39
40 /* Checks whether the supplied bytes match the PNG signature. We allow
41 * checking less than the full 8-byte signature so that those apps that
42 * already read the first few bytes of a file to determine the file type
43 * can simply check the remaining bytes for extra assurance. Returns
44 * an integer less than, equal to, or greater than zero if sig is found,
45 * respectively, to be less than, to match, or be greater than the correct
46 * PNG signature (this is the same behavior as strcmp, memcmp, etc).
47 */
48 int PNGAPI
49 png_sig_cmp(png_const_bytep sig, png_size_t start, png_size_t num_to_check)
50 {
51 png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
52
53 if (num_to_check > 8)
54 num_to_check = 8;
55
56 else if (num_to_check < 1)
57 return (-1);
58
59 if (start > 7)
60 return (-1);
61
62 if (start + num_to_check > 8)
63 num_to_check = 8 - start;
64
65 return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
66 }
67
68 #endif /* PNG_READ_SUPPORTED */
69
70 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
71 /* Function to allocate memory for zlib */
72 PNG_FUNCTION(voidpf /* PRIVATE */,
73 png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)
74 {
75 png_voidp ptr;
76 png_structp p;
77 png_uint_32 save_flags;
78 png_alloc_size_t num_bytes;
79
80 if (png_ptr == NULL)
81 return (NULL);
82
83 p=(png_structp)png_ptr;
84 save_flags=p->flags;
85
86 if (items > PNG_UINT_32_MAX/size)
87 {
88 png_warning (p, "Potential overflow in png_zalloc()");
89 return (NULL);
90 }
91 num_bytes = (png_alloc_size_t)items * size;
92
93 p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
94 ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
95 p->flags=save_flags;
96
97 return ((voidpf)ptr);
98 }
99
100 /* Function to free memory for zlib */
101 void /* PRIVATE */
102 png_zfree(voidpf png_ptr, voidpf ptr)
103 {
104 png_free((png_structp)png_ptr, (png_voidp)ptr);
105 }
106
107 /* Reset the CRC variable to 32 bits of 1's. Care must be taken
108 * in case CRC is > 32 bits to leave the top bits 0.
109 */
110 void /* PRIVATE */
111 png_reset_crc(png_structp png_ptr)
112 {
113 /* The cast is safe because the crc is a 32 bit value. */
114 png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
115 }
116
117 /* Calculate the CRC over a section of data. We can only pass as
118 * much data to this routine as the largest single buffer size. We
119 * also check that this data will actually be used before going to the
120 * trouble of calculating it.
121 */
122 void /* PRIVATE */
123 png_calculate_crc(png_structp png_ptr, png_const_bytep ptr, png_size_t length)
124 {
125 int need_crc = 1;
126
127 if (PNG_CHUNK_ANCILLIARY(png_ptr->chunk_name))
128 {
129 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
130 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
131 need_crc = 0;
132 }
133
134 else /* critical */
135 {
136 if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
137 need_crc = 0;
138 }
139
140 /* 'uLong' is defined as unsigned long, this means that on some systems it is
141 * a 64 bit value. crc32, however, returns 32 bits so the following cast is
142 * safe. 'uInt' may be no more than 16 bits, so it is necessary to perform a
143 * loop here.
144 */
145 if (need_crc && length > 0)
146 {
147 uLong crc = png_ptr->crc; /* Should never issue a warning */
148
149 do
150 {
151 uInt safeLength = (uInt)length;
152 if (safeLength == 0)
153 safeLength = (uInt)-1; /* evil, but safe */
154
155 crc = crc32(crc, ptr, safeLength);
156
157 /* The following should never issue compiler warnings, if they do the
158 * target system has characteristics that will probably violate other
159 * assumptions within the libpng code.
160 */
161 ptr += safeLength;
162 length -= safeLength;
163 }
164 while (length > 0);
165
166 /* And the following is always safe because the crc is only 32 bits. */
167 png_ptr->crc = (png_uint_32)crc;
168 }
169 }
170
171 /* Check a user supplied version number, called from both read and write
172 * functions that create a png_struct
173 */
174 int
175 png_user_version_check(png_structp png_ptr, png_const_charp user_png_ver)
176 {
177 if (user_png_ver)
178 {
179 int i = 0;
180
181 do
182 {
183 if (user_png_ver[i] != png_libpng_ver[i])
184 png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
185 } while (png_libpng_ver[i++]);
186 }
187
188 else
189 png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
190
191 if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
192 {
193 /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
194 * we must recompile any applications that use any older library version.
195 * For versions after libpng 1.0, we will be compatible, so we need
196 * only check the first digit.
197 */
198 if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
199 (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
200 (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
201 {
202 #ifdef PNG_WARNINGS_SUPPORTED
203 size_t pos = 0;
204 char m[128];
205
206 pos = png_safecat(m, sizeof m, pos, "Application built with libpng-");
207 pos = png_safecat(m, sizeof m, pos, user_png_ver);
208 pos = png_safecat(m, sizeof m, pos, " but running with ");
209 pos = png_safecat(m, sizeof m, pos, png_libpng_ver);
210
211 png_warning(png_ptr, m);
212 #endif
213
214 #ifdef PNG_ERROR_NUMBERS_SUPPORTED
215 png_ptr->flags = 0;
216 #endif
217
218 return 0;
219 }
220 }
221
222 /* Success return. */
223 return 1;
224 }
225
226 /* Allocate the memory for an info_struct for the application. We don't
227 * really need the png_ptr, but it could potentially be useful in the
228 * future. This should be used in favour of malloc(png_sizeof(png_info))
229 * and png_info_init() so that applications that want to use a shared
230 * libpng don't have to be recompiled if png_info changes size.
231 */
232 PNG_FUNCTION(png_infop,PNGAPI
233 png_create_info_struct,(png_structp png_ptr),PNG_ALLOCATED)
234 {
235 png_infop info_ptr;
236
237 png_debug(1, "in png_create_info_struct");
238
239 if (png_ptr == NULL)
240 return (NULL);
241
242 #ifdef PNG_USER_MEM_SUPPORTED
243 info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
244 png_ptr->malloc_fn, png_ptr->mem_ptr);
245 #else
246 info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
247 #endif
248 if (info_ptr != NULL)
249 png_info_init_3(&info_ptr, png_sizeof(png_info));
250
251 return (info_ptr);
252 }
253
254 /* This function frees the memory associated with a single info struct.
255 * Normally, one would use either png_destroy_read_struct() or
256 * png_destroy_write_struct() to free an info struct, but this may be
257 * useful for some applications.
258 */
259 void PNGAPI
260 png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
261 {
262 png_infop info_ptr = NULL;
263
264 png_debug(1, "in png_destroy_info_struct");
265
266 if (png_ptr == NULL)
267 return;
268
269 if (info_ptr_ptr != NULL)
270 info_ptr = *info_ptr_ptr;
271
272 if (info_ptr != NULL)
273 {
274 png_info_destroy(png_ptr, info_ptr);
275
276 #ifdef PNG_USER_MEM_SUPPORTED
277 png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
278 png_ptr->mem_ptr);
279 #else
280 png_destroy_struct((png_voidp)info_ptr);
281 #endif
282 *info_ptr_ptr = NULL;
283 }
284 }
285
286 /* Initialize the info structure. This is now an internal function (0.89)
287 * and applications using it are urged to use png_create_info_struct()
288 * instead.
289 */
290
291 void PNGAPI
292 png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
293 {
294 png_infop info_ptr = *ptr_ptr;
295
296 png_debug(1, "in png_info_init_3");
297
298 if (info_ptr == NULL)
299 return;
300
301 if (png_sizeof(png_info) > png_info_struct_size)
302 {
303 png_destroy_struct(info_ptr);
304 info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
305 *ptr_ptr = info_ptr;
306 }
307
308 /* Set everything to 0 */
309 png_memset(info_ptr, 0, png_sizeof(png_info));
310 }
311
312 void PNGAPI
313 png_data_freer(png_structp png_ptr, png_infop info_ptr,
314 int freer, png_uint_32 mask)
315 {
316 png_debug(1, "in png_data_freer");
317
318 if (png_ptr == NULL || info_ptr == NULL)
319 return;
320
321 if (freer == PNG_DESTROY_WILL_FREE_DATA)
322 info_ptr->free_me |= mask;
323
324 else if (freer == PNG_USER_WILL_FREE_DATA)
325 info_ptr->free_me &= ~mask;
326
327 else
328 png_warning(png_ptr,
329 "Unknown freer parameter in png_data_freer");
330 }
331
332 void PNGAPI
333 png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
334 int num)
335 {
336 png_debug(1, "in png_free_data");
337
338 if (png_ptr == NULL || info_ptr == NULL)
339 return;
340
341 #ifdef PNG_TEXT_SUPPORTED
342 /* Free text item num or (if num == -1) all text items */
343 if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
344 {
345 if (num != -1)
346 {
347 if (info_ptr->text && info_ptr->text[num].key)
348 {
349 png_free(png_ptr, info_ptr->text[num].key);
350 info_ptr->text[num].key = NULL;
351 }
352 }
353
354 else
355 {
356 int i;
357 for (i = 0; i < info_ptr->num_text; i++)
358 png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
359 png_free(png_ptr, info_ptr->text);
360 info_ptr->text = NULL;
361 info_ptr->num_text=0;
362 }
363 }
364 #endif
365
366 #ifdef PNG_tRNS_SUPPORTED
367 /* Free any tRNS entry */
368 if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
369 {
370 png_free(png_ptr, info_ptr->trans_alpha);
371 info_ptr->trans_alpha = NULL;
372 info_ptr->valid &= ~PNG_INFO_tRNS;
373 }
374 #endif
375
376 #ifdef PNG_sCAL_SUPPORTED
377 /* Free any sCAL entry */
378 if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
379 {
380 png_free(png_ptr, info_ptr->scal_s_width);
381 png_free(png_ptr, info_ptr->scal_s_height);
382 info_ptr->scal_s_width = NULL;
383 info_ptr->scal_s_height = NULL;
384 info_ptr->valid &= ~PNG_INFO_sCAL;
385 }
386 #endif
387
388 #ifdef PNG_pCAL_SUPPORTED
389 /* Free any pCAL entry */
390 if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
391 {
392 png_free(png_ptr, info_ptr->pcal_purpose);
393 png_free(png_ptr, info_ptr->pcal_units);
394 info_ptr->pcal_purpose = NULL;
395 info_ptr->pcal_units = NULL;
396 if (info_ptr->pcal_params != NULL)
397 {
398 int i;
399 for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
400 {
401 png_free(png_ptr, info_ptr->pcal_params[i]);
402 info_ptr->pcal_params[i] = NULL;
403 }
404 png_free(png_ptr, info_ptr->pcal_params);
405 info_ptr->pcal_params = NULL;
406 }
407 info_ptr->valid &= ~PNG_INFO_pCAL;
408 }
409 #endif
410
411 #ifdef PNG_iCCP_SUPPORTED
412 /* Free any iCCP entry */
413 if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
414 {
415 png_free(png_ptr, info_ptr->iccp_name);
416 png_free(png_ptr, info_ptr->iccp_profile);
417 info_ptr->iccp_name = NULL;
418 info_ptr->iccp_profile = NULL;
419 info_ptr->valid &= ~PNG_INFO_iCCP;
420 }
421 #endif
422
423 #ifdef PNG_sPLT_SUPPORTED
424 /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
425 if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
426 {
427 if (num != -1)
428 {
429 if (info_ptr->splt_palettes)
430 {
431 png_free(png_ptr, info_ptr->splt_palettes[num].name);
432 png_free(png_ptr, info_ptr->splt_palettes[num].entries);
433 info_ptr->splt_palettes[num].name = NULL;
434 info_ptr->splt_palettes[num].entries = NULL;
435 }
436 }
437
438 else
439 {
440 if (info_ptr->splt_palettes_num)
441 {
442 int i;
443 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
444 png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
445
446 png_free(png_ptr, info_ptr->splt_palettes);
447 info_ptr->splt_palettes = NULL;
448 info_ptr->splt_palettes_num = 0;
449 }
450 info_ptr->valid &= ~PNG_INFO_sPLT;
451 }
452 }
453 #endif
454
455 #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
456 if (png_ptr->unknown_chunk.data)
457 {
458 png_free(png_ptr, png_ptr->unknown_chunk.data);
459 png_ptr->unknown_chunk.data = NULL;
460 }
461
462 if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
463 {
464 if (num != -1)
465 {
466 if (info_ptr->unknown_chunks)
467 {
468 png_free(png_ptr, info_ptr->unknown_chunks[num].data);
469 info_ptr->unknown_chunks[num].data = NULL;
470 }
471 }
472
473 else
474 {
475 int i;
476
477 if (info_ptr->unknown_chunks_num)
478 {
479 for (i = 0; i < info_ptr->unknown_chunks_num; i++)
480 png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
481
482 png_free(png_ptr, info_ptr->unknown_chunks);
483 info_ptr->unknown_chunks = NULL;
484 info_ptr->unknown_chunks_num = 0;
485 }
486 }
487 }
488 #endif
489
490 #ifdef PNG_hIST_SUPPORTED
491 /* Free any hIST entry */
492 if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
493 {
494 png_free(png_ptr, info_ptr->hist);
495 info_ptr->hist = NULL;
496 info_ptr->valid &= ~PNG_INFO_hIST;
497 }
498 #endif
499
500 /* Free any PLTE entry that was internally allocated */
501 if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
502 {
503 png_zfree(png_ptr, info_ptr->palette);
504 info_ptr->palette = NULL;
505 info_ptr->valid &= ~PNG_INFO_PLTE;
506 info_ptr->num_palette = 0;
507 }
508
509 #ifdef PNG_INFO_IMAGE_SUPPORTED
510 /* Free any image bits attached to the info structure */
511 if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
512 {
513 if (info_ptr->row_pointers)
514 {
515 int row;
516 for (row = 0; row < (int)info_ptr->height; row++)
517 {
518 png_free(png_ptr, info_ptr->row_pointers[row]);
519 info_ptr->row_pointers[row] = NULL;
520 }
521 png_free(png_ptr, info_ptr->row_pointers);
522 info_ptr->row_pointers = NULL;
523 }
524 info_ptr->valid &= ~PNG_INFO_IDAT;
525 }
526 #endif
527
528 if (num != -1)
529 mask &= ~PNG_FREE_MUL;
530
531 info_ptr->free_me &= ~mask;
532 }
533
534 /* This is an internal routine to free any memory that the info struct is
535 * pointing to before re-using it or freeing the struct itself. Recall
536 * that png_free() checks for NULL pointers for us.
537 */
538 void /* PRIVATE */
539 png_info_destroy(png_structp png_ptr, png_infop info_ptr)
540 {
541 png_debug(1, "in png_info_destroy");
542
543 png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
544
545 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
546 if (png_ptr->num_chunk_list)
547 {
548 png_free(png_ptr, png_ptr->chunk_list);
549 png_ptr->chunk_list = NULL;
550 png_ptr->num_chunk_list = 0;
551 }
552 #endif
553
554 png_info_init_3(&info_ptr, png_sizeof(png_info));
555 }
556 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
557
558 /* This function returns a pointer to the io_ptr associated with the user
559 * functions. The application should free any memory associated with this
560 * pointer before png_write_destroy() or png_read_destroy() are called.
561 */
562 png_voidp PNGAPI
563 png_get_io_ptr(png_structp png_ptr)
564 {
565 if (png_ptr == NULL)
566 return (NULL);
567
568 return (png_ptr->io_ptr);
569 }
570
571 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
572 # ifdef PNG_STDIO_SUPPORTED
573 /* Initialize the default input/output functions for the PNG file. If you
574 * use your own read or write routines, you can call either png_set_read_fn()
575 * or png_set_write_fn() instead of png_init_io(). If you have defined
576 * PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a
577 * function of your own because "FILE *" isn't necessarily available.
578 */
579 void PNGAPI
580 png_init_io(png_structp png_ptr, png_FILE_p fp)
581 {
582 png_debug(1, "in png_init_io");
583
584 if (png_ptr == NULL)
585 return;
586
587 png_ptr->io_ptr = (png_voidp)fp;
588 }
589 # endif
590
591 # ifdef PNG_TIME_RFC1123_SUPPORTED
592 /* Convert the supplied time into an RFC 1123 string suitable for use in
593 * a "Creation Time" or other text-based time string.
594 */
595 png_const_charp PNGAPI
596 png_convert_to_rfc1123(png_structp png_ptr, png_const_timep ptime)
597 {
598 static PNG_CONST char short_months[12][4] =
599 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
600 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
601
602 if (png_ptr == NULL)
603 return (NULL);
604
605 if (ptime->year > 9999 /* RFC1123 limitation */ ||
606 ptime->month == 0 || ptime->month > 12 ||
607 ptime->day == 0 || ptime->day > 31 ||
608 ptime->hour > 23 || ptime->minute > 59 ||
609 ptime->second > 60)
610 {
611 png_warning(png_ptr, "Ignoring invalid time value");
612 return (NULL);
613 }
614
615 {
616 size_t pos = 0;
617 char number_buf[5]; /* enough for a four-digit year */
618
619 # define APPEND_STRING(string)\
620 pos = png_safecat(png_ptr->time_buffer, sizeof png_ptr->time_buffer,\
621 pos, (string))
622 # define APPEND_NUMBER(format, value)\
623 APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))
624 # define APPEND(ch)\
625 if (pos < (sizeof png_ptr->time_buffer)-1)\
626 png_ptr->time_buffer[pos++] = (ch)
627
628 APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);
629 APPEND(' ');
630 APPEND_STRING(short_months[(ptime->month - 1)]);
631 APPEND(' ');
632 APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);
633 APPEND(' ');
634 APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);
635 APPEND(':');
636 APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);
637 APPEND(':');
638 APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
639 APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
640
641 # undef APPEND
642 # undef APPEND_NUMBER
643 # undef APPEND_STRING
644 }
645
646 return png_ptr->time_buffer;
647 }
648 # endif /* PNG_TIME_RFC1123_SUPPORTED */
649
650 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
651
652 png_const_charp PNGAPI
653 png_get_copyright(png_const_structp png_ptr)
654 {
655 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
656 #ifdef PNG_STRING_COPYRIGHT
657 return PNG_STRING_COPYRIGHT
658 #else
659 # ifdef __STDC__
660 return PNG_STRING_NEWLINE \
661 "libpng version 1.5.14 - January 24, 2013" PNG_STRING_NEWLINE \
662 "Copyright (c) 1998-2013 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
663 "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
664 "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
665 PNG_STRING_NEWLINE;
666 # else
667 return "libpng version 1.5.14 - January 24, 2013\
668 Copyright (c) 1998-2013 Glenn Randers-Pehrson\
669 Copyright (c) 1996-1997 Andreas Dilger\
670 Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
671 # endif
672 #endif
673 }
674
675 /* The following return the library version as a short string in the
676 * format 1.0.0 through 99.99.99zz. To get the version of *.h files
677 * used with your application, print out PNG_LIBPNG_VER_STRING, which
678 * is defined in png.h.
679 * Note: now there is no difference between png_get_libpng_ver() and
680 * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
681 * it is guaranteed that png.c uses the correct version of png.h.
682 */
683 png_const_charp PNGAPI
684 png_get_libpng_ver(png_const_structp png_ptr)
685 {
686 /* Version of *.c files used when building libpng */
687 return png_get_header_ver(png_ptr);
688 }
689
690 png_const_charp PNGAPI
691 png_get_header_ver(png_const_structp png_ptr)
692 {
693 /* Version of *.h files used when building libpng */
694 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
695 return PNG_LIBPNG_VER_STRING;
696 }
697
698 png_const_charp PNGAPI
699 png_get_header_version(png_const_structp png_ptr)
700 {
701 /* Returns longer string containing both version and date */
702 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
703 #ifdef __STDC__
704 return PNG_HEADER_VERSION_STRING
705 # ifndef PNG_READ_SUPPORTED
706 " (NO READ SUPPORT)"
707 # endif
708 PNG_STRING_NEWLINE;
709 #else
710 return PNG_HEADER_VERSION_STRING;
711 #endif
712 }
713
714 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
715 int PNGAPI
716 png_handle_as_unknown(png_structp png_ptr, png_const_bytep chunk_name)
717 {
718 /* Check chunk_name and return "keep" value if it's on the list, else 0 */
719 png_const_bytep p, p_end;
720
721 if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list <= 0)
722 return PNG_HANDLE_CHUNK_AS_DEFAULT;
723
724 p_end = png_ptr->chunk_list;
725 p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
726
727 /* The code is the fifth byte after each four byte string. Historically this
728 * code was always searched from the end of the list, so it should continue
729 * to do so in case there are duplicated entries.
730 */
731 do /* num_chunk_list > 0, so at least one */
732 {
733 p -= 5;
734 if (!png_memcmp(chunk_name, p, 4))
735 return p[4];
736 }
737 while (p > p_end);
738
739 return PNG_HANDLE_CHUNK_AS_DEFAULT;
740 }
741
742 int /* PRIVATE */
743 png_chunk_unknown_handling(png_structp png_ptr, png_uint_32 chunk_name)
744 {
745 png_byte chunk_string[5];
746
747 PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);
748 return png_handle_as_unknown(png_ptr, chunk_string);
749 }
750 #endif
751
752 #ifdef PNG_READ_SUPPORTED
753 /* This function, added to libpng-1.0.6g, is untested. */
754 int PNGAPI
755 png_reset_zstream(png_structp png_ptr)
756 {
757 if (png_ptr == NULL)
758 return Z_STREAM_ERROR;
759
760 return (inflateReset(&png_ptr->zstream));
761 }
762 #endif /* PNG_READ_SUPPORTED */
763
764 /* This function was added to libpng-1.0.7 */
765 png_uint_32 PNGAPI
766 png_access_version_number(void)
767 {
768 /* Version of *.c files used when building libpng */
769 return((png_uint_32)PNG_LIBPNG_VER);
770 }
771
772
773
774 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
775 /* png_convert_size: a PNGAPI but no longer in png.h, so deleted
776 * at libpng 1.5.5!
777 */
778
779 /* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */
780 # ifdef PNG_CHECK_cHRM_SUPPORTED
781
782 int /* PRIVATE */
783 png_check_cHRM_fixed(png_structp png_ptr,
784 png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
785 png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
786 png_fixed_point blue_x, png_fixed_point blue_y)
787 {
788 int ret = 1;
789 unsigned long xy_hi,xy_lo,yx_hi,yx_lo;
790
791 png_debug(1, "in function png_check_cHRM_fixed");
792
793 if (png_ptr == NULL)
794 return 0;
795
796 /* (x,y,z) values are first limited to 0..100000 (PNG_FP_1), the white
797 * y must also be greater than 0. To test for the upper limit calculate
798 * (PNG_FP_1-y) - x must be <= to this for z to be >= 0 (and the expression
799 * cannot overflow.) At this point we know x and y are >= 0 and (x+y) is
800 * <= PNG_FP_1. The previous test on PNG_MAX_UINT_31 is removed because it
801 * pointless (and it produces compiler warnings!)
802 */
803 if (white_x < 0 || white_y <= 0 ||
804 red_x < 0 || red_y < 0 ||
805 green_x < 0 || green_y < 0 ||
806 blue_x < 0 || blue_y < 0)
807 {
808 png_warning(png_ptr,
809 "Ignoring attempt to set negative chromaticity value");
810 ret = 0;
811 }
812 /* And (x+y) must be <= PNG_FP_1 (so z is >= 0) */
813 if (white_x > PNG_FP_1 - white_y)
814 {
815 png_warning(png_ptr, "Invalid cHRM white point");
816 ret = 0;
817 }
818
819 if (red_x > PNG_FP_1 - red_y)
820 {
821 png_warning(png_ptr, "Invalid cHRM red point");
822 ret = 0;
823 }
824
825 if (green_x > PNG_FP_1 - green_y)
826 {
827 png_warning(png_ptr, "Invalid cHRM green point");
828 ret = 0;
829 }
830
831 if (blue_x > PNG_FP_1 - blue_y)
832 {
833 png_warning(png_ptr, "Invalid cHRM blue point");
834 ret = 0;
835 }
836
837 png_64bit_product(green_x - red_x, blue_y - red_y, &xy_hi, &xy_lo);
838 png_64bit_product(green_y - red_y, blue_x - red_x, &yx_hi, &yx_lo);
839
840 if (xy_hi == yx_hi && xy_lo == yx_lo)
841 {
842 png_warning(png_ptr,
843 "Ignoring attempt to set cHRM RGB triangle with zero area");
844 ret = 0;
845 }
846
847 return ret;
848 }
849 # endif /* PNG_CHECK_cHRM_SUPPORTED */
850
851 #ifdef PNG_cHRM_SUPPORTED
852 /* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for
853 * cHRM, as opposed to using chromaticities. These internal APIs return
854 * non-zero on a parameter error. The X, Y and Z values are required to be
855 * positive and less than 1.0.
856 */
857 int png_xy_from_XYZ(png_xy *xy, png_XYZ XYZ)
858 {
859 png_int_32 d, dwhite, whiteX, whiteY;
860
861 d = XYZ.redX + XYZ.redY + XYZ.redZ;
862 if (!png_muldiv(&xy->redx, XYZ.redX, PNG_FP_1, d)) return 1;
863 if (!png_muldiv(&xy->redy, XYZ.redY, PNG_FP_1, d)) return 1;
864 dwhite = d;
865 whiteX = XYZ.redX;
866 whiteY = XYZ.redY;
867
868 d = XYZ.greenX + XYZ.greenY + XYZ.greenZ;
869 if (!png_muldiv(&xy->greenx, XYZ.greenX, PNG_FP_1, d)) return 1;
870 if (!png_muldiv(&xy->greeny, XYZ.greenY, PNG_FP_1, d)) return 1;
871 dwhite += d;
872 whiteX += XYZ.greenX;
873 whiteY += XYZ.greenY;
874
875 d = XYZ.blueX + XYZ.blueY + XYZ.blueZ;
876 if (!png_muldiv(&xy->bluex, XYZ.blueX, PNG_FP_1, d)) return 1;
877 if (!png_muldiv(&xy->bluey, XYZ.blueY, PNG_FP_1, d)) return 1;
878 dwhite += d;
879 whiteX += XYZ.blueX;
880 whiteY += XYZ.blueY;
881
882 /* The reference white is simply the same of the end-point (X,Y,Z) vectors,
883 * thus:
884 */
885 if (!png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite)) return 1;
886 if (!png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite)) return 1;
887
888 return 0;
889 }
890
891 int png_XYZ_from_xy(png_XYZ *XYZ, png_xy xy)
892 {
893 png_fixed_point red_inverse, green_inverse, blue_scale;
894 png_fixed_point left, right, denominator;
895
896 /* Check xy and, implicitly, z. Note that wide gamut color spaces typically
897 * have end points with 0 tristimulus values (these are impossible end
898 * points, but they are used to cover the possible colors.)
899 */
900 if (xy.redx < 0 || xy.redx > PNG_FP_1) return 1;
901 if (xy.redy < 0 || xy.redy > PNG_FP_1-xy.redx) return 1;
902 if (xy.greenx < 0 || xy.greenx > PNG_FP_1) return 1;
903 if (xy.greeny < 0 || xy.greeny > PNG_FP_1-xy.greenx) return 1;
904 if (xy.bluex < 0 || xy.bluex > PNG_FP_1) return 1;
905 if (xy.bluey < 0 || xy.bluey > PNG_FP_1-xy.bluex) return 1;
906 if (xy.whitex < 0 || xy.whitex > PNG_FP_1) return 1;
907 if (xy.whitey < 0 || xy.whitey > PNG_FP_1-xy.whitex) return 1;
908
909 /* The reverse calculation is more difficult because the original tristimulus
910 * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
911 * derived values were recorded in the cHRM chunk;
912 * (red,green,blue,white)x(x,y). This loses one degree of freedom and
913 * therefore an arbitrary ninth value has to be introduced to undo the
914 * original transformations.
915 *
916 * Think of the original end-points as points in (X,Y,Z) space. The
917 * chromaticity values (c) have the property:
918 *
919 * C
920 * c = ---------
921 * X + Y + Z
922 *
923 * For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the
924 * three chromaticity values (x,y,z) for each end-point obey the
925 * relationship:
926 *
927 * x + y + z = 1
928 *
929 * This describes the plane in (X,Y,Z) space that intersects each axis at the
930 * value 1.0; call this the chromaticity plane. Thus the chromaticity
931 * calculation has scaled each end-point so that it is on the x+y+z=1 plane
932 * and chromaticity is the intersection of the vector from the origin to the
933 * (X,Y,Z) value with the chromaticity plane.
934 *
935 * To fully invert the chromaticity calculation we would need the three
936 * end-point scale factors, (red-scale, green-scale, blue-scale), but these
937 * were not recorded. Instead we calculated the reference white (X,Y,Z) and
938 * recorded the chromaticity of this. The reference white (X,Y,Z) would have
939 * given all three of the scale factors since:
940 *
941 * color-C = color-c * color-scale
942 * white-C = red-C + green-C + blue-C
943 * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
944 *
945 * But cHRM records only white-x and white-y, so we have lost the white scale
946 * factor:
947 *
948 * white-C = white-c*white-scale
949 *
950 * To handle this the inverse transformation makes an arbitrary assumption
951 * about white-scale:
952 *
953 * Assume: white-Y = 1.0
954 * Hence: white-scale = 1/white-y
955 * Or: red-Y + green-Y + blue-Y = 1.0
956 *
957 * Notice the last statement of the assumption gives an equation in three of
958 * the nine values we want to calculate. 8 more equations come from the
959 * above routine as summarised at the top above (the chromaticity
960 * calculation):
961 *
962 * Given: color-x = color-X / (color-X + color-Y + color-Z)
963 * Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 0
964 *
965 * This is 9 simultaneous equations in the 9 variables "color-C" and can be
966 * solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix
967 * determinants, however this is not as bad as it seems because only 28 of
968 * the total of 90 terms in the various matrices are non-zero. Nevertheless
969 * Cramer's rule is notoriously numerically unstable because the determinant
970 * calculation involves the difference of large, but similar, numbers. It is
971 * difficult to be sure that the calculation is stable for real world values
972 * and it is certain that it becomes unstable where the end points are close
973 * together.
974 *
975 * So this code uses the perhaps slightly less optimal but more
976 * understandable and totally obvious approach of calculating color-scale.
977 *
978 * This algorithm depends on the precision in white-scale and that is
979 * (1/white-y), so we can immediately see that as white-y approaches 0 the
980 * accuracy inherent in the cHRM chunk drops off substantially.
981 *
982 * libpng arithmetic: a simple invertion of the above equations
983 * ------------------------------------------------------------
984 *
985 * white_scale = 1/white-y
986 * white-X = white-x * white-scale
987 * white-Y = 1.0
988 * white-Z = (1 - white-x - white-y) * white_scale
989 *
990 * white-C = red-C + green-C + blue-C
991 * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
992 *
993 * This gives us three equations in (red-scale,green-scale,blue-scale) where
994 * all the coefficients are now known:
995 *
996 * red-x*red-scale + green-x*green-scale + blue-x*blue-scale
997 * = white-x/white-y
998 * red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 1
999 * red-z*red-scale + green-z*green-scale + blue-z*blue-scale
1000 * = (1 - white-x - white-y)/white-y
1001 *
1002 * In the last equation color-z is (1 - color-x - color-y) so we can add all
1003 * three equations together to get an alternative third:
1004 *
1005 * red-scale + green-scale + blue-scale = 1/white-y = white-scale
1006 *
1007 * So now we have a Cramer's rule solution where the determinants are just
1008 * 3x3 - far more tractible. Unfortunately 3x3 determinants still involve
1009 * multiplication of three coefficients so we can't guarantee to avoid
1010 * overflow in the libpng fixed point representation. Using Cramer's rule in
1011 * floating point is probably a good choice here, but it's not an option for
1012 * fixed point. Instead proceed to simplify the first two equations by
1013 * eliminating what is likely to be the largest value, blue-scale:
1014 *
1015 * blue-scale = white-scale - red-scale - green-scale
1016 *
1017 * Hence:
1018 *
1019 * (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =
1020 * (white-x - blue-x)*white-scale
1021 *
1022 * (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =
1023 * 1 - blue-y*white-scale
1024 *
1025 * And now we can trivially solve for (red-scale,green-scale):
1026 *
1027 * green-scale =
1028 * (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale
1029 * -----------------------------------------------------------
1030 * green-x - blue-x
1031 *
1032 * red-scale =
1033 * 1 - blue-y*white-scale - (green-y - blue-y) * green-scale
1034 * ---------------------------------------------------------
1035 * red-y - blue-y
1036 *
1037 * Hence:
1038 *
1039 * red-scale =
1040 * ( (green-x - blue-x) * (white-y - blue-y) -
1041 * (green-y - blue-y) * (white-x - blue-x) ) / white-y
1042 * -------------------------------------------------------------------------
1043 * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
1044 *
1045 * green-scale =
1046 * ( (red-y - blue-y) * (white-x - blue-x) -
1047 * (red-x - blue-x) * (white-y - blue-y) ) / white-y
1048 * -------------------------------------------------------------------------
1049 * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
1050 *
1051 * Accuracy:
1052 * The input values have 5 decimal digits of accuracy. The values are all in
1053 * the range 0 < value < 1, so simple products are in the same range but may
1054 * need up to 10 decimal digits to preserve the original precision and avoid
1055 * underflow. Because we are using a 32-bit signed representation we cannot
1056 * match this; the best is a little over 9 decimal digits, less than 10.
1057 *
1058 * The approach used here is to preserve the maximum precision within the
1059 * signed representation. Because the red-scale calculation above uses the
1060 * difference between two products of values that must be in the range -1..+1
1061 * it is sufficient to divide the product by 7; ceil(100,000/32767*2). The
1062 * factor is irrelevant in the calculation because it is applied to both
1063 * numerator and denominator.
1064 *
1065 * Note that the values of the differences of the products of the
1066 * chromaticities in the above equations tend to be small, for example for
1067 * the sRGB chromaticities they are:
1068 *
1069 * red numerator: -0.04751
1070 * green numerator: -0.08788
1071 * denominator: -0.2241 (without white-y multiplication)
1072 *
1073 * The resultant Y coefficients from the chromaticities of some widely used
1074 * color space definitions are (to 15 decimal places):
1075 *
1076 * sRGB
1077 * 0.212639005871510 0.715168678767756 0.072192315360734
1078 * Kodak ProPhoto
1079 * 0.288071128229293 0.711843217810102 0.000085653960605
1080 * Adobe RGB
1081 * 0.297344975250536 0.627363566255466 0.075291458493998
1082 * Adobe Wide Gamut RGB
1083 * 0.258728243040113 0.724682314948566 0.016589442011321
1084 */
1085 /* By the argument, above overflow should be impossible here. The return
1086 * value of 2 indicates an internal error to the caller.
1087 */
1088 if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.redy - xy.bluey, 7)) return 2;
1089 if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.redx - xy.bluex, 7)) return 2;
1090 denominator = left - right;
1091
1092 /* Now find the red numerator. */
1093 if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
1094 if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
1095
1096 /* Overflow is possible here and it indicates an extreme set of PNG cHRM
1097 * chunk values. This calculation actually returns the reciprocal of the
1098 * scale value because this allows us to delay the multiplication of white-y
1099 * into the denominator, which tends to produce a small number.
1100 */
1101 if (!png_muldiv(&red_inverse, xy.whitey, denominator, left-right) ||
1102 red_inverse <= xy.whitey /* r+g+b scales = white scale */)
1103 return 1;
1104
1105 /* Similarly for green_inverse: */
1106 if (!png_muldiv(&left, xy.redy-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
1107 if (!png_muldiv(&right, xy.redx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
1108 if (!png_muldiv(&green_inverse, xy.whitey, denominator, left-right) ||
1109 green_inverse <= xy.whitey)
1110 return 1;
1111
1112 /* And the blue scale, the checks above guarantee this can't overflow but it
1113 * can still produce 0 for extreme cHRM values.
1114 */
1115 blue_scale = png_reciprocal(xy.whitey) - png_reciprocal(red_inverse) -
1116 png_reciprocal(green_inverse);
1117 if (blue_scale <= 0) return 1;
1118
1119
1120 /* And fill in the png_XYZ: */
1121 if (!png_muldiv(&XYZ->redX, xy.redx, PNG_FP_1, red_inverse)) return 1;
1122 if (!png_muldiv(&XYZ->redY, xy.redy, PNG_FP_1, red_inverse)) return 1;
1123 if (!png_muldiv(&XYZ->redZ, PNG_FP_1 - xy.redx - xy.redy, PNG_FP_1,
1124 red_inverse))
1125 return 1;
1126
1127 if (!png_muldiv(&XYZ->greenX, xy.greenx, PNG_FP_1, green_inverse)) return 1;
1128 if (!png_muldiv(&XYZ->greenY, xy.greeny, PNG_FP_1, green_inverse)) return 1;
1129 if (!png_muldiv(&XYZ->greenZ, PNG_FP_1 - xy.greenx - xy.greeny, PNG_FP_1,
1130 green_inverse))
1131 return 1;
1132
1133 if (!png_muldiv(&XYZ->blueX, xy.bluex, blue_scale, PNG_FP_1)) return 1;
1134 if (!png_muldiv(&XYZ->blueY, xy.bluey, blue_scale, PNG_FP_1)) return 1;
1135 if (!png_muldiv(&XYZ->blueZ, PNG_FP_1 - xy.bluex - xy.bluey, blue_scale,
1136 PNG_FP_1))
1137 return 1;
1138
1139 return 0; /*success*/
1140 }
1141
1142 int png_XYZ_from_xy_checked(png_structp png_ptr, png_XYZ *XYZ, png_xy xy)
1143 {
1144 switch (png_XYZ_from_xy(XYZ, xy))
1145 {
1146 case 0: /* success */
1147 return 1;
1148
1149 case 1:
1150 /* The chunk may be technically valid, but we got png_fixed_point
1151 * overflow while trying to get XYZ values out of it. This is
1152 * entirely benign - the cHRM chunk is pretty extreme.
1153 */
1154 png_warning(png_ptr,
1155 "extreme cHRM chunk cannot be converted to tristimulus values");
1156 break;
1157
1158 default:
1159 /* libpng is broken; this should be a warning but if it happens we
1160 * want error reports so for the moment it is an error.
1161 */
1162 png_error(png_ptr, "internal error in png_XYZ_from_xy");
1163 break;
1164 }
1165
1166 /* ERROR RETURN */
1167 return 0;
1168 }
1169 #endif
1170
1171 void /* PRIVATE */
1172 png_check_IHDR(png_structp png_ptr,
1173 png_uint_32 width, png_uint_32 height, int bit_depth,
1174 int color_type, int interlace_type, int compression_type,
1175 int filter_type)
1176 {
1177 int error = 0;
1178
1179 /* Check for width and height valid values */
1180 if (width == 0)
1181 {
1182 png_warning(png_ptr, "Image width is zero in IHDR");
1183 error = 1;
1184 }
1185
1186 if (height == 0)
1187 {
1188 png_warning(png_ptr, "Image height is zero in IHDR");
1189 error = 1;
1190 }
1191
1192 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
1193 if (width > png_ptr->user_width_max)
1194
1195 # else
1196 if (width > PNG_USER_WIDTH_MAX)
1197 # endif
1198 {
1199 png_warning(png_ptr, "Image width exceeds user limit in IHDR");
1200 error = 1;
1201 }
1202
1203 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
1204 if (height > png_ptr->user_height_max)
1205 # else
1206 if (height > PNG_USER_HEIGHT_MAX)
1207 # endif
1208 {
1209 png_warning(png_ptr, "Image height exceeds user limit in IHDR");
1210 error = 1;
1211 }
1212
1213 if (width > PNG_UINT_31_MAX)
1214 {
1215 png_warning(png_ptr, "Invalid image width in IHDR");
1216 error = 1;
1217 }
1218
1219 if (height > PNG_UINT_31_MAX)
1220 {
1221 png_warning(png_ptr, "Invalid image height in IHDR");
1222 error = 1;
1223 }
1224
1225 if (width > (PNG_UINT_32_MAX
1226 >> 3) /* 8-byte RGBA pixels */
1227 - 48 /* bigrowbuf hack */
1228 - 1 /* filter byte */
1229 - 7*8 /* rounding of width to multiple of 8 pixels */
1230 - 8) /* extra max_pixel_depth pad */
1231 png_warning(png_ptr, "Width is too large for libpng to process pixels");
1232
1233 /* Check other values */
1234 if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
1235 bit_depth != 8 && bit_depth != 16)
1236 {
1237 png_warning(png_ptr, "Invalid bit depth in IHDR");
1238 error = 1;
1239 }
1240
1241 if (color_type < 0 || color_type == 1 ||
1242 color_type == 5 || color_type > 6)
1243 {
1244 png_warning(png_ptr, "Invalid color type in IHDR");
1245 error = 1;
1246 }
1247
1248 if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
1249 ((color_type == PNG_COLOR_TYPE_RGB ||
1250 color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
1251 color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
1252 {
1253 png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
1254 error = 1;
1255 }
1256
1257 if (interlace_type >= PNG_INTERLACE_LAST)
1258 {
1259 png_warning(png_ptr, "Unknown interlace method in IHDR");
1260 error = 1;
1261 }
1262
1263 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
1264 {
1265 png_warning(png_ptr, "Unknown compression method in IHDR");
1266 error = 1;
1267 }
1268
1269 # ifdef PNG_MNG_FEATURES_SUPPORTED
1270 /* Accept filter_method 64 (intrapixel differencing) only if
1271 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
1272 * 2. Libpng did not read a PNG signature (this filter_method is only
1273 * used in PNG datastreams that are embedded in MNG datastreams) and
1274 * 3. The application called png_permit_mng_features with a mask that
1275 * included PNG_FLAG_MNG_FILTER_64 and
1276 * 4. The filter_method is 64 and
1277 * 5. The color_type is RGB or RGBA
1278 */
1279 if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) &&
1280 png_ptr->mng_features_permitted)
1281 png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
1282
1283 if (filter_type != PNG_FILTER_TYPE_BASE)
1284 {
1285 if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
1286 (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
1287 ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
1288 (color_type == PNG_COLOR_TYPE_RGB ||
1289 color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
1290 {
1291 png_warning(png_ptr, "Unknown filter method in IHDR");
1292 error = 1;
1293 }
1294
1295 if (png_ptr->mode & PNG_HAVE_PNG_SIGNATURE)
1296 {
1297 png_warning(png_ptr, "Invalid filter method in IHDR");
1298 error = 1;
1299 }
1300 }
1301
1302 # else
1303 if (filter_type != PNG_FILTER_TYPE_BASE)
1304 {
1305 png_warning(png_ptr, "Unknown filter method in IHDR");
1306 error = 1;
1307 }
1308 # endif
1309
1310 if (error == 1)
1311 png_error(png_ptr, "Invalid IHDR data");
1312 }
1313
1314 #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
1315 /* ASCII to fp functions */
1316 /* Check an ASCII formated floating point value, see the more detailed
1317 * comments in pngpriv.h
1318 */
1319 /* The following is used internally to preserve the sticky flags */
1320 #define png_fp_add(state, flags) ((state) |= (flags))
1321 #define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
1322
1323 int /* PRIVATE */
1324 png_check_fp_number(png_const_charp string, png_size_t size, int *statep,
1325 png_size_tp whereami)
1326 {
1327 int state = *statep;
1328 png_size_t i = *whereami;
1329
1330 while (i < size)
1331 {
1332 int type;
1333 /* First find the type of the next character */
1334 switch (string[i])
1335 {
1336 case 43: type = PNG_FP_SAW_SIGN; break;
1337 case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;
1338 case 46: type = PNG_FP_SAW_DOT; break;
1339 case 48: type = PNG_FP_SAW_DIGIT; break;
1340 case 49: case 50: case 51: case 52:
1341 case 53: case 54: case 55: case 56:
1342 case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;
1343 case 69:
1344 case 101: type = PNG_FP_SAW_E; break;
1345 default: goto PNG_FP_End;
1346 }
1347
1348 /* Now deal with this type according to the current
1349 * state, the type is arranged to not overlap the
1350 * bits of the PNG_FP_STATE.
1351 */
1352 switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))
1353 {
1354 case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:
1355 if (state & PNG_FP_SAW_ANY)
1356 goto PNG_FP_End; /* not a part of the number */
1357
1358 png_fp_add(state, type);
1359 break;
1360
1361 case PNG_FP_INTEGER + PNG_FP_SAW_DOT:
1362 /* Ok as trailer, ok as lead of fraction. */
1363 if (state & PNG_FP_SAW_DOT) /* two dots */
1364 goto PNG_FP_End;
1365
1366 else if (state & PNG_FP_SAW_DIGIT) /* trailing dot? */
1367 png_fp_add(state, type);
1368
1369 else
1370 png_fp_set(state, PNG_FP_FRACTION | type);
1371
1372 break;
1373
1374 case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:
1375 if (state & PNG_FP_SAW_DOT) /* delayed fraction */
1376 png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
1377
1378 png_fp_add(state, type | PNG_FP_WAS_VALID);
1379
1380 break;
1381
1382 case PNG_FP_INTEGER + PNG_FP_SAW_E:
1383 if ((state & PNG_FP_SAW_DIGIT) == 0)
1384 goto PNG_FP_End;
1385
1386 png_fp_set(state, PNG_FP_EXPONENT);
1387
1388 break;
1389
1390 /* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:
1391 goto PNG_FP_End; ** no sign in fraction */
1392
1393 /* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:
1394 goto PNG_FP_End; ** Because SAW_DOT is always set */
1395
1396 case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:
1397 png_fp_add(state, type | PNG_FP_WAS_VALID);
1398 break;
1399
1400 case PNG_FP_FRACTION + PNG_FP_SAW_E:
1401 /* This is correct because the trailing '.' on an
1402 * integer is handled above - so we can only get here
1403 * with the sequence ".E" (with no preceding digits).
1404 */
1405 if ((state & PNG_FP_SAW_DIGIT) == 0)
1406 goto PNG_FP_End;
1407
1408 png_fp_set(state, PNG_FP_EXPONENT);
1409
1410 break;
1411
1412 case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:
1413 if (state & PNG_FP_SAW_ANY)
1414 goto PNG_FP_End; /* not a part of the number */
1415
1416 png_fp_add(state, PNG_FP_SAW_SIGN);
1417
1418 break;
1419
1420 /* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:
1421 goto PNG_FP_End; */
1422
1423 case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:
1424 png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);
1425
1426 break;
1427
1428 /* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:
1429 goto PNG_FP_End; */
1430
1431 default: goto PNG_FP_End; /* I.e. break 2 */
1432 }
1433
1434 /* The character seems ok, continue. */
1435 ++i;
1436 }
1437
1438 PNG_FP_End:
1439 /* Here at the end, update the state and return the correct
1440 * return code.
1441 */
1442 *statep = state;
1443 *whereami = i;
1444
1445 return (state & PNG_FP_SAW_DIGIT) != 0;
1446 }
1447
1448
1449 /* The same but for a complete string. */
1450 int
1451 png_check_fp_string(png_const_charp string, png_size_t size)
1452 {
1453 int state=0;
1454 png_size_t char_index=0;
1455
1456 if (png_check_fp_number(string, size, &state, &char_index) &&
1457 (char_index == size || string[char_index] == 0))
1458 return state /* must be non-zero - see above */;
1459
1460 return 0; /* i.e. fail */
1461 }
1462 #endif /* pCAL or sCAL */
1463
1464 #ifdef PNG_sCAL_SUPPORTED
1465 # ifdef PNG_FLOATING_POINT_SUPPORTED
1466 /* Utility used below - a simple accurate power of ten from an integral
1467 * exponent.
1468 */
1469 static double
1470 png_pow10(int power)
1471 {
1472 int recip = 0;
1473 double d = 1.0;
1474
1475 /* Handle negative exponent with a reciprocal at the end because
1476 * 10 is exact whereas .1 is inexact in base 2
1477 */
1478 if (power < 0)
1479 {
1480 if (power < DBL_MIN_10_EXP) return 0;
1481 recip = 1, power = -power;
1482 }
1483
1484 if (power > 0)
1485 {
1486 /* Decompose power bitwise. */
1487 double mult = 10.0;
1488 do
1489 {
1490 if (power & 1) d *= mult;
1491 mult *= mult;
1492 power >>= 1;
1493 }
1494 while (power > 0);
1495
1496 if (recip) d = 1/d;
1497 }
1498 /* else power is 0 and d is 1 */
1499
1500 return d;
1501 }
1502
1503 /* Function to format a floating point value in ASCII with a given
1504 * precision.
1505 */
1506 void /* PRIVATE */
1507 png_ascii_from_fp(png_structp png_ptr, png_charp ascii, png_size_t size,
1508 double fp, unsigned int precision)
1509 {
1510 /* We use standard functions from math.h, but not printf because
1511 * that would require stdio. The caller must supply a buffer of
1512 * sufficient size or we will png_error. The tests on size and
1513 * the space in ascii[] consumed are indicated below.
1514 */
1515 if (precision < 1)
1516 precision = DBL_DIG;
1517
1518 /* Enforce the limit of the implementation precision too. */
1519 if (precision > DBL_DIG+1)
1520 precision = DBL_DIG+1;
1521
1522 /* Basic sanity checks */
1523 if (size >= precision+5) /* See the requirements below. */
1524 {
1525 if (fp < 0)
1526 {
1527 fp = -fp;
1528 *ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */
1529 --size;
1530 }
1531
1532 if (fp >= DBL_MIN && fp <= DBL_MAX)
1533 {
1534 int exp_b10; /* A base 10 exponent */
1535 double base; /* 10^exp_b10 */
1536
1537 /* First extract a base 10 exponent of the number,
1538 * the calculation below rounds down when converting
1539 * from base 2 to base 10 (multiply by log10(2) -
1540 * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
1541 * be increased. Note that the arithmetic shift
1542 * performs a floor() unlike C arithmetic - using a
1543 * C multiply would break the following for negative
1544 * exponents.
1545 */
1546 (void)frexp(fp, &exp_b10); /* exponent to base 2 */
1547
1548 exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
1549
1550 /* Avoid underflow here. */
1551 base = png_pow10(exp_b10); /* May underflow */
1552
1553 while (base < DBL_MIN || base < fp)
1554 {
1555 /* And this may overflow. */
1556 double test = png_pow10(exp_b10+1);
1557
1558 if (test <= DBL_MAX)
1559 ++exp_b10, base = test;
1560
1561 else
1562 break;
1563 }
1564
1565 /* Normalize fp and correct exp_b10, after this fp is in the
1566 * range [.1,1) and exp_b10 is both the exponent and the digit
1567 * *before* which the decimal point should be inserted
1568 * (starting with 0 for the first digit). Note that this
1569 * works even if 10^exp_b10 is out of range because of the
1570 * test on DBL_MAX above.
1571 */
1572 fp /= base;
1573 while (fp >= 1) fp /= 10, ++exp_b10;
1574
1575 /* Because of the code above fp may, at this point, be
1576 * less than .1, this is ok because the code below can
1577 * handle the leading zeros this generates, so no attempt
1578 * is made to correct that here.
1579 */
1580
1581 {
1582 int czero, clead, cdigits;
1583 char exponent[10];
1584
1585 /* Allow up to two leading zeros - this will not lengthen
1586 * the number compared to using E-n.
1587 */
1588 if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
1589 {
1590 czero = -exp_b10; /* PLUS 2 digits: TOTAL 3 */
1591 exp_b10 = 0; /* Dot added below before first output. */
1592 }
1593 else
1594 czero = 0; /* No zeros to add */
1595
1596 /* Generate the digit list, stripping trailing zeros and
1597 * inserting a '.' before a digit if the exponent is 0.
1598 */
1599 clead = czero; /* Count of leading zeros */
1600 cdigits = 0; /* Count of digits in list. */
1601
1602 do
1603 {
1604 double d;
1605
1606 fp *= 10.0;
1607
1608 /* Use modf here, not floor and subtract, so that
1609 * the separation is done in one step. At the end
1610 * of the loop don't break the number into parts so
1611 * that the final digit is rounded.
1612 */
1613 if (cdigits+czero-clead+1 < (int)precision)
1614 fp = modf(fp, &d);
1615
1616 else
1617 {
1618 d = floor(fp + .5);
1619
1620 if (d > 9.0)
1621 {
1622 /* Rounding up to 10, handle that here. */
1623 if (czero > 0)
1624 {
1625 --czero, d = 1;
1626 if (cdigits == 0) --clead;
1627 }
1628
1629 else
1630 {
1631 while (cdigits > 0 && d > 9.0)
1632 {
1633 int ch = *--ascii;
1634
1635 if (exp_b10 != (-1))
1636 ++exp_b10;
1637
1638 else if (ch == 46)
1639 {
1640 ch = *--ascii, ++size;
1641 /* Advance exp_b10 to '1', so that the
1642 * decimal point happens after the
1643 * previous digit.
1644 */
1645 exp_b10 = 1;
1646 }
1647
1648 --cdigits;
1649 d = ch - 47; /* I.e. 1+(ch-48) */
1650 }
1651
1652 /* Did we reach the beginning? If so adjust the
1653 * exponent but take into account the leading
1654 * decimal point.
1655 */
1656 if (d > 9.0) /* cdigits == 0 */
1657 {
1658 if (exp_b10 == (-1))
1659 {
1660 /* Leading decimal point (plus zeros?), if
1661 * we lose the decimal point here it must
1662 * be reentered below.
1663 */
1664 int ch = *--ascii;
1665
1666 if (ch == 46)
1667 ++size, exp_b10 = 1;
1668
1669 /* Else lost a leading zero, so 'exp_b10' is
1670 * still ok at (-1)
1671 */
1672 }
1673 else
1674 ++exp_b10;
1675
1676 /* In all cases we output a '1' */
1677 d = 1.0;
1678 }
1679 }
1680 }
1681 fp = 0; /* Guarantees termination below. */
1682 }
1683
1684 if (d == 0.0)
1685 {
1686 ++czero;
1687 if (cdigits == 0) ++clead;
1688 }
1689
1690 else
1691 {
1692 /* Included embedded zeros in the digit count. */
1693 cdigits += czero - clead;
1694 clead = 0;
1695
1696 while (czero > 0)
1697 {
1698 /* exp_b10 == (-1) means we just output the decimal
1699 * place - after the DP don't adjust 'exp_b10' any
1700 * more!
1701 */
1702 if (exp_b10 != (-1))
1703 {
1704 if (exp_b10 == 0) *ascii++ = 46, --size;
1705 /* PLUS 1: TOTAL 4 */
1706 --exp_b10;
1707 }
1708 *ascii++ = 48, --czero;
1709 }
1710
1711 if (exp_b10 != (-1))
1712 {
1713 if (exp_b10 == 0) *ascii++ = 46, --size; /* counted
1714 above */
1715 --exp_b10;
1716 }
1717
1718 *ascii++ = (char)(48 + (int)d), ++cdigits;
1719 }
1720 }
1721 while (cdigits+czero-clead < (int)precision && fp > DBL_MIN);
1722
1723 /* The total output count (max) is now 4+precision */
1724
1725 /* Check for an exponent, if we don't need one we are
1726 * done and just need to terminate the string. At
1727 * this point exp_b10==(-1) is effectively if flag - it got
1728 * to '-1' because of the decrement after outputing
1729 * the decimal point above (the exponent required is
1730 * *not* -1!)
1731 */
1732 if (exp_b10 >= (-1) && exp_b10 <= 2)
1733 {
1734 /* The following only happens if we didn't output the
1735 * leading zeros above for negative exponent, so this
1736 * doest add to the digit requirement. Note that the
1737 * two zeros here can only be output if the two leading
1738 * zeros were *not* output, so this doesn't increase
1739 * the output count.
1740 */
1741 while (--exp_b10 >= 0) *ascii++ = 48;
1742
1743 *ascii = 0;
1744
1745 /* Total buffer requirement (including the '\0') is
1746 * 5+precision - see check at the start.
1747 */
1748 return;
1749 }
1750
1751 /* Here if an exponent is required, adjust size for
1752 * the digits we output but did not count. The total
1753 * digit output here so far is at most 1+precision - no
1754 * decimal point and no leading or trailing zeros have
1755 * been output.
1756 */
1757 size -= cdigits;
1758
1759 *ascii++ = 69, --size; /* 'E': PLUS 1 TOTAL 2+precision */
1760
1761 /* The following use of an unsigned temporary avoids ambiguities in
1762 * the signed arithmetic on exp_b10 and permits GCC at least to do
1763 * better optimization.
1764 */
1765 {
1766 unsigned int uexp_b10;
1767
1768 if (exp_b10 < 0)
1769 {
1770 *ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */
1771 uexp_b10 = -exp_b10;
1772 }
1773
1774 else
1775 uexp_b10 = exp_b10;
1776
1777 cdigits = 0;
1778
1779 while (uexp_b10 > 0)
1780 {
1781 exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
1782 uexp_b10 /= 10;
1783 }
1784 }
1785
1786 /* Need another size check here for the exponent digits, so
1787 * this need not be considered above.
1788 */
1789 if ((int)size > cdigits)
1790 {
1791 while (cdigits > 0) *ascii++ = exponent[--cdigits];
1792
1793 *ascii = 0;
1794
1795 return;
1796 }
1797 }
1798 }
1799 else if (!(fp >= DBL_MIN))
1800 {
1801 *ascii++ = 48; /* '0' */
1802 *ascii = 0;
1803 return;
1804 }
1805 else
1806 {
1807 *ascii++ = 105; /* 'i' */
1808 *ascii++ = 110; /* 'n' */
1809 *ascii++ = 102; /* 'f' */
1810 *ascii = 0;
1811 return;
1812 }
1813 }
1814
1815 /* Here on buffer too small. */
1816 png_error(png_ptr, "ASCII conversion buffer too small");
1817 }
1818
1819 # endif /* FLOATING_POINT */
1820
1821 # ifdef PNG_FIXED_POINT_SUPPORTED
1822 /* Function to format a fixed point value in ASCII.
1823 */
1824 void /* PRIVATE */
1825 png_ascii_from_fixed(png_structp png_ptr, png_charp ascii, png_size_t size,
1826 png_fixed_point fp)
1827 {
1828 /* Require space for 10 decimal digits, a decimal point, a minus sign and a
1829 * trailing \0, 13 characters:
1830 */
1831 if (size > 12)
1832 {
1833 png_uint_32 num;
1834
1835 /* Avoid overflow here on the minimum integer. */
1836 if (fp < 0)
1837 *ascii++ = 45, --size, num = -fp;
1838 else
1839 num = fp;
1840
1841 if (num <= 0x80000000) /* else overflowed */
1842 {
1843 unsigned int ndigits = 0, first = 16 /* flag value */;
1844 char digits[10];
1845
1846 while (num)
1847 {
1848 /* Split the low digit off num: */
1849 unsigned int tmp = num/10;
1850 num -= tmp*10;
1851 digits[ndigits++] = (char)(48 + num);
1852 /* Record the first non-zero digit, note that this is a number
1853 * starting at 1, it's not actually the array index.
1854 */
1855 if (first == 16 && num > 0)
1856 first = ndigits;
1857 num = tmp;
1858 }
1859
1860 if (ndigits > 0)
1861 {
1862 while (ndigits > 5) *ascii++ = digits[--ndigits];
1863 /* The remaining digits are fractional digits, ndigits is '5' or
1864 * smaller at this point. It is certainly not zero. Check for a
1865 * non-zero fractional digit:
1866 */
1867 if (first <= 5)
1868 {
1869 unsigned int i;
1870 *ascii++ = 46; /* decimal point */
1871 /* ndigits may be <5 for small numbers, output leading zeros
1872 * then ndigits digits to first:
1873 */
1874 i = 5;
1875 while (ndigits < i) *ascii++ = 48, --i;
1876 while (ndigits >= first) *ascii++ = digits[--ndigits];
1877 /* Don't output the trailing zeros! */
1878 }
1879 }
1880 else
1881 *ascii++ = 48;
1882
1883 /* And null terminate the string: */
1884 *ascii = 0;
1885 return;
1886 }
1887 }
1888
1889 /* Here on buffer too small. */
1890 png_error(png_ptr, "ASCII conversion buffer too small");
1891 }
1892 # endif /* FIXED_POINT */
1893 #endif /* READ_SCAL */
1894
1895 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
1896 !defined(PNG_FIXED_POINT_MACRO_SUPPORTED)
1897 png_fixed_point
1898 png_fixed(png_structp png_ptr, double fp, png_const_charp text)
1899 {
1900 double r = floor(100000 * fp + .5);
1901
1902 if (r > 2147483647. || r < -2147483648.)
1903 png_fixed_error(png_ptr, text);
1904
1905 return (png_fixed_point)r;
1906 }
1907 #endif
1908
1909 #if defined(PNG_READ_GAMMA_SUPPORTED) || \
1910 defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG__READ_pHYs_SUPPORTED)
1911 /* muldiv functions */
1912 /* This API takes signed arguments and rounds the result to the nearest
1913 * integer (or, for a fixed point number - the standard argument - to
1914 * the nearest .00001). Overflow and divide by zero are signalled in
1915 * the result, a boolean - true on success, false on overflow.
1916 */
1917 int
1918 png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
1919 png_int_32 divisor)
1920 {
1921 /* Return a * times / divisor, rounded. */
1922 if (divisor != 0)
1923 {
1924 if (a == 0 || times == 0)
1925 {
1926 *res = 0;
1927 return 1;
1928 }
1929 else
1930 {
1931 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1932 double r = a;
1933 r *= times;
1934 r /= divisor;
1935 r = floor(r+.5);
1936
1937 /* A png_fixed_point is a 32-bit integer. */
1938 if (r <= 2147483647. && r >= -2147483648.)
1939 {
1940 *res = (png_fixed_point)r;
1941 return 1;
1942 }
1943 #else
1944 int negative = 0;
1945 png_uint_32 A, T, D;
1946 png_uint_32 s16, s32, s00;
1947
1948 if (a < 0)
1949 negative = 1, A = -a;
1950 else
1951 A = a;
1952
1953 if (times < 0)
1954 negative = !negative, T = -times;
1955 else
1956 T = times;
1957
1958 if (divisor < 0)
1959 negative = !negative, D = -divisor;
1960 else
1961 D = divisor;
1962
1963 /* Following can't overflow because the arguments only
1964 * have 31 bits each, however the result may be 32 bits.
1965 */
1966 s16 = (A >> 16) * (T & 0xffff) +
1967 (A & 0xffff) * (T >> 16);
1968 /* Can't overflow because the a*times bit is only 30
1969 * bits at most.
1970 */
1971 s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
1972 s00 = (A & 0xffff) * (T & 0xffff);
1973
1974 s16 = (s16 & 0xffff) << 16;
1975 s00 += s16;
1976
1977 if (s00 < s16)
1978 ++s32; /* carry */
1979
1980 if (s32 < D) /* else overflow */
1981 {
1982 /* s32.s00 is now the 64-bit product, do a standard
1983 * division, we know that s32 < D, so the maximum
1984 * required shift is 31.
1985 */
1986 int bitshift = 32;
1987 png_fixed_point result = 0; /* NOTE: signed */
1988
1989 while (--bitshift >= 0)
1990 {
1991 png_uint_32 d32, d00;
1992
1993 if (bitshift > 0)
1994 d32 = D >> (32-bitshift), d00 = D << bitshift;
1995
1996 else
1997 d32 = 0, d00 = D;
1998
1999 if (s32 > d32)
2000 {
2001 if (s00 < d00) --s32; /* carry */
2002 s32 -= d32, s00 -= d00, result += 1<<bitshift;
2003 }
2004
2005 else
2006 if (s32 == d32 && s00 >= d00)
2007 s32 = 0, s00 -= d00, result += 1<<bitshift;
2008 }
2009
2010 /* Handle the rounding. */
2011 if (s00 >= (D >> 1))
2012 ++result;
2013
2014 if (negative)
2015 result = -result;
2016
2017 /* Check for overflow. */
2018 if ((negative && result <= 0) || (!negative && result >= 0))
2019 {
2020 *res = result;
2021 return 1;
2022 }
2023 }
2024 #endif
2025 }
2026 }
2027
2028 return 0;
2029 }
2030 #endif /* READ_GAMMA || INCH_CONVERSIONS */
2031
2032 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
2033 /* The following is for when the caller doesn't much care about the
2034 * result.
2035 */
2036 png_fixed_point
2037 png_muldiv_warn(png_structp png_ptr, png_fixed_point a, png_int_32 times,
2038 png_int_32 divisor)
2039 {
2040 png_fixed_point result;
2041
2042 if (png_muldiv(&result, a, times, divisor))
2043 return result;
2044
2045 png_warning(png_ptr, "fixed point overflow ignored");
2046 return 0;
2047 }
2048 #endif
2049
2050 #if (defined PNG_READ_GAMMA_SUPPORTED) || (defined PNG_cHRM_SUPPORTED)
2051 /* more fixed point functions for gamma and cHRM (xy/XYZ) suport. */
2052 /* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
2053 png_fixed_point
2054 png_reciprocal(png_fixed_point a)
2055 {
2056 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2057 double r = floor(1E10/a+.5);
2058
2059 if (r <= 2147483647. && r >= -2147483648.)
2060 return (png_fixed_point)r;
2061 #else
2062 png_fixed_point res;
2063
2064 if (png_muldiv(&res, 100000, 100000, a))
2065 return res;
2066 #endif
2067
2068 return 0; /* error/overflow */
2069 }
2070
2071 #ifdef PNG_READ_GAMMA_SUPPORTED
2072 /* A local convenience routine. */
2073 static png_fixed_point
2074 png_product2(png_fixed_point a, png_fixed_point b)
2075 {
2076 /* The required result is 1/a * 1/b; the following preserves accuracy. */
2077 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2078 double r = a * 1E-5;
2079 r *= b;
2080 r = floor(r+.5);
2081
2082 if (r <= 2147483647. && r >= -2147483648.)
2083 return (png_fixed_point)r;
2084 #else
2085 png_fixed_point res;
2086
2087 if (png_muldiv(&res, a, b, 100000))
2088 return res;
2089 #endif
2090
2091 return 0; /* overflow */
2092 }
2093 #endif /* READ_GAMMA */
2094
2095 /* The inverse of the above. */
2096 png_fixed_point
2097 png_reciprocal2(png_fixed_point a, png_fixed_point b)
2098 {
2099 /* The required result is 1/a * 1/b; the following preserves accuracy. */
2100 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2101 double r = 1E15/a;
2102 r /= b;
2103 r = floor(r+.5);
2104
2105 if (r <= 2147483647. && r >= -2147483648.)
2106 return (png_fixed_point)r;
2107 #else
2108 /* This may overflow because the range of png_fixed_point isn't symmetric,
2109 * but this API is only used for the product of file and screen gamma so it
2110 * doesn't matter that the smallest number it can produce is 1/21474, not
2111 * 1/100000
2112 */
2113 png_fixed_point res = png_product2(a, b);
2114
2115 if (res != 0)
2116 return png_reciprocal(res);
2117 #endif
2118
2119 return 0; /* overflow */
2120 }
2121 #endif /* READ_GAMMA || cHRM */
2122
2123 #ifdef PNG_CHECK_cHRM_SUPPORTED
2124 /* Added at libpng version 1.2.34 (Dec 8, 2008) and 1.4.0 (Jan 2,
2125 * 2010: moved from pngset.c) */
2126 /*
2127 * Multiply two 32-bit numbers, V1 and V2, using 32-bit
2128 * arithmetic, to produce a 64-bit result in the HI/LO words.
2129 *
2130 * A B
2131 * x C D
2132 * ------
2133 * AD || BD
2134 * AC || CB || 0
2135 *
2136 * where A and B are the high and low 16-bit words of V1,
2137 * C and D are the 16-bit words of V2, AD is the product of
2138 * A and D, and X || Y is (X << 16) + Y.
2139 */
2140
2141 void /* PRIVATE */
2142 png_64bit_product (long v1, long v2, unsigned long *hi_product,
2143 unsigned long *lo_product)
2144 {
2145 int a, b, c, d;
2146 long lo, hi, x, y;
2147
2148 a = (v1 >> 16) & 0xffff;
2149 b = v1 & 0xffff;
2150 c = (v2 >> 16) & 0xffff;
2151 d = v2 & 0xffff;
2152
2153 lo = b * d; /* BD */
2154 x = a * d + c * b; /* AD + CB */
2155 y = ((lo >> 16) & 0xffff) + x;
2156
2157 lo = (lo & 0xffff) | ((y & 0xffff) << 16);
2158 hi = (y >> 16) & 0xffff;
2159
2160 hi += a * c; /* AC */
2161
2162 *hi_product = (unsigned long)hi;
2163 *lo_product = (unsigned long)lo;
2164 }
2165 #endif /* CHECK_cHRM */
2166
2167 #ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
2168 #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
2169 /* Fixed point gamma.
2170 *
2171 * To calculate gamma this code implements fast log() and exp() calls using only
2172 * fixed point arithmetic. This code has sufficient precision for either 8-bit
2173 * or 16-bit sample values.
2174 *
2175 * The tables used here were calculated using simple 'bc' programs, but C double
2176 * precision floating point arithmetic would work fine. The programs are given
2177 * at the head of each table.
2178 *
2179 * 8-bit log table
2180 * This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
2181 * 255, so it's the base 2 logarithm of a normalized 8-bit floating point
2182 * mantissa. The numbers are 32-bit fractions.
2183 */
2184 static png_uint_32
2185 png_8bit_l2[128] =
2186 {
2187 # ifdef PNG_DO_BC
2188 for (i=128;i<256;++i) { .5 - l(i/255)/l(2)*65536*65536; }
2189 # else
2190 4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
2191 3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
2192 3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
2193 3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
2194 3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
2195 2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
2196 2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
2197 2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
2198 2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
2199 2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
2200 1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
2201 1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
2202 1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
2203 1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
2204 1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
2205 971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
2206 803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
2207 639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
2208 479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
2209 324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
2210 172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
2211 24347096U, 0U
2212 # endif
2213
2214 #if 0
2215 /* The following are the values for 16-bit tables - these work fine for the
2216 * 8-bit conversions but produce very slightly larger errors in the 16-bit
2217 * log (about 1.2 as opposed to 0.7 absolute error in the final value). To
2218 * use these all the shifts below must be adjusted appropriately.
2219 */
2220 65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
2221 57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
2222 50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
2223 43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
2224 37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
2225 31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
2226 25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
2227 20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
2228 15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
2229 10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
2230 6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
2231 1119, 744, 372
2232 #endif
2233 };
2234
2235 PNG_STATIC png_int_32
2236 png_log8bit(unsigned int x)
2237 {
2238 unsigned int lg2 = 0;
2239 /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
2240 * because the log is actually negate that means adding 1. The final
2241 * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
2242 * input), return 7.99998 for the overflow (log 0) case - so the result is
2243 * always at most 19 bits.
2244 */
2245 if ((x &= 0xff) == 0)
2246 return 0xffffffff;
2247
2248 if ((x & 0xf0) == 0)
2249 lg2 = 4, x <<= 4;
2250
2251 if ((x & 0xc0) == 0)
2252 lg2 += 2, x <<= 2;
2253
2254 if ((x & 0x80) == 0)
2255 lg2 += 1, x <<= 1;
2256
2257 /* result is at most 19 bits, so this cast is safe: */
2258 return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
2259 }
2260
2261 /* The above gives exact (to 16 binary places) log2 values for 8-bit images,
2262 * for 16-bit images we use the most significant 8 bits of the 16-bit value to
2263 * get an approximation then multiply the approximation by a correction factor
2264 * determined by the remaining up to 8 bits. This requires an additional step
2265 * in the 16-bit case.
2266 *
2267 * We want log2(value/65535), we have log2(v'/255), where:
2268 *
2269 * value = v' * 256 + v''
2270 * = v' * f
2271 *
2272 * So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
2273 * to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
2274 * than 258. The final factor also needs to correct for the fact that our 8-bit
2275 * value is scaled by 255, whereas the 16-bit values must be scaled by 65535.
2276 *
2277 * This gives a final formula using a calculated value 'x' which is value/v' and
2278 * scaling by 65536 to match the above table:
2279 *
2280 * log2(x/257) * 65536
2281 *
2282 * Since these numbers are so close to '1' we can use simple linear
2283 * interpolation between the two end values 256/257 (result -368.61) and 258/257
2284 * (result 367.179). The values used below are scaled by a further 64 to give
2285 * 16-bit precision in the interpolation:
2286 *
2287 * Start (256): -23591
2288 * Zero (257): 0
2289 * End (258): 23499
2290 */
2291 PNG_STATIC png_int_32
2292 png_log16bit(png_uint_32 x)
2293 {
2294 unsigned int lg2 = 0;
2295
2296 /* As above, but now the input has 16 bits. */
2297 if ((x &= 0xffff) == 0)
2298 return 0xffffffff;
2299
2300 if ((x & 0xff00) == 0)
2301 lg2 = 8, x <<= 8;
2302
2303 if ((x & 0xf000) == 0)
2304 lg2 += 4, x <<= 4;
2305
2306 if ((x & 0xc000) == 0)
2307 lg2 += 2, x <<= 2;
2308
2309 if ((x & 0x8000) == 0)
2310 lg2 += 1, x <<= 1;
2311
2312 /* Calculate the base logarithm from the top 8 bits as a 28-bit fractional
2313 * value.
2314 */
2315 lg2 <<= 28;
2316 lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
2317
2318 /* Now we need to interpolate the factor, this requires a division by the top
2319 * 8 bits. Do this with maximum precision.
2320 */
2321 x = ((x << 16) + (x >> 9)) / (x >> 8);
2322
2323 /* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
2324 * the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly
2325 * 16 bits to interpolate to get the low bits of the result. Round the
2326 * answer. Note that the end point values are scaled by 64 to retain overall
2327 * precision and that 'lg2' is current scaled by an extra 12 bits, so adjust
2328 * the overall scaling by 6-12. Round at every step.
2329 */
2330 x -= 1U << 24;
2331
2332 if (x <= 65536U) /* <= '257' */
2333 lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);
2334
2335 else
2336 lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
2337
2338 /* Safe, because the result can't have more than 20 bits: */
2339 return (png_int_32)((lg2 + 2048) >> 12);
2340 }
2341
2342 /* The 'exp()' case must invert the above, taking a 20-bit fixed point
2343 * logarithmic value and returning a 16 or 8-bit number as appropriate. In
2344 * each case only the low 16 bits are relevant - the fraction - since the
2345 * integer bits (the top 4) simply determine a shift.
2346 *
2347 * The worst case is the 16-bit distinction between 65535 and 65534, this
2348 * requires perhaps spurious accuracy in the decoding of the logarithm to
2349 * distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance
2350 * of getting this accuracy in practice.
2351 *
2352 * To deal with this the following exp() function works out the exponent of the
2353 * frational part of the logarithm by using an accurate 32-bit value from the
2354 * top four fractional bits then multiplying in the remaining bits.
2355 */
2356 static png_uint_32
2357 png_32bit_exp[16] =
2358 {
2359 # ifdef PNG_DO_BC
2360 for (i=0;i<16;++i) { .5 + e(-i/16*l(2))*2^32; }
2361 # else
2362 /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
2363 4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
2364 3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
2365 2553802834U, 2445529972U, 2341847524U, 2242560872U
2366 # endif
2367 };
2368
2369 /* Adjustment table; provided to explain the numbers in the code below. */
2370 #ifdef PNG_DO_BC
2371 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
2372 11 44937.64284865548751208448
2373 10 45180.98734845585101160448
2374 9 45303.31936980687359311872
2375 8 45364.65110595323018870784
2376 7 45395.35850361789624614912
2377 6 45410.72259715102037508096
2378 5 45418.40724413220722311168
2379 4 45422.25021786898173001728
2380 3 45424.17186732298419044352
2381 2 45425.13273269940811464704
2382 1 45425.61317555035558641664
2383 0 45425.85339951654943850496
2384 #endif
2385
2386 PNG_STATIC png_uint_32
2387 png_exp(png_fixed_point x)
2388 {
2389 if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
2390 {
2391 /* Obtain a 4-bit approximation */
2392 png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
2393
2394 /* Incorporate the low 12 bits - these decrease the returned value by
2395 * multiplying by a number less than 1 if the bit is set. The multiplier
2396 * is determined by the above table and the shift. Notice that the values
2397 * converge on 45426 and this is used to allow linear interpolation of the
2398 * low bits.
2399 */
2400 if (x & 0x800)
2401 e -= (((e >> 16) * 44938U) + 16U) >> 5;
2402
2403 if (x & 0x400)
2404 e -= (((e >> 16) * 45181U) + 32U) >> 6;
2405
2406 if (x & 0x200)
2407 e -= (((e >> 16) * 45303U) + 64U) >> 7;
2408
2409 if (x & 0x100)
2410 e -= (((e >> 16) * 45365U) + 128U) >> 8;
2411
2412 if (x & 0x080)
2413 e -= (((e >> 16) * 45395U) + 256U) >> 9;
2414
2415 if (x & 0x040)
2416 e -= (((e >> 16) * 45410U) + 512U) >> 10;
2417
2418 /* And handle the low 6 bits in a single block. */
2419 e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
2420
2421 /* Handle the upper bits of x. */
2422 e >>= x >> 16;
2423 return e;
2424 }
2425
2426 /* Check for overflow */
2427 if (x <= 0)
2428 return png_32bit_exp[0];
2429
2430 /* Else underflow */
2431 return 0;
2432 }
2433
2434 PNG_STATIC png_byte
2435 png_exp8bit(png_fixed_point lg2)
2436 {
2437 /* Get a 32-bit value: */
2438 png_uint_32 x = png_exp(lg2);
2439
2440 /* Convert the 32-bit value to 0..255 by multiplying by 256-1, note that the
2441 * second, rounding, step can't overflow because of the first, subtraction,
2442 * step.
2443 */
2444 x -= x >> 8;
2445 return (png_byte)((x + 0x7fffffU) >> 24);
2446 }
2447
2448 PNG_STATIC png_uint_16
2449 png_exp16bit(png_fixed_point lg2)
2450 {
2451 /* Get a 32-bit value: */
2452 png_uint_32 x = png_exp(lg2);
2453
2454 /* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
2455 x -= x >> 16;
2456 return (png_uint_16)((x + 32767U) >> 16);
2457 }
2458 #endif /* FLOATING_ARITHMETIC */
2459
2460 png_byte
2461 png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
2462 {
2463 if (value > 0 && value < 255)
2464 {
2465 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2466 double r = floor(255*pow(value/255.,gamma_val*.00001)+.5);
2467 return (png_byte)r;
2468 # else
2469 png_int_32 lg2 = png_log8bit(value);
2470 png_fixed_point res;
2471
2472 if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2473 return png_exp8bit(res);
2474
2475 /* Overflow. */
2476 value = 0;
2477 # endif
2478 }
2479
2480 return (png_byte)value;
2481 }
2482
2483 png_uint_16
2484 png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)
2485 {
2486 if (value > 0 && value < 65535)
2487 {
2488 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2489 double r = floor(65535*pow(value/65535.,gamma_val*.00001)+.5);
2490 return (png_uint_16)r;
2491 # else
2492 png_int_32 lg2 = png_log16bit(value);
2493 png_fixed_point res;
2494
2495 if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2496 return png_exp16bit(res);
2497
2498 /* Overflow. */
2499 value = 0;
2500 # endif
2501 }
2502
2503 return (png_uint_16)value;
2504 }
2505
2506 /* This does the right thing based on the bit_depth field of the
2507 * png_struct, interpreting values as 8-bit or 16-bit. While the result
2508 * is nominally a 16-bit value if bit depth is 8 then the result is
2509 * 8-bit (as are the arguments.)
2510 */
2511 png_uint_16 /* PRIVATE */
2512 png_gamma_correct(png_structp png_ptr, unsigned int value,
2513 png_fixed_point gamma_val)
2514 {
2515 if (png_ptr->bit_depth == 8)
2516 return png_gamma_8bit_correct(value, gamma_val);
2517
2518 else
2519 return png_gamma_16bit_correct(value, gamma_val);
2520 }
2521
2522 /* This is the shared test on whether a gamma value is 'significant' - whether
2523 * it is worth doing gamma correction.
2524 */
2525 int /* PRIVATE */
2526 png_gamma_significant(png_fixed_point gamma_val)
2527 {
2528 return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
2529 gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
2530 }
2531
2532 /* Internal function to build a single 16-bit table - the table consists of
2533 * 'num' 256-entry subtables, where 'num' is determined by 'shift' - the amount
2534 * to shift the input values right (or 16-number_of_signifiant_bits).
2535 *
2536 * The caller is responsible for ensuring that the table gets cleaned up on
2537 * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
2538 * should be somewhere that will be cleaned.
2539 */
2540 static void
2541 png_build_16bit_table(png_structp png_ptr, png_uint_16pp *ptable,
2542 PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
2543 {
2544 /* Various values derived from 'shift': */
2545 PNG_CONST unsigned int num = 1U << (8U - shift);
2546 PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
2547 PNG_CONST unsigned int max_by_2 = 1U << (15U-shift);
2548 unsigned int i;
2549
2550 png_uint_16pp table = *ptable =
2551 (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
2552
2553 for (i = 0; i < num; i++)
2554 {
2555 png_uint_16p sub_table = table[i] =
2556 (png_uint_16p)png_malloc(png_ptr, 256 * png_sizeof(png_uint_16));
2557
2558 /* The 'threshold' test is repeated here because it can arise for one of
2559 * the 16-bit tables even if the others don't hit it.
2560 */
2561 if (png_gamma_significant(gamma_val))
2562 {
2563 /* The old code would overflow at the end and this would cause the
2564 * 'pow' function to return a result >1, resulting in an
2565 * arithmetic error. This code follows the spec exactly; ig is
2566 * the recovered input sample, it always has 8-16 bits.
2567 *
2568 * We want input * 65535/max, rounded, the arithmetic fits in 32
2569 * bits (unsigned) so long as max <= 32767.
2570 */
2571 unsigned int j;
2572 for (j = 0; j < 256; j++)
2573 {
2574 png_uint_32 ig = (j << (8-shift)) + i;
2575 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2576 /* Inline the 'max' scaling operation: */
2577 double d = floor(65535*pow(ig/(double)max, gamma_val*.00001)+.5);
2578 sub_table[j] = (png_uint_16)d;
2579 # else
2580 if (shift)
2581 ig = (ig * 65535U + max_by_2)/max;
2582
2583 sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);
2584 # endif
2585 }
2586 }
2587 else
2588 {
2589 /* We must still build a table, but do it the fast way. */
2590 unsigned int j;
2591
2592 for (j = 0; j < 256; j++)
2593 {
2594 png_uint_32 ig = (j << (8-shift)) + i;
2595
2596 if (shift)
2597 ig = (ig * 65535U + max_by_2)/max;
2598
2599 sub_table[j] = (png_uint_16)ig;
2600 }
2601 }
2602 }
2603 }
2604
2605 /* NOTE: this function expects the *inverse* of the overall gamma transformation
2606 * required.
2607 */
2608 static void
2609 png_build_16to8_table(png_structp png_ptr, png_uint_16pp *ptable,
2610 PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
2611 {
2612 PNG_CONST unsigned int num = 1U << (8U - shift);
2613 PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
2614 unsigned int i;
2615 png_uint_32 last;
2616
2617 png_uint_16pp table = *ptable =
2618 (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
2619
2620 /* 'num' is the number of tables and also the number of low bits of the
2621 * input 16-bit value used to select a table. Each table is itself indexed
2622 * by the high 8 bits of the value.
2623 */
2624 for (i = 0; i < num; i++)
2625 table[i] = (png_uint_16p)png_malloc(png_ptr,
2626 256 * png_sizeof(png_uint_16));
2627
2628 /* 'gamma_val' is set to the reciprocal of the value calculated above, so
2629 * pow(out,g) is an *input* value. 'last' is the last input value set.
2630 *
2631 * In the loop 'i' is used to find output values. Since the output is
2632 * 8-bit there are only 256 possible values. The tables are set up to
2633 * select the closest possible output value for each input by finding
2634 * the input value at the boundary between each pair of output values
2635 * and filling the table up to that boundary with the lower output
2636 * value.
2637 *
2638 * The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit
2639 * values the code below uses a 16-bit value in i; the values start at
2640 * 128.5 (for 0.5) and step by 257, for a total of 254 values (the last
2641 * entries are filled with 255). Start i at 128 and fill all 'last'
2642 * table entries <= 'max'
2643 */
2644 last = 0;
2645 for (i = 0; i < 255; ++i) /* 8-bit output value */
2646 {
2647 /* Find the corresponding maximum input value */
2648 png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */
2649
2650 /* Find the boundary value in 16 bits: */
2651 png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
2652
2653 /* Adjust (round) to (16-shift) bits: */
2654 bound = (bound * max + 32768U)/65535U + 1U;
2655
2656 while (last < bound)
2657 {
2658 table[last & (0xffU >> shift)][last >> (8U - shift)] = out;
2659 last++;
2660 }
2661 }
2662
2663 /* And fill in the final entries. */
2664 while (last < (num << 8))
2665 {
2666 table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
2667 last++;
2668 }
2669 }
2670
2671 /* Build a single 8-bit table: same as the 16-bit case but much simpler (and
2672 * typically much faster). Note that libpng currently does no sBIT processing
2673 * (apparently contrary to the spec) so a 256-entry table is always generated.
2674 */
2675 static void
2676 png_build_8bit_table(png_structp png_ptr, png_bytepp ptable,
2677 PNG_CONST png_fixed_point gamma_val)
2678 {
2679 unsigned int i;
2680 png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
2681
2682 if (png_gamma_significant(gamma_val)) for (i=0; i<256; i++)
2683 table[i] = png_gamma_8bit_correct(i, gamma_val);
2684
2685 else for (i=0; i<256; ++i)
2686 table[i] = (png_byte)i;
2687 }
2688
2689 /* Used from png_read_destroy and below to release the memory used by the gamma
2690 * tables.
2691 */
2692 void /* PRIVATE */
2693 png_destroy_gamma_table(png_structp png_ptr)
2694 {
2695 png_free(png_ptr, png_ptr->gamma_table);
2696 png_ptr->gamma_table = NULL;
2697
2698 if (png_ptr->gamma_16_table != NULL)
2699 {
2700 int i;
2701 int istop = (1 << (8 - png_ptr->gamma_shift));
2702 for (i = 0; i < istop; i++)
2703 {
2704 png_free(png_ptr, png_ptr->gamma_16_table[i]);
2705 }
2706 png_free(png_ptr, png_ptr->gamma_16_table);
2707 png_ptr->gamma_16_table = NULL;
2708 }
2709
2710 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2711 defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
2712 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2713 png_free(png_ptr, png_ptr->gamma_from_1);
2714 png_ptr->gamma_from_1 = NULL;
2715 png_free(png_ptr, png_ptr->gamma_to_1);
2716 png_ptr->gamma_to_1 = NULL;
2717
2718 if (png_ptr->gamma_16_from_1 != NULL)
2719 {
2720 int i;
2721 int istop = (1 << (8 - png_ptr->gamma_shift));
2722 for (i = 0; i < istop; i++)
2723 {
2724 png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
2725 }
2726 png_free(png_ptr, png_ptr->gamma_16_from_1);
2727 png_ptr->gamma_16_from_1 = NULL;
2728 }
2729 if (png_ptr->gamma_16_to_1 != NULL)
2730 {
2731 int i;
2732 int istop = (1 << (8 - png_ptr->gamma_shift));
2733 for (i = 0; i < istop; i++)
2734 {
2735 png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
2736 }
2737 png_free(png_ptr, png_ptr->gamma_16_to_1);
2738 png_ptr->gamma_16_to_1 = NULL;
2739 }
2740 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
2741 }
2742
2743 /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
2744 * tables, we don't make a full table if we are reducing to 8-bit in
2745 * the future. Note also how the gamma_16 tables are segmented so that
2746 * we don't need to allocate > 64K chunks for a full 16-bit table.
2747 */
2748 void /* PRIVATE */
2749 png_build_gamma_table(png_structp png_ptr, int bit_depth)
2750 {
2751 png_debug(1, "in png_build_gamma_table");
2752
2753 /* Remove any existing table; this copes with multiple calls to
2754 * png_read_update_info. The warning is because building the gamma tables
2755 * multiple times is a performance hit - it's harmless but the ability to call
2756 * png_read_update_info() multiple times is new in 1.5.6 so it seems sensible
2757 * to warn if the app introduces such a hit.
2758 */
2759 if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)
2760 {
2761 png_warning(png_ptr, "gamma table being rebuilt");
2762 png_destroy_gamma_table(png_ptr);
2763 }
2764
2765 if (bit_depth <= 8)
2766 {
2767 png_build_8bit_table(png_ptr, &png_ptr->gamma_table,
2768 png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
2769 png_ptr->screen_gamma) : PNG_FP_1);
2770
2771 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2772 defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
2773 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2774 if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
2775 {
2776 png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1,
2777 png_reciprocal(png_ptr->gamma));
2778
2779 png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
2780 png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
2781 png_ptr->gamma/* Probably doing rgb_to_gray */);
2782 }
2783 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
2784 }
2785 else
2786 {
2787 png_byte shift, sig_bit;
2788
2789 if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
2790 {
2791 sig_bit = png_ptr->sig_bit.red;
2792
2793 if (png_ptr->sig_bit.green > sig_bit)
2794 sig_bit = png_ptr->sig_bit.green;
2795
2796 if (png_ptr->sig_bit.blue > sig_bit)
2797 sig_bit = png_ptr->sig_bit.blue;
2798 }
2799 else
2800 sig_bit = png_ptr->sig_bit.gray;
2801
2802 /* 16-bit gamma code uses this equation:
2803 *
2804 * ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
2805 *
2806 * Where 'iv' is the input color value and 'ov' is the output value -
2807 * pow(iv, gamma).
2808 *
2809 * Thus the gamma table consists of up to 256 256-entry tables. The table
2810 * is selected by the (8-gamma_shift) most significant of the low 8 bits of
2811 * the color value then indexed by the upper 8 bits:
2812 *
2813 * table[low bits][high 8 bits]
2814 *
2815 * So the table 'n' corresponds to all those 'iv' of:
2816 *
2817 * <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
2818 *
2819 */
2820 if (sig_bit > 0 && sig_bit < 16U)
2821 shift = (png_byte)(16U - sig_bit); /* shift == insignificant bits */
2822
2823 else
2824 shift = 0; /* keep all 16 bits */
2825
2826 if (png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8))
2827 {
2828 /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively
2829 * the significant bits in the *input* when the output will
2830 * eventually be 8 bits. By default it is 11.
2831 */
2832 if (shift < (16U - PNG_MAX_GAMMA_8))
2833 shift = (16U - PNG_MAX_GAMMA_8);
2834 }
2835
2836 if (shift > 8U)
2837 shift = 8U; /* Guarantees at least one table! */
2838
2839 png_ptr->gamma_shift = shift;
2840
2841 #ifdef PNG_16BIT_SUPPORTED
2842 /* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now
2843 * PNG_COMPOSE). This effectively smashed the background calculation for
2844 * 16-bit output because the 8-bit table assumes the result will be reduced
2845 * to 8 bits.
2846 */
2847 if (png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8))
2848 #endif
2849 png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
2850 png_ptr->screen_gamma > 0 ? png_product2(png_ptr->gamma,
2851 png_ptr->screen_gamma) : PNG_FP_1);
2852
2853 #ifdef PNG_16BIT_SUPPORTED
2854 else
2855 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
2856 png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
2857 png_ptr->screen_gamma) : PNG_FP_1);
2858 #endif
2859
2860 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2861 defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
2862 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2863 if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
2864 {
2865 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
2866 png_reciprocal(png_ptr->gamma));
2867
2868 /* Notice that the '16 from 1' table should be full precision, however
2869 * the lookup on this table still uses gamma_shift, so it can't be.
2870 * TODO: fix this.
2871 */
2872 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
2873 png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
2874 png_ptr->gamma/* Probably doing rgb_to_gray */);
2875 }
2876 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
2877 }
2878 }
2879 #endif /* READ_GAMMA */
2880 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */