Missing flags and a typo
[AROS.git] / compiler / libpng / png.c
blob764f47c20cabbb9bc83033f1cc0ded77fe6e6f91
2 /* png.c - location for general purpose libpng functions
4 * Last changed in libpng 1.5.1 [February 3, 2011]
5 * Copyright (c) 1998-2011 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.)
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
14 #include "pngpriv.h"
16 /* Generate a compiler error if there is an old png.h in the search path. */
17 typedef png_libpng_version_1_5_1 Your_png_h_is_not_version_1_5_1;
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.
25 #ifdef PNG_READ_SUPPORTED
26 void PNGAPI
27 png_set_sig_bytes(png_structp png_ptr, int num_bytes)
29 png_debug(1, "in png_set_sig_bytes");
31 if (png_ptr == NULL)
32 return;
34 if (num_bytes > 8)
35 png_error(png_ptr, "Too many bytes for PNG signature");
37 png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
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 behaviour as strcmp, memcmp, etc).
48 int PNGAPI
49 png_sig_cmp(png_const_bytep sig, png_size_t start, png_size_t num_to_check)
51 png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
53 if (num_to_check > 8)
54 num_to_check = 8;
56 else if (num_to_check < 1)
57 return (-1);
59 if (start > 7)
60 return (-1);
62 if (start + num_to_check > 8)
63 num_to_check = 8 - start;
65 return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
68 #endif /* PNG_READ_SUPPORTED */
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)
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;
80 if (png_ptr == NULL)
81 return (NULL);
83 if (items > PNG_UINT_32_MAX/size)
85 png_warning (p, "Potential overflow in png_zalloc()");
86 return (NULL);
88 num_bytes = (png_alloc_size_t)items * size;
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;
94 return ((voidpf)ptr);
97 /* Function to free memory for zlib */
98 void /* PRIVATE */
99 png_zfree(voidpf png_ptr, voidpf ptr)
101 png_free((png_structp)png_ptr, (png_voidp)ptr);
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.
107 void /* PRIVATE */
108 png_reset_crc(png_structp png_ptr)
110 png_ptr->crc = crc32(0, Z_NULL, 0);
113 /* Calculate the CRC over a section of data. We can only pass as
114 * much data to this routine as the largest single buffer size. We
115 * also check that this data will actually be used before going to the
116 * trouble of calculating it.
118 void /* PRIVATE */
119 png_calculate_crc(png_structp png_ptr, png_const_bytep ptr, png_size_t length)
121 int need_crc = 1;
123 if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
125 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
126 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
127 need_crc = 0;
130 else /* critical */
132 if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
133 need_crc = 0;
136 if (need_crc)
137 png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
140 /* Allocate the memory for an info_struct for the application. We don't
141 * really need the png_ptr, but it could potentially be useful in the
142 * future. This should be used in favour of malloc(png_sizeof(png_info))
143 * and png_info_init() so that applications that want to use a shared
144 * libpng don't have to be recompiled if png_info changes size.
146 PNG_FUNCTION(png_infop,PNGAPI
147 png_create_info_struct,(png_structp png_ptr),PNG_ALLOCATED)
149 png_infop info_ptr;
151 png_debug(1, "in png_create_info_struct");
153 if (png_ptr == NULL)
154 return (NULL);
156 #ifdef PNG_USER_MEM_SUPPORTED
157 info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
158 png_ptr->malloc_fn, png_ptr->mem_ptr);
159 #else
160 info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
161 #endif
162 if (info_ptr != NULL)
163 png_info_init_3(&info_ptr, png_sizeof(png_info));
165 return (info_ptr);
168 /* This function frees the memory associated with a single info struct.
169 * Normally, one would use either png_destroy_read_struct() or
170 * png_destroy_write_struct() to free an info struct, but this may be
171 * useful for some applications.
173 void PNGAPI
174 png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
176 png_infop info_ptr = NULL;
178 png_debug(1, "in png_destroy_info_struct");
180 if (png_ptr == NULL)
181 return;
183 if (info_ptr_ptr != NULL)
184 info_ptr = *info_ptr_ptr;
186 if (info_ptr != NULL)
188 png_info_destroy(png_ptr, info_ptr);
190 #ifdef PNG_USER_MEM_SUPPORTED
191 png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
192 png_ptr->mem_ptr);
193 #else
194 png_destroy_struct((png_voidp)info_ptr);
195 #endif
196 *info_ptr_ptr = NULL;
200 /* Initialize the info structure. This is now an internal function (0.89)
201 * and applications using it are urged to use png_create_info_struct()
202 * instead.
205 void PNGAPI
206 png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
208 png_infop info_ptr = *ptr_ptr;
210 png_debug(1, "in png_info_init_3");
212 if (info_ptr == NULL)
213 return;
215 if (png_sizeof(png_info) > png_info_struct_size)
217 png_destroy_struct(info_ptr);
218 info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
219 *ptr_ptr = info_ptr;
222 /* Set everything to 0 */
223 png_memset(info_ptr, 0, png_sizeof(png_info));
226 void PNGAPI
227 png_data_freer(png_structp png_ptr, png_infop info_ptr,
228 int freer, png_uint_32 mask)
230 png_debug(1, "in png_data_freer");
232 if (png_ptr == NULL || info_ptr == NULL)
233 return;
235 if (freer == PNG_DESTROY_WILL_FREE_DATA)
236 info_ptr->free_me |= mask;
238 else if (freer == PNG_USER_WILL_FREE_DATA)
239 info_ptr->free_me &= ~mask;
241 else
242 png_warning(png_ptr,
243 "Unknown freer parameter in png_data_freer");
246 void PNGAPI
247 png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
248 int num)
250 png_debug(1, "in png_free_data");
252 if (png_ptr == NULL || info_ptr == NULL)
253 return;
255 #ifdef PNG_TEXT_SUPPORTED
256 /* Free text item num or (if num == -1) all text items */
257 if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
259 if (num != -1)
261 if (info_ptr->text && info_ptr->text[num].key)
263 png_free(png_ptr, info_ptr->text[num].key);
264 info_ptr->text[num].key = NULL;
268 else
270 int i;
271 for (i = 0; i < info_ptr->num_text; i++)
272 png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
273 png_free(png_ptr, info_ptr->text);
274 info_ptr->text = NULL;
275 info_ptr->num_text=0;
278 #endif
280 #ifdef PNG_tRNS_SUPPORTED
281 /* Free any tRNS entry */
282 if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
284 png_free(png_ptr, info_ptr->trans_alpha);
285 info_ptr->trans_alpha = NULL;
286 info_ptr->valid &= ~PNG_INFO_tRNS;
288 #endif
290 #ifdef PNG_sCAL_SUPPORTED
291 /* Free any sCAL entry */
292 if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
294 #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
295 png_free(png_ptr, info_ptr->scal_s_width);
296 png_free(png_ptr, info_ptr->scal_s_height);
297 info_ptr->scal_s_width = NULL;
298 info_ptr->scal_s_height = NULL;
299 #endif
300 info_ptr->valid &= ~PNG_INFO_sCAL;
302 #endif
304 #ifdef PNG_pCAL_SUPPORTED
305 /* Free any pCAL entry */
306 if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
308 png_free(png_ptr, info_ptr->pcal_purpose);
309 png_free(png_ptr, info_ptr->pcal_units);
310 info_ptr->pcal_purpose = NULL;
311 info_ptr->pcal_units = NULL;
312 if (info_ptr->pcal_params != NULL)
314 int i;
315 for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
317 png_free(png_ptr, info_ptr->pcal_params[i]);
318 info_ptr->pcal_params[i] = NULL;
320 png_free(png_ptr, info_ptr->pcal_params);
321 info_ptr->pcal_params = NULL;
323 info_ptr->valid &= ~PNG_INFO_pCAL;
325 #endif
327 #ifdef PNG_iCCP_SUPPORTED
328 /* Free any iCCP entry */
329 if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
331 png_free(png_ptr, info_ptr->iccp_name);
332 png_free(png_ptr, info_ptr->iccp_profile);
333 info_ptr->iccp_name = NULL;
334 info_ptr->iccp_profile = NULL;
335 info_ptr->valid &= ~PNG_INFO_iCCP;
337 #endif
339 #ifdef PNG_sPLT_SUPPORTED
340 /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
341 if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
343 if (num != -1)
345 if (info_ptr->splt_palettes)
347 png_free(png_ptr, info_ptr->splt_palettes[num].name);
348 png_free(png_ptr, info_ptr->splt_palettes[num].entries);
349 info_ptr->splt_palettes[num].name = NULL;
350 info_ptr->splt_palettes[num].entries = NULL;
354 else
356 if (info_ptr->splt_palettes_num)
358 int i;
359 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
360 png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
362 png_free(png_ptr, info_ptr->splt_palettes);
363 info_ptr->splt_palettes = NULL;
364 info_ptr->splt_palettes_num = 0;
366 info_ptr->valid &= ~PNG_INFO_sPLT;
369 #endif
371 #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
372 if (png_ptr->unknown_chunk.data)
374 png_free(png_ptr, png_ptr->unknown_chunk.data);
375 png_ptr->unknown_chunk.data = NULL;
378 if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
380 if (num != -1)
382 if (info_ptr->unknown_chunks)
384 png_free(png_ptr, info_ptr->unknown_chunks[num].data);
385 info_ptr->unknown_chunks[num].data = NULL;
389 else
391 int i;
393 if (info_ptr->unknown_chunks_num)
395 for (i = 0; i < info_ptr->unknown_chunks_num; i++)
396 png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
398 png_free(png_ptr, info_ptr->unknown_chunks);
399 info_ptr->unknown_chunks = NULL;
400 info_ptr->unknown_chunks_num = 0;
404 #endif
406 #ifdef PNG_hIST_SUPPORTED
407 /* Free any hIST entry */
408 if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
410 png_free(png_ptr, info_ptr->hist);
411 info_ptr->hist = NULL;
412 info_ptr->valid &= ~PNG_INFO_hIST;
414 #endif
416 /* Free any PLTE entry that was internally allocated */
417 if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
419 png_zfree(png_ptr, info_ptr->palette);
420 info_ptr->palette = NULL;
421 info_ptr->valid &= ~PNG_INFO_PLTE;
422 info_ptr->num_palette = 0;
425 #ifdef PNG_INFO_IMAGE_SUPPORTED
426 /* Free any image bits attached to the info structure */
427 if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
429 if (info_ptr->row_pointers)
431 int row;
432 for (row = 0; row < (int)info_ptr->height; row++)
434 png_free(png_ptr, info_ptr->row_pointers[row]);
435 info_ptr->row_pointers[row] = NULL;
437 png_free(png_ptr, info_ptr->row_pointers);
438 info_ptr->row_pointers = NULL;
440 info_ptr->valid &= ~PNG_INFO_IDAT;
442 #endif
444 if (num != -1)
445 mask &= ~PNG_FREE_MUL;
447 info_ptr->free_me &= ~mask;
450 /* This is an internal routine to free any memory that the info struct is
451 * pointing to before re-using it or freeing the struct itself. Recall
452 * that png_free() checks for NULL pointers for us.
454 void /* PRIVATE */
455 png_info_destroy(png_structp png_ptr, png_infop info_ptr)
457 png_debug(1, "in png_info_destroy");
459 png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
461 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
462 if (png_ptr->num_chunk_list)
464 png_free(png_ptr, png_ptr->chunk_list);
465 png_ptr->chunk_list = NULL;
466 png_ptr->num_chunk_list = 0;
468 #endif
470 png_info_init_3(&info_ptr, png_sizeof(png_info));
472 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
474 /* This function returns a pointer to the io_ptr associated with the user
475 * functions. The application should free any memory associated with this
476 * pointer before png_write_destroy() or png_read_destroy() are called.
478 png_voidp PNGAPI
479 png_get_io_ptr(png_structp png_ptr)
481 if (png_ptr == NULL)
482 return (NULL);
484 return (png_ptr->io_ptr);
487 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
488 # ifdef PNG_STDIO_SUPPORTED
489 /* Initialize the default input/output functions for the PNG file. If you
490 * use your own read or write routines, you can call either png_set_read_fn()
491 * or png_set_write_fn() instead of png_init_io(). If you have defined
492 * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
493 * necessarily available.
495 void PNGAPI
496 png_init_io(png_structp png_ptr, png_FILE_p fp)
498 png_debug(1, "in png_init_io");
500 if (png_ptr == NULL)
501 return;
503 png_ptr->io_ptr = (png_voidp)fp;
505 # endif
507 # ifdef PNG_TIME_RFC1123_SUPPORTED
508 /* Convert the supplied time into an RFC 1123 string suitable for use in
509 * a "Creation Time" or other text-based time string.
511 png_const_charp PNGAPI
512 png_convert_to_rfc1123(png_structp png_ptr, png_const_timep ptime)
514 static PNG_CONST char short_months[12][4] =
515 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
516 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
518 if (png_ptr == NULL)
519 return (NULL);
521 if (png_ptr->time_buffer == NULL)
523 png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
524 png_sizeof(char)));
527 # ifdef USE_FAR_KEYWORD
529 char near_time_buf[29];
530 png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
531 ptime->day % 32, short_months[(ptime->month - 1) % 12],
532 ptime->year, ptime->hour % 24, ptime->minute % 60,
533 ptime->second % 61);
534 png_memcpy(png_ptr->time_buffer, near_time_buf,
535 29*png_sizeof(char));
537 # else
538 png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
539 ptime->day % 32, short_months[(ptime->month - 1) % 12],
540 ptime->year, ptime->hour % 24, ptime->minute % 60,
541 ptime->second % 61);
542 # endif
543 return png_ptr->time_buffer;
545 # endif /* PNG_TIME_RFC1123_SUPPORTED */
547 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
549 png_const_charp PNGAPI
550 png_get_copyright(png_const_structp png_ptr)
552 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
553 #ifdef PNG_STRING_COPYRIGHT
554 return PNG_STRING_COPYRIGHT
555 #else
556 # ifdef __STDC__
557 return PNG_STRING_NEWLINE \
558 "libpng version 1.5.1 - February 3, 2011" PNG_STRING_NEWLINE \
559 "Copyright (c) 1998-2011 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
560 "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
561 "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
562 PNG_STRING_NEWLINE;
563 # else
564 return "libpng version 1.5.1 - February 3, 2011\
565 Copyright (c) 1998-2011 Glenn Randers-Pehrson\
566 Copyright (c) 1996-1997 Andreas Dilger\
567 Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
568 # endif
569 #endif
572 /* The following return the library version as a short string in the
573 * format 1.0.0 through 99.99.99zz. To get the version of *.h files
574 * used with your application, print out PNG_LIBPNG_VER_STRING, which
575 * is defined in png.h.
576 * Note: now there is no difference between png_get_libpng_ver() and
577 * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
578 * it is guaranteed that png.c uses the correct version of png.h.
580 png_const_charp PNGAPI
581 png_get_libpng_ver(png_const_structp png_ptr)
583 /* Version of *.c files used when building libpng */
584 return png_get_header_ver(png_ptr);
587 png_const_charp PNGAPI
588 png_get_header_ver(png_const_structp png_ptr)
590 /* Version of *.h files used when building libpng */
591 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
592 return PNG_LIBPNG_VER_STRING;
595 png_const_charp PNGAPI
596 png_get_header_version(png_const_structp png_ptr)
598 /* Returns longer string containing both version and date */
599 PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
600 #ifdef __STDC__
601 return PNG_HEADER_VERSION_STRING
602 # ifndef PNG_READ_SUPPORTED
603 " (NO READ SUPPORT)"
604 # endif
605 PNG_STRING_NEWLINE;
606 #else
607 return PNG_HEADER_VERSION_STRING;
608 #endif
611 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
612 # ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
613 int PNGAPI
614 png_handle_as_unknown(png_structp png_ptr, png_const_bytep chunk_name)
616 /* Check chunk_name and return "keep" value if it's on the list, else 0 */
617 int i;
618 png_bytep p;
619 if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
620 return 0;
622 p = png_ptr->chunk_list + png_ptr->num_chunk_list*5 - 5;
623 for (i = png_ptr->num_chunk_list; i; i--, p -= 5)
624 if (!png_memcmp(chunk_name, p, 4))
625 return ((int)*(p + 4));
626 return 0;
628 # endif
629 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
631 #ifdef PNG_READ_SUPPORTED
632 /* This function, added to libpng-1.0.6g, is untested. */
633 int PNGAPI
634 png_reset_zstream(png_structp png_ptr)
636 if (png_ptr == NULL)
637 return Z_STREAM_ERROR;
639 return (inflateReset(&png_ptr->zstream));
641 #endif /* PNG_READ_SUPPORTED */
643 /* This function was added to libpng-1.0.7 */
644 png_uint_32 PNGAPI
645 png_access_version_number(void)
647 /* Version of *.c files used when building libpng */
648 return((png_uint_32)PNG_LIBPNG_VER);
653 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
654 # ifdef PNG_SIZE_T
655 /* Added at libpng version 1.2.6 */
656 PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
657 png_size_t PNGAPI
658 png_convert_size(size_t size)
660 if (size > (png_size_t)-1)
661 PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
663 return ((png_size_t)size);
665 # endif /* PNG_SIZE_T */
667 /* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */
668 # ifdef PNG_CHECK_cHRM_SUPPORTED
670 int /* PRIVATE */
671 png_check_cHRM_fixed(png_structp png_ptr,
672 png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
673 png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
674 png_fixed_point blue_x, png_fixed_point blue_y)
676 int ret = 1;
677 unsigned long xy_hi,xy_lo,yx_hi,yx_lo;
679 png_debug(1, "in function png_check_cHRM_fixed");
681 if (png_ptr == NULL)
682 return 0;
684 if (white_x < 0 || white_y <= 0 ||
685 red_x < 0 || red_y < 0 ||
686 green_x < 0 || green_y < 0 ||
687 blue_x < 0 || blue_y < 0)
689 png_warning(png_ptr,
690 "Ignoring attempt to set negative chromaticity value");
691 ret = 0;
693 if (white_x > (png_fixed_point)PNG_UINT_31_MAX ||
694 white_y > (png_fixed_point)PNG_UINT_31_MAX ||
695 red_x > (png_fixed_point)PNG_UINT_31_MAX ||
696 red_y > (png_fixed_point)PNG_UINT_31_MAX ||
697 green_x > (png_fixed_point)PNG_UINT_31_MAX ||
698 green_y > (png_fixed_point)PNG_UINT_31_MAX ||
699 blue_x > (png_fixed_point)PNG_UINT_31_MAX ||
700 blue_y > (png_fixed_point)PNG_UINT_31_MAX )
702 png_warning(png_ptr,
703 "Ignoring attempt to set chromaticity value exceeding 21474.83");
704 ret = 0;
706 if (white_x > 100000L - white_y)
708 png_warning(png_ptr, "Invalid cHRM white point");
709 ret = 0;
712 if (red_x > 100000L - red_y)
714 png_warning(png_ptr, "Invalid cHRM red point");
715 ret = 0;
718 if (green_x > 100000L - green_y)
720 png_warning(png_ptr, "Invalid cHRM green point");
721 ret = 0;
724 if (blue_x > 100000L - blue_y)
726 png_warning(png_ptr, "Invalid cHRM blue point");
727 ret = 0;
730 png_64bit_product(green_x - red_x, blue_y - red_y, &xy_hi, &xy_lo);
731 png_64bit_product(green_y - red_y, blue_x - red_x, &yx_hi, &yx_lo);
733 if (xy_hi == yx_hi && xy_lo == yx_lo)
735 png_warning(png_ptr,
736 "Ignoring attempt to set cHRM RGB triangle with zero area");
737 ret = 0;
740 return ret;
742 # endif /* PNG_CHECK_cHRM_SUPPORTED */
744 void /* PRIVATE */
745 png_check_IHDR(png_structp png_ptr,
746 png_uint_32 width, png_uint_32 height, int bit_depth,
747 int color_type, int interlace_type, int compression_type,
748 int filter_type)
750 int error = 0;
752 /* Check for width and height valid values */
753 if (width == 0)
755 png_warning(png_ptr, "Image width is zero in IHDR");
756 error = 1;
759 if (height == 0)
761 png_warning(png_ptr, "Image height is zero in IHDR");
762 error = 1;
765 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
766 if (width > png_ptr->user_width_max || width > PNG_USER_WIDTH_MAX)
768 # else
769 if (width > PNG_USER_WIDTH_MAX)
770 # endif
772 png_warning(png_ptr, "Image width exceeds user limit in IHDR");
773 error = 1;
776 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
777 if (height > png_ptr->user_height_max || height > PNG_USER_HEIGHT_MAX)
778 # else
779 if (height > PNG_USER_HEIGHT_MAX)
780 # endif
782 png_warning(png_ptr, "Image height exceeds user limit in IHDR");
783 error = 1;
786 if (width > PNG_UINT_31_MAX)
788 png_warning(png_ptr, "Invalid image width in IHDR");
789 error = 1;
792 if (height > PNG_UINT_31_MAX)
794 png_warning(png_ptr, "Invalid image height in IHDR");
795 error = 1;
798 if (width > (PNG_UINT_32_MAX
799 >> 3) /* 8-byte RGBA pixels */
800 - 48 /* bigrowbuf hack */
801 - 1 /* filter byte */
802 - 7*8 /* rounding of width to multiple of 8 pixels */
803 - 8) /* extra max_pixel_depth pad */
804 png_warning(png_ptr, "Width is too large for libpng to process pixels");
806 /* Check other values */
807 if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
808 bit_depth != 8 && bit_depth != 16)
810 png_warning(png_ptr, "Invalid bit depth in IHDR");
811 error = 1;
814 if (color_type < 0 || color_type == 1 ||
815 color_type == 5 || color_type > 6)
817 png_warning(png_ptr, "Invalid color type in IHDR");
818 error = 1;
821 if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
822 ((color_type == PNG_COLOR_TYPE_RGB ||
823 color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
824 color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
826 png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
827 error = 1;
830 if (interlace_type >= PNG_INTERLACE_LAST)
832 png_warning(png_ptr, "Unknown interlace method in IHDR");
833 error = 1;
836 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
838 png_warning(png_ptr, "Unknown compression method in IHDR");
839 error = 1;
842 # ifdef PNG_MNG_FEATURES_SUPPORTED
843 /* Accept filter_method 64 (intrapixel differencing) only if
844 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
845 * 2. Libpng did not read a PNG signature (this filter_method is only
846 * used in PNG datastreams that are embedded in MNG datastreams) and
847 * 3. The application called png_permit_mng_features with a mask that
848 * included PNG_FLAG_MNG_FILTER_64 and
849 * 4. The filter_method is 64 and
850 * 5. The color_type is RGB or RGBA
852 if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) &&
853 png_ptr->mng_features_permitted)
854 png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
856 if (filter_type != PNG_FILTER_TYPE_BASE)
858 if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
859 (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
860 ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
861 (color_type == PNG_COLOR_TYPE_RGB ||
862 color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
864 png_warning(png_ptr, "Unknown filter method in IHDR");
865 error = 1;
868 if (png_ptr->mode & PNG_HAVE_PNG_SIGNATURE)
870 png_warning(png_ptr, "Invalid filter method in IHDR");
871 error = 1;
875 # else
876 if (filter_type != PNG_FILTER_TYPE_BASE)
878 png_warning(png_ptr, "Unknown filter method in IHDR");
879 error = 1;
881 # endif
883 if (error == 1)
884 png_error(png_ptr, "Invalid IHDR data");
887 #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
888 /* ASCII to fp functions */
889 /* Check an ASCII formated floating point value, see the more detailed
890 * comments in pngpriv.h
892 /* The following is used internally to preserve the 'valid' flag */
893 #define png_fp_add(state, flags) ((state) |= (flags))
894 #define png_fp_set(state, value)\
895 ((state) = (value) | ((state) & PNG_FP_WAS_VALID))
897 /* Internal type codes: bits above the base state! */
898 #define PNG_FP_SIGN 0 /* [+-] */
899 #define PNG_FP_DOT 4 /* . */
900 #define PNG_FP_DIGIT 8 /* [0123456789] */
901 #define PNG_FP_E 12 /* [Ee] */
903 int /* PRIVATE */
904 png_check_fp_number(png_const_charp string, png_size_t size, int *statep,
905 png_size_tp whereami)
907 int state = *statep;
908 png_size_t i = *whereami;
910 while (i < size)
912 int type;
913 /* First find the type of the next character */
915 char ch = string[i];
917 if (ch >= 48 && ch <= 57)
918 type = PNG_FP_DIGIT;
920 else switch (ch)
922 case 43: case 45: type = PNG_FP_SIGN; break;
923 case 46: type = PNG_FP_DOT; break;
924 case 69: case 101: type = PNG_FP_E; break;
925 default: goto PNG_FP_End;
929 /* Now deal with this type according to the current
930 * state, the type is arranged to not overlap the
931 * bits of the PNG_FP_STATE.
933 switch ((state & PNG_FP_STATE) + type)
935 case PNG_FP_INTEGER + PNG_FP_SIGN:
936 if (state & PNG_FP_SAW_ANY)
937 goto PNG_FP_End; /* not a part of the number */
939 png_fp_add(state, PNG_FP_SAW_SIGN);
940 break;
942 case PNG_FP_INTEGER + PNG_FP_DOT:
943 /* Ok as trailer, ok as lead of fraction. */
944 if (state & PNG_FP_SAW_DOT) /* two dots */
945 goto PNG_FP_End;
947 else if (state & PNG_FP_SAW_DIGIT) /* trailing dot? */
948 png_fp_add(state, PNG_FP_SAW_DOT);
950 else
951 png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
953 break;
955 case PNG_FP_INTEGER + PNG_FP_DIGIT:
956 if (state & PNG_FP_SAW_DOT) /* delayed fraction */
957 png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
959 png_fp_add(state, PNG_FP_SAW_DIGIT + PNG_FP_WAS_VALID);
961 break;
962 case PNG_FP_INTEGER + PNG_FP_E:
963 if ((state & PNG_FP_SAW_DIGIT) == 0)
964 goto PNG_FP_End;
966 png_fp_set(state, PNG_FP_EXPONENT);
968 break;
970 /* case PNG_FP_FRACTION + PNG_FP_SIGN:
971 goto PNG_FP_End; ** no sign in exponent */
973 /* case PNG_FP_FRACTION + PNG_FP_DOT:
974 goto PNG_FP_End; ** Because SAW_DOT is always set */
976 case PNG_FP_FRACTION + PNG_FP_DIGIT:
977 png_fp_add(state, PNG_FP_SAW_DIGIT + PNG_FP_WAS_VALID);
978 break;
980 case PNG_FP_FRACTION + PNG_FP_E:
981 /* This is correct because the trailing '.' on an
982 * integer is handled above - so we can only get here
983 * with the sequence ".E" (with no preceding digits).
985 if ((state & PNG_FP_SAW_DIGIT) == 0)
986 goto PNG_FP_End;
988 png_fp_set(state, PNG_FP_EXPONENT);
990 break;
992 case PNG_FP_EXPONENT + PNG_FP_SIGN:
993 if (state & PNG_FP_SAW_ANY)
994 goto PNG_FP_End; /* not a part of the number */
996 png_fp_add(state, PNG_FP_SAW_SIGN);
998 break;
1000 /* case PNG_FP_EXPONENT + PNG_FP_DOT:
1001 goto PNG_FP_End; */
1003 case PNG_FP_EXPONENT + PNG_FP_DIGIT:
1004 png_fp_add(state, PNG_FP_SAW_DIGIT + PNG_FP_WAS_VALID);
1006 break;
1008 /* case PNG_FP_EXPONEXT + PNG_FP_E:
1009 goto PNG_FP_End; */
1011 default: goto PNG_FP_End; /* I.e. break 2 */
1014 /* The character seems ok, continue. */
1015 ++i;
1018 PNG_FP_End:
1019 /* Here at the end, update the state and return the correct
1020 * return code.
1022 *statep = state;
1023 *whereami = i;
1025 return (state & PNG_FP_SAW_DIGIT) != 0;
1029 /* The same but for a complete string. */
1031 png_check_fp_string(png_const_charp string, png_size_t size)
1033 int state=0;
1034 png_size_t char_index=0;
1036 return png_check_fp_number(string, size, &state, &char_index) &&
1037 (char_index == size || string[char_index] == 0);
1039 #endif /* pCAL or sCAL */
1041 #ifdef PNG_READ_sCAL_SUPPORTED
1042 # ifdef PNG_FLOATING_POINT_SUPPORTED
1043 /* Utility used below - a simple accurate power of ten from an integral
1044 * exponent.
1046 static double
1047 png_pow10(int power)
1049 int recip = 0;
1050 double d = 1;
1052 /* Handle negative exponent with a reciprocal at the end because
1053 * 10 is exact whereas .1 is inexact in base 2
1055 if (power < 0)
1057 if (power < DBL_MIN_10_EXP) return 0;
1058 recip = 1, power = -power;
1061 if (power > 0)
1063 /* Decompose power bitwise. */
1064 double mult = 10;
1067 if (power & 1) d *= mult;
1068 mult *= mult;
1069 power >>= 1;
1071 while (power > 0);
1073 if (recip) d = 1/d;
1075 /* else power is 0 and d is 1 */
1077 return d;
1080 /* Function to format a floating point value in ASCII with a given
1081 * precision.
1083 void /* PRIVATE */
1084 png_ascii_from_fp(png_structp png_ptr, png_charp ascii, png_size_t size,
1085 double fp, unsigned int precision)
1087 /* We use standard functions from math.h, but not printf because
1088 * that would require stdio. The caller must supply a buffer of
1089 * sufficient size or we will png_error. The tests on size and
1090 * the space in ascii[] consumed are indicated below.
1092 if (precision < 1)
1093 precision = DBL_DIG;
1095 /* Enforce the limit of the implementation precision too. */
1096 if (precision > DBL_DIG+1)
1097 precision = DBL_DIG+1;
1099 /* Basic sanity checks */
1100 if (size >= precision+5) /* See the requirements below. */
1102 if (fp < 0)
1104 fp = -fp;
1105 *ascii++ = 45; /* '-' PLUS 1 TOTAL 1*/
1106 --size;
1109 if (fp >= DBL_MIN && fp <= DBL_MAX)
1111 int exp_b10; /* A base 10 exponent */
1112 double base; /* 10^exp_b10 */
1114 /* First extract a base 10 exponent of the number,
1115 * the calculation below rounds down when converting
1116 * from base 2 to base 10 (multiply by log10(2) -
1117 * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
1118 * be increased. Note that the arithmetic shift
1119 * performs a floor() unlike C arithmetic - using a
1120 * C multiply would break the following for negative
1121 * exponents.
1123 (void)frexp(fp, &exp_b10); /* exponent to base 2 */
1125 exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
1127 /* Avoid underflow here. */
1128 base = png_pow10(exp_b10); /* May underflow */
1130 while (base < DBL_MIN || base < fp)
1132 /* And this may overflow. */
1133 double test = png_pow10(exp_b10+1);
1135 if (test <= DBL_MAX)
1136 ++exp_b10, base = test;
1138 else
1139 break;
1142 /* Normalize fp and correct exp_b10, after this fp is in the
1143 * range [.1,1) and exp_b10 is both the exponent and the digit
1144 * *before* which the decimal point should be inserted
1145 * (starting with 0 for the first digit). Note that this
1146 * works even if 10^exp_b10 is out of range because of the
1147 * test on DBL_MAX above.
1149 fp /= base;
1150 while (fp >= 1) fp /= 10, ++exp_b10;
1152 /* Because of the code above fp may, at this point, be
1153 * less than .1, this is ok because the code below can
1154 * handle the leading zeros this generates, so no attempt
1155 * is made to correct that here.
1159 int czero, clead, cdigits;
1160 char exponent[10];
1162 /* Allow up to two leading zeros - this will not lengthen
1163 * the number compared to using E-n.
1165 if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
1167 czero = -exp_b10; /* PLUS 2 digits: TOTAL 3 */
1168 exp_b10 = 0; /* Dot added below before first output. */
1170 else
1171 czero = 0; /* No zeros to add */
1173 /* Generate the digit list, stripping trailing zeros and
1174 * inserting a '.' before a digit if the exponent is 0.
1176 clead = czero; /* Count of leading zeros */
1177 cdigits = 0; /* Count of digits in list. */
1181 double d;
1183 fp *= 10;
1184 /* Use modf here, not floor and subtract, so that
1185 * the separation is done in one step. At the end
1186 * of the loop don't break the number into parts so
1187 * that the final digit is rounded.
1189 if (cdigits+czero-clead+1 < (int)precision)
1190 fp = modf(fp, &d);
1192 else
1194 d = floor(fp + .5);
1196 if (d > 9)
1198 /* Rounding up to 10, handle that here. */
1199 if (czero > 0)
1201 --czero, d = 1;
1202 if (cdigits == 0) --clead;
1204 else
1206 while (cdigits > 0 && d > 9)
1208 int ch = *--ascii;
1210 if (exp_b10 != (-1))
1211 ++exp_b10;
1213 else if (ch == 46)
1215 ch = *--ascii, ++size;
1216 /* Advance exp_b10 to '1', so that the
1217 * decimal point happens after the
1218 * previous digit.
1220 exp_b10 = 1;
1223 --cdigits;
1224 d = ch - 47; /* I.e. 1+(ch-48) */
1227 /* Did we reach the beginning? If so adjust the
1228 * exponent but take into account the leading
1229 * decimal point.
1231 if (d > 9) /* cdigits == 0 */
1233 if (exp_b10 == (-1))
1235 /* Leading decimal point (plus zeros?), if
1236 * we lose the decimal point here it must
1237 * be reentered below.
1239 int ch = *--ascii;
1241 if (ch == 46)
1242 ++size, exp_b10 = 1;
1244 /* Else lost a leading zero, so 'exp_b10' is
1245 * still ok at (-1)
1248 else
1249 ++exp_b10;
1251 /* In all cases we output a '1' */
1252 d = 1;
1256 fp = 0; /* Guarantees termination below. */
1259 if (d == 0)
1261 ++czero;
1262 if (cdigits == 0) ++clead;
1264 else
1266 /* Included embedded zeros in the digit count. */
1267 cdigits += czero - clead;
1268 clead = 0;
1270 while (czero > 0)
1272 /* exp_b10 == (-1) means we just output the decimal
1273 * place - after the DP don't adjust 'exp_b10' any
1274 * more!
1276 if (exp_b10 != (-1))
1278 if (exp_b10 == 0) *ascii++ = 46, --size;
1279 /* PLUS 1: TOTAL 4 */
1280 --exp_b10;
1282 *ascii++ = 48, --czero;
1285 if (exp_b10 != (-1))
1287 if (exp_b10 == 0) *ascii++ = 46, --size; /* counted
1288 above */
1289 --exp_b10;
1291 *ascii++ = (char)(48 + (int)d), ++cdigits;
1294 while (cdigits+czero-clead < (int)precision && fp > DBL_MIN);
1296 /* The total output count (max) is now 4+precision */
1298 /* Check for an exponent, if we don't need one we are
1299 * done and just need to terminate the string. At
1300 * this point exp_b10==(-1) is effectively if flag - it got
1301 * to '-1' because of the decrement after outputing
1302 * the decimal point above (the exponent required is
1303 * *not* -1!)
1305 if (exp_b10 >= (-1) && exp_b10 <= 2)
1307 /* The following only happens if we didn't output the
1308 * leading zeros above for negative exponent, so this
1309 * doest add to the digit requirement. Note that the
1310 * two zeros here can only be output if the two leading
1311 * zeros were *not* output, so this doesn't increase
1312 * the output count.
1314 while (--exp_b10 >= 0) *ascii++ = 48;
1316 *ascii = 0;
1318 /* Total buffer requirement (including the '\0') is
1319 * 5+precision - see check at the start.
1321 return;
1324 /* Here if an exponent is required, adjust size for
1325 * the digits we output but did not count. The total
1326 * digit output here so far is at most 1+precision - no
1327 * decimal point and no leading or trailing zeros have
1328 * been output.
1330 size -= cdigits;
1332 *ascii++ = 69, --size; /* 'E': PLUS 1 TOTAL 2+precision*/
1333 if (exp_b10 < 0)
1335 *ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */
1336 exp_b10 = -exp_b10;
1339 cdigits = 0;
1341 while (exp_b10 > 0)
1343 exponent[cdigits++] = (char)(48 + exp_b10 % 10);
1344 exp_b10 /= 10;
1347 /* Need another size check here for the exponent digits, so
1348 * this need not be considered above.
1350 if ((int)size > cdigits)
1352 while (cdigits > 0) *ascii++ = exponent[--cdigits];
1354 *ascii = 0;
1356 return;
1360 else if (!(fp >= DBL_MIN))
1362 *ascii++ = 48; /* '0' */
1363 *ascii = 0;
1364 return;
1366 else
1368 *ascii++ = 105; /* 'i' */
1369 *ascii++ = 110; /* 'n' */
1370 *ascii++ = 102; /* 'f' */
1371 *ascii = 0;
1372 return;
1376 /* Here on buffer too small. */
1377 png_error(png_ptr, "ASCII conversion buffer too small");
1380 # endif /* FLOATING_POINT */
1382 # ifdef PNG_FIXED_POINT_SUPPORTED
1383 /* Function to format a fixed point value in ASCII.
1385 void /* PRIVATE */
1386 png_ascii_from_fixed(png_structp png_ptr, png_charp ascii, png_size_t size,
1387 png_fixed_point fp)
1389 /* Require space for 10 decimal digits, a decimal point, a minus sign and a
1390 * trailing \0, 13 characters:
1392 if (size > 12)
1394 png_uint_32 num;
1396 /* Avoid overflow here on the minimum integer. */
1397 if (fp < 0)
1398 *ascii++ = 45, --size, num = -fp;
1399 else
1400 num = fp;
1402 if (num <= 0x80000000U) /* else overflowed */
1404 unsigned int ndigits = 0, first = 16/*flag value*/;
1405 char digits[10];
1407 while (num)
1409 /* Split the low digit off num: */
1410 unsigned int tmp = num/10;
1411 num -= tmp*10;
1412 digits[ndigits++] = (char)(48 + num);
1413 /* Record the first non-zero digit, note that this is a number
1414 * starting at 1, it's not actually the array index.
1416 if (first == 16 && num > 0)
1417 first = ndigits;
1418 num = tmp;
1421 if (ndigits > 0)
1423 while (ndigits > 5) *ascii++ = digits[--ndigits];
1424 /* The remaining digits are fractional digits, ndigits is '5' or
1425 * smaller at this point. It is certainly not zero. Check for a
1426 * non-zero fractional digit:
1428 if (first <= 5)
1430 unsigned int i;
1431 *ascii++ = 46; /* decimal point */
1432 /* ndigits may be <5 for small numbers, output leading zeros
1433 * then ndigits digits to first:
1435 i = 5;
1436 while (ndigits < i) *ascii++ = 48, --i;
1437 while (ndigits >= first) *ascii++ = digits[--ndigits];
1438 /* Don't output the trailing zeros! */
1441 else
1442 *ascii++ = 48;
1444 /* And null terminate the string: */
1445 *ascii = 0;
1446 return;
1450 /* Here on buffer too small. */
1451 png_error(png_ptr, "ASCII conversion buffer too small");
1453 # endif /* FIXED_POINT */
1454 #endif /* READ_SCAL */
1456 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
1457 !defined(PNG_FIXED_POINT_MACRO_SUPPORTED)
1458 png_fixed_point
1459 png_fixed(png_structp png_ptr, double fp, png_const_charp text)
1461 double r = floor(100000 * fp + .5);
1463 if (r > 2147483647. || r < -2147483648.)
1464 png_fixed_error(png_ptr, text);
1466 return (png_fixed_point)r;
1468 #endif
1470 #if defined(PNG_READ_GAMMA_SUPPORTED) || \
1471 defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG__READ_pHYs_SUPPORTED)
1472 /* muldiv functions */
1473 /* This API takes signed arguments and rounds the result to the nearest
1474 * integer (or, for a fixed point number - the standard argument - to
1475 * the nearest .00001). Overflow and divide by zero are signalled in
1476 * the result, a boolean - true on success, false on overflow.
1479 png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
1480 png_int_32 divisor)
1482 /* Return a * times / divisor, rounded. */
1483 if (divisor != 0)
1485 if (a == 0 || times == 0)
1487 *res = 0;
1488 return 1;
1490 else
1492 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1493 double r = a;
1494 r *= times;
1495 r /= divisor;
1496 r = floor(r+.5);
1498 /* A png_fixed_point is a 32 bit integer. */
1499 if (r <= 2147483647. && r >= -2147483648.)
1501 *res = (png_fixed_point)r;
1502 return 1;
1504 #else
1505 int negative = 0;
1506 png_uint_32 A, T, D;
1507 png_uint_32 s16, s32, s00;
1509 if (a < 0)
1510 negative = 1, A = -a;
1511 else
1512 A = a;
1514 if (times < 0)
1515 negative = !negative, T = -times;
1516 else
1517 T = times;
1519 if (divisor < 0)
1520 negative = !negative, D = -divisor;
1521 else
1522 D = divisor;
1524 /* Following can't overflow because the arguments only
1525 * have 31 bits each, however the result may be 32 bits.
1527 s16 = (A >> 16) * (T & 0xffff) +
1528 (A & 0xffff) * (T >> 16);
1529 /* Can't overflow because the a*times bit is only 30
1530 * bits at most.
1532 s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
1533 s00 = (A & 0xffff) * (T & 0xffff);
1535 s16 = (s16 & 0xffff) << 16;
1536 s00 += s16;
1538 if (s00 < s16)
1539 ++s32; /* carry */
1541 if (s32 < D) /* else overflow */
1543 /* s32.s00 is now the 64 bit product, do a standard
1544 * division, we know that s32 < D, so the maximum
1545 * required shift is 31.
1547 int bitshift = 32;
1548 png_fixed_point result = 0; /* NOTE: signed */
1550 while (--bitshift >= 0)
1552 png_uint_32 d32, d00;
1554 if (bitshift > 0)
1555 d32 = D >> (32-bitshift), d00 = D << bitshift;
1557 else
1558 d32 = 0, d00 = D;
1560 if (s32 > d32)
1562 if (s00 < d00) --s32; /* carry */
1563 s32 -= d32, s00 -= d00, result += 1<<bitshift;
1566 else
1567 if (s32 == d32 && s00 >= d00)
1568 s32 = 0, s00 -= d00, result += 1<<bitshift;
1571 /* Handle the rounding. */
1572 if (s00 >= (D >> 1))
1573 ++result;
1575 if (negative)
1576 result = -result;
1578 /* Check for overflow. */
1579 if ((negative && result <= 0) || (!negative && result >= 0))
1581 *res = result;
1582 return 1;
1585 #endif
1589 return 0;
1591 #endif /* READ_GAMMA || INCH_CONVERSIONS */
1593 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
1594 /* The following is for when the caller doesn't much care about the
1595 * result.
1597 png_fixed_point
1598 png_muldiv_warn(png_structp png_ptr, png_fixed_point a, png_int_32 times,
1599 png_int_32 divisor)
1601 png_fixed_point result;
1603 if (png_muldiv(&result, a, times, divisor))
1604 return result;
1606 png_warning(png_ptr, "fixed point overflow ignored");
1607 return 0;
1609 #endif
1611 #ifdef PNG_READ_GAMMA_SUPPORTED /* more fixed point functions for gammma */
1612 /* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
1613 png_fixed_point
1614 png_reciprocal(png_fixed_point a)
1616 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1617 double r = floor(1E10/a+.5);
1619 if (r <= 2147483647. && r >= -2147483648.)
1620 return (png_fixed_point)r;
1621 #else
1622 png_fixed_point res;
1624 if (png_muldiv(&res, 100000, 100000, a))
1625 return res;
1626 #endif
1628 return 0; /* error/overflow */
1631 /* A local convenience routine. */
1632 static png_fixed_point
1633 png_product2(png_fixed_point a, png_fixed_point b)
1635 /* The required result is 1/a * 1/b; the following preserves accuracy. */
1636 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1637 double r = a * 1E-5;
1638 r *= b;
1639 r = floor(r+.5);
1641 if (r <= 2147483647. && r >= -2147483648.)
1642 return (png_fixed_point)r;
1643 #else
1644 png_fixed_point res;
1646 if (png_muldiv(&res, a, b, 100000))
1647 return res;
1648 #endif
1650 return 0; /* overflow */
1653 /* The inverse of the above. */
1654 png_fixed_point
1655 png_reciprocal2(png_fixed_point a, png_fixed_point b)
1657 /* The required result is 1/a * 1/b; the following preserves accuracy. */
1658 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1659 double r = 1E15/a;
1660 r /= b;
1661 r = floor(r+.5);
1663 if (r <= 2147483647. && r >= -2147483648.)
1664 return (png_fixed_point)r;
1665 #else
1666 /* This may overflow because the range of png_fixed_point isn't symmetric,
1667 * but this API is only used for the product of file and screen gamma so it
1668 * doesn't matter that the smallest number it can produce is 1/21474, not
1669 * 1/100000
1671 png_fixed_point res = png_product2(a, b);
1673 if (res != 0)
1674 return png_reciprocal(res);
1675 #endif
1677 return 0; /* overflow */
1679 #endif /* READ_GAMMA */
1681 #ifdef PNG_CHECK_cHRM_SUPPORTED
1682 /* Added at libpng version 1.2.34 (Dec 8, 2008) and 1.4.0 (Jan 2,
1683 * 2010: moved from pngset.c) */
1685 * Multiply two 32-bit numbers, V1 and V2, using 32-bit
1686 * arithmetic, to produce a 64 bit result in the HI/LO words.
1688 * A B
1689 * x C D
1690 * ------
1691 * AD || BD
1692 * AC || CB || 0
1694 * where A and B are the high and low 16-bit words of V1,
1695 * C and D are the 16-bit words of V2, AD is the product of
1696 * A and D, and X || Y is (X << 16) + Y.
1699 void /* PRIVATE */
1700 png_64bit_product (long v1, long v2, unsigned long *hi_product,
1701 unsigned long *lo_product)
1703 int a, b, c, d;
1704 long lo, hi, x, y;
1706 a = (v1 >> 16) & 0xffff;
1707 b = v1 & 0xffff;
1708 c = (v2 >> 16) & 0xffff;
1709 d = v2 & 0xffff;
1711 lo = b * d; /* BD */
1712 x = a * d + c * b; /* AD + CB */
1713 y = ((lo >> 16) & 0xffff) + x;
1715 lo = (lo & 0xffff) | ((y & 0xffff) << 16);
1716 hi = (y >> 16) & 0xffff;
1718 hi += a * c; /* AC */
1720 *hi_product = (unsigned long)hi;
1721 *lo_product = (unsigned long)lo;
1723 #endif /* CHECK_cHRM */
1725 #ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
1726 #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
1727 /* Fixed point gamma.
1729 * To calculate gamma this code implements fast log() and exp() calls using only
1730 * fixed point arithmetic. This code has sufficient precision for either 8 or
1731 * 16 bit sample values.
1733 * The tables used here were calculated using simple 'bc' programs, but C double
1734 * precision floating point arithmetic would work fine. The programs are given
1735 * at the head of each table.
1737 * 8 bit log table
1738 * This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
1739 * 255, so it's the base 2 logarithm of a normalized 8 bit floating point
1740 * mantissa. The numbers are 32 bit fractions.
1742 static png_uint_32
1743 png_8bit_l2[128] =
1745 # if PNG_DO_BC
1746 for (i=128;i<256;++i) { .5 - l(i/255)/l(2)*65536*65536; }
1747 # endif
1748 4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
1749 3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
1750 3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
1751 3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
1752 3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
1753 2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
1754 2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
1755 2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
1756 2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
1757 2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
1758 1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
1759 1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
1760 1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
1761 1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
1762 1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
1763 971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
1764 803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
1765 639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
1766 479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
1767 324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
1768 172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
1769 24347096U, 0U
1770 #if 0
1771 /* The following are the values for 16 bit tables - these work fine for the 8
1772 * bit conversions but produce very slightly larger errors in the 16 bit log
1773 * (about 1.2 as opposed to 0.7 absolute error in the final value). To use
1774 * these all the shifts below must be adjusted appropriately.
1776 65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
1777 57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
1778 50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
1779 43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
1780 37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
1781 31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
1782 25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
1783 20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
1784 15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
1785 10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
1786 6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
1787 1119, 744, 372
1788 #endif
1791 static png_int_32
1792 png_log8bit(unsigned int x)
1794 unsigned int lg2 = 0;
1795 /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
1796 * because the log is actually negate that means adding 1. The final
1797 * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
1798 * input), return 7.99998 for the overflow (log 0) case - so the result is
1799 * always at most 19 bits.
1801 if ((x &= 0xff) == 0)
1802 return 0xffffffff;
1804 if ((x & 0xf0) == 0)
1805 lg2 = 4, x <<= 4;
1807 if ((x & 0xc0) == 0)
1808 lg2 += 2, x <<= 2;
1810 if ((x & 0x80) == 0)
1811 lg2 += 1, x <<= 1;
1813 /* result is at most 19 bits, so this cast is safe: */
1814 return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
1817 /* The above gives exact (to 16 binary places) log2 values for 8 bit images,
1818 * for 16 bit images we use the most significant 8 bits of the 16 bit value to
1819 * get an approximation then multiply the approximation by a correction factor
1820 * determined by the remaining up to 8 bits. This requires an additional step
1821 * in the 16 bit case.
1823 * We want log2(value/65535), we have log2(v'/255), where:
1825 * value = v' * 256 + v''
1826 * = v' * f
1828 * So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
1829 * to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
1830 * than 258. The final factor also needs to correct for the fact that our 8 bit
1831 * value is scaled by 255, whereas the 16 bit values must be scaled by 65535.
1833 * This gives a final formula using a calculated value 'x' which is value/v' and
1834 * scaling by 65536 to match the above table:
1836 * log2(x/257) * 65536
1838 * Since these numbers are so close to '1' we can use simple linear
1839 * interpolation between the two end values 256/257 (result -368.61) and 258/257
1840 * (result 367.179). The values used below are scaled by a further 64 to give
1841 * 16 bit precision in the interpolation:
1843 * Start (256): -23591
1844 * Zero (257): 0
1845 * End (258): 23499
1847 static png_int_32
1848 png_log16bit(png_uint_32 x)
1850 unsigned int lg2 = 0;
1852 /* As above, but now the input has 16 bits. */
1853 if ((x &= 0xffff) == 0)
1854 return 0xffffffff;
1856 if ((x & 0xff00) == 0)
1857 lg2 = 8, x <<= 8;
1859 if ((x & 0xf000) == 0)
1860 lg2 += 4, x <<= 4;
1862 if ((x & 0xc000) == 0)
1863 lg2 += 2, x <<= 2;
1865 if ((x & 0x8000) == 0)
1866 lg2 += 1, x <<= 1;
1868 /* Calculate the base logarithm from the top 8 bits as a 28 bit fractional
1869 * value.
1871 lg2 <<= 28;
1872 lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
1874 /* Now we need to interpolate the factor, this requires a division by the top
1875 * 8 bits. Do this with maximum precision.
1877 x = ((x << 16) + (x >> 9)) / (x >> 8);
1879 /* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
1880 * the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly
1881 * 16 bits to interpolate to get the low bits of the result. Round the
1882 * answer. Note that the end point values are scaled by 64 to retain overall
1883 * precision and that 'lg2' is current scaled by an extra 12 bits, so adjust
1884 * the overall scaling by 6-12. Round at every step.
1886 x -= 1U << 24;
1888 if (x <= 65536U) /* <= '257' */
1889 lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);
1891 else
1892 lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
1894 /* Safe, because the result can't have more than 20 bits: */
1895 return (png_int_32)((lg2 + 2048) >> 12);
1898 /* The 'exp()' case must invert the above, taking a 20 bit fixed point
1899 * logarithmic value and returning a 16 or 8 bit number as appropriate. In
1900 * each case only the low 16 bits are relevant - the fraction - since the
1901 * integer bits (the top 4) simply determine a shift.
1903 * The worst case is the 16 bit distinction between 65535 and 65534, this
1904 * requires perhaps spurious accuracty in the decoding of the logarithm to
1905 * distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance
1906 * of getting this accuracy in practice.
1908 * To deal with this the following exp() function works out the exponent of the
1909 * frational part of the logarithm by using an accurate 32 bit value from the
1910 * top four fractional bits then multiplying in the remaining bits.
1912 static png_uint_32
1913 png_32bit_exp[16] =
1915 # if PNG_DO_BC
1916 for (i=0;i<16;++i) { .5 + e(-i/16*l(2))*2^32; }
1917 # endif
1918 /* NOTE: the first entry is deliberately set to the maximum 32 bit value. */
1919 4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
1920 3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
1921 2553802834U, 2445529972U, 2341847524U, 2242560872U
1924 /* Adjustment table; provided to explain the numbers in the code below. */
1925 #if PNG_DO_BC
1926 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
1927 11 44937.64284865548751208448
1928 10 45180.98734845585101160448
1929 9 45303.31936980687359311872
1930 8 45364.65110595323018870784
1931 7 45395.35850361789624614912
1932 6 45410.72259715102037508096
1933 5 45418.40724413220722311168
1934 4 45422.25021786898173001728
1935 3 45424.17186732298419044352
1936 2 45425.13273269940811464704
1937 1 45425.61317555035558641664
1938 0 45425.85339951654943850496
1939 #endif
1941 static png_uint_32
1942 png_exp(png_fixed_point x)
1944 if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
1946 /* Obtain a 4 bit approximation */
1947 png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
1949 /* Incorporate the low 12 bits - these decrease the returned value by
1950 * multiplying by a number less than 1 if the bit is set. The multiplier
1951 * is determined by the above table and the shift. Notice that the values
1952 * converge on 45426 and this is used to allow linear interpolation of the
1953 * low bits.
1955 if (x & 0x800)
1956 e -= (((e >> 16) * 44938U) + 16U) >> 5;
1958 if (x & 0x400)
1959 e -= (((e >> 16) * 45181U) + 32U) >> 6;
1961 if (x & 0x200)
1962 e -= (((e >> 16) * 45303U) + 64U) >> 7;
1964 if (x & 0x100)
1965 e -= (((e >> 16) * 45365U) + 128U) >> 8;
1967 if (x & 0x080)
1968 e -= (((e >> 16) * 45395U) + 256U) >> 9;
1970 if (x & 0x040)
1971 e -= (((e >> 16) * 45410U) + 512U) >> 10;
1973 /* And handle the low 6 bits in a single block. */
1974 e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
1976 /* Handle the upper bits of x. */
1977 e >>= x >> 16;
1978 return e;
1981 /* Check for overflow */
1982 if (x <= 0)
1983 return png_32bit_exp[0];
1985 /* Else underflow */
1986 return 0;
1989 static png_byte
1990 png_exp8bit(png_fixed_point lg2)
1992 /* Get a 32 bit value: */
1993 png_uint_32 x = png_exp(lg2);
1995 /* Convert the 32 bit value to 0..255 by multiplying by 256-1, note that the
1996 * second, rounding, step can't overflow because of the first, subtraction,
1997 * step.
1999 x -= x >> 8;
2000 return (png_byte)((x + 0x7fffffU) >> 24);
2003 static png_uint_16
2004 png_exp16bit(png_fixed_point lg2)
2006 /* Get a 32 bit value: */
2007 png_uint_32 x = png_exp(lg2);
2009 /* Convert the 32 bit value to 0..65535 by multiplying by 65536-1: */
2010 x -= x >> 16;
2011 return (png_uint_16)((x + 32767U) >> 16);
2013 #endif /* FLOATING_ARITHMETIC */
2015 png_byte
2016 png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
2018 if (value > 0 && value < 255)
2020 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2021 double r = floor(255*pow(value/255.,gamma_val*.00001)+.5);
2022 return (png_byte)r;
2023 # else
2024 png_int_32 lg2 = png_log8bit(value);
2025 png_fixed_point res;
2027 if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2028 return png_exp8bit(res);
2030 /* Overflow. */
2031 value = 0;
2032 # endif
2035 return (png_byte)value;
2038 png_uint_16
2039 png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)
2041 if (value > 0 && value < 65535)
2043 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2044 double r = floor(65535*pow(value/65535.,gamma_val*.00001)+.5);
2045 return (png_uint_16)r;
2046 # else
2047 png_int_32 lg2 = png_log16bit(value);
2048 png_fixed_point res;
2050 if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2051 return png_exp16bit(res);
2053 /* Overflow. */
2054 value = 0;
2055 # endif
2058 return (png_uint_16)value;
2061 /* This does the right thing based on the bit_depth field of the
2062 * png_struct, interpreting values as 8 or 16 bit. While the result
2063 * is nominally a 16 bit value if bit depth is 8 then the result is
2064 * 8 bit (as are the arguments.)
2066 png_uint_16 /* PRIVATE */
2067 png_gamma_correct(png_structp png_ptr, unsigned int value,
2068 png_fixed_point gamma_val)
2070 if (png_ptr->bit_depth == 8)
2071 return png_gamma_8bit_correct(value, gamma_val);
2073 else
2074 return png_gamma_16bit_correct(value, gamma_val);
2077 /* This is the shared test on whether a gamma value is 'significant' - whether
2078 * it is worth doing gamma correction.
2080 int /* PRIVATE */
2081 png_gamma_significant(png_fixed_point gamma_val)
2083 return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
2084 gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
2087 /* Internal function to build a single 16 bit table - the table consists of
2088 * 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount
2089 * to shift the input values right (or 16-number_of_signifiant_bits).
2091 * The caller is responsible for ensuring that the table gets cleaned up on
2092 * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
2093 * should be somewhere that will be cleaned.
2095 static void
2096 png_build_16bit_table(png_structp png_ptr, png_uint_16pp *ptable,
2097 PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
2099 /* Various values derived from 'shift': */
2100 PNG_CONST unsigned int num = 1U << (8U - shift);
2101 PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
2102 PNG_CONST unsigned int max_by_2 = 1U << (15U-shift);
2103 unsigned int i;
2105 png_uint_16pp table = *ptable =
2106 (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
2108 for (i = 0; i < num; i++)
2110 png_uint_16p sub_table = table[i] =
2111 (png_uint_16p)png_malloc(png_ptr, 256 * png_sizeof(png_uint_16));
2113 /* The 'threshold' test is repeated here because it can arise for one of
2114 * the 16 bit tables even if the others don't hit it.
2116 if (png_gamma_significant(gamma_val))
2118 /* The old code would overflow at the end and this would cause the
2119 * 'pow' function to return a result >1, resulting in an
2120 * arithmetic error. This code follows the spec exactly; ig is
2121 * the recovered input sample, it always has 8-16 bits.
2123 * We want input * 65535/max, rounded, the arithmetic fits in 32
2124 * bits (unsigned) so long as max <= 32767.
2126 unsigned int j;
2127 for (j = 0; j < 256; j++)
2129 png_uint_32 ig = (j << (8-shift)) + i;
2130 # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2131 /* Inline the 'max' scaling operation: */
2132 double d = floor(65535*pow(ig/(double)max, gamma_val*.00001)+.5);
2133 sub_table[j] = (png_uint_16)d;
2134 # else
2135 if (shift)
2136 ig = (ig * 65535U + max_by_2)/max;
2138 sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);
2139 # endif
2142 else
2144 /* We must still build a table, but do it the fast way. */
2145 unsigned int j;
2147 for (j = 0; j < 256; j++)
2149 png_uint_32 ig = (j << (8-shift)) + i;
2151 if (shift)
2152 ig = (ig * 65535U + max_by_2)/max;
2154 sub_table[j] = (png_uint_16)ig;
2160 /* NOTE: this function expects the *inverse* of the overall gamma transformation
2161 * required.
2163 static void
2164 png_build_16to8_table(png_structp png_ptr, png_uint_16pp *ptable,
2165 PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
2167 PNG_CONST unsigned int num = 1U << (8U - shift);
2168 PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
2169 unsigned int i;
2170 png_uint_32 last;
2172 png_uint_16pp table = *ptable =
2173 (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
2175 /* 'num' is the number of tables and also the number of low bits of low
2176 * bits of the input 16 bit value used to select a table. Each table is
2177 * itself index by the high 8 bits of the value.
2179 for (i = 0; i < num; i++)
2180 table[i] = (png_uint_16p)png_malloc(png_ptr,
2181 256 * png_sizeof(png_uint_16));
2183 /* 'gamma_val' is set to the reciprocal of the value calculated above, so
2184 * pow(out,g) is an *input* value. 'last' is the last input value set.
2186 * In the loop 'i' is used to find output values. Since the output is 8
2187 * bit there are only 256 possible values. The tables are set up to
2188 * select the closest possible output value for each input by finding
2189 * the input value at the boundary between each pair of output values
2190 * and filling the table up to that boundary with the lower output
2191 * value.
2193 * The boundary values are 0.5,1.5..253.5,254.5. Since these are 9 bit
2194 * values the code below uses a 16 bit value in i; the values start at
2195 * 128.5 (for 0.5) and step by 257, for a total of 254 values (the last
2196 * entries are filled with 255). Start i at 128 and fill all 'last'
2197 * table entries <= 'max'
2199 last = 0;
2200 for (i = 0; i < 255; ++i) /* 8 bit output value */
2202 /* Find the corresponding maximum input value */
2203 png_uint_16 out = (png_uint_16)(i * 257U); /* 16 bit output value */
2205 /* Find the boundary value in 16 bits: */
2206 png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
2208 /* Adjust (round) to (16-shift) bits: */
2209 bound = (bound * max + 32768U)/65535U + 1U;
2211 while (last < bound)
2213 table[last & (0xffU >> shift)][last >> (8U - shift)] = out;
2214 last++;
2218 /* And fill in the final entries. */
2219 while (last < (num << 8))
2221 table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
2222 last++;
2226 /* Build a single 8 bit table: same as the 16 bit case but much simpler (and
2227 * typically much faster). Note that libpng currently does no sBIT processing
2228 * (apparently contrary to the spec) so a 256 entry table is always generated.
2230 static void
2231 png_build_8bit_table(png_structp png_ptr, png_bytepp ptable,
2232 PNG_CONST png_fixed_point gamma_val)
2234 unsigned int i;
2235 png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
2237 if (png_gamma_significant(gamma_val)) for (i=0; i<256; i++)
2238 table[i] = png_gamma_8bit_correct(i, gamma_val);
2240 else for (i=0; i<256; ++i)
2241 table[i] = (png_byte)i;
2244 /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
2245 * tables, we don't make a full table if we are reducing to 8-bit in
2246 * the future. Note also how the gamma_16 tables are segmented so that
2247 * we don't need to allocate > 64K chunks for a full 16-bit table.
2249 void /* PRIVATE */
2250 png_build_gamma_table(png_structp png_ptr, int bit_depth)
2252 png_debug(1, "in png_build_gamma_table");
2254 if (bit_depth <= 8)
2256 png_build_8bit_table(png_ptr, &png_ptr->gamma_table,
2257 png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
2258 png_ptr->screen_gamma) : PNG_FP_1);
2260 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2261 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2262 if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
2264 png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1,
2265 png_reciprocal(png_ptr->gamma));
2267 png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
2268 png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
2269 png_ptr->gamma/* Probably doing rgb_to_gray */);
2271 #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
2273 else
2275 png_byte shift, sig_bit;
2277 if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
2279 sig_bit = png_ptr->sig_bit.red;
2281 if (png_ptr->sig_bit.green > sig_bit)
2282 sig_bit = png_ptr->sig_bit.green;
2284 if (png_ptr->sig_bit.blue > sig_bit)
2285 sig_bit = png_ptr->sig_bit.blue;
2287 else
2288 sig_bit = png_ptr->sig_bit.gray;
2290 /* 16 bit gamma code uses this equation:
2292 * ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
2294 * Where 'iv' is the input color value and 'ov' is the output value -
2295 * pow(iv, gamma).
2297 * Thus the gamma table consists of up to 256 256 entry tables. The table
2298 * is selected by the (8-gamma_shift) most significant of the low 8 bits of
2299 * the color value then indexed by the upper 8 bits:
2301 * table[low bits][high 8 bits]
2303 * So the table 'n' corresponds to all those 'iv' of:
2305 * <all high 8 bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
2308 if (sig_bit > 0 && sig_bit < 16U)
2309 shift = (png_byte)(16U - sig_bit); /* shift == insignificant bits */
2311 else
2312 shift = 0; /* keep all 16 bits */
2314 if (png_ptr->transformations & PNG_16_TO_8)
2316 /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively
2317 * the significant bits in the *input* when the output will
2318 * eventually be 8 bits. By default it is 11.
2320 if (shift < (16U - PNG_MAX_GAMMA_8))
2321 shift = (16U - PNG_MAX_GAMMA_8);
2324 if (shift > 8U)
2325 shift = 8U; /* Guarantees at least one table! */
2327 png_ptr->gamma_shift = shift;
2329 #ifdef PNG_16BIT_SUPPORTED
2330 if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
2331 #endif
2332 png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
2333 png_ptr->screen_gamma > 0 ? png_product2(png_ptr->gamma,
2334 png_ptr->screen_gamma) : PNG_FP_1);
2336 #ifdef PNG_16BIT_SUPPORTED
2337 else
2338 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
2339 png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
2340 png_ptr->screen_gamma) : PNG_FP_1);
2341 #endif
2343 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2344 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2345 if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
2347 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
2348 png_reciprocal(png_ptr->gamma));
2350 /* Notice that the '16 from 1' table should be full precision, however
2351 * the lookup on this table still uses gamma_shift, so it can't be.
2352 * TODO: fix this.
2354 png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
2355 png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
2356 png_ptr->gamma/* Probably doing rgb_to_gray */);
2358 #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
2361 #endif /* READ_GAMMA */
2362 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */