Chameleon

Chameleon Svn Source Tree

Root/branches/cparm/i386/modules/Libpng/png.c

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

Archive Download this file

Revision: 2154