]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/libpng/lib/dist/libpng-manual.txt
update
[l4.git] / l4 / pkg / libpng / lib / dist / libpng-manual.txt
1 libpng-manual.txt - A description on how to use and modify libpng
2
3  libpng version 1.5.2 - March 31, 2011
4  Updated and distributed by Glenn Randers-Pehrson
5  <glennrp at users.sourceforge.net>
6  Copyright (c) 1998-2011 Glenn Randers-Pehrson
7
8  This document is released under the libpng license.
9  For conditions of distribution and use, see the disclaimer
10  and license in png.h
11
12  Based on:
13
14  libpng versions 0.97, January 1998, through 1.5.2 - March 31, 2011
15  Updated and distributed by Glenn Randers-Pehrson
16  Copyright (c) 1998-2011 Glenn Randers-Pehrson
17
18  libpng 1.0 beta 6  version 0.96 May 28, 1997
19  Updated and distributed by Andreas Dilger
20  Copyright (c) 1996, 1997 Andreas Dilger
21
22  libpng 1.0 beta 2 - version 0.88  January 26, 1996
23  For conditions of distribution and use, see copyright
24  notice in png.h. Copyright (c) 1995, 1996 Guy Eric
25  Schalnat, Group 42, Inc.
26
27  Updated/rewritten per request in the libpng FAQ
28  Copyright (c) 1995, 1996 Frank J. T. Wojcik
29  December 18, 1995 & January 20, 1996
30
31 I. Introduction
32
33 This file describes how to use and modify the PNG reference library
34 (known as libpng) for your own use.  There are five sections to this
35 file: introduction, structures, reading, writing, and modification and
36 configuration notes for various special platforms.  In addition to this
37 file, example.c is a good starting point for using the library, as
38 it is heavily commented and should include everything most people
39 will need.  We assume that libpng is already installed; see the
40 INSTALL file for instructions on how to install libpng.
41
42 For examples of libpng usage, see the files "example.c", "pngtest.c",
43 and the files in the "contrib" directory, all of which are included in
44 the libpng distribution.
45
46 Libpng was written as a companion to the PNG specification, as a way
47 of reducing the amount of time and effort it takes to support the PNG
48 file format in application programs.
49
50 The PNG specification (second edition), November 2003, is available as
51 a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2003 (E)) at
52 <http://www.w3.org/TR/2003/REC-PNG-20031110/
53 The W3C and ISO documents have identical technical content.
54
55 The PNG-1.2 specification is available at
56 <http://www.libpng.org/pub/png/documents/>.  It is technically equivalent
57 to the PNG specification (second edition) but has some additional material.
58
59 The PNG-1.0 specification is available
60 as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
61 W3C Recommendation <http://www.w3.org/TR/REC.png.html>.
62
63 Some additional chunks are described in the special-purpose public chunks
64 documents at <http://www.libpng.org/pub/png/documents/>.
65
66 Other information
67 about PNG, and the latest version of libpng, can be found at the PNG home
68 page, <http://www.libpng.org/pub/png/>.
69
70 Most users will not have to modify the library significantly; advanced
71 users may want to modify it more.  All attempts were made to make it as
72 complete as possible, while keeping the code easy to understand.
73 Currently, this library only supports C.  Support for other languages
74 is being considered.
75
76 Libpng has been designed to handle multiple sessions at one time,
77 to be easily modifiable, to be portable to the vast majority of
78 machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and to be easy
79 to use.  The ultimate goal of libpng is to promote the acceptance of
80 the PNG file format in whatever way possible.  While there is still
81 work to be done (see the TODO file), libpng should cover the
82 majority of the needs of its users.
83
84 Libpng uses zlib for its compression and decompression of PNG files.
85 Further information about zlib, and the latest version of zlib, can
86 be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
87 The zlib compression utility is a general purpose utility that is
88 useful for more than PNG files, and can be used without libpng.
89 See the documentation delivered with zlib for more details.
90 You can usually find the source files for the zlib utility wherever you
91 find the libpng source files.
92
93 Libpng is thread safe, provided the threads are using different
94 instances of the structures.  Each thread should have its own
95 png_struct and png_info instances, and thus its own image.
96 Libpng does not protect itself against two threads using the
97 same instance of a structure.
98
99 II. Structures
100
101 There are two main structures that are important to libpng, png_struct
102 and png_info.  Both are internal structures that are no longer exposed
103 in the libpng interface (as of libpng 1.5.0).
104
105 The png_info structure is designed to provide information about the
106 PNG file.  At one time, the fields of png_info were intended to be
107 directly accessible to the user.  However, this tended to cause problems
108 with applications using dynamically loaded libraries, and as a result
109 a set of interface functions for png_info (the png_get_*() and png_set_*()
110 functions) was developed.
111
112 The png_struct structure is the object used by the library to decode a
113 single image.  As of 1.5.0 this structure is also not exposed.
114
115 Almost all libpng APIs require a pointer to a png_struct as the first argument.
116 Many (in particular the png_set and png_get APIs) also require a pointer
117 to png_info as the second argument.  Some application visible macros
118 defined in png.h designed for basic data access (reading and writing
119 integers in the PNG format) break this rule, but it's almost always safe
120 to assume that a (png_struct*) has to be passed to call an API function.
121
122 The png.h header file is an invaluable reference for programming with libpng.
123 And while I'm on the topic, make sure you include the libpng header file:
124
125 #include <png.h>
126
127 Types
128
129 The png.h header file defines a number of integral types used by the
130 APIs.  Most of these are fairly obvious; for example types corresponding
131 to integers of particular sizes and types for passing color values.
132
133 One exception is how non-integral numbers are handled.  For application
134 convenience most APIs that take such numbers have C (double) arguments,
135 however internally PNG, and libpng, use 32 bit signed integers and encode
136 the value by multiplying by 100,000.  As of libpng 1.5.0 a convenience
137 macro PNG_FP_1 is defined in png.h along with a type (png_fixed_point)
138 which is simply (png_int_32).
139
140 All APIs that take (double) arguments also have an matching API that
141 takes the corresponding fixed point integer arguments.  The fixed point
142 API has the same name as the floating point one with _fixed appended.
143 The actual range of values permitted in the APIs is frequently less than
144 the full range of (png_fixed_point) (-21474 to +21474).  When APIs require
145 a non-negative argument the type is recorded as png_uint_32 above.  Consult
146 the header file and the text below for more information.
147
148 Special care must be take with sCAL chunk handling because the chunk itself
149 uses non-integral values encoded as strings containing decimal floating point
150 numbers.  See the comments in the header file.
151
152 Configuration
153
154 The main header file function declarations are frequently protected by C
155 preprocessing directives of the form:
156
157     #ifdef PNG_feature_SUPPORTED
158     declare-function
159     #endif
160
161 The library can be built without support for these APIs, although a
162 standard build will have all implemented APIs.  Application programs
163 should check the feature macros before using an API for maximum
164 portability.  From libpng 1.5.0 the feature macros set during the build
165 of libpng are recorded in the header file "pnglibconf.h" and this file
166 is always included by png.h.
167
168 If you don't need to change the library configuration from the default skip to
169 the next section ("Reading").
170
171 Notice that some of the makefiles in the 'scripts' directory and (in 1.5.0) all
172 of the build project files in the 'projects' directory simply copy
173 scripts/pnglibconf.h.prebuilt to pnglibconf.h.  This means that these build
174 systems do not permit easy auto-configuration of the library - they only
175 support the default configuration.
176
177 The easiest way to make minor changes to the libpng configuration when
178 auto-configuration is supported is to add definitions to the command line
179 using (typically) CPPFLAGS.  For example:
180
181 CPPFLAGS=-DPNG_NO_FLOATING_ARITHMETIC
182
183 will change the internal libpng math implementation for gamma correction and
184 other arithmetic calculations to fixed point, avoiding the need for fast
185 floating point support.  The result can be seen in the generated pnglibconf.h -
186 make sure it contains the changed feature macro setting.
187
188 If you need to make more extensive configuration changes - more than one or two
189 feature macro settings - you can either add -DPNG_USER_CONFIG to the build
190 command line and put a list of feature macro settings in pngusr.h or you can set
191 DFA_XTRA (a makefile variable) to a file containing the same information in the
192 form of 'option' settings.
193
194 A. Changing pnglibconf.h
195
196 A variety of methods exist to build libpng.  Not all of these support
197 reconfiguration of pnglibconf.h.  To reconfigure pnglibconf.h it must either be
198 rebuilt from scripts/pnglibconf.dfa using awk or it must be edited by hand.
199
200 Hand editing is achieved by copying scripts/pnglibconf.h.prebuilt and changing
201 the lines defining the supported features, paying very close attention to the
202 'option' information in scripts/pnglibconf.dfa that describes those features and
203 their requirements.  This is easy to get wrong.
204
205 B. Configuration using DFA_XTRA
206
207 Rebuilding from pnglibconf.dfa is easy if a functioning 'awk', or a later
208 variant such as 'nawk' or 'gawk', is available.  The configure build will
209 automatically find an appropriate awk and build pnglibconf.h.
210 scripts/pnglibconf.mak contains a set of make rules for doing the same thing if
211 configure is not used, and many of the makefiles in the scripts directory use
212 this approach.
213
214 When rebuilding simply write new file containing changed options and set
215 DFA_XTRA to the name of this file.  This causes the build to append the new file
216 to the end of scripts/pnglibconf.dfa.  pngusr.dfa should contain lines of the
217 following forms:
218
219 everything = off
220
221 This turns all optional features off.  Include it at the start of pngusr.dfa to
222 make it easier to build a minimal configuration.  You will need to turn at least
223 some features on afterward to enable either reading or writing code, or both.
224
225 option feature on
226 option feature off
227
228 Enable or disable a single feature.  This will automatically enable other
229 features required by a feature that is turned on or disable other features that
230 require a feature which is turned off.  Conflicting settings will cause an error
231 message to be emitted by awk.
232
233 setting feature default value
234
235 Changes the default value of setting 'feature' to 'value'.  There are a small
236 number of settings listed at the top of pnglibconf.h, they are documented in the
237 source code.  Most of these values have performance implications for the library
238 but most of them have no visible effect on the API.  Some can also be overridden
239 from the API.
240
241 C. Configuration using PNG_USR_CONFIG
242
243 If -DPNG_USR_CONFIG is added to the CFLAGS when pnglibconf.h is built the file
244 pngusr.h will automatically be included before the options in
245 scripts/pnglibconf.dfa are processed.  pngusr.h should contain only macro
246 definitions turning features on or off or setting settings.
247
248 Apart from the global setting "everything = off" all the options listed above
249 can be set using macros in pngusr.h:
250
251 #define PNG_feature_SUPPORTED
252
253 is equivalent to:
254
255 option feature on
256
257 #define PNG_NO_feature
258
259 is equivalent to:
260
261 option feature off
262
263 #define PNG_feature value
264
265 is equivalent to:
266
267 setting feature default value
268
269 Notice that in both cases, pngusr.dfa and pngusr.h, the contents of the
270 pngusr file you supply override the contents of scripts/pnglibconf.dfa
271
272 If confusing or incomprehensible behavior results it is possible to
273 examine the intermediate file pnglibconf.dfn to find the full set of
274 dependency information for each setting and option.  Simply locate the
275 feature in the file and read the C comments that precede it.
276
277 III. Reading
278
279 We'll now walk you through the possible functions to call when reading
280 in a PNG file sequentially, briefly explaining the syntax and purpose
281 of each one.  See example.c and png.h for more detail.  While
282 progressive reading is covered in the next section, you will still
283 need some of the functions discussed in this section to read a PNG
284 file.
285
286 Setup
287
288 You will want to do the I/O initialization(*) before you get into libpng,
289 so if it doesn't work, you don't have much to undo.  Of course, you
290 will also want to insure that you are, in fact, dealing with a PNG
291 file.  Libpng provides a simple check to see if a file is a PNG file.
292 To use it, pass in the first 1 to 8 bytes of the file to the function
293 png_sig_cmp(), and it will return 0 (false) if the bytes match the
294 corresponding bytes of the PNG signature, or nonzero (true) otherwise.
295 Of course, the more bytes you pass in, the greater the accuracy of the
296 prediction.
297
298 If you are intending to keep the file pointer open for use in libpng,
299 you must ensure you don't read more than 8 bytes from the beginning
300 of the file, and you also have to make a call to png_set_sig_bytes_read()
301 with the number of bytes you read from the beginning.  Libpng will
302 then only check the bytes (if any) that your program didn't read.
303
304 (*): If you are not using the standard I/O functions, you will need
305 to replace them with custom functions.  See the discussion under
306 Customizing libpng.
307
308
309     FILE *fp = fopen(file_name, "rb");
310     if (!fp)
311     {
312        return (ERROR);
313     }
314
315     fread(header, 1, number, fp);
316     is_png = !png_sig_cmp(header, 0, number);
317
318     if (!is_png)
319     {
320        return (NOT_PNG);
321     }
322
323
324 Next, png_struct and png_info need to be allocated and initialized.  In
325 order to ensure that the size of these structures is correct even with a
326 dynamically linked libpng, there are functions to initialize and
327 allocate the structures.  We also pass the library version, optional
328 pointers to error handling functions, and a pointer to a data struct for
329 use by the error functions, if necessary (the pointer and functions can
330 be NULL if the default error handlers are to be used).  See the section
331 on Changes to Libpng below regarding the old initialization functions.
332 The structure allocation functions quietly return NULL if they fail to
333 create the structure, so your application should check for that.
334
335     png_structp png_ptr = png_create_read_struct
336         (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
337         user_error_fn, user_warning_fn);
338
339     if (!png_ptr)
340        return (ERROR);
341
342     png_infop info_ptr = png_create_info_struct(png_ptr);
343
344     if (!info_ptr)
345     {
346        png_destroy_read_struct(&png_ptr,
347            (png_infopp)NULL, (png_infopp)NULL);
348        return (ERROR);
349     }
350
351     png_infop end_info = png_create_info_struct(png_ptr);
352
353     if (!end_info)
354     {
355        png_destroy_read_struct(&png_ptr, &info_ptr,
356           (png_infopp)NULL);
357        return (ERROR);
358     }
359
360 If you want to use your own memory allocation routines,
361 use a libpng that was built with PNG_USER_MEM_SUPPORTED defined, and use
362 png_create_read_struct_2() instead of png_create_read_struct():
363
364     png_structp png_ptr = png_create_read_struct_2
365        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
366         user_error_fn, user_warning_fn, (png_voidp)
367         user_mem_ptr, user_malloc_fn, user_free_fn);
368
369 The error handling routines passed to png_create_read_struct()
370 and the memory alloc/free routines passed to png_create_struct_2()
371 are only necessary if you are not using the libpng supplied error
372 handling and memory alloc/free functions.
373
374 When libpng encounters an error, it expects to longjmp back
375 to your routine.  Therefore, you will need to call setjmp and pass
376 your png_jmpbuf(png_ptr).  If you read the file from different
377 routines, you will need to update the jmpbuf field every time you enter
378 a new routine that will call a png_*() function.
379
380 See your documentation of setjmp/longjmp for your compiler for more
381 information on setjmp/longjmp.  See the discussion on libpng error
382 handling in the Customizing Libpng section below for more information
383 on the libpng error handling.  If an error occurs, and libpng longjmp's
384 back to your setjmp, you will want to call png_destroy_read_struct() to
385 free any memory.
386
387     if (setjmp(png_jmpbuf(png_ptr)))
388     {
389        png_destroy_read_struct(&png_ptr, &info_ptr,
390            &end_info);
391        fclose(fp);
392        return (ERROR);
393     }
394
395 If you would rather avoid the complexity of setjmp/longjmp issues,
396 you can compile libpng with PNG_NO_SETJMP, in which case
397 errors will result in a call to PNG_ABORT() which defaults to abort().
398
399 You can #define PNG_ABORT() to a function that does something
400 more useful than abort(), as long as your function does not
401 return.
402
403 Now you need to set up the input code.  The default for libpng is to
404 use the C function fread().  If you use this, you will need to pass a
405 valid FILE * in the function png_init_io().  Be sure that the file is
406 opened in binary mode.  If you wish to handle reading data in another
407 way, you need not call the png_init_io() function, but you must then
408 implement the libpng I/O methods discussed in the Customizing Libpng
409 section below.
410
411     png_init_io(png_ptr, fp);
412
413 If you had previously opened the file and read any of the signature from
414 the beginning in order to see if this was a PNG file, you need to let
415 libpng know that there are some bytes missing from the start of the file.
416
417     png_set_sig_bytes(png_ptr, number);
418
419 You can change the zlib compression buffer size to be used while
420 reading compressed data with
421
422     png_set_compression_buffer_size(png_ptr, buffer_size);
423
424 where the default size is 8192 bytes.  Note that the buffer size
425 is changed immediately and the buffer is reallocated immediately,
426 instead of setting a flag to be acted upon later.
427
428 If you want CRC errors to be handled in a different manner than
429 the default, use
430
431     png_set_crc_action(png_ptr, crit_action, ancil_action);
432
433 The values for png_set_crc_action() say how libpng is to handle CRC errors in
434 ancillary and critical chunks, and whether to use the data contained
435 therein.  Note that it is impossible to "discard" data in a critical
436 chunk.
437
438 Choices for (int) crit_action are
439    PNG_CRC_DEFAULT      0  error/quit
440    PNG_CRC_ERROR_QUIT   1  error/quit
441    PNG_CRC_WARN_USE     3  warn/use data
442    PNG_CRC_QUIET_USE    4  quiet/use data
443    PNG_CRC_NO_CHANGE    5  use the current value
444
445 Choices for (int) ancil_action are
446    PNG_CRC_DEFAULT      0  error/quit
447    PNG_CRC_ERROR_QUIT   1  error/quit
448    PNG_CRC_WARN_DISCARD 2  warn/discard data
449    PNG_CRC_WARN_USE     3  warn/use data
450    PNG_CRC_QUIET_USE    4  quiet/use data
451    PNG_CRC_NO_CHANGE    5  use the current value
452
453 Setting up callback code
454
455 You can set up a callback function to handle any unknown chunks in the
456 input stream. You must supply the function
457
458     read_chunk_callback(png_structp png_ptr,
459          png_unknown_chunkp chunk);
460     {
461        /* The unknown chunk structure contains your
462           chunk data, along with similar data for any other
463           unknown chunks: */
464
465            png_byte name[5];
466            png_byte *data;
467            png_size_t size;
468
469        /* Note that libpng has already taken care of
470           the CRC handling */
471
472        /* put your code here.  Search for your chunk in the
473           unknown chunk structure, process it, and return one
474           of the following: */
475
476        return (-n); /* chunk had an error */
477        return (0); /* did not recognize */
478        return (n); /* success */
479     }
480
481 (You can give your function another name that you like instead of
482 "read_chunk_callback")
483
484 To inform libpng about your function, use
485
486     png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr,
487         read_chunk_callback);
488
489 This names not only the callback function, but also a user pointer that
490 you can retrieve with
491
492     png_get_user_chunk_ptr(png_ptr);
493
494 If you call the png_set_read_user_chunk_fn() function, then all unknown
495 chunks will be saved when read, in case your callback function will need
496 one or more of them.  This behavior can be changed with the
497 png_set_keep_unknown_chunks() function, described below.
498
499 At this point, you can set up a callback function that will be
500 called after each row has been read, which you can use to control
501 a progress meter or the like.  It's demonstrated in pngtest.c.
502 You must supply a function
503
504     void read_row_callback(png_structp png_ptr,
505        png_uint_32 row, int pass);
506     {
507       /* put your code here */
508     }
509
510 (You can give it another name that you like instead of "read_row_callback")
511
512 To inform libpng about your function, use
513
514     png_set_read_status_fn(png_ptr, read_row_callback);
515
516 When this function is called the row has already been completely processed and
517 the 'row' and 'pass' refer to the next row to be handled.  For the
518 non-interlaced case the row that was just handled is simply one less than the
519 passed in row number, and pass will always be 0.  For the interlaced case the
520 same applies unless the row value is 0, in which case the row just handled was
521 the last one from one of the preceding passes.  Because interlacing may skip a
522 pass you cannot be sure that the preceding pass is just 'pass-1', if you really
523 need to know what the last pass is record (row,pass) from the callback and use
524 the last recorded value each time.
525
526 As with the user transform you can find the output row using the
527 PNG_ROW_FROM_PASS_ROW macro.
528
529 Unknown-chunk handling
530
531 Now you get to set the way the library processes unknown chunks in the
532 input PNG stream. Both known and unknown chunks will be read.  Normal
533 behavior is that known chunks will be parsed into information in
534 various info_ptr members while unknown chunks will be discarded. This
535 behavior can be wasteful if your application will never use some known
536 chunk types. To change this, you can call:
537
538     png_set_keep_unknown_chunks(png_ptr, keep,
539         chunk_list, num_chunks);
540     keep       - 0: default unknown chunk handling
541                  1: ignore; do not keep
542                  2: keep only if safe-to-copy
543                  3: keep even if unsafe-to-copy
544
545                You can use these definitions:
546                  PNG_HANDLE_CHUNK_AS_DEFAULT   0
547                  PNG_HANDLE_CHUNK_NEVER        1
548                  PNG_HANDLE_CHUNK_IF_SAFE      2
549                  PNG_HANDLE_CHUNK_ALWAYS       3
550
551     chunk_list - list of chunks affected (a byte string,
552                  five bytes per chunk, NULL or '\0' if
553                  num_chunks is 0)
554
555     num_chunks - number of chunks affected; if 0, all
556                  unknown chunks are affected.  If nonzero,
557                  only the chunks in the list are affected
558
559 Unknown chunks declared in this way will be saved as raw data onto a
560 list of png_unknown_chunk structures.  If a chunk that is normally
561 known to libpng is named in the list, it will be handled as unknown,
562 according to the "keep" directive.  If a chunk is named in successive
563 instances of png_set_keep_unknown_chunks(), the final instance will
564 take precedence.  The IHDR and IEND chunks should not be named in
565 chunk_list; if they are, libpng will process them normally anyway.
566
567 Here is an example of the usage of png_set_keep_unknown_chunks(),
568 where the private "vpAg" chunk will later be processed by a user chunk
569 callback function:
570
571     png_byte vpAg[5]={118, 112,  65, 103, (png_byte) '\0'};
572
573     #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
574       png_byte unused_chunks[]=
575       {
576         104,  73,  83,  84, (png_byte) '\0',   /* hIST */
577         105,  84,  88, 116, (png_byte) '\0',   /* iTXt */
578         112,  67,  65,  76, (png_byte) '\0',   /* pCAL */
579         115,  67,  65,  76, (png_byte) '\0',   /* sCAL */
580         115,  80,  76,  84, (png_byte) '\0',   /* sPLT */
581         116,  73,  77,  69, (png_byte) '\0',   /* tIME */
582       };
583     #endif
584
585     ...
586
587     #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
588       /* ignore all unknown chunks: */
589       png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
590
591       /* except for vpAg: */
592       png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
593
594       /* also ignore unused known chunks: */
595       png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
596          (int)sizeof(unused_chunks)/5);
597     #endif
598
599 User limits
600
601 The PNG specification allows the width and height of an image to be as
602 large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
603 Since very few applications really need to process such large images,
604 we have imposed an arbitrary 1-million limit on rows and columns.
605 Larger images will be rejected immediately with a png_error() call. If
606 you wish to override this limit, you can use
607
608    png_set_user_limits(png_ptr, width_max, height_max);
609
610 to set your own limits, or use width_max = height_max = 0x7fffffffL
611 to allow all valid dimensions (libpng may reject some very large images
612 anyway because of potential buffer overflow conditions).
613
614 You should put this statement after you create the PNG structure and
615 before calling png_read_info(), png_read_png(), or png_process_data().
616 If you need to retrieve the limits that are being applied, use
617
618    width_max = png_get_user_width_max(png_ptr);
619    height_max = png_get_user_height_max(png_ptr);
620
621 The PNG specification sets no limit on the number of ancillary chunks
622 allowed in a PNG datastream.  You can impose a limit on the total number
623 of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
624
625    png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
626
627 where 0x7fffffffL means unlimited.  You can retrieve this limit with
628
629    chunk_cache_max = png_get_chunk_cache_max(png_ptr);
630
631 This limit also applies to the number of buffers that can be allocated
632 by png_decompress_chunk() while decompressing iTXt, zTXt, and iCCP chunks.
633
634 You can also set a limit on the amount of memory that a compressed chunk
635 other than IDAT can occupy, with
636
637    png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
638
639 and you can retrieve the limit with
640
641    chunk_malloc_max = png_get_chunk_malloc_max(png_ptr);
642
643 Any chunks that would cause either of these limits to be exceeded will
644 be ignored.
645
646 The high-level read interface
647
648 At this point there are two ways to proceed; through the high-level
649 read interface, or through a sequence of low-level read operations.
650 You can use the high-level interface if (a) you are willing to read
651 the entire image into memory, and (b) the input transformations
652 you want to do are limited to the following set:
653
654     PNG_TRANSFORM_IDENTITY      No transformation
655     PNG_TRANSFORM_STRIP_16      Strip 16-bit samples to
656                                 8 bits
657     PNG_TRANSFORM_STRIP_ALPHA   Discard the alpha channel
658     PNG_TRANSFORM_PACKING       Expand 1, 2 and 4-bit
659                                 samples to bytes
660     PNG_TRANSFORM_PACKSWAP      Change order of packed
661                                 pixels to LSB first
662     PNG_TRANSFORM_EXPAND        Perform set_expand()
663     PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
664     PNG_TRANSFORM_SHIFT         Normalize pixels to the
665                                 sBIT depth
666     PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA
667                                 to BGRA
668     PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA
669                                 to AG
670     PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity
671                                 to transparency
672     PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
673     PNG_TRANSFORM_GRAY_TO_RGB   Expand grayscale samples
674                                 to RGB (or GA to RGBA)
675
676 (This excludes setting a background color, doing gamma transformation,
677 quantizing, and setting filler.)  If this is the case, simply do this:
678
679     png_read_png(png_ptr, info_ptr, png_transforms, NULL)
680
681 where png_transforms is an integer containing the bitwise OR of some
682 set of transformation flags.  This call is equivalent to png_read_info(),
683 followed the set of transformations indicated by the transform mask,
684 then png_read_image(), and finally png_read_end().
685
686 (The final parameter of this call is not yet used.  Someday it might point
687 to transformation parameters required by some future input transform.)
688
689 You must use png_transforms and not call any png_set_transform() functions
690 when you use png_read_png().
691
692 After you have called png_read_png(), you can retrieve the image data
693 with
694
695    row_pointers = png_get_rows(png_ptr, info_ptr);
696
697 where row_pointers is an array of pointers to the pixel data for each row:
698
699    png_bytep row_pointers[height];
700
701 If you know your image size and pixel size ahead of time, you can allocate
702 row_pointers prior to calling png_read_png() with
703
704    if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
705       png_error (png_ptr,
706           "Image is too tall to process in memory");
707
708    if (width > PNG_UINT_32_MAX/pixel_size)
709       png_error (png_ptr,
710           "Image is too wide to process in memory");
711
712    row_pointers = png_malloc(png_ptr,
713        height*png_sizeof(png_bytep));
714
715    for (int i=0; i<height, i++)
716       row_pointers[i]=NULL;  /* security precaution */
717
718    for (int i=0; i<height, i++)
719       row_pointers[i]=png_malloc(png_ptr,
720           width*pixel_size);
721
722    png_set_rows(png_ptr, info_ptr, &row_pointers);
723
724 Alternatively you could allocate your image in one big block and define
725 row_pointers[i] to point into the proper places in your block.
726
727 If you use png_set_rows(), the application is responsible for freeing
728 row_pointers (and row_pointers[i], if they were separately allocated).
729
730 If you don't allocate row_pointers ahead of time, png_read_png() will
731 do it, and it'll be free'ed by libpng when you call png_destroy_*().
732
733 The low-level read interface
734
735 If you are going the low-level route, you are now ready to read all
736 the file information up to the actual image data.  You do this with a
737 call to png_read_info().
738
739     png_read_info(png_ptr, info_ptr);
740
741 This will process all chunks up to but not including the image data.
742
743 Querying the info structure
744
745 Functions are used to get the information from the info_ptr once it
746 has been read.  Note that these fields may not be completely filled
747 in until png_read_end() has read the chunk data following the image.
748
749     png_get_IHDR(png_ptr, info_ptr, &width, &height,
750        &bit_depth, &color_type, &interlace_type,
751        &compression_type, &filter_method);
752
753     width          - holds the width of the image
754                      in pixels (up to 2^31).
755
756     height         - holds the height of the image
757                      in pixels (up to 2^31).
758
759     bit_depth      - holds the bit depth of one of the
760                      image channels.  (valid values are
761                      1, 2, 4, 8, 16 and depend also on
762                      the color_type.  See also
763                      significant bits (sBIT) below).
764
765     color_type     - describes which color/alpha channels
766                          are present.
767                      PNG_COLOR_TYPE_GRAY
768                         (bit depths 1, 2, 4, 8, 16)
769                      PNG_COLOR_TYPE_GRAY_ALPHA
770                         (bit depths 8, 16)
771                      PNG_COLOR_TYPE_PALETTE
772                         (bit depths 1, 2, 4, 8)
773                      PNG_COLOR_TYPE_RGB
774                         (bit_depths 8, 16)
775                      PNG_COLOR_TYPE_RGB_ALPHA
776                         (bit_depths 8, 16)
777
778                      PNG_COLOR_MASK_PALETTE
779                      PNG_COLOR_MASK_COLOR
780                      PNG_COLOR_MASK_ALPHA
781
782     interlace_type - (PNG_INTERLACE_NONE or
783                      PNG_INTERLACE_ADAM7)
784
785     compression_type - (must be PNG_COMPRESSION_TYPE_BASE
786                      for PNG 1.0)
787
788     filter_method  - (must be PNG_FILTER_TYPE_BASE
789                      for PNG 1.0, and can also be
790                      PNG_INTRAPIXEL_DIFFERENCING if
791                      the PNG datastream is embedded in
792                      a MNG-1.0 datastream)
793
794     Any or all of interlace_type, compression_type, or
795     filter_method can be NULL if you are
796     not interested in their values.
797
798     Note that png_get_IHDR() returns 32-bit data into
799     the application's width and height variables.
800     This is an unsafe situation if these are 16-bit
801     variables.  In such situations, the
802     png_get_image_width() and png_get_image_height()
803     functions described below are safer.
804
805     width            = png_get_image_width(png_ptr,
806                          info_ptr);
807
808     height           = png_get_image_height(png_ptr,
809                          info_ptr);
810
811     bit_depth        = png_get_bit_depth(png_ptr,
812                          info_ptr);
813
814     color_type       = png_get_color_type(png_ptr,
815                          info_ptr);
816
817     interlace_type   = png_get_interlace_type(png_ptr,
818                          info_ptr);
819
820     compression_type = png_get_compression_type(png_ptr,
821                          info_ptr);
822
823     filter_method    = png_get_filter_type(png_ptr,
824                          info_ptr);
825
826     channels = png_get_channels(png_ptr, info_ptr);
827
828     channels       - number of channels of info for the
829                      color type (valid values are 1 (GRAY,
830                      PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
831                      4 (RGB_ALPHA or RGB + filler byte))
832
833     rowbytes = png_get_rowbytes(png_ptr, info_ptr);
834
835     rowbytes       - number of bytes needed to hold a row
836
837     signature = png_get_signature(png_ptr, info_ptr);
838
839     signature      - holds the signature read from the
840                      file (if any).  The data is kept in
841                      the same offset it would be if the
842                      whole signature were read (i.e. if an
843                      application had already read in 4
844                      bytes of signature before starting
845                      libpng, the remaining 4 bytes would
846                      be in signature[4] through signature[7]
847                      (see png_set_sig_bytes())).
848
849 These are also important, but their validity depends on whether the chunk
850 has been read.  The png_get_valid(png_ptr, info_ptr, PNG_INFO_<chunk>) and
851 png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
852 data has been read, or zero if it is missing.  The parameters to the
853 png_get_<chunk> are set directly if they are simple data types, or a
854 pointer into the info_ptr is returned for any complex types.
855
856     png_get_PLTE(png_ptr, info_ptr, &palette,
857                      &num_palette);
858
859     palette        - the palette for the file
860                      (array of png_color)
861
862     num_palette    - number of entries in the palette
863
864     png_get_gAMA(png_ptr, info_ptr, &file_gamma);
865     png_get_gAMA_fixed(png_ptr, info_ptr, &int_file_gamma);
866
867     file_gamma     - the gamma at which the file is
868                      written (PNG_INFO_gAMA)
869
870     int_file_gamma - 100,000 times the gamma at which the
871                      file is written
872
873     png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
874
875     file_srgb_intent - the rendering intent (PNG_INFO_sRGB)
876                      The presence of the sRGB chunk
877                      means that the pixel data is in the
878                      sRGB color space.  This chunk also
879                      implies specific values of gAMA and
880                      cHRM.
881
882     png_get_iCCP(png_ptr, info_ptr, &name,
883        &compression_type, &profile, &proflen);
884
885     name             - The profile name.
886
887     compression_type - The compression type; always
888                        PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
889                        You may give NULL to this argument to
890                        ignore it.
891
892     profile          - International Color Consortium color
893                        profile data. May contain NULs.
894
895     proflen          - length of profile data in bytes.
896
897     png_get_sBIT(png_ptr, info_ptr, &sig_bit);
898
899     sig_bit        - the number of significant bits for
900                      (PNG_INFO_sBIT) each of the gray,
901                      red, green, and blue channels,
902                      whichever are appropriate for the
903                      given color type (png_color_16)
904
905     png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
906                      &num_trans, &trans_color);
907
908     trans_alpha    - array of alpha (transparency)
909                      entries for palette (PNG_INFO_tRNS)
910
911     num_trans      - number of transparent entries
912                      (PNG_INFO_tRNS)
913
914     trans_color    - graylevel or color sample values of
915                      the single transparent color for
916                      non-paletted images (PNG_INFO_tRNS)
917
918     png_get_hIST(png_ptr, info_ptr, &hist);
919                      (PNG_INFO_hIST)
920
921     hist           - histogram of palette (array of
922                      png_uint_16)
923
924     png_get_tIME(png_ptr, info_ptr, &mod_time);
925
926     mod_time       - time image was last modified
927                     (PNG_VALID_tIME)
928
929     png_get_bKGD(png_ptr, info_ptr, &background);
930
931     background     - background color (PNG_VALID_bKGD)
932                      valid 16-bit red, green and blue
933                      values, regardless of color_type
934
935     num_comments   = png_get_text(png_ptr, info_ptr,
936                      &text_ptr, &num_text);
937
938     num_comments   - number of comments
939
940     text_ptr       - array of png_text holding image
941                      comments
942
943     text_ptr[i].compression - type of compression used
944                  on "text" PNG_TEXT_COMPRESSION_NONE
945                            PNG_TEXT_COMPRESSION_zTXt
946                            PNG_ITXT_COMPRESSION_NONE
947                            PNG_ITXT_COMPRESSION_zTXt
948
949     text_ptr[i].key   - keyword for comment.  Must contain
950                          1-79 characters.
951
952     text_ptr[i].text  - text comments for current
953                          keyword.  Can be empty.
954
955     text_ptr[i].text_length - length of text string,
956                  after decompression, 0 for iTXt
957
958     text_ptr[i].itxt_length - length of itxt string,
959                  after decompression, 0 for tEXt/zTXt
960
961     text_ptr[i].lang  - language of comment (empty
962                          string for unknown).
963
964     text_ptr[i].lang_key  - keyword in UTF-8
965                          (empty string for unknown).
966
967     Note that the itxt_length, lang, and lang_key
968     members of the text_ptr structure only exist
969     when the library is built with iTXt chunk support.
970
971     num_text       - number of comments (same as
972                      num_comments; you can put NULL here
973                      to avoid the duplication)
974
975     Note while png_set_text() will accept text, language,
976     and translated keywords that can be NULL pointers, the
977     structure returned by png_get_text will always contain
978     regular zero-terminated C strings.  They might be
979     empty strings but they will never be NULL pointers.
980
981     num_spalettes = png_get_sPLT(png_ptr, info_ptr,
982        &palette_ptr);
983
984     num_spalettes  - number of sPLT chunks read.
985
986     palette_ptr    - array of palette structures holding
987                      contents of one or more sPLT chunks
988                      read.
989
990     png_get_oFFs(png_ptr, info_ptr, &offset_x, &offset_y,
991        &unit_type);
992
993     offset_x       - positive offset from the left edge
994                      of the screen
995
996     offset_y       - positive offset from the top edge
997                      of the screen
998
999     unit_type      - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
1000
1001     png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y,
1002        &unit_type);
1003
1004     res_x          - pixels/unit physical resolution in
1005                      x direction
1006
1007     res_y          - pixels/unit physical resolution in
1008                      x direction
1009
1010     unit_type      - PNG_RESOLUTION_UNKNOWN,
1011                      PNG_RESOLUTION_METER
1012
1013     png_get_sCAL(png_ptr, info_ptr, &unit, &width,
1014        &height)
1015
1016     unit        - physical scale units (an integer)
1017
1018     width       - width of a pixel in physical scale units
1019
1020     height      - height of a pixel in physical scale units
1021                  (width and height are doubles)
1022
1023     png_get_sCAL_s(png_ptr, info_ptr, &unit, &width,
1024        &height)
1025
1026     unit        - physical scale units (an integer)
1027
1028     width       - width of a pixel in physical scale units
1029
1030     height      - height of a pixel in physical scale units
1031                  (width and height are strings like "2.54")
1032
1033     num_unknown_chunks = png_get_unknown_chunks(png_ptr,
1034        info_ptr, &unknowns)
1035
1036     unknowns          - array of png_unknown_chunk
1037                         structures holding unknown chunks
1038
1039     unknowns[i].name  - name of unknown chunk
1040
1041     unknowns[i].data  - data of unknown chunk
1042
1043     unknowns[i].size  - size of unknown chunk's data
1044
1045     unknowns[i].location - position of chunk in file
1046
1047     The value of "i" corresponds to the order in which the
1048     chunks were read from the PNG file or inserted with the
1049     png_set_unknown_chunks() function.
1050
1051 The data from the pHYs chunk can be retrieved in several convenient
1052 forms:
1053
1054     res_x = png_get_x_pixels_per_meter(png_ptr,
1055        info_ptr)
1056
1057     res_y = png_get_y_pixels_per_meter(png_ptr,
1058        info_ptr)
1059
1060     res_x_and_y = png_get_pixels_per_meter(png_ptr,
1061        info_ptr)
1062
1063     res_x = png_get_x_pixels_per_inch(png_ptr,
1064        info_ptr)
1065
1066     res_y = png_get_y_pixels_per_inch(png_ptr,
1067        info_ptr)
1068
1069     res_x_and_y = png_get_pixels_per_inch(png_ptr,
1070        info_ptr)
1071
1072     aspect_ratio = png_get_pixel_aspect_ratio(png_ptr,
1073        info_ptr)
1074
1075     Each of these returns 0 [signifying "unknown"] if
1076        the data is not present or if res_x is 0;
1077        res_x_and_y is 0 if res_x != res_y
1078
1079     Note that because of the way the resolutions are
1080        stored internally, the inch conversions won't
1081        come out to exactly even number.  For example,
1082        72 dpi is stored as 0.28346 pixels/meter, and
1083        when this is retrieved it is 71.9988 dpi, so
1084        be sure to round the returned value appropriately
1085        if you want to display a reasonable-looking result.
1086
1087 The data from the oFFs chunk can be retrieved in several convenient
1088 forms:
1089
1090     x_offset = png_get_x_offset_microns(png_ptr, info_ptr);
1091
1092     y_offset = png_get_y_offset_microns(png_ptr, info_ptr);
1093
1094     x_offset = png_get_x_offset_inches(png_ptr, info_ptr);
1095
1096     y_offset = png_get_y_offset_inches(png_ptr, info_ptr);
1097
1098     Each of these returns 0 [signifying "unknown" if both
1099        x and y are 0] if the data is not present or if the
1100        chunk is present but the unit is the pixel.  The
1101        remark about inexact inch conversions applies here
1102        as well, because a value in inches can't always be
1103        converted to microns and back without some loss
1104        of precision.
1105
1106 For more information, see the png_info definition in png.h and the
1107 PNG specification for chunk contents.  Be careful with trusting
1108 rowbytes, as some of the transformations could increase the space
1109 needed to hold a row (expand, filler, gray_to_rgb, etc.).
1110 See png_read_update_info(), below.
1111
1112 A quick word about text_ptr and num_text.  PNG stores comments in
1113 keyword/text pairs, one pair per chunk, with no limit on the number
1114 of text chunks, and a 2^31 byte limit on their size.  While there are
1115 suggested keywords, there is no requirement to restrict the use to these
1116 strings.  It is strongly suggested that keywords and text be sensible
1117 to humans (that's the point), so don't use abbreviations.  Non-printing
1118 symbols are not allowed.  See the PNG specification for more details.
1119 There is also no requirement to have text after the keyword.
1120
1121 Keywords should be limited to 79 Latin-1 characters without leading or
1122 trailing spaces, but non-consecutive spaces are allowed within the
1123 keyword.  It is possible to have the same keyword any number of times.
1124 The text_ptr is an array of png_text structures, each holding a
1125 pointer to a language string, a pointer to a keyword and a pointer to
1126 a text string.  The text string, language code, and translated
1127 keyword may be empty or NULL pointers.  The keyword/text
1128 pairs are put into the array in the order that they are received.
1129 However, some or all of the text chunks may be after the image, so, to
1130 make sure you have read all the text chunks, don't mess with these
1131 until after you read the stuff after the image.  This will be
1132 mentioned again below in the discussion that goes with png_read_end().
1133
1134 Input transformations
1135
1136 After you've read the header information, you can set up the library
1137 to handle any special transformations of the image data.  The various
1138 ways to transform the data will be described in the order that they
1139 should occur.  This is important, as some of these change the color
1140 type and/or bit depth of the data, and some others only work on
1141 certain color types and bit depths.  Even though each transformation
1142 checks to see if it has data that it can do something with, you should
1143 make sure to only enable a transformation if it will be valid for the
1144 data.  For example, don't swap red and blue on grayscale data.
1145
1146 The colors used for the background and transparency values should be
1147 supplied in the same format/depth as the current image data.  They
1148 are stored in the same format/depth as the image data in a bKGD or tRNS
1149 chunk, so this is what libpng expects for this data.  The colors are
1150 transformed to keep in sync with the image data when an application
1151 calls the png_read_update_info() routine (see below).
1152
1153 Data will be decoded into the supplied row buffers packed into bytes
1154 unless the library has been told to transform it into another format.
1155 For example, 4 bit/pixel paletted or grayscale data will be returned
1156 2 pixels/byte with the leftmost pixel in the high-order bits of the
1157 byte, unless png_set_packing() is called.  8-bit RGB data will be stored
1158 in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
1159 is called to insert filler bytes, either before or after each RGB triplet.
1160 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
1161 byte of the color value first, unless png_set_strip_16() is called to
1162 transform it to regular RGB RGB triplets, or png_set_filler() or
1163 png_set_add alpha() is called to insert filler bytes, either before or
1164 after each RRGGBB triplet.  Similarly, 8-bit or 16-bit grayscale data can
1165 be modified with
1166 png_set_filler(), png_set_add_alpha(), or png_set_strip_16().
1167
1168 The following code transforms grayscale images of less than 8 to 8 bits,
1169 changes paletted images to RGB, and adds a full alpha channel if there is
1170 transparency information in a tRNS chunk.  This is most useful on
1171 grayscale images with bit depths of 2 or 4 or if there is a multiple-image
1172 viewing application that wishes to treat all images in the same way.
1173
1174     if (color_type == PNG_COLOR_TYPE_PALETTE)
1175         png_set_palette_to_rgb(png_ptr);
1176
1177     if (png_get_valid(png_ptr, info_ptr,
1178         PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
1179
1180     if (color_type == PNG_COLOR_TYPE_GRAY &&
1181         bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr);
1182
1183 The first two functions are actually aliases for png_set_expand(), added
1184 in libpng version 1.0.4, with the function names expanded to improve code
1185 readability.  In some future version they may actually do different
1186 things.
1187
1188 As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
1189 added.  It expands the sample depth without changing tRNS to alpha.
1190
1191 As of libpng version 1.5.2, png_set_expand_16() was added.  It behaves as
1192 png_set_expand(), however, the resultant channels have 16 bits rather than 8.
1193 Use this when the output color or gray channels are made linear to avoid fairly
1194 severe accuracy loss.
1195
1196    if (bit_depth < 16)
1197       png_set_expand_16(png_ptr);
1198
1199 PNG can have files with 16 bits per channel.  If you only can handle
1200 8 bits per channel, this will strip the pixels down to 8 bit.
1201
1202     if (bit_depth == 16)
1203        png_set_strip_16(png_ptr);
1204
1205 If, for some reason, you don't need the alpha channel on an image,
1206 and you want to remove it rather than combining it with the background
1207 (but the image author certainly had in mind that you *would* combine
1208 it with the background, so that's what you should probably do):
1209
1210     if (color_type & PNG_COLOR_MASK_ALPHA)
1211        png_set_strip_alpha(png_ptr);
1212
1213 See below for png_set_background(), which does the correct composition on a
1214 single opaque color.  This is probably what you should do in all cases rather
1215 than use png_set_strip_alpha() - unless you know for sure that it is the wrong
1216 thing to do.
1217
1218 As of libpng version 1.5.2, almost all useful expansions are supported, the
1219 major ommissions are convertion of grayscale to indexed images (which can be
1220 done trivially in the application) and convertion of indexed to grayscale (which
1221 can be done by a trivial manipulation of the palette.)
1222
1223 In the following table, the 01 means grayscale with depth<8, 31 means
1224 indexed with depth<8, other numerals represent the color type, "T" means
1225 the tRNS chunk is present, A means an alpha channel is present, and O
1226 means tRNS or alpha is present but all pixels in the image are opaque.
1227
1228   FROM  01  31   0  0T  0O   2  2T  2O   3  3T  3O  4A  4O  6A  6O
1229    TO
1230    01    -  [G]  -   -   -   -   -   -   -   -   -   -   -   -   -
1231    31   [Q]  Q  [Q] [Q] [Q]  Q   Q   Q   Q   Q   Q  [Q] [Q]  Q   Q
1232     0    1   G   +   .   .   G   G   G   G   G   G   B   B  GB  GB
1233    0T    lt  Gt  t   +   .   Gt  G   G   Gt  G   G   Bt  Bt GBt GBt
1234    0O    lt  Gt  t   .   +   Gt  Gt  G   Gt  Gt  G   Bt  Bt GBt GBt
1235     2    C   P   C   C   C   +   .   .   C   -   -  CB  CB   B   B
1236    2T    Ct  -   Ct  C   C   t   +   t   -   -   -  CBt CBt  Bt  Bt
1237    2O    Ct  -   Ct  C   C   t   t   +   -   -   -  CBt CBt  Bt  Bt
1238     3   [Q]  p  [Q] [Q] [Q]  Q   Q   Q   +   .   .  [Q] [Q]  Q   Q
1239    3T   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   +   t  [Qt][Qt] Qt  Qt
1240    3O   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   t   +  [Qt][Qt] Qt  Qt
1241    4A    lA  G   A   T   T   GA  GT  GT  GA  GT  GT  +   BA  G  GBA
1242    4O    lA GBA  A   T   T   GA  GT  GT  GA  GT  GT  BA  +  GBA  G
1243    6A    CA  PA  CA  C   C   A   T  tT   PA  P   P   C  CBA  +   BA
1244    6O    CA PBA  CA  C   C   A  tT   T   PA  P   P  CBA  C   BA  +
1245
1246 Within the matrix,
1247      "+" identifies entries where 'from' and 'to' are the same.
1248      "-" means the transformation is not supported.
1249      "." means nothing is necessary (a tRNS chunk can just be ignored).
1250      "t" means the transformation is obtained by png_set_tRNS.
1251      "A" means the transformation is obtained by png_set_add_alpha().
1252      "X" means the transformation is obtained by png_set_expand().
1253      "1" means the transformation is obtained by
1254          png_set_expand_gray_1_2_4_to_8() (and by png_set_expand() if there
1255          is no transparency in the original or the final format).
1256      "C" means the transformation is obtained by png_set_gray_to_rgb().
1257      "G" means the transformation is obtained by png_set_rgb_to_gray() or
1258          png_set_rgb_to_Y().
1259      "P" means the transformation is obtained by
1260          png_set_expand_palette_to_rgb().
1261      "p" means the transformation is obtained by png_set_packing().
1262      "Q" means the transformation is obtained by png_set_quantize().
1263      "T" means the transformation is obtained by png_set_tRNS_to_alpha().
1264      "B" means the transformation is obtained by png_set_background(), or
1265          png_strip_alpha().
1266
1267 When an entry has multiple transforms listed all are required to cause the
1268 right overall transformation.  When two transforms are separated by a comma
1269 either will do the job.  When transforms are enclosed in [] the transform should
1270 do the job but this is currently unimplemented - a different format will result
1271 if the suggested transformations are used.
1272
1273 In PNG files, the alpha channel in an image
1274 is the level of opacity.  If you need the alpha channel in an image to
1275 be the level of transparency instead of opacity, you can invert the
1276 alpha channel (or the tRNS chunk data) after it's read, so that 0 is
1277 fully opaque and 255 (in 8-bit or paletted images) or 65535 (in 16-bit
1278 images) is fully transparent, with
1279
1280     png_set_invert_alpha(png_ptr);
1281
1282 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
1283 they can, resulting in, for example, 8 pixels per byte for 1 bit
1284 files.  This code expands to 1 pixel per byte without changing the
1285 values of the pixels:
1286
1287     if (bit_depth < 8)
1288        png_set_packing(png_ptr);
1289
1290 PNG files have possible bit depths of 1, 2, 4, 8, and 16.  All pixels
1291 stored in a PNG image have been "scaled" or "shifted" up to the next
1292 higher possible bit depth (e.g. from 5 bits/sample in the range [0,31]
1293 to 8 bits/sample in the range [0, 255]).  However, it is also possible
1294 to convert the PNG pixel data back to the original bit depth of the
1295 image.  This call reduces the pixels back down to the original bit depth:
1296
1297     png_color_8p sig_bit;
1298
1299     if (png_get_sBIT(png_ptr, info_ptr, &sig_bit))
1300        png_set_shift(png_ptr, sig_bit);
1301
1302 PNG files store 3-color pixels in red, green, blue order.  This code
1303 changes the storage of the pixels to blue, green, red:
1304
1305     if (color_type == PNG_COLOR_TYPE_RGB ||
1306         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1307        png_set_bgr(png_ptr);
1308
1309 PNG files store RGB pixels packed into 3 or 6 bytes. This code expands them
1310 into 4 or 8 bytes for windowing systems that need them in this format:
1311
1312     if (color_type == PNG_COLOR_TYPE_RGB)
1313        png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
1314
1315 where "filler" is the 8 or 16-bit number to fill with, and the location is
1316 either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
1317 you want the filler before the RGB or after.  This transformation
1318 does not affect images that already have full alpha channels.  To add an
1319 opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
1320 will generate RGBA pixels.
1321
1322 Note that png_set_filler() does not change the color type.  If you want
1323 to do that, you can add a true alpha channel with
1324
1325     if (color_type == PNG_COLOR_TYPE_RGB ||
1326        color_type == PNG_COLOR_TYPE_GRAY)
1327        png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
1328
1329 where "filler" contains the alpha value to assign to each pixel.
1330 This function was added in libpng-1.2.7.
1331
1332 If you are reading an image with an alpha channel, and you need the
1333 data as ARGB instead of the normal PNG format RGBA:
1334
1335     if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1336        png_set_swap_alpha(png_ptr);
1337
1338 For some uses, you may want a grayscale image to be represented as
1339 RGB.  This code will do that conversion:
1340
1341     if (color_type == PNG_COLOR_TYPE_GRAY ||
1342         color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1343        png_set_gray_to_rgb(png_ptr);
1344
1345 Conversely, you can convert an RGB or RGBA image to grayscale or grayscale
1346 with alpha.
1347
1348     if (color_type == PNG_COLOR_TYPE_RGB ||
1349         color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1350        png_set_rgb_to_gray_fixed(png_ptr, error_action,
1351            int red_weight, int green_weight);
1352
1353     error_action = 1: silently do the conversion
1354
1355     error_action = 2: issue a warning if the original
1356                       image has any pixel where
1357                       red != green or red != blue
1358
1359     error_action = 3: issue an error and abort the
1360                       conversion if the original
1361                       image has any pixel where
1362                       red != green or red != blue
1363
1364     red_weight:       weight of red component times 100000
1365
1366     green_weight:     weight of green component times 100000
1367                       If either weight is negative, default
1368                       weights (21268, 71514) are used.
1369
1370 If you have set error_action = 1 or 2, you can
1371 later check whether the image really was gray, after processing
1372 the image rows, with the png_get_rgb_to_gray_status(png_ptr) function.
1373 It will return a png_byte that is zero if the image was gray or
1374 1 if there were any non-gray pixels.  bKGD and sBIT data
1375 will be silently converted to grayscale, using the green channel
1376 data, regardless of the error_action setting.
1377
1378 With red_weight+green_weight<=100000,
1379 the normalized graylevel is computed:
1380
1381     int rw = red_weight * 65536;
1382     int gw = green_weight * 65536;
1383     int bw = 65536 - (rw + gw);
1384     gray = (rw*red + gw*green + bw*blue)/65536;
1385
1386 The default values approximate those recommended in the Charles
1387 Poynton's Color FAQ, <http://www.inforamp.net/~poynton/>
1388 Copyright (c) 1998-01-04 Charles Poynton <poynton at inforamp.net>
1389
1390     Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
1391
1392 Libpng approximates this with integers scaled by 32768:
1393
1394     Y = (6968 * R + 23434 * G + 2366 * B)/32768
1395
1396 The calculation is done in a linear colorspace, if the image gamma
1397 can be determined.
1398
1399 If you have a grayscale and you are using png_set_expand_gray_1_2_4_to_8(),
1400 png_set_expand(), or png_set_gray_to_rgb to change to truecolor or to
1401 a higher bit-depth, you must either supply the background color as a gray
1402 value at the original file bit-depth (need_expand = 1) or else supply the
1403 background color as an RGB triplet at the final, expanded bit depth
1404 (need_expand = 0).  Similarly, if you are reading a paletted image, you
1405 must either supply the background color as a palette index (need_expand = 1)
1406 or as an RGB triplet that may or may not be in the palette (need_expand = 0).
1407
1408     png_color_16 my_background;
1409     png_color_16p image_background;
1410
1411     if (png_get_bKGD(png_ptr, info_ptr, &image_background))
1412        png_set_background(png_ptr, image_background,
1413            PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
1414     else
1415        png_set_background(png_ptr, &my_background,
1416            PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
1417
1418 The png_set_background() function tells libpng to composite images
1419 with alpha or simple transparency against the supplied background
1420 color.  If the PNG file contains a bKGD chunk (PNG_INFO_bKGD valid),
1421 you may use this color, or supply another color more suitable for
1422 the current display (e.g., the background color from a web page).  You
1423 need to tell libpng whether the color is in the gamma space of the
1424 display (PNG_BACKGROUND_GAMMA_SCREEN for colors you supply), the file
1425 (PNG_BACKGROUND_GAMMA_FILE for colors from the bKGD chunk), or one
1426 that is neither of these gammas (PNG_BACKGROUND_GAMMA_UNIQUE - I don't
1427 know why anyone would use this, but it's here).
1428
1429 To properly display PNG images on any kind of system, the application needs
1430 to know what the display gamma is.  Ideally, the user will know this, and
1431 the application will allow them to set it.  One method of allowing the user
1432 to set the display gamma separately for each system is to check for a
1433 SCREEN_GAMMA or DISPLAY_GAMMA environment variable, which will hopefully be
1434 correctly set.
1435
1436 Note that display_gamma is the overall gamma correction required to produce
1437 pleasing results, which depends on the lighting conditions in the surrounding
1438 environment.  In a dim or brightly lit room, no compensation other than
1439 the physical gamma exponent of the monitor is needed, while in a dark room
1440 a slightly smaller exponent is better.
1441
1442    double gamma, screen_gamma;
1443
1444    if (/* We have a user-defined screen
1445        gamma value */)
1446    {
1447       screen_gamma = user_defined_screen_gamma;
1448    }
1449
1450    /* One way that applications can share the same
1451       screen gamma value */
1452    else if ((gamma_str = getenv("SCREEN_GAMMA"))
1453       != NULL)
1454    {
1455       screen_gamma = (double)atof(gamma_str);
1456    }
1457
1458    /* If we don't have another value */
1459    else
1460    {
1461       screen_gamma = 2.2; /* A good guess for a
1462            PC monitor in a bright office or a dim room */
1463
1464       screen_gamma = 2.0; /* A good guess for a
1465            PC monitor in a dark room */
1466
1467       screen_gamma = 1.7 or 1.0;  /* A good
1468            guess for Mac systems */
1469    }
1470
1471 The functions png_set_gamma() and its fixed point equivalent
1472 png_set_gamma_fixed() handle gamma transformations of the data.
1473 Pass both the file gamma and the current screen_gamma.  If the file does
1474 not have a gamma value, you can pass one anyway if you have an idea what
1475 it is (usually 0.45455 is a good guess for GIF images on PCs).  Note
1476 that file gammas are inverted from screen gammas.  See the discussions
1477 on gamma in the PNG specification for an excellent description of what
1478 gamma is, and why all applications should support it.  It is strongly
1479 recommended that PNG viewers support gamma correction.
1480
1481    if (png_get_gAMA(png_ptr, info_ptr, &file_gamma))
1482       png_set_gamma(png_ptr, screen_gamma, file_gamma);
1483
1484    else
1485       png_set_gamma(png_ptr, screen_gamma, 0.45455);
1486
1487 If you need to reduce an RGB file to a paletted file, or if a paletted
1488 file has more entries then will fit on your screen, png_set_quantize()
1489 will do that.  Note that this is a simple match quantization that merely
1490 finds the closest color available.  This should work fairly well with
1491 optimized palettes, but fairly badly with linear color cubes.  If you
1492 pass a palette that is larger then maximum_colors, the file will
1493 reduce the number of colors in the palette so it will fit into
1494 maximum_colors.  If there is a histogram, it will use it to make
1495 more intelligent choices when reducing the palette.  If there is no
1496 histogram, it may not do as good a job.
1497
1498    if (color_type & PNG_COLOR_MASK_COLOR)
1499    {
1500       if (png_get_valid(png_ptr, info_ptr,
1501           PNG_INFO_PLTE))
1502       {
1503          png_uint_16p histogram = NULL;
1504
1505          png_get_hIST(png_ptr, info_ptr,
1506              &histogram);
1507          png_set_quantize(png_ptr, palette, num_palette,
1508             max_screen_colors, histogram, 1);
1509       }
1510
1511       else
1512       {
1513          png_color std_color_cube[MAX_SCREEN_COLORS] =
1514             { ... colors ... };
1515
1516          png_set_quantize(png_ptr, std_color_cube,
1517             MAX_SCREEN_COLORS, MAX_SCREEN_COLORS,
1518             NULL,0);
1519       }
1520    }
1521
1522 PNG files describe monochrome as black being zero and white being one.
1523 The following code will reverse this (make black be one and white be
1524 zero):
1525
1526    if (bit_depth == 1 && color_type == PNG_COLOR_TYPE_GRAY)
1527       png_set_invert_mono(png_ptr);
1528
1529 This function can also be used to invert grayscale and gray-alpha images:
1530
1531    if (color_type == PNG_COLOR_TYPE_GRAY ||
1532        color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1533       png_set_invert_mono(png_ptr);
1534
1535 PNG files store 16 bit pixels in network byte order (big-endian,
1536 ie. most significant bits first).  This code changes the storage to the
1537 other way (little-endian, i.e. least significant bits first, the
1538 way PCs store them):
1539
1540     if (bit_depth == 16)
1541        png_set_swap(png_ptr);
1542
1543 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
1544 need to change the order the pixels are packed into bytes, you can use:
1545
1546     if (bit_depth < 8)
1547        png_set_packswap(png_ptr);
1548
1549 Finally, you can write your own transformation function if none of
1550 the existing ones meets your needs.  This is done by setting a callback
1551 with
1552
1553     png_set_read_user_transform_fn(png_ptr,
1554         read_transform_fn);
1555
1556 You must supply the function
1557
1558     void read_transform_fn(png_structp png_ptr, png_row_infop
1559         row_info, png_bytep data)
1560
1561 See pngtest.c for a working example.  Your function will be called
1562 after all of the other transformations have been processed.  Take care with
1563 interlaced images if you do the interlace yourself - the width of the row is the
1564 width in 'row_info', not the overall image width.
1565
1566 If supported libpng provides two information routines that you can use to find
1567 where you are in processing the image:
1568
1569    png_get_current_pass_number(png_structp png_ptr);
1570    png_get_current_row_number(png_structp png_ptr);
1571
1572 Don't try using these outside a transform callback - firstly they are only
1573 supported if user transforms are supported, secondly they may well return
1574 unexpected results unless the row is actually being processed at the moment they
1575 are called.
1576
1577 With interlaced
1578 images the value returned is the row in the input sub-image image.  Use
1579 PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
1580 find the output pixel (x,y) given an interlaced sub-image pixel (row,col,pass).
1581
1582 The discussion of interlace handling above contains more information on how to
1583 use these values.
1584
1585 You can also set up a pointer to a user structure for use by your
1586 callback function, and you can inform libpng that your transform
1587 function will change the number of channels or bit depth with the
1588 function
1589
1590     png_set_user_transform_info(png_ptr, user_ptr,
1591         user_depth, user_channels);
1592
1593 The user's application, not libpng, is responsible for allocating and
1594 freeing any memory required for the user structure.
1595
1596 You can retrieve the pointer via the function
1597 png_get_user_transform_ptr().  For example:
1598
1599     voidp read_user_transform_ptr =
1600         png_get_user_transform_ptr(png_ptr);
1601
1602 The last thing to handle is interlacing; this is covered in detail below,
1603 but you must call the function here if you want libpng to handle expansion
1604 of the interlaced image.
1605
1606     number_of_passes = png_set_interlace_handling(png_ptr);
1607
1608 After setting the transformations, libpng can update your png_info
1609 structure to reflect any transformations you've requested with this
1610 call.  This is most useful to update the info structure's rowbytes
1611 field so you can use it to allocate your image memory.  This function
1612 will also update your palette with the correct screen_gamma and
1613 background if these have been given with the calls above.
1614
1615     png_read_update_info(png_ptr, info_ptr);
1616
1617 After you call png_read_update_info(), you can allocate any
1618 memory you need to hold the image.  The row data is simply
1619 raw byte data for all forms of images.  As the actual allocation
1620 varies among applications, no example will be given.  If you
1621 are allocating one large chunk, you will need to build an
1622 array of pointers to each row, as it will be needed for some
1623 of the functions below.
1624
1625 Remember: Before you call png_read_update_info(), the png_get_
1626 functions return the values corresponding to the original PNG image.
1627 After you call png_read_update_info the values refer to the image
1628 that libpng will output.  Consequently you must call all the png_set_
1629 functions before you call png_read_update_info().  This is particularly
1630 important for png_set_interlace_handling() - if you are going to call
1631 png_read_update_info() you must call png_set_interlace_handling() before
1632 it unless you want to receive interlaced output.
1633
1634 Reading image data
1635
1636 After you've allocated memory, you can read the image data.
1637 The simplest way to do this is in one function call.  If you are
1638 allocating enough memory to hold the whole image, you can just
1639 call png_read_image() and libpng will read in all the image data
1640 and put it in the memory area supplied.  You will need to pass in
1641 an array of pointers to each row.
1642
1643 This function automatically handles interlacing, so you don't
1644 need to call png_set_interlace_handling() (unless you call
1645 png_read_update_info()) or call this function multiple times, or any
1646 of that other stuff necessary with png_read_rows().
1647
1648    png_read_image(png_ptr, row_pointers);
1649
1650 where row_pointers is:
1651
1652    png_bytep row_pointers[height];
1653
1654 You can point to void or char or whatever you use for pixels.
1655
1656 If you don't want to read in the whole image at once, you can
1657 use png_read_rows() instead.  If there is no interlacing (check
1658 interlace_type == PNG_INTERLACE_NONE), this is simple:
1659
1660     png_read_rows(png_ptr, row_pointers, NULL,
1661         number_of_rows);
1662
1663 where row_pointers is the same as in the png_read_image() call.
1664
1665 If you are doing this just one row at a time, you can do this with
1666 a single row_pointer instead of an array of row_pointers:
1667
1668     png_bytep row_pointer = row;
1669     png_read_row(png_ptr, row_pointer, NULL);
1670
1671 If the file is interlaced (interlace_type != 0 in the IHDR chunk), things
1672 get somewhat harder.  The only current (PNG Specification version 1.2)
1673 interlacing type for PNG is (interlace_type == PNG_INTERLACE_ADAM7);
1674 a somewhat complicated 2D interlace scheme, known as Adam7, that
1675 breaks down an image into seven smaller images of varying size, based
1676 on an 8x8 grid.  This number is defined (from libpng 1.5) as
1677 PNG_INTERLACE_ADAM7_PASSES in png.h
1678
1679 libpng can fill out those images or it can give them to you "as is".
1680 It is almost always better to have libpng handle the interlacing for you.
1681 If you want the images filled out, there are two ways to do that.  The one
1682 mentioned in the PNG specification is to expand each pixel to cover
1683 those pixels that have not been read yet (the "rectangle" method).
1684 This results in a blocky image for the first pass, which gradually
1685 smooths out as more pixels are read.  The other method is the "sparkle"
1686 method, where pixels are drawn only in their final locations, with the
1687 rest of the image remaining whatever colors they were initialized to
1688 before the start of the read.  The first method usually looks better,
1689 but tends to be slower, as there are more pixels to put in the rows.
1690
1691 If, as is likely, you want libpng to expand the images, call this before
1692 calling png_start_read_image() or png_read_update_info():
1693
1694     if (interlace_type == PNG_INTERLACE_ADAM7)
1695        number_of_passes
1696            = png_set_interlace_handling(png_ptr);
1697
1698 This will return the number of passes needed.  Currently, this is seven,
1699 but may change if another interlace type is added.  This function can be
1700 called even if the file is not interlaced, where it will return one pass.
1701 You then need to read the whole image 'number_of_passes' times.  Each time
1702 will distribute the pixels from the current pass to the correct place in
1703 the output image, so you need to supply the same rows to png_read_rows in
1704 each pass.
1705
1706 If you are not going to display the image after each pass, but are
1707 going to wait until the entire image is read in, use the sparkle
1708 effect.  This effect is faster and the end result of either method
1709 is exactly the same.  If you are planning on displaying the image
1710 after each pass, the "rectangle" effect is generally considered the
1711 better looking one.
1712
1713 If you only want the "sparkle" effect, just call png_read_rows() as
1714 normal, with the third parameter NULL.  Make sure you make pass over
1715 the image number_of_passes times, and you don't change the data in the
1716 rows between calls.  You can change the locations of the data, just
1717 not the data.  Each pass only writes the pixels appropriate for that
1718 pass, and assumes the data from previous passes is still valid.
1719
1720     png_read_rows(png_ptr, row_pointers, NULL,
1721         number_of_rows);
1722
1723 If you only want the first effect (the rectangles), do the same as
1724 before except pass the row buffer in the third parameter, and leave
1725 the second parameter NULL.
1726
1727     png_read_rows(png_ptr, NULL, row_pointers,
1728         number_of_rows);
1729
1730 If you don't want libpng to handle the interlacing details, just call
1731 png_read_rows() PNG_INTERLACE_ADAM7_PASSES times to read in all the images.
1732 Each of the images is a valid image by itself, however you will almost
1733 certainly need to distribute the pixels from each sub-image to the
1734 correct place.  This is where everything gets very tricky.
1735
1736 If you want to retrieve the separate images you must pass the correct
1737 number of rows to each successive call of png_read_rows().  The calculation
1738 gets pretty complicated for small images, where some sub-images may
1739 not even exist because either their width or height ends up zero.
1740 libpng provides two macros to help you in 1.5 and later versions:
1741
1742    png_uint_32 width = PNG_PASS_COLS(image_width, pass_number);
1743    png_uint_32 height = PNG_PASS_ROWS(image_height, pass_number);
1744
1745 Respectively these tell you the width and height of the sub-image
1746 corresponding to the numbered pass.  'pass' is in in the range 0 to 6 -
1747 this can be confusing because the specification refers to the same passes
1748 as 1 to 7!  Be careful, you must check both the width and height before
1749 calling png_read_rows() and not call it for that pass if either is zero.
1750
1751 You can, of course, read each sub-image row by row.  If you want to
1752 produce optimal code to make a pixel-by-pixel transformation of an
1753 interlaced image this is the best approach; read each row of each pass,
1754 transform it, and write it out to a new interlaced image.
1755
1756 If you want to de-interlace the image yourself libpng provides further
1757 macros to help that tell you where to place the pixels in the output image.
1758 Because the interlacing scheme is rectangular - sub-image pixels are always
1759 arranged on a rectangular grid - all you need to know for each pass is the
1760 starting column and row in the output image of the first pixel plus the
1761 spacing between each pixel.  As of libpng 1.5 there are four macros to
1762 retrieve this information:
1763
1764    png_uint_32 x = PNG_PASS_START_COL(pass);
1765    png_uint_32 y = PNG_PASS_START_ROW(pass);
1766    png_uint_32 xStep = 1U << PNG_PASS_COL_SHIFT(pass);
1767    png_uint_32 yStep = 1U << PNG_PASS_ROW_SHIFT(pass);
1768
1769 These allow you to write the obvious loop:
1770
1771    png_uint_32 input_y = 0;
1772    png_uint_32 output_y = PNG_PASS_START_ROW(pass);
1773
1774    while (output_y < output_image_height)
1775    {
1776       png_uint_32 input_x = 0;
1777       png_uint_32 output_x = PNG_PASS_START_COL(pass);
1778
1779       while (output_x < output_image_width)
1780       {
1781          image[output_y][output_x] =
1782              subimage[pass][input_y][input_x++];
1783
1784          output_x += xStep;
1785       }
1786
1787       ++input_y;
1788       output_y += yStep;
1789    }
1790
1791 Notice that the steps between successive output rows and columns are
1792 returned as shifts.  This is possible because the pixels in the subimages
1793 are always a power of 2 apart - 1, 2, 4 or 8 pixels - in the original
1794 image.  In practice you may need to directly calculate the output coordinate
1795 given an input coordinate.  libpng provides two further macros for this
1796 purpose:
1797
1798    png_uint_32 output_x = PNG_COL_FROM_PASS_COL(input_x, pass);
1799    png_uint_32 output_y = PNG_ROW_FROM_PASS_ROW(input_y, pass);
1800
1801 Finally a pair of macros are provided to tell you if a particular image
1802 row or column appears in a given pass:
1803
1804    int col_in_pass = PNG_COL_IN_INTERLACE_PASS(output_x, pass);
1805    int row_in_pass = PNG_ROW_IN_INTERLACE_PASS(output_y, pass);
1806
1807 Bear in mind that you will probably also need to check the width and height
1808 of the pass in addition to the above to be sure the pass even exists!
1809
1810 With any luck you are convinced by now that you don't want to do your own
1811 interlace handling.  In reality normally the only good reason for doing this
1812 is if you are processing PNG files on a pixel-by-pixel basis and don't want
1813 to load the whole file into memory when it is interlaced.
1814
1815 libpng includes a test program, pngvalid, that illustrates reading and
1816 writing of interlaced images.  If you can't get interlacing to work in your
1817 code and don't want to leave it to libpng (the recommended approach) see
1818 how pngvalid.c does it.
1819
1820 Finishing a sequential read
1821
1822 After you are finished reading the image through the
1823 low-level interface, you can finish reading the file.  If you are
1824 interested in comments or time, which may be stored either before or
1825 after the image data, you should pass the separate png_info struct if
1826 you want to keep the comments from before and after the image
1827 separate.  If you are not interested, you can pass NULL.
1828
1829    png_read_end(png_ptr, end_info);
1830
1831 When you are done, you can free all memory allocated by libpng like this:
1832
1833    png_destroy_read_struct(&png_ptr, &info_ptr,
1834        &end_info);
1835
1836 It is also possible to individually free the info_ptr members that
1837 point to libpng-allocated storage with the following function:
1838
1839     png_free_data(png_ptr, info_ptr, mask, seq)
1840
1841     mask - identifies data to be freed, a mask
1842            containing the bitwise OR of one or
1843            more of
1844              PNG_FREE_PLTE, PNG_FREE_TRNS,
1845              PNG_FREE_HIST, PNG_FREE_ICCP,
1846              PNG_FREE_PCAL, PNG_FREE_ROWS,
1847              PNG_FREE_SCAL, PNG_FREE_SPLT,
1848              PNG_FREE_TEXT, PNG_FREE_UNKN,
1849            or simply PNG_FREE_ALL
1850
1851     seq  - sequence number of item to be freed
1852            (-1 for all items)
1853
1854 This function may be safely called when the relevant storage has
1855 already been freed, or has not yet been allocated, or was allocated
1856 by the user and not by libpng,  and will in those cases do nothing.
1857 The "seq" parameter is ignored if only one item of the selected data
1858 type, such as PLTE, is allowed.  If "seq" is not -1, and multiple items
1859 are allowed for the data type identified in the mask, such as text or
1860 sPLT, only the n'th item in the structure is freed, where n is "seq".
1861
1862 The default behavior is only to free data that was allocated internally
1863 by libpng.  This can be changed, so that libpng will not free the data,
1864 or so that it will free data that was allocated by the user with png_malloc()
1865 or png_zalloc() and passed in via a png_set_*() function, with
1866
1867     png_data_freer(png_ptr, info_ptr, freer, mask)
1868
1869     freer  - one of
1870                PNG_DESTROY_WILL_FREE_DATA
1871                PNG_SET_WILL_FREE_DATA
1872                PNG_USER_WILL_FREE_DATA
1873
1874     mask   - which data elements are affected
1875              same choices as in png_free_data()
1876
1877 This function only affects data that has already been allocated.
1878 You can call this function after reading the PNG data but before calling
1879 any png_set_*() functions, to control whether the user or the png_set_*()
1880 function is responsible for freeing any existing data that might be present,
1881 and again after the png_set_*() functions to control whether the user
1882 or png_destroy_*() is supposed to free the data.  When the user assumes
1883 responsibility for libpng-allocated data, the application must use
1884 png_free() to free it, and when the user transfers responsibility to libpng
1885 for data that the user has allocated, the user must have used png_malloc()
1886 or png_zalloc() to allocate it.
1887
1888 If you allocated your row_pointers in a single block, as suggested above in
1889 the description of the high level read interface, you must not transfer
1890 responsibility for freeing it to the png_set_rows or png_read_destroy function,
1891 because they would also try to free the individual row_pointers[i].
1892
1893 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
1894 separately, do not transfer responsibility for freeing text_ptr to libpng,
1895 because when libpng fills a png_text structure it combines these members with
1896 the key member, and png_free_data() will free only text_ptr.key.  Similarly,
1897 if you transfer responsibility for free'ing text_ptr from libpng to your
1898 application, your application must not separately free those members.
1899
1900 The png_free_data() function will turn off the "valid" flag for anything
1901 it frees.  If you need to turn the flag off for a chunk that was freed by
1902 your application instead of by libpng, you can use
1903
1904     png_set_invalid(png_ptr, info_ptr, mask);
1905
1906     mask - identifies the chunks to be made invalid,
1907            containing the bitwise OR of one or
1908            more of
1909              PNG_INFO_gAMA, PNG_INFO_sBIT,
1910              PNG_INFO_cHRM, PNG_INFO_PLTE,
1911              PNG_INFO_tRNS, PNG_INFO_bKGD,
1912              PNG_INFO_hIST, PNG_INFO_pHYs,
1913              PNG_INFO_oFFs, PNG_INFO_tIME,
1914              PNG_INFO_pCAL, PNG_INFO_sRGB,
1915              PNG_INFO_iCCP, PNG_INFO_sPLT,
1916              PNG_INFO_sCAL, PNG_INFO_IDAT
1917
1918 For a more compact example of reading a PNG image, see the file example.c.
1919
1920 Reading PNG files progressively
1921
1922 The progressive reader is slightly different then the non-progressive
1923 reader.  Instead of calling png_read_info(), png_read_rows(), and
1924 png_read_end(), you make one call to png_process_data(), which calls
1925 callbacks when it has the info, a row, or the end of the image.  You
1926 set up these callbacks with png_set_progressive_read_fn().  You don't
1927 have to worry about the input/output functions of libpng, as you are
1928 giving the library the data directly in png_process_data().  I will
1929 assume that you have read the section on reading PNG files above,
1930 so I will only highlight the differences (although I will show
1931 all of the code).
1932
1933 png_structp png_ptr;
1934 png_infop info_ptr;
1935
1936  /*  An example code fragment of how you would
1937      initialize the progressive reader in your
1938      application. */
1939  int
1940  initialize_png_reader()
1941  {
1942     png_ptr = png_create_read_struct
1943         (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
1944          user_error_fn, user_warning_fn);
1945
1946     if (!png_ptr)
1947         return (ERROR);
1948
1949     info_ptr = png_create_info_struct(png_ptr);
1950
1951     if (!info_ptr)
1952     {
1953        png_destroy_read_struct(&png_ptr,
1954           (png_infopp)NULL, (png_infopp)NULL);
1955        return (ERROR);
1956     }
1957
1958     if (setjmp(png_jmpbuf(png_ptr)))
1959     {
1960        png_destroy_read_struct(&png_ptr, &info_ptr,
1961           (png_infopp)NULL);
1962        return (ERROR);
1963     }
1964
1965     /* This one's new.  You can provide functions
1966        to be called when the header info is valid,
1967        when each row is completed, and when the image
1968        is finished.  If you aren't using all functions,
1969        you can specify NULL parameters.  Even when all
1970        three functions are NULL, you need to call
1971        png_set_progressive_read_fn().  You can use
1972        any struct as the user_ptr (cast to a void pointer
1973        for the function call), and retrieve the pointer
1974        from inside the callbacks using the function
1975
1976           png_get_progressive_ptr(png_ptr);
1977
1978        which will return a void pointer, which you have
1979        to cast appropriately.
1980      */
1981     png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
1982         info_callback, row_callback, end_callback);
1983
1984     return 0;
1985  }
1986
1987  /* A code fragment that you call as you receive blocks
1988    of data */
1989  int
1990  process_data(png_bytep buffer, png_uint_32 length)
1991  {
1992     if (setjmp(png_jmpbuf(png_ptr)))
1993     {
1994        png_destroy_read_struct(&png_ptr, &info_ptr,
1995            (png_infopp)NULL);
1996        return (ERROR);
1997     }
1998
1999     /* This one's new also.  Simply give it a chunk
2000        of data from the file stream (in order, of
2001        course).  On machines with segmented memory
2002        models machines, don't give it any more than
2003        64K.  The library seems to run fine with sizes
2004        of 4K. Although you can give it much less if
2005        necessary (I assume you can give it chunks of
2006        1 byte, I haven't tried less then 256 bytes
2007        yet).  When this function returns, you may
2008        want to display any rows that were generated
2009        in the row callback if you don't already do
2010        so there.
2011      */
2012     png_process_data(png_ptr, info_ptr, buffer, length);
2013
2014     /* At this point you can call png_process_data_skip if
2015        you want to handle data the library will skip yourself;
2016        it simply returns the number of bytes to skip (and stops
2017        libpng skipping that number of bytes on the next
2018        png_process_data call).
2019     return 0;
2020  }
2021
2022  /* This function is called (as set by
2023     png_set_progressive_read_fn() above) when enough data
2024     has been supplied so all of the header has been
2025     read.
2026  */
2027  void
2028  info_callback(png_structp png_ptr, png_infop info)
2029  {
2030     /* Do any setup here, including setting any of
2031        the transformations mentioned in the Reading
2032        PNG files section.  For now, you _must_ call
2033        either png_start_read_image() or
2034        png_read_update_info() after all the
2035        transformations are set (even if you don't set
2036        any).  You may start getting rows before
2037        png_process_data() returns, so this is your
2038        last chance to prepare for that.
2039
2040        This is where you turn on interlace handling,
2041        assuming you don't want to do it yourself.
2042
2043        If you need to you can stop the processing of
2044        your original input data at this point by calling
2045        png_process_data_pause.  This returns the number
2046        of unprocessed bytes from the last png_process_data
2047        call - it is up to you to ensure that the next call
2048        sees these bytes again.  If you don't want to bother
2049        with this you can get libpng to cache the unread
2050        bytes by setting the 'save' parameter (see png.h) but
2051        then libpng will have to copy the data internally.
2052      */
2053  }
2054
2055  /* This function is called when each row of image
2056     data is complete */
2057  void
2058  row_callback(png_structp png_ptr, png_bytep new_row,
2059     png_uint_32 row_num, int pass)
2060  {
2061     /* If the image is interlaced, and you turned
2062        on the interlace handler, this function will
2063        be called for every row in every pass.  Some
2064        of these rows will not be changed from the
2065        previous pass.  When the row is not changed,
2066        the new_row variable will be NULL.  The rows
2067        and passes are called in order, so you don't
2068        really need the row_num and pass, but I'm
2069        supplying them because it may make your life
2070        easier.
2071
2072        If you did not turn on interlace handling then
2073        the callback is called for each row of each
2074        sub-image when the image is interlaced.  In this
2075        case 'row_num' is the row in the sub-image, not
2076        the row in the output image as it is in all other
2077        cases.
2078
2079        For the non-NULL rows of interlaced images when
2080        you have switched on libpng interlace handling,
2081        you must call png_progressive_combine_row()
2082        passing in the row and the old row.  You can
2083        call this function for NULL rows (it will just
2084        return) and for non-interlaced images (it just
2085        does the memcpy for you) if it will make the
2086        code easier.  Thus, you can just do this for
2087        all cases if you switch on interlace handling;
2088      */
2089
2090         png_progressive_combine_row(png_ptr, old_row,
2091           new_row);
2092
2093     /* where old_row is what was displayed for
2094        previously for the row.  Note that the first
2095        pass (pass == 0, really) will completely cover
2096        the old row, so the rows do not have to be
2097        initialized.  After the first pass (and only
2098        for interlaced images), you will have to pass
2099        the current row, and the function will combine
2100        the old row and the new row.
2101
2102        You can also call png_process_data_pause in this
2103        callback - see above.
2104     */
2105  }
2106
2107  void
2108  end_callback(png_structp png_ptr, png_infop info)
2109  {
2110     /* This function is called after the whole image
2111        has been read, including any chunks after the
2112        image (up to and including the IEND).  You
2113        will usually have the same info chunk as you
2114        had in the header, although some data may have
2115        been added to the comments and time fields.
2116
2117        Most people won't do much here, perhaps setting
2118        a flag that marks the image as finished.
2119      */
2120  }
2121
2122
2123
2124 IV. Writing
2125
2126 Much of this is very similar to reading.  However, everything of
2127 importance is repeated here, so you won't have to constantly look
2128 back up in the reading section to understand writing.
2129
2130 Setup
2131
2132 You will want to do the I/O initialization before you get into libpng,
2133 so if it doesn't work, you don't have anything to undo. If you are not
2134 using the standard I/O functions, you will need to replace them with
2135 custom writing functions.  See the discussion under Customizing libpng.
2136
2137     FILE *fp = fopen(file_name, "wb");
2138
2139     if (!fp)
2140        return (ERROR);
2141
2142 Next, png_struct and png_info need to be allocated and initialized.
2143 As these can be both relatively large, you may not want to store these
2144 on the stack, unless you have stack space to spare.  Of course, you
2145 will want to check if they return NULL.  If you are also reading,
2146 you won't want to name your read structure and your write structure
2147 both "png_ptr"; you can call them anything you like, such as
2148 "read_ptr" and "write_ptr".  Look at pngtest.c, for example.
2149
2150     png_structp png_ptr = png_create_write_struct
2151        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
2152         user_error_fn, user_warning_fn);
2153
2154     if (!png_ptr)
2155        return (ERROR);
2156
2157     png_infop info_ptr = png_create_info_struct(png_ptr);
2158     if (!info_ptr)
2159     {
2160        png_destroy_write_struct(&png_ptr,
2161            (png_infopp)NULL);
2162        return (ERROR);
2163     }
2164
2165 If you want to use your own memory allocation routines,
2166 define PNG_USER_MEM_SUPPORTED and use
2167 png_create_write_struct_2() instead of png_create_write_struct():
2168
2169     png_structp png_ptr = png_create_write_struct_2
2170        (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
2171         user_error_fn, user_warning_fn, (png_voidp)
2172         user_mem_ptr, user_malloc_fn, user_free_fn);
2173
2174 After you have these structures, you will need to set up the
2175 error handling.  When libpng encounters an error, it expects to
2176 longjmp() back to your routine.  Therefore, you will need to call
2177 setjmp() and pass the png_jmpbuf(png_ptr).  If you
2178 write the file from different routines, you will need to update
2179 the png_jmpbuf(png_ptr) every time you enter a new routine that will
2180 call a png_*() function.  See your documentation of setjmp/longjmp
2181 for your compiler for more information on setjmp/longjmp.  See
2182 the discussion on libpng error handling in the Customizing Libpng
2183 section below for more information on the libpng error handling.
2184
2185     if (setjmp(png_jmpbuf(png_ptr)))
2186     {
2187     png_destroy_write_struct(&png_ptr, &info_ptr);
2188        fclose(fp);
2189        return (ERROR);
2190     }
2191     ...
2192     return;
2193
2194 If you would rather avoid the complexity of setjmp/longjmp issues,
2195 you can compile libpng with PNG_NO_SETJMP, in which case
2196 errors will result in a call to PNG_ABORT() which defaults to abort().
2197
2198 You can #define PNG_ABORT() to a function that does something
2199 more useful than abort(), as long as your function does not
2200 return.
2201
2202 Now you need to set up the output code.  The default for libpng is to
2203 use the C function fwrite().  If you use this, you will need to pass a
2204 valid FILE * in the function png_init_io().  Be sure that the file is
2205 opened in binary mode.  Again, if you wish to handle writing data in
2206 another way, see the discussion on libpng I/O handling in the Customizing
2207 Libpng section below.
2208
2209     png_init_io(png_ptr, fp);
2210
2211 If you are embedding your PNG into a datastream such as MNG, and don't
2212 want libpng to write the 8-byte signature, or if you have already
2213 written the signature in your application, use
2214
2215     png_set_sig_bytes(png_ptr, 8);
2216
2217 to inform libpng that it should not write a signature.
2218
2219 Write callbacks
2220
2221 At this point, you can set up a callback function that will be
2222 called after each row has been written, which you can use to control
2223 a progress meter or the like.  It's demonstrated in pngtest.c.
2224 You must supply a function
2225
2226     void write_row_callback(png_structp png_ptr, png_uint_32 row,
2227        int pass);
2228     {
2229       /* put your code here */
2230     }
2231
2232 (You can give it another name that you like instead of "write_row_callback")
2233
2234 To inform libpng about your function, use
2235
2236     png_set_write_status_fn(png_ptr, write_row_callback);
2237
2238 When this function is called the row has already been completely processed and
2239 it has also been written out.  The 'row' and 'pass' refer to the next row to be
2240 handled.  For the
2241 non-interlaced case the row that was just handled is simply one less than the
2242 passed in row number, and pass will always be 0.  For the interlaced case the
2243 same applies unless the row value is 0, in which case the row just handled was
2244 the last one from one of the preceding passes.  Because interlacing may skip a
2245 pass you cannot be sure that the preceding pass is just 'pass-1', if you really
2246 need to know what the last pass is record (row,pass) from the callback and use
2247 the last recorded value each time.
2248
2249 As with the user transform you can find the output row using the
2250 PNG_ROW_FROM_PASS_ROW macro.
2251
2252 You now have the option of modifying how the compression library will
2253 run.  The following functions are mainly for testing, but may be useful
2254 in some cases, like if you need to write PNG files extremely fast and
2255 are willing to give up some compression, or if you want to get the
2256 maximum possible compression at the expense of slower writing.  If you
2257 have no special needs in this area, let the library do what it wants by
2258 not calling this function at all, as it has been tuned to deliver a good
2259 speed/compression ratio. The second parameter to png_set_filter() is
2260 the filter method, for which the only valid values are 0 (as of the
2261 July 1999 PNG specification, version 1.2) or 64 (if you are writing
2262 a PNG datastream that is to be embedded in a MNG datastream).  The third
2263 parameter is a flag that indicates which filter type(s) are to be tested
2264 for each scanline.  See the PNG specification for details on the specific
2265 filter types.
2266
2267
2268     /* turn on or off filtering, and/or choose
2269        specific filters.  You can use either a single
2270        PNG_FILTER_VALUE_NAME or the bitwise OR of one
2271        or more PNG_FILTER_NAME masks.
2272      */
2273     png_set_filter(png_ptr, 0,
2274        PNG_FILTER_NONE  | PNG_FILTER_VALUE_NONE |
2275        PNG_FILTER_SUB   | PNG_FILTER_VALUE_SUB  |
2276        PNG_FILTER_UP    | PNG_FILTER_VALUE_UP   |
2277        PNG_FILTER_AVG   | PNG_FILTER_VALUE_AVG  |
2278        PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH|
2279        PNG_ALL_FILTERS);
2280
2281 If an application wants to start and stop using particular filters during
2282 compression, it should start out with all of the filters (to ensure that
2283 the previous row of pixels will be stored in case it's needed later),
2284 and then add and remove them after the start of compression.
2285
2286 If you are writing a PNG datastream that is to be embedded in a MNG
2287 datastream, the second parameter can be either 0 or 64.
2288
2289 The png_set_compression_*() functions interface to the zlib compression
2290 library, and should mostly be ignored unless you really know what you are
2291 doing.  The only generally useful call is png_set_compression_level()
2292 which changes how much time zlib spends on trying to compress the image
2293 data.  See the Compression Library (zlib.h and algorithm.txt, distributed
2294 with zlib) for details on the compression levels.
2295
2296     #include zlib.h
2297
2298     /* set the zlib compression level */
2299     png_set_compression_level(png_ptr,
2300         Z_BEST_COMPRESSION);
2301
2302     /* set other zlib parameters */
2303     png_set_compression_mem_level(png_ptr, 8);
2304     png_set_compression_strategy(png_ptr,
2305         Z_DEFAULT_STRATEGY);
2306     png_set_compression_window_bits(png_ptr, 15);
2307     png_set_compression_method(png_ptr, 8);
2308     png_set_compression_buffer_size(png_ptr, 8192)
2309
2310 extern PNG_EXPORT(void,png_set_zbuf_size)
2311
2312 Setting the contents of info for output
2313
2314 You now need to fill in the png_info structure with all the data you
2315 wish to write before the actual image.  Note that the only thing you
2316 are allowed to write after the image is the text chunks and the time
2317 chunk (as of PNG Specification 1.2, anyway).  See png_write_end() and
2318 the latest PNG specification for more information on that.  If you
2319 wish to write them before the image, fill them in now, and flag that
2320 data as being valid.  If you want to wait until after the data, don't
2321 fill them until png_write_end().  For all the fields in png_info and
2322 their data types, see png.h.  For explanations of what the fields
2323 contain, see the PNG specification.
2324
2325 Some of the more important parts of the png_info are:
2326
2327     png_set_IHDR(png_ptr, info_ptr, width, height,
2328        bit_depth, color_type, interlace_type,
2329        compression_type, filter_method)
2330
2331     width          - holds the width of the image
2332                      in pixels (up to 2^31).
2333
2334     height         - holds the height of the image
2335                      in pixels (up to 2^31).
2336
2337     bit_depth      - holds the bit depth of one of the
2338                      image channels.
2339                      (valid values are 1, 2, 4, 8, 16
2340                      and depend also on the
2341                      color_type.  See also significant
2342                      bits (sBIT) below).
2343
2344     color_type     - describes which color/alpha
2345                      channels are present.
2346                      PNG_COLOR_TYPE_GRAY
2347                         (bit depths 1, 2, 4, 8, 16)
2348                      PNG_COLOR_TYPE_GRAY_ALPHA
2349                         (bit depths 8, 16)
2350                      PNG_COLOR_TYPE_PALETTE
2351                         (bit depths 1, 2, 4, 8)
2352                      PNG_COLOR_TYPE_RGB
2353                         (bit_depths 8, 16)
2354                      PNG_COLOR_TYPE_RGB_ALPHA
2355                         (bit_depths 8, 16)
2356
2357                      PNG_COLOR_MASK_PALETTE
2358                      PNG_COLOR_MASK_COLOR
2359                      PNG_COLOR_MASK_ALPHA
2360
2361     interlace_type - PNG_INTERLACE_NONE or
2362                      PNG_INTERLACE_ADAM7
2363
2364     compression_type - (must be
2365                      PNG_COMPRESSION_TYPE_DEFAULT)
2366
2367     filter_method  - (must be PNG_FILTER_TYPE_DEFAULT
2368                      or, if you are writing a PNG to
2369                      be embedded in a MNG datastream,
2370                      can also be
2371                      PNG_INTRAPIXEL_DIFFERENCING)
2372
2373 If you call png_set_IHDR(), the call must appear before any of the
2374 other png_set_*() functions, because they might require access to some of
2375 the IHDR settings.  The remaining png_set_*() functions can be called
2376 in any order.
2377
2378 If you wish, you can reset the compression_type, interlace_type, or
2379 filter_method later by calling png_set_IHDR() again; if you do this, the
2380 width, height, bit_depth, and color_type must be the same in each call.
2381
2382     png_set_PLTE(png_ptr, info_ptr, palette,
2383        num_palette);
2384
2385     palette        - the palette for the file
2386                      (array of png_color)
2387     num_palette    - number of entries in the palette
2388
2389     png_set_gAMA(png_ptr, info_ptr, file_gamma);
2390     png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
2391
2392     file_gamma     - the gamma at which the image was
2393                      created (PNG_INFO_gAMA)
2394
2395     int_file_gamma - 100,000 times the gamma at which
2396                      the image was created
2397
2398     png_set_sRGB(png_ptr, info_ptr, srgb_intent);
2399
2400     srgb_intent    - the rendering intent
2401                      (PNG_INFO_sRGB) The presence of
2402                      the sRGB chunk means that the pixel
2403                      data is in the sRGB color space.
2404                      This chunk also implies specific
2405                      values of gAMA and cHRM.  Rendering
2406                      intent is the CSS-1 property that
2407                      has been defined by the International
2408                      Color Consortium
2409                      (http://www.color.org).
2410                      It can be one of
2411                      PNG_sRGB_INTENT_SATURATION,
2412                      PNG_sRGB_INTENT_PERCEPTUAL,
2413                      PNG_sRGB_INTENT_ABSOLUTE, or
2414                      PNG_sRGB_INTENT_RELATIVE.
2415
2416
2417     png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr,
2418        srgb_intent);
2419
2420     srgb_intent    - the rendering intent
2421                      (PNG_INFO_sRGB) The presence of the
2422                      sRGB chunk means that the pixel
2423                      data is in the sRGB color space.
2424                      This function also causes gAMA and
2425                      cHRM chunks with the specific values
2426                      that are consistent with sRGB to be
2427                      written.
2428
2429     png_set_iCCP(png_ptr, info_ptr, name, compression_type,
2430                        profile, proflen);
2431
2432     name             - The profile name.
2433
2434     compression_type - The compression type; always
2435                        PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
2436                        You may give NULL to this argument to
2437                        ignore it.
2438
2439     profile          - International Color Consortium color
2440                        profile data. May contain NULs.
2441
2442     proflen          - length of profile data in bytes.
2443
2444     png_set_sBIT(png_ptr, info_ptr, sig_bit);
2445
2446     sig_bit        - the number of significant bits for
2447                      (PNG_INFO_sBIT) each of the gray, red,
2448                      green, and blue channels, whichever are
2449                      appropriate for the given color type
2450                      (png_color_16)
2451
2452     png_set_tRNS(png_ptr, info_ptr, trans_alpha,
2453        num_trans, trans_color);
2454
2455     trans_alpha    - array of alpha (transparency)
2456                      entries for palette (PNG_INFO_tRNS)
2457
2458     trans_color    - graylevel or color sample values
2459                      (in order red, green, blue) of the
2460                      single transparent color for
2461                      non-paletted images (PNG_INFO_tRNS)
2462
2463     num_trans      - number of transparent entries
2464                      (PNG_INFO_tRNS)
2465
2466     png_set_hIST(png_ptr, info_ptr, hist);
2467
2468     hist           - histogram of palette (array of
2469                      png_uint_16) (PNG_INFO_hIST)
2470
2471     png_set_tIME(png_ptr, info_ptr, mod_time);
2472
2473     mod_time       - time image was last modified
2474                      (PNG_VALID_tIME)
2475
2476     png_set_bKGD(png_ptr, info_ptr, background);
2477
2478     background     - background color (PNG_VALID_bKGD)
2479
2480     png_set_text(png_ptr, info_ptr, text_ptr, num_text);
2481
2482     text_ptr       - array of png_text holding image
2483                      comments
2484
2485     text_ptr[i].compression - type of compression used
2486                  on "text" PNG_TEXT_COMPRESSION_NONE
2487                            PNG_TEXT_COMPRESSION_zTXt
2488                            PNG_ITXT_COMPRESSION_NONE
2489                            PNG_ITXT_COMPRESSION_zTXt
2490     text_ptr[i].key   - keyword for comment.  Must contain
2491                  1-79 characters.
2492     text_ptr[i].text  - text comments for current
2493                          keyword.  Can be NULL or empty.
2494     text_ptr[i].text_length - length of text string,
2495                  after decompression, 0 for iTXt
2496     text_ptr[i].itxt_length - length of itxt string,
2497                  after decompression, 0 for tEXt/zTXt
2498     text_ptr[i].lang  - language of comment (NULL or
2499                          empty for unknown).
2500     text_ptr[i].translated_keyword  - keyword in UTF-8 (NULL
2501                          or empty for unknown).
2502     Note that the itxt_length, lang, and lang_key
2503     members of the text_ptr structure only exist
2504     when the library is built with iTXt chunk support.
2505
2506     num_text       - number of comments
2507
2508     png_set_sPLT(png_ptr, info_ptr, &palette_ptr,
2509        num_spalettes);
2510
2511     palette_ptr    - array of png_sPLT_struct structures
2512                      to be added to the list of palettes
2513                      in the info structure.
2514     num_spalettes  - number of palette structures to be
2515                      added.
2516
2517     png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y,
2518         unit_type);
2519
2520     offset_x  - positive offset from the left
2521                      edge of the screen
2522
2523     offset_y  - positive offset from the top
2524                      edge of the screen
2525
2526     unit_type - PNG_OFFSET_PIXEL, PNG_OFFSET_MICROMETER
2527
2528     png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
2529         unit_type);
2530
2531     res_x       - pixels/unit physical resolution
2532                   in x direction
2533
2534     res_y       - pixels/unit physical resolution
2535                   in y direction
2536
2537     unit_type   - PNG_RESOLUTION_UNKNOWN,
2538                   PNG_RESOLUTION_METER
2539
2540     png_set_sCAL(png_ptr, info_ptr, unit, width, height)
2541
2542     unit        - physical scale units (an integer)
2543
2544     width       - width of a pixel in physical scale units
2545
2546     height      - height of a pixel in physical scale units
2547                   (width and height are doubles)
2548
2549     png_set_sCAL_s(png_ptr, info_ptr, unit, width, height)
2550
2551     unit        - physical scale units (an integer)
2552
2553     width       - width of a pixel in physical scale units
2554
2555     height      - height of a pixel in physical scale units
2556                  (width and height are strings like "2.54")
2557
2558     png_set_unknown_chunks(png_ptr, info_ptr, &unknowns,
2559        num_unknowns)
2560
2561     unknowns          - array of png_unknown_chunk
2562                         structures holding unknown chunks
2563     unknowns[i].name  - name of unknown chunk
2564     unknowns[i].data  - data of unknown chunk
2565     unknowns[i].size  - size of unknown chunk's data
2566     unknowns[i].location - position to write chunk in file
2567                            0: do not write chunk
2568                            PNG_HAVE_IHDR: before PLTE
2569                            PNG_HAVE_PLTE: before IDAT
2570                            PNG_AFTER_IDAT: after IDAT
2571
2572 The "location" member is set automatically according to
2573 what part of the output file has already been written.
2574 You can change its value after calling png_set_unknown_chunks()
2575 as demonstrated in pngtest.c.  Within each of the "locations",
2576 the chunks are sequenced according to their position in the
2577 structure (that is, the value of "i", which is the order in which
2578 the chunk was either read from the input file or defined with
2579 png_set_unknown_chunks).
2580
2581 A quick word about text and num_text.  text is an array of png_text
2582 structures.  num_text is the number of valid structures in the array.
2583 Each png_text structure holds a language code, a keyword, a text value,
2584 and a compression type.
2585
2586 The compression types have the same valid numbers as the compression
2587 types of the image data.  Currently, the only valid number is zero.
2588 However, you can store text either compressed or uncompressed, unlike
2589 images, which always have to be compressed.  So if you don't want the
2590 text compressed, set the compression type to PNG_TEXT_COMPRESSION_NONE.
2591 Because tEXt and zTXt chunks don't have a language field, if you
2592 specify PNG_TEXT_COMPRESSION_NONE or PNG_TEXT_COMPRESSION_zTXt
2593 any language code or translated keyword will not be written out.
2594
2595 Until text gets around 1000 bytes, it is not worth compressing it.
2596 After the text has been written out to the file, the compression type
2597 is set to PNG_TEXT_COMPRESSION_NONE_WR or PNG_TEXT_COMPRESSION_zTXt_WR,
2598 so that it isn't written out again at the end (in case you are calling
2599 png_write_end() with the same struct).
2600
2601 The keywords that are given in the PNG Specification are:
2602
2603     Title            Short (one line) title or
2604                      caption for image
2605
2606     Author           Name of image's creator
2607
2608     Description      Description of image (possibly long)
2609
2610     Copyright        Copyright notice
2611
2612     Creation Time    Time of original image creation
2613                      (usually RFC 1123 format, see below)
2614
2615     Software         Software used to create the image
2616
2617     Disclaimer       Legal disclaimer
2618
2619     Warning          Warning of nature of content
2620
2621     Source           Device used to create the image
2622
2623     Comment          Miscellaneous comment; conversion
2624                      from other image format
2625
2626 The keyword-text pairs work like this.  Keywords should be short
2627 simple descriptions of what the comment is about.  Some typical
2628 keywords are found in the PNG specification, as is some recommendations
2629 on keywords.  You can repeat keywords in a file.  You can even write
2630 some text before the image and some after.  For example, you may want
2631 to put a description of the image before the image, but leave the
2632 disclaimer until after, so viewers working over modem connections
2633 don't have to wait for the disclaimer to go over the modem before
2634 they start seeing the image.  Finally, keywords should be full
2635 words, not abbreviations.  Keywords and text are in the ISO 8859-1
2636 (Latin-1) character set (a superset of regular ASCII) and can not
2637 contain NUL characters, and should not contain control or other
2638 unprintable characters.  To make the comments widely readable, stick
2639 with basic ASCII, and avoid machine specific character set extensions
2640 like the IBM-PC character set.  The keyword must be present, but
2641 you can leave off the text string on non-compressed pairs.
2642 Compressed pairs must have a text string, as only the text string
2643 is compressed anyway, so the compression would be meaningless.
2644
2645 PNG supports modification time via the png_time structure.  Two
2646 conversion routines are provided, png_convert_from_time_t() for
2647 time_t and png_convert_from_struct_tm() for struct tm.  The
2648 time_t routine uses gmtime().  You don't have to use either of
2649 these, but if you wish to fill in the png_time structure directly,
2650 you should provide the time in universal time (GMT) if possible
2651 instead of your local time.  Note that the year number is the full
2652 year (e.g. 1998, rather than 98 - PNG is year 2000 compliant!), and
2653 that months start with 1.
2654
2655 If you want to store the time of the original image creation, you should
2656 use a plain tEXt chunk with the "Creation Time" keyword.  This is
2657 necessary because the "creation time" of a PNG image is somewhat vague,
2658 depending on whether you mean the PNG file, the time the image was
2659 created in a non-PNG format, a still photo from which the image was
2660 scanned, or possibly the subject matter itself.  In order to facilitate
2661 machine-readable dates, it is recommended that the "Creation Time"
2662 tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
2663 although this isn't a requirement.  Unlike the tIME chunk, the
2664 "Creation Time" tEXt chunk is not expected to be automatically changed
2665 by the software.  To facilitate the use of RFC 1123 dates, a function
2666 png_convert_to_rfc1123(png_timep) is provided to convert from PNG
2667 time to an RFC 1123 format string.
2668
2669 Writing unknown chunks
2670
2671 You can use the png_set_unknown_chunks function to queue up chunks
2672 for writing.  You give it a chunk name, raw data, and a size; that's
2673 all there is to it.  The chunks will be written by the next following
2674 png_write_info_before_PLTE, png_write_info, or png_write_end function.
2675 Any chunks previously read into the info structure's unknown-chunk
2676 list will also be written out in a sequence that satisfies the PNG
2677 specification's ordering rules.
2678
2679 The high-level write interface
2680
2681 At this point there are two ways to proceed; through the high-level
2682 write interface, or through a sequence of low-level write operations.
2683 You can use the high-level interface if your image data is present
2684 in the info structure.  All defined output
2685 transformations are permitted, enabled by the following masks.
2686
2687     PNG_TRANSFORM_IDENTITY      No transformation
2688     PNG_TRANSFORM_PACKING       Pack 1, 2 and 4-bit samples
2689     PNG_TRANSFORM_PACKSWAP      Change order of packed
2690                                 pixels to LSB first
2691     PNG_TRANSFORM_INVERT_MONO   Invert monochrome images
2692     PNG_TRANSFORM_SHIFT         Normalize pixels to the
2693                                 sBIT depth
2694     PNG_TRANSFORM_BGR           Flip RGB to BGR, RGBA
2695                                 to BGRA
2696     PNG_TRANSFORM_SWAP_ALPHA    Flip RGBA to ARGB or GA
2697                                 to AG
2698     PNG_TRANSFORM_INVERT_ALPHA  Change alpha from opacity
2699                                 to transparency
2700     PNG_TRANSFORM_SWAP_ENDIAN   Byte-swap 16-bit samples
2701     PNG_TRANSFORM_STRIP_FILLER        Strip out filler
2702                                       bytes (deprecated).
2703     PNG_TRANSFORM_STRIP_FILLER_BEFORE Strip out leading
2704                                       filler bytes
2705     PNG_TRANSFORM_STRIP_FILLER_AFTER  Strip out trailing
2706                                       filler bytes
2707
2708 If you have valid image data in the info structure (you can use
2709 png_set_rows() to put image data in the info structure), simply do this:
2710
2711     png_write_png(png_ptr, info_ptr, png_transforms, NULL)
2712
2713 where png_transforms is an integer containing the bitwise OR of some set of
2714 transformation flags.  This call is equivalent to png_write_info(),
2715 followed the set of transformations indicated by the transform mask,
2716 then png_write_image(), and finally png_write_end().
2717
2718 (The final parameter of this call is not yet used.  Someday it might point
2719 to transformation parameters required by some future output transform.)
2720
2721 You must use png_transforms and not call any png_set_transform() functions
2722 when you use png_write_png().
2723
2724 The low-level write interface
2725
2726 If you are going the low-level route instead, you are now ready to
2727 write all the file information up to the actual image data.  You do
2728 this with a call to png_write_info().
2729
2730     png_write_info(png_ptr, info_ptr);
2731
2732 Note that there is one transformation you may need to do before
2733 png_write_info().  In PNG files, the alpha channel in an image is the
2734 level of opacity.  If your data is supplied as a level of transparency,
2735 you can invert the alpha channel before you write it, so that 0 is
2736 fully transparent and 255 (in 8-bit or paletted images) or 65535
2737 (in 16-bit images) is fully opaque, with
2738
2739     png_set_invert_alpha(png_ptr);
2740
2741 This must appear before png_write_info() instead of later with the
2742 other transformations because in the case of paletted images the tRNS
2743 chunk data has to be inverted before the tRNS chunk is written.  If
2744 your image is not a paletted image, the tRNS data (which in such cases
2745 represents a single color to be rendered as transparent) won't need to
2746 be changed, and you can safely do this transformation after your
2747 png_write_info() call.
2748
2749 If you need to write a private chunk that you want to appear before
2750 the PLTE chunk when PLTE is present, you can write the PNG info in
2751 two steps, and insert code to write your own chunk between them:
2752
2753     png_write_info_before_PLTE(png_ptr, info_ptr);
2754     png_set_unknown_chunks(png_ptr, info_ptr, ...);
2755     png_write_info(png_ptr, info_ptr);
2756
2757 After you've written the file information, you can set up the library
2758 to handle any special transformations of the image data.  The various
2759 ways to transform the data will be described in the order that they
2760 should occur.  This is important, as some of these change the color
2761 type and/or bit depth of the data, and some others only work on
2762 certain color types and bit depths.  Even though each transformation
2763 checks to see if it has data that it can do something with, you should
2764 make sure to only enable a transformation if it will be valid for the
2765 data.  For example, don't swap red and blue on grayscale data.
2766
2767 PNG files store RGB pixels packed into 3 or 6 bytes.  This code tells
2768 the library to strip input data that has 4 or 8 bytes per pixel down
2769 to 3 or 6 bytes (or strip 2 or 4-byte grayscale+filler data to 1 or 2
2770 bytes per pixel).
2771
2772     png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
2773
2774 where the 0 is unused, and the location is either PNG_FILLER_BEFORE or
2775 PNG_FILLER_AFTER, depending upon whether the filler byte in the pixel
2776 is stored XRGB or RGBX.
2777
2778 PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
2779 they can, resulting in, for example, 8 pixels per byte for 1 bit files.
2780 If the data is supplied at 1 pixel per byte, use this code, which will
2781 correctly pack the pixels into a single byte:
2782
2783     png_set_packing(png_ptr);
2784
2785 PNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your
2786 data is of another bit depth, you can write an sBIT chunk into the
2787 file so that decoders can recover the original data if desired.
2788
2789     /* Set the true bit depth of the image data */
2790     if (color_type & PNG_COLOR_MASK_COLOR)
2791     {
2792        sig_bit.red = true_bit_depth;
2793        sig_bit.green = true_bit_depth;
2794        sig_bit.blue = true_bit_depth;
2795     }
2796
2797     else
2798     {
2799        sig_bit.gray = true_bit_depth;
2800     }
2801
2802     if (color_type & PNG_COLOR_MASK_ALPHA)
2803     {
2804        sig_bit.alpha = true_bit_depth;
2805     }
2806
2807     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2808
2809 If the data is stored in the row buffer in a bit depth other than
2810 one supported by PNG (e.g. 3 bit data in the range 0-7 for a 4-bit PNG),
2811 this will scale the values to appear to be the correct bit depth as
2812 is required by PNG.
2813
2814     png_set_shift(png_ptr, &sig_bit);
2815
2816 PNG files store 16 bit pixels in network byte order (big-endian,
2817 ie. most significant bits first).  This code would be used if they are
2818 supplied the other way (little-endian, i.e. least significant bits
2819 first, the way PCs store them):
2820
2821     if (bit_depth > 8)
2822        png_set_swap(png_ptr);
2823
2824 If you are using packed-pixel images (1, 2, or 4 bits/pixel), and you
2825 need to change the order the pixels are packed into bytes, you can use:
2826
2827     if (bit_depth < 8)
2828        png_set_packswap(png_ptr);
2829
2830 PNG files store 3 color pixels in red, green, blue order.  This code
2831 would be used if they are supplied as blue, green, red:
2832
2833     png_set_bgr(png_ptr);
2834
2835 PNG files describe monochrome as black being zero and white being
2836 one. This code would be used if the pixels are supplied with this reversed
2837 (black being one and white being zero):
2838
2839     png_set_invert_mono(png_ptr);
2840
2841 Finally, you can write your own transformation function if none of
2842 the existing ones meets your needs.  This is done by setting a callback
2843 with
2844
2845     png_set_write_user_transform_fn(png_ptr,
2846        write_transform_fn);
2847
2848 You must supply the function
2849
2850     void write_transform_fn(png_structp png_ptr, png_row_infop
2851        row_info, png_bytep data)
2852
2853 See pngtest.c for a working example.  Your function will be called
2854 before any of the other transformations are processed.  If supported
2855 libpng also supplies an information routine that may be called from
2856 your callback:
2857
2858    png_get_current_row_number(png_ptr);
2859    png_get_current_pass_number(png_ptr);
2860
2861 This returns the current row passed to the transform.  With interlaced
2862 images the value returned is the row in the input sub-image image.  Use
2863 PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
2864 find the output pixel (x,y) given an interlaced sub-image pixel (row,col,pass).
2865
2866 The discussion of interlace handling above contains more information on how to
2867 use these values.
2868
2869 You can also set up a pointer to a user structure for use by your
2870 callback function.
2871
2872     png_set_user_transform_info(png_ptr, user_ptr, 0, 0);
2873
2874 The user_channels and user_depth parameters of this function are ignored
2875 when writing; you can set them to zero as shown.
2876
2877 You can retrieve the pointer via the function png_get_user_transform_ptr().
2878 For example:
2879
2880     voidp write_user_transform_ptr =
2881        png_get_user_transform_ptr(png_ptr);
2882
2883 It is possible to have libpng flush any pending output, either manually,
2884 or automatically after a certain number of lines have been written.  To
2885 flush the output stream a single time call:
2886
2887     png_write_flush(png_ptr);
2888
2889 and to have libpng flush the output stream periodically after a certain
2890 number of scanlines have been written, call:
2891
2892     png_set_flush(png_ptr, nrows);
2893
2894 Note that the distance between rows is from the last time png_write_flush()
2895 was called, or the first row of the image if it has never been called.
2896 So if you write 50 lines, and then png_set_flush 25, it will flush the
2897 output on the next scanline, and every 25 lines thereafter, unless
2898 png_write_flush() is called before 25 more lines have been written.
2899 If nrows is too small (less than about 10 lines for a 640 pixel wide
2900 RGB image) the image compression may decrease noticeably (although this
2901 may be acceptable for real-time applications).  Infrequent flushing will
2902 only degrade the compression performance by a few percent over images
2903 that do not use flushing.
2904
2905 Writing the image data
2906
2907 That's it for the transformations.  Now you can write the image data.
2908 The simplest way to do this is in one function call.  If you have the
2909 whole image in memory, you can just call png_write_image() and libpng
2910 will write the image.  You will need to pass in an array of pointers to
2911 each row.  This function automatically handles interlacing, so you don't
2912 need to call png_set_interlace_handling() or call this function multiple
2913 times, or any of that other stuff necessary with png_write_rows().
2914
2915     png_write_image(png_ptr, row_pointers);
2916
2917 where row_pointers is:
2918
2919     png_byte *row_pointers[height];
2920
2921 You can point to void or char or whatever you use for pixels.
2922
2923 If you don't want to write the whole image at once, you can
2924 use png_write_rows() instead.  If the file is not interlaced,
2925 this is simple:
2926
2927     png_write_rows(png_ptr, row_pointers,
2928        number_of_rows);
2929
2930 row_pointers is the same as in the png_write_image() call.
2931
2932 If you are just writing one row at a time, you can do this with
2933 a single row_pointer instead of an array of row_pointers:
2934
2935     png_bytep row_pointer = row;
2936
2937     png_write_row(png_ptr, row_pointer);
2938
2939 When the file is interlaced, things can get a good deal more complicated.
2940 The only currently (as of the PNG Specification version 1.2, dated July
2941 1999) defined interlacing scheme for PNG files is the "Adam7" interlace
2942 scheme, that breaks down an image into seven smaller images of varying
2943 size.  libpng will build these images for you, or you can do them
2944 yourself.  If you want to build them yourself, see the PNG specification
2945 for details of which pixels to write when.
2946
2947 If you don't want libpng to handle the interlacing details, just
2948 use png_set_interlace_handling() and call png_write_rows() the
2949 correct number of times to write all the sub-images
2950 (png_set_interlace_handling() returns the number of sub-images.)
2951
2952 If you want libpng to build the sub-images, call this before you start
2953 writing any rows:
2954
2955     number_of_passes = png_set_interlace_handling(png_ptr);
2956
2957 This will return the number of passes needed.  Currently, this is seven,
2958 but may change if another interlace type is added.
2959
2960 Then write the complete image number_of_passes times.
2961
2962     png_write_rows(png_ptr, row_pointers, number_of_rows);
2963
2964 Think carefully before you write an interlaced image.  Typically code that
2965 reads such images reads all the image data into memory, uncompressed, before
2966 doing any processing.  Only code that can display an image on the fly can
2967 take advantage of the interlacing and even then the image has to be exactly
2968 the correct size for the output device, because scaling an image requires
2969 adjacent pixels and these are not available until all the passes have been
2970 read.
2971
2972 If you do write an interlaced image you will hardly ever need to handle
2973 the interlacing yourself.  Call png_set_interlace_handling() and use the
2974 approach described above.
2975
2976 The only time it is conceivable that you will really need to write an
2977 interlaced image pass-by-pass is when you have read one pass by pass and
2978 made some pixel-by-pixel transformation to it, as described in the read
2979 code above.  In this case use the PNG_PASS_ROWS and PNG_PASS_COLS macros
2980 to determine the size of each sub-image in turn and simply write the rows
2981 you obtained from the read code.
2982
2983 Finishing a sequential write
2984
2985 After you are finished writing the image, you should finish writing
2986 the file.  If you are interested in writing comments or time, you should
2987 pass an appropriately filled png_info pointer.  If you are not interested,
2988 you can pass NULL.
2989
2990     png_write_end(png_ptr, info_ptr);
2991
2992 When you are done, you can free all memory used by libpng like this:
2993
2994     png_destroy_write_struct(&png_ptr, &info_ptr);
2995
2996 It is also possible to individually free the info_ptr members that
2997 point to libpng-allocated storage with the following function:
2998
2999     png_free_data(png_ptr, info_ptr, mask, seq)
3000
3001     mask  - identifies data to be freed, a mask
3002             containing the bitwise OR of one or
3003             more of
3004               PNG_FREE_PLTE, PNG_FREE_TRNS,
3005               PNG_FREE_HIST, PNG_FREE_ICCP,
3006               PNG_FREE_PCAL, PNG_FREE_ROWS,
3007               PNG_FREE_SCAL, PNG_FREE_SPLT,
3008               PNG_FREE_TEXT, PNG_FREE_UNKN,
3009             or simply PNG_FREE_ALL
3010
3011     seq   - sequence number of item to be freed
3012             (-1 for all items)
3013
3014 This function may be safely called when the relevant storage has
3015 already been freed, or has not yet been allocated, or was allocated
3016 by the user  and not by libpng,  and will in those cases do nothing.
3017 The "seq" parameter is ignored if only one item of the selected data
3018 type, such as PLTE, is allowed.  If "seq" is not -1, and multiple items
3019 are allowed for the data type identified in the mask, such as text or
3020 sPLT, only the n'th item in the structure is freed, where n is "seq".
3021
3022 If you allocated data such as a palette that you passed in to libpng
3023 with png_set_*, you must not free it until just before the call to
3024 png_destroy_write_struct().
3025
3026 The default behavior is only to free data that was allocated internally
3027 by libpng.  This can be changed, so that libpng will not free the data,
3028 or so that it will free data that was allocated by the user with png_malloc()
3029 or png_zalloc() and passed in via a png_set_*() function, with
3030
3031     png_data_freer(png_ptr, info_ptr, freer, mask)
3032
3033     freer  - one of
3034                PNG_DESTROY_WILL_FREE_DATA
3035                PNG_SET_WILL_FREE_DATA
3036                PNG_USER_WILL_FREE_DATA
3037
3038     mask   - which data elements are affected
3039              same choices as in png_free_data()
3040
3041 For example, to transfer responsibility for some data from a read structure
3042 to a write structure, you could use
3043
3044     png_data_freer(read_ptr, read_info_ptr,
3045        PNG_USER_WILL_FREE_DATA,
3046        PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
3047
3048     png_data_freer(write_ptr, write_info_ptr,
3049        PNG_DESTROY_WILL_FREE_DATA,
3050        PNG_FREE_PLTE|PNG_FREE_tRNS|PNG_FREE_hIST)
3051
3052 thereby briefly reassigning responsibility for freeing to the user but
3053 immediately afterwards reassigning it once more to the write_destroy
3054 function.  Having done this, it would then be safe to destroy the read
3055 structure and continue to use the PLTE, tRNS, and hIST data in the write
3056 structure.
3057
3058 This function only affects data that has already been allocated.
3059 You can call this function before calling after the png_set_*() functions
3060 to control whether the user or png_destroy_*() is supposed to free the data.
3061 When the user assumes responsibility for libpng-allocated data, the
3062 application must use
3063 png_free() to free it, and when the user transfers responsibility to libpng
3064 for data that the user has allocated, the user must have used png_malloc()
3065 or png_zalloc() to allocate it.
3066
3067 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
3068 separately, do not transfer responsibility for freeing text_ptr to libpng,
3069 because when libpng fills a png_text structure it combines these members with
3070 the key member, and png_free_data() will free only text_ptr.key.  Similarly,
3071 if you transfer responsibility for free'ing text_ptr from libpng to your
3072 application, your application must not separately free those members.
3073 For a more compact example of writing a PNG image, see the file example.c.
3074
3075 V. Modifying/Customizing libpng:
3076
3077 There are two issues here.  The first is changing how libpng does
3078 standard things like memory allocation, input/output, and error handling.
3079 The second deals with more complicated things like adding new chunks,
3080 adding new transformations, and generally changing how libpng works.
3081 Both of those are compile-time issues; that is, they are generally
3082 determined at the time the code is written, and there is rarely a need
3083 to provide the user with a means of changing them.
3084
3085 Memory allocation, input/output, and error handling
3086
3087 All of the memory allocation, input/output, and error handling in libpng
3088 goes through callbacks that are user-settable.  The default routines are
3089 in pngmem.c, pngrio.c, pngwio.c, and pngerror.c, respectively.  To change
3090 these functions, call the appropriate png_set_*_fn() function.
3091
3092 Memory allocation is done through the functions png_malloc(), png_calloc(),
3093 and png_free().  These currently just call the standard C functions.
3094 png_calloc() calls png_malloc() and then clears the newly
3095 allocated memory to zero.  There is limited support for certain systems
3096 with segmented memory architectures and the types of pointers declared by
3097 png.h match this; you will have to use appropriate pointers in your
3098 application.  Since it is
3099 unlikely that the method of handling memory allocation on a platform
3100 will change between applications, these functions must be modified in
3101 the library at compile time.  If you prefer to use a different method
3102 of allocating and freeing data, you can use png_create_read_struct_2() or
3103 png_create_write_struct_2() to register your own functions as described
3104 above.  These functions also provide a void pointer that can be retrieved
3105 via
3106
3107     mem_ptr=png_get_mem_ptr(png_ptr);
3108
3109 Your replacement memory functions must have prototypes as follows:
3110
3111     png_voidp malloc_fn(png_structp png_ptr,
3112        png_alloc_size_t size);
3113
3114     void free_fn(png_structp png_ptr, png_voidp ptr);
3115
3116 Your malloc_fn() must return NULL in case of failure.  The png_malloc()
3117 function will normally call png_error() if it receives a NULL from the
3118 system memory allocator or from your replacement malloc_fn().
3119
3120 Your free_fn() will never be called with a NULL ptr, since libpng's
3121 png_free() checks for NULL before calling free_fn().
3122
3123 Input/Output in libpng is done through png_read() and png_write(),
3124 which currently just call fread() and fwrite().  The FILE * is stored in
3125 png_struct and is initialized via png_init_io().  If you wish to change
3126 the method of I/O, the library supplies callbacks that you can set
3127 through the function png_set_read_fn() and png_set_write_fn() at run
3128 time, instead of calling the png_init_io() function.  These functions
3129 also provide a void pointer that can be retrieved via the function
3130 png_get_io_ptr().  For example:
3131
3132     png_set_read_fn(png_structp read_ptr,
3133         voidp read_io_ptr, png_rw_ptr read_data_fn)
3134
3135     png_set_write_fn(png_structp write_ptr,
3136         voidp write_io_ptr, png_rw_ptr write_data_fn,
3137         png_flush_ptr output_flush_fn);
3138
3139     voidp read_io_ptr = png_get_io_ptr(read_ptr);
3140     voidp write_io_ptr = png_get_io_ptr(write_ptr);
3141
3142 The replacement I/O functions must have prototypes as follows:
3143
3144     void user_read_data(png_structp png_ptr,
3145         png_bytep data, png_size_t length);
3146
3147     void user_write_data(png_structp png_ptr,
3148         png_bytep data, png_size_t length);
3149
3150     void user_flush_data(png_structp png_ptr);
3151
3152 The user_read_data() function is responsible for detecting and
3153 handling end-of-data errors.
3154
3155 Supplying NULL for the read, write, or flush functions sets them back
3156 to using the default C stream functions, which expect the io_ptr to
3157 point to a standard *FILE structure.  It is probably a mistake
3158 to use NULL for one of write_data_fn and output_flush_fn but not both
3159 of them, unless you have built libpng with PNG_NO_WRITE_FLUSH defined.
3160 It is an error to read from a write stream, and vice versa.
3161
3162 Error handling in libpng is done through png_error() and png_warning().
3163 Errors handled through png_error() are fatal, meaning that png_error()
3164 should never return to its caller.  Currently, this is handled via
3165 setjmp() and longjmp() (unless you have compiled libpng with
3166 PNG_NO_SETJMP, in which case it is handled via PNG_ABORT()),
3167 but you could change this to do things like exit() if you should wish,
3168 as long as your function does not return.
3169
3170 On non-fatal errors, png_warning() is called
3171 to print a warning message, and then control returns to the calling code.
3172 By default png_error() and png_warning() print a message on stderr via
3173 fprintf() unless the library is compiled with PNG_NO_CONSOLE_IO defined
3174 (because you don't want the messages) or PNG_NO_STDIO defined (because
3175 fprintf() isn't available).  If you wish to change the behavior of the error
3176 functions, you will need to set up your own message callbacks.  These
3177 functions are normally supplied at the time that the png_struct is created.
3178 It is also possible to redirect errors and warnings to your own replacement
3179 functions after png_create_*_struct() has been called by calling:
3180
3181     png_set_error_fn(png_structp png_ptr,
3182         png_voidp error_ptr, png_error_ptr error_fn,
3183         png_error_ptr warning_fn);
3184
3185     png_voidp error_ptr = png_get_error_ptr(png_ptr);
3186
3187 If NULL is supplied for either error_fn or warning_fn, then the libpng
3188 default function will be used, calling fprintf() and/or longjmp() if a
3189 problem is encountered.  The replacement error functions should have
3190 parameters as follows:
3191
3192     void user_error_fn(png_structp png_ptr,
3193         png_const_charp error_msg);
3194
3195     void user_warning_fn(png_structp png_ptr,
3196         png_const_charp warning_msg);
3197
3198 The motivation behind using setjmp() and longjmp() is the C++ throw and
3199 catch exception handling methods.  This makes the code much easier to write,
3200 as there is no need to check every return code of every function call.
3201 However, there are some uncertainties about the status of local variables
3202 after a longjmp, so the user may want to be careful about doing anything
3203 after setjmp returns non-zero besides returning itself.  Consult your
3204 compiler documentation for more details.  For an alternative approach, you
3205 may wish to use the "cexcept" facility (see http://cexcept.sourceforge.net).
3206
3207 Custom chunks
3208
3209 If you need to read or write custom chunks, you may need to get deeper
3210 into the libpng code.  The library now has mechanisms for storing
3211 and writing chunks of unknown type; you can even declare callbacks
3212 for custom chunks.  However, this may not be good enough if the
3213 library code itself needs to know about interactions between your
3214 chunk and existing `intrinsic' chunks.
3215
3216 If you need to write a new intrinsic chunk, first read the PNG
3217 specification. Acquire a first level of understanding of how it works.
3218 Pay particular attention to the sections that describe chunk names,
3219 and look at how other chunks were designed, so you can do things
3220 similarly.  Second, check out the sections of libpng that read and
3221 write chunks.  Try to find a chunk that is similar to yours and use
3222 it as a template.  More details can be found in the comments inside
3223 the code.  It is best to handle unknown chunks in a generic method,
3224 via callback functions, instead of by modifying libpng functions.
3225
3226 If you wish to write your own transformation for the data, look through
3227 the part of the code that does the transformations, and check out some of
3228 the simpler ones to get an idea of how they work.  Try to find a similar
3229 transformation to the one you want to add and copy off of it.  More details
3230 can be found in the comments inside the code itself.
3231
3232 Configuring for 16 bit platforms
3233
3234 You will want to look into zconf.h to tell zlib (and thus libpng) that
3235 it cannot allocate more then 64K at a time.  Even if you can, the memory
3236 won't be accessible.  So limit zlib and libpng to 64K by defining MAXSEG_64K.
3237
3238 Configuring for DOS
3239
3240 For DOS users who only have access to the lower 640K, you will
3241 have to limit zlib's memory usage via a png_set_compression_mem_level()
3242 call.  See zlib.h or zconf.h in the zlib library for more information.
3243
3244 Configuring for Medium Model
3245
3246 Libpng's support for medium model has been tested on most of the popular
3247 compilers.  Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
3248 defined, and FAR gets defined to far in pngconf.h, and you should be
3249 all set.  Everything in the library (except for zlib's structure) is
3250 expecting far data.  You must use the typedefs with the p or pp on
3251 the end for pointers (or at least look at them and be careful).  Make
3252 note that the rows of data are defined as png_bytepp, which is an
3253 unsigned char far * far *.
3254
3255 Configuring for gui/windowing platforms:
3256
3257 You will need to write new error and warning functions that use the GUI
3258 interface, as described previously, and set them to be the error and
3259 warning functions at the time that png_create_*_struct() is called,
3260 in order to have them available during the structure initialization.
3261 They can be changed later via png_set_error_fn().  On some compilers,
3262 you may also have to change the memory allocators (png_malloc, etc.).
3263
3264 Configuring for compiler xxx:
3265
3266 All includes for libpng are in pngconf.h.  If you need to add, change
3267 or delete an include, this is the place to do it.
3268 The includes that are not needed outside libpng are placed in pngpriv.h,
3269 which is only used by the routines inside libpng itself.
3270 The files in libpng proper only include pngpriv.h and png.h, which
3271 in turn includes pngconf.h.
3272
3273 Configuring zlib:
3274
3275 There are special functions to configure the compression.  Perhaps the
3276 most useful one changes the compression level, which currently uses
3277 input compression values in the range 0 - 9.  The library normally
3278 uses the default compression level (Z_DEFAULT_COMPRESSION = 6).  Tests
3279 have shown that for a large majority of images, compression values in
3280 the range 3-6 compress nearly as well as higher levels, and do so much
3281 faster.  For online applications it may be desirable to have maximum speed
3282 (Z_BEST_SPEED = 1).  With versions of zlib after v0.99, you can also
3283 specify no compression (Z_NO_COMPRESSION = 0), but this would create
3284 files larger than just storing the raw bitmap.  You can specify the
3285 compression level by calling:
3286
3287     #include zlib.h
3288     png_set_compression_level(png_ptr, level);
3289
3290 Another useful one is to reduce the memory level used by the library.
3291 The memory level defaults to 8, but it can be lowered if you are
3292 short on memory (running DOS, for example, where you only have 640K).
3293 Note that the memory level does have an effect on compression; among
3294 other things, lower levels will result in sections of incompressible
3295 data being emitted in smaller stored blocks, with a correspondingly
3296 larger relative overhead of up to 15% in the worst case.
3297
3298     #include zlib.h
3299     png_set_compression_mem_level(png_ptr, level);
3300
3301 The other functions are for configuring zlib.  They are not recommended
3302 for normal use and may result in writing an invalid PNG file.  See
3303 zlib.h for more information on what these mean.
3304
3305     #include zlib.h
3306     png_set_compression_strategy(png_ptr,
3307         strategy);
3308
3309     png_set_compression_window_bits(png_ptr,
3310         window_bits);
3311
3312     png_set_compression_method(png_ptr, method);
3313     png_set_compression_buffer_size(png_ptr, size);
3314
3315 Controlling row filtering
3316
3317 If you want to control whether libpng uses filtering or not, which
3318 filters are used, and how it goes about picking row filters, you
3319 can call one of these functions.  The selection and configuration
3320 of row filters can have a significant impact on the size and
3321 encoding speed and a somewhat lesser impact on the decoding speed
3322 of an image.  Filtering is enabled by default for RGB and grayscale
3323 images (with and without alpha), but not for paletted images nor
3324 for any images with bit depths less than 8 bits/pixel.
3325
3326 The 'method' parameter sets the main filtering method, which is
3327 currently only '0' in the PNG 1.2 specification.  The 'filters'
3328 parameter sets which filter(s), if any, should be used for each
3329 scanline.  Possible values are PNG_ALL_FILTERS and PNG_NO_FILTERS
3330 to turn filtering on and off, respectively.
3331
3332 Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
3333 PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
3334 ORed together with '|' to specify one or more filters to use.
3335 These filters are described in more detail in the PNG specification.
3336 If you intend to change the filter type during the course of writing
3337 the image, you should start with flags set for all of the filters
3338 you intend to use so that libpng can initialize its internal
3339 structures appropriately for all of the filter types.  (Note that this
3340 means the first row must always be adaptively filtered, because libpng
3341 currently does not allocate the filter buffers until png_write_row()
3342 is called for the first time.)
3343
3344     filters = PNG_FILTER_NONE | PNG_FILTER_SUB
3345               PNG_FILTER_UP | PNG_FILTER_AVG |
3346               PNG_FILTER_PAETH | PNG_ALL_FILTERS;
3347
3348     png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE,
3349        filters);
3350               The second parameter can also be
3351               PNG_INTRAPIXEL_DIFFERENCING if you are
3352               writing a PNG to be embedded in a MNG
3353               datastream.  This parameter must be the
3354               same as the value of filter_method used
3355               in png_set_IHDR().
3356
3357 It is also possible to influence how libpng chooses from among the
3358 available filters.  This is done in one or both of two ways - by
3359 telling it how important it is to keep the same filter for successive
3360 rows, and by telling it the relative computational costs of the filters.
3361
3362     double weights[3] = {1.5, 1.3, 1.1},
3363        costs[PNG_FILTER_VALUE_LAST] =
3364        {1.0, 1.3, 1.3, 1.5, 1.7};
3365
3366     png_set_filter_heuristics(png_ptr,
3367        PNG_FILTER_HEURISTIC_WEIGHTED, 3,
3368        weights, costs);
3369
3370 The weights are multiplying factors that indicate to libpng that the
3371 row filter should be the same for successive rows unless another row filter
3372 is that many times better than the previous filter.  In the above example,
3373 if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
3374 "sum of absolute differences" 1.5 x 1.3 times higher than other filters
3375 and still be chosen, while the NONE filter could have a sum 1.1 times
3376 higher than other filters and still be chosen.  Unspecified weights are
3377 taken to be 1.0, and the specified weights should probably be declining
3378 like those above in order to emphasize recent filters over older filters.
3379
3380 The filter costs specify for each filter type a relative decoding cost
3381 to be considered when selecting row filters.  This means that filters
3382 with higher costs are less likely to be chosen over filters with lower
3383 costs, unless their "sum of absolute differences" is that much smaller.
3384 The costs do not necessarily reflect the exact computational speeds of
3385 the various filters, since this would unduly influence the final image
3386 size.
3387
3388 Note that the numbers above were invented purely for this example and
3389 are given only to help explain the function usage.  Little testing has
3390 been done to find optimum values for either the costs or the weights.
3391
3392 Removing unwanted object code
3393
3394 There are a bunch of #define's in pngconf.h that control what parts of
3395 libpng are compiled.  All the defines end in _SUPPORTED.  If you are
3396 never going to use a capability, you can change the #define to #undef
3397 before recompiling libpng and save yourself code and data space, or
3398 you can turn off individual capabilities with defines that begin with
3399 PNG_NO_.
3400
3401 In libpng-1.5.0 and later, the #define's are in pnglibconf.h instead.
3402
3403 You can also turn all of the transforms and ancillary chunk capabilities
3404 off en masse with compiler directives that define
3405 PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS,
3406 or all four,
3407 along with directives to turn on any of the capabilities that you do
3408 want.  The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable the extra
3409 transformations but still leave the library fully capable of reading
3410 and writing PNG files with all known public chunks. Use of the
3411 PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive produces a library
3412 that is incapable of reading or writing ancillary chunks.  If you are
3413 not using the progressive reading capability, you can turn that off
3414 with PNG_NO_PROGRESSIVE_READ (don't confuse this with the INTERLACING
3415 capability, which you'll still have).
3416
3417 All the reading and writing specific code are in separate files, so the
3418 linker should only grab the files it needs.  However, if you want to
3419 make sure, or if you are building a stand alone library, all the
3420 reading files start with pngr and all the writing files start with
3421 pngw.  The files that don't match either (like png.c, pngtrans.c, etc.)
3422 are used for both reading and writing, and always need to be included.
3423 The progressive reader is in pngpread.c
3424
3425 If you are creating or distributing a dynamically linked library (a .so
3426 or DLL file), you should not remove or disable any parts of the library,
3427 as this will cause applications linked with different versions of the
3428 library to fail if they call functions not available in your library.
3429 The size of the library itself should not be an issue, because only
3430 those sections that are actually used will be loaded into memory.
3431
3432 Requesting debug printout
3433
3434 The macro definition PNG_DEBUG can be used to request debugging
3435 printout.  Set it to an integer value in the range 0 to 3.  Higher
3436 numbers result in increasing amounts of debugging information.  The
3437 information is printed to the "stderr" file, unless another file
3438 name is specified in the PNG_DEBUG_FILE macro definition.
3439
3440 When PNG_DEBUG > 0, the following functions (macros) become available:
3441
3442    png_debug(level, message)
3443    png_debug1(level, message, p1)
3444    png_debug2(level, message, p1, p2)
3445
3446 in which "level" is compared to PNG_DEBUG to decide whether to print
3447 the message, "message" is the formatted string to be printed,
3448 and p1 and p2 are parameters that are to be embedded in the string
3449 according to printf-style formatting directives.  For example,
3450
3451    png_debug1(2, "foo=%d\n", foo);
3452
3453 is expanded to
3454
3455    if (PNG_DEBUG > 2)
3456       fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
3457
3458 When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
3459 can still use PNG_DEBUG to control your own debugging:
3460
3461    #ifdef PNG_DEBUG
3462        fprintf(stderr, ...
3463    #endif
3464
3465 When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
3466 having level = 0 will be printed.  There aren't any such statements in
3467 this version of libpng, but if you insert some they will be printed.
3468
3469 VI.  MNG support
3470
3471 The MNG specification (available at http://www.libpng.org/pub/mng) allows
3472 certain extensions to PNG for PNG images that are embedded in MNG datastreams.
3473 Libpng can support some of these extensions.  To enable them, use the
3474 png_permit_mng_features() function:
3475
3476    feature_set = png_permit_mng_features(png_ptr, mask)
3477
3478    mask is a png_uint_32 containing the bitwise OR of the
3479         features you want to enable.  These include
3480         PNG_FLAG_MNG_EMPTY_PLTE
3481         PNG_FLAG_MNG_FILTER_64
3482         PNG_ALL_MNG_FEATURES
3483
3484    feature_set is a png_uint_32 that is the bitwise AND of
3485       your mask with the set of MNG features that is
3486       supported by the version of libpng that you are using.
3487
3488 It is an error to use this function when reading or writing a standalone
3489 PNG file with the PNG 8-byte signature.  The PNG datastream must be wrapped
3490 in a MNG datastream.  As a minimum, it must have the MNG 8-byte signature
3491 and the MHDR and MEND chunks.  Libpng does not provide support for these
3492 or any other MNG chunks; your application must provide its own support for
3493 them.  You may wish to consider using libmng (available at
3494 http://www.libmng.com) instead.
3495
3496 VII.  Changes to Libpng from version 0.88
3497
3498 It should be noted that versions of libpng later than 0.96 are not
3499 distributed by the original libpng author, Guy Schalnat, nor by
3500 Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
3501 distributed versions 0.89 through 0.96, but rather by another member
3502 of the original PNG Group, Glenn Randers-Pehrson.  Guy and Andreas are
3503 still alive and well, but they have moved on to other things.
3504
3505 The old libpng functions png_read_init(), png_write_init(),
3506 png_info_init(), png_read_destroy(), and png_write_destroy() have been
3507 moved to PNG_INTERNAL in version 0.95 to discourage their use.  These
3508 functions will be removed from libpng version 1.4.0.
3509
3510 The preferred method of creating and initializing the libpng structures is
3511 via the png_create_read_struct(), png_create_write_struct(), and
3512 png_create_info_struct() because they isolate the size of the structures
3513 from the application, allow version error checking, and also allow the
3514 use of custom error handling routines during the initialization, which
3515 the old functions do not.  The functions png_read_destroy() and
3516 png_write_destroy() do not actually free the memory that libpng
3517 allocated for these structs, but just reset the data structures, so they
3518 can be used instead of png_destroy_read_struct() and
3519 png_destroy_write_struct() if you feel there is too much system overhead
3520 allocating and freeing the png_struct for each image read.
3521
3522 Setting the error callbacks via png_set_message_fn() before
3523 png_read_init() as was suggested in libpng-0.88 is no longer supported
3524 because this caused applications that do not use custom error functions
3525 to fail if the png_ptr was not initialized to zero.  It is still possible
3526 to set the error callbacks AFTER png_read_init(), or to change them with
3527 png_set_error_fn(), which is essentially the same function, but with a new
3528 name to force compilation errors with applications that try to use the old
3529 method.
3530
3531 Starting with version 1.0.7, you can find out which version of the library
3532 you are using at run-time:
3533
3534    png_uint_32 libpng_vn = png_access_version_number();
3535
3536 The number libpng_vn is constructed from the major version, minor
3537 version with leading zero, and release number with leading zero,
3538 (e.g., libpng_vn for version 1.0.7 is 10007).
3539
3540 You can also check which version of png.h you used when compiling your
3541 application:
3542
3543    png_uint_32 application_vn = PNG_LIBPNG_VER;
3544
3545 VIII.  Changes to Libpng from version 1.0.x to 1.2.x
3546
3547 Support for user memory management was enabled by default.  To
3548 accomplish this, the functions png_create_read_struct_2(),
3549 png_create_write_struct_2(), png_set_mem_fn(), png_get_mem_ptr(),
3550 png_malloc_default(), and png_free_default() were added.
3551
3552 Support for the iTXt chunk has been enabled by default as of
3553 version 1.2.41.
3554
3555 Support for certain MNG features was enabled.
3556
3557 Support for numbered error messages was added.  However, we never got
3558 around to actually numbering the error messages.  The function
3559 png_set_strip_error_numbers() was added (Note: the prototype for this
3560 function was inadvertently removed from png.h in PNG_NO_ASSEMBLER_CODE
3561 builds of libpng-1.2.15.  It was restored in libpng-1.2.36).
3562
3563 The png_malloc_warn() function was added at libpng-1.2.3.  This issues
3564 a png_warning and returns NULL instead of aborting when it fails to
3565 acquire the requested memory allocation.
3566
3567 Support for setting user limits on image width and height was enabled
3568 by default.  The functions png_set_user_limits(), png_get_user_width_max(),
3569 and png_get_user_height_max() were added at libpng-1.2.6.
3570
3571 The png_set_add_alpha() function was added at libpng-1.2.7.
3572
3573 The function png_set_expand_gray_1_2_4_to_8() was added at libpng-1.2.9.
3574 Unlike png_set_gray_1_2_4_to_8(), the new function does not expand the
3575 tRNS chunk to alpha. The png_set_gray_1_2_4_to_8() function is
3576 deprecated.
3577
3578 A number of macro definitions in support of runtime selection of
3579 assembler code features (especially Intel MMX code support) were
3580 added at libpng-1.2.0:
3581
3582     PNG_ASM_FLAG_MMX_SUPPORT_COMPILED
3583     PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU
3584     PNG_ASM_FLAG_MMX_READ_COMBINE_ROW
3585     PNG_ASM_FLAG_MMX_READ_INTERLACE
3586     PNG_ASM_FLAG_MMX_READ_FILTER_SUB
3587     PNG_ASM_FLAG_MMX_READ_FILTER_UP
3588     PNG_ASM_FLAG_MMX_READ_FILTER_AVG
3589     PNG_ASM_FLAG_MMX_READ_FILTER_PAETH
3590     PNG_ASM_FLAGS_INITIALIZED
3591     PNG_MMX_READ_FLAGS
3592     PNG_MMX_FLAGS
3593     PNG_MMX_WRITE_FLAGS
3594     PNG_MMX_FLAGS
3595
3596 We added the following functions in support of runtime
3597 selection of assembler code features:
3598
3599     png_get_mmx_flagmask()
3600     png_set_mmx_thresholds()
3601     png_get_asm_flags()
3602     png_get_mmx_bitdepth_threshold()
3603     png_get_mmx_rowbytes_threshold()
3604     png_set_asm_flags()
3605
3606 We replaced all of these functions with simple stubs in libpng-1.2.20,
3607 when the Intel assembler code was removed due to a licensing issue.
3608
3609 These macros are deprecated:
3610
3611     PNG_READ_TRANSFORMS_NOT_SUPPORTED
3612     PNG_PROGRESSIVE_READ_NOT_SUPPORTED
3613     PNG_NO_SEQUENTIAL_READ_SUPPORTED
3614     PNG_WRITE_TRANSFORMS_NOT_SUPPORTED
3615     PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED
3616     PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED
3617
3618 They have been replaced, respectively, by:
3619
3620     PNG_NO_READ_TRANSFORMS
3621     PNG_NO_PROGRESSIVE_READ
3622     PNG_NO_SEQUENTIAL_READ
3623     PNG_NO_WRITE_TRANSFORMS
3624     PNG_NO_READ_ANCILLARY_CHUNKS
3625     PNG_NO_WRITE_ANCILLARY_CHUNKS
3626
3627 PNG_MAX_UINT was replaced with PNG_UINT_31_MAX.  It has been
3628 deprecated since libpng-1.0.16 and libpng-1.2.6.
3629
3630 The function
3631     png_check_sig(sig, num)
3632 was replaced with
3633     !png_sig_cmp(sig, 0, num)
3634 It has been deprecated since libpng-0.90.
3635
3636 The function
3637     png_set_gray_1_2_4_to_8()
3638 which also expands tRNS to alpha was replaced with
3639     png_set_expand_gray_1_2_4_to_8()
3640 which does not. It has been deprecated since libpng-1.0.18 and 1.2.9.
3641
3642 IX.  Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
3643
3644 Private libpng prototypes and macro definitions were moved from
3645 png.h and pngconf.h into a new pngpriv.h header file.
3646
3647 Functions png_set_benign_errors(), png_benign_error(), and
3648 png_chunk_benign_error() were added.
3649
3650 Support for setting the maximum amount of memory that the application
3651 will allocate for reading chunks was added, as a security measure.
3652 The functions png_set_chunk_cache_max() and png_get_chunk_cache_max()
3653 were added to the library.
3654
3655 We implemented support for I/O states by adding png_ptr member io_state
3656 and functions png_get_io_chunk_name() and png_get_io_state() in pngget.c
3657
3658 We added PNG_TRANSFORM_GRAY_TO_RGB to the available high-level
3659 input transforms.
3660
3661 Checking for and reporting of errors in the IHDR chunk is more thorough.
3662
3663 Support for global arrays was removed, to improve thread safety.
3664
3665 Some obsolete/deprecated macros and functions have been removed.
3666
3667 Typecasted NULL definitions such as
3668    #define png_voidp_NULL            (png_voidp)NULL
3669 were eliminated.  If you used these in your application, just use
3670 NULL instead.
3671
3672 The png_struct and info_struct members "trans" and "trans_values" were
3673 changed to "trans_alpha" and "trans_color", respectively.
3674
3675 The obsolete, unused pnggccrd.c and pngvcrd.c files and related makefiles
3676 were removed.
3677
3678 The PNG_1_0_X and PNG_1_2_X macros were eliminated.
3679
3680 The PNG_LEGACY_SUPPORTED macro was eliminated.
3681
3682 Many WIN32_WCE #ifdefs were removed.
3683
3684 The functions png_read_init(info_ptr), png_write_init(info_ptr),
3685 png_info_init(info_ptr), png_read_destroy(), and png_write_destroy()
3686 have been removed.  They have been deprecated since libpng-0.95.
3687
3688 The png_permit_empty_plte() was removed. It has been deprecated
3689 since libpng-1.0.9.  Use png_permit_mng_features() instead.
3690
3691 We removed the obsolete stub functions png_get_mmx_flagmask(),
3692 png_set_mmx_thresholds(), png_get_asm_flags(),
3693 png_get_mmx_bitdepth_threshold(), png_get_mmx_rowbytes_threshold(),
3694 png_set_asm_flags(), and png_mmx_supported()
3695
3696 We removed the obsolete png_check_sig(), png_memcpy_check(), and
3697 png_memset_check() functions.  Instead use !png_sig_cmp(), memcpy(),
3698 and memset(), respectively.
3699
3700 The function png_set_gray_1_2_4_to_8() was removed. It has been
3701 deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
3702 png_set_expand_gray_1_2_4_to_8() because the former function also
3703 expanded any tRNS chunk to an alpha channel.
3704
3705 Macros for png_get_uint_16, png_get_uint_32, and png_get_int_32
3706 were added and are used by default instead of the corresponding
3707 functions. Unfortunately,
3708 from libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3709 function) incorrectly returned a value of type png_uint_32.
3710
3711 We changed the prototype for png_malloc() from
3712     png_malloc(png_structp png_ptr, png_uint_32 size)
3713 to
3714     png_malloc(png_structp png_ptr, png_alloc_size_t size)
3715
3716 This also applies to the prototype for the user replacement malloc_fn().
3717
3718 The png_calloc() function was added and is used in place of
3719 of "png_malloc(); memset();" except in the case in png_read_png()
3720 where the array consists of pointers; in this case a "for" loop is used
3721 after the png_malloc() to set the pointers to NULL, to give robust.
3722 behavior in case the application runs out of memory part-way through
3723 the process.
3724
3725 We changed the prototypes of png_get_compression_buffer_size() and
3726 png_set_compression_buffer_size() to work with png_size_t instead of
3727 png_uint_32.
3728
3729 Support for numbered error messages was removed by default, since we
3730 never got around to actually numbering the error messages. The function
3731 png_set_strip_error_numbers() was removed from the library by default.
3732
3733 The png_zalloc() and png_zfree() functions are no longer exported.
3734 The png_zalloc() function no longer zeroes out the memory that it
3735 allocates.
3736
3737 Support for dithering was disabled by default in libpng-1.4.0, because
3738 been well tested and doesn't actually "dither".  The code was not
3739 removed, however, and could be enabled by building libpng with
3740 PNG_READ_DITHER_SUPPORTED defined.  In libpng-1.4.2, this support
3741 was reenabled, but the function was renamed png_set_quantize() to
3742 reflect more accurately what it actually does.  At the same time,
3743 the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to
3744 PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS, and PNG_READ_DITHER_SUPPORTED
3745 was renamed to PNG_READ_QUANTIZE_SUPPORTED.
3746
3747 We removed the trailing '.' from the warning and error messages.
3748
3749 X.  Changes to Libpng from version 1.4.x to 1.5.x
3750
3751 From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3752 function) incorrectly returned a value of type png_uint_32.
3753
3754 A. Changes that affect users of libpng
3755
3756 There are no substantial API changes between the non-deprecated parts of
3757 the 1.4.5 API and the 1.5.0 API, however the ability to directly access
3758 the main libpng control structures, png_struct and png_info, deprecated
3759 in earlier versions of libpng, has been completely removed from
3760 libpng 1.5.
3761
3762 We no longer include zlib.h in png.h.  Applications that need access
3763 to information in zlib.h will need to add the '#include "zlib.h"'
3764 directive.  It does not matter whether it is placed prior to or after
3765 the '"#include png.h"' directive.
3766
3767 We moved the png_strcpy(), png_strncpy(), png_strlen(), png_memcpy(),
3768 png_memcmp(), png_sprintf, and png_memcpy() macros into a private
3769 header file (pngpriv.h) that is not accessible to applications.
3770
3771 In png_get_iCCP, the type of "profile" was changed from png_charpp
3772 to png_bytepp, and in png_set_iCCP, from png_charp to png_const_bytep.
3773
3774 There are changes of form in png.h, including new and changed macros to
3775 declare
3776 parts of the API.  Some API functions with arguments that are pointers to
3777 data not modified within the function have been corrected to declare
3778 these arguments with PNG_CONST.
3779
3780 Much of the internal use of C macros to control the library build has also
3781 changed and some of this is visible in the exported header files, in
3782 particular the use of macros to control data and API elements visible
3783 during application compilation may require significant revision to
3784 application code.  (It is extremely rare for an application to do this.)
3785
3786 Any program that compiled against libpng 1.4 and did not use deprecated
3787 features or access internal library structures should compile and work
3788 against libpng 1.5, except for the change in the prototype for
3789 png_get_iCCP() and png_set_iCCP() API functions mentioned above.
3790
3791 libpng 1.5.0 adds PNG_ PASS macros to help in the reading and writing of
3792 interlaced images.  The macros return the number of rows and columns in
3793 each pass and information that can be used to de-interlace and (if
3794 absolutely necessary) interlace an image.
3795
3796 libpng 1.5.0 adds an API png_longjmp(png_ptr, value).  This API calls
3797 the application-provided png_longjmp_ptr on the internal, but application
3798 initialized, jmpbuf.  It is provided as a convenience to avoid the need
3799 to use the png_jmpbuf macro, which had the unnecessary side effect of
3800 resetting the internal png_longjmp_ptr value.
3801
3802 libpng 1.5.0 includes a complete fixed point API.  By default this is
3803 present along with the corresponding floating point API.  In general the
3804 fixed point API is faster and smaller than the floating point one because
3805 the PNG file format used fixed point, not floating point.  This applies
3806 even if the library uses floating point in internal calculations.  A new
3807 macro, PNG_FLOATING_ARITHMETIC_SUPPORTED, reveals whether the library
3808 uses floating point arithmetic (the default) or fixed point arithmetic
3809 internally for performance critical calculations such as gamma correction.
3810 In some cases, the gamma calculations may produce slightly different
3811 results.  This has changed the results in png_rgb_to_gray and in alpha
3812 composition (png_set_background for example). This applies even if the
3813 original image was already linear (gamma == 1.0) and, therefore, it is
3814 not necessary to linearize the image.  This is because libpng has *not*
3815 been changed to optimize that case correctly, yet.
3816
3817 Fixed point support for the sCAL chunk comes with an important caveat;
3818 the sCAL specification uses a decimal encoding of floating point values
3819 and the accuracy of PNG fixed point values is insufficient for
3820 representation of these values. Consequently a "string" API
3821 (png_get_sCAL_s and png_set_sCAL_s) is the only reliable way of reading
3822 arbitrary sCAL chunks in the absence of either the floating point API or
3823 internal floating point calculations.
3824
3825 Applications no longer need to include the optional distribution header
3826 file pngusr.h or define the corresponding macros during application
3827 build in order to see the correct variant of the libpng API.  From 1.5.0
3828 application code can check for the corresponding _SUPPORTED macro:
3829
3830 #ifdef PNG_INCH_CONVERSIONS_SUPPORTED
3831    /* code that uses the inch conversion APIs. */
3832 #endif
3833
3834 This macro will only be defined if the inch conversion functions have been
3835 compiled into libpng.  The full set of macros, and whether or not support
3836 has been compiled in, are available in the header file pnglibconf.h.
3837 This header file is specific to the libpng build.  Notice that prior to
3838 1.5.0 the _SUPPORTED macros would always have the default definition unless
3839 reset by pngusr.h or by explicit settings on the compiler command line.
3840 These settings may produce compiler warnings or errors in 1.5.0 because
3841 of macro redefinition.
3842
3843 From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
3844 function) incorrectly returned a value of type png_uint_32.  libpng 1.5.0
3845 is consistent with the implementation in 1.4.5 and 1.2.x (where the macro
3846 did not exist.)
3847
3848 Applications can now choose whether to use these macros or to call the
3849 corresponding function by defining PNG_USE_READ_MACROS or
3850 PNG_NO_USE_READ_MACROS before including png.h.  Notice that this is
3851 only supported from 1.5.0 -defining PNG_NO_USE_READ_MACROS prior to 1.5.0
3852  will lead to a link failure.
3853
3854 B. Changes to the build and configuration of libpng
3855
3856 Details of internal changes to the library code can be found in the CHANGES
3857 file.  These will be of no concern to the vast majority of library users or
3858 builders, however the few who configure libpng to a non-default feature
3859 set may need to change how this is done.
3860
3861 There should be no need for library builders to alter build scripts if
3862 these use the distributed build support - configure or the makefiles -
3863 however users of the makefiles may care to update their build scripts
3864 to build pnglibconf.h where the corresponding makefile does not do so.
3865
3866 Building libpng with a non-default configuration has changed completely.
3867 The old method using pngusr.h should still work correctly even though the
3868 way pngusr.h is used in the build has been changed, however library
3869 builders will probably want to examine the changes to take advantage of
3870 new capabilities and to simplify their build system.
3871
3872 B.1 Specific changes to library configuration capabilities
3873
3874 The library now supports a complete fixed point implementation and can
3875 thus be used on systems which have no floating point support or very
3876 limited or slow support.  Previously gamma correction, an essential part
3877 of complete PNG support, required reasonably fast floating point.
3878
3879 As part of this the choice of internal implementation has been made
3880 independent of the choice of fixed versus floating point APIs and all the
3881 missing fixed point APIs have been implemented.
3882
3883 The exact mechanism used to control attributes of API functions has
3884 changed.  A single set of operating system independent macro definitions
3885 is used and operating system specific directives are defined in
3886 pnglibconf.h
3887
3888 As part of this the mechanism used to choose procedure call standards on
3889 those systems that allow a choice has been changed.  At present this only
3890 affects certain Microsoft (DOS, Windows) and IBM (OS/2) operating systems
3891 running on Intel processors.  As before PNGAPI is defined where required
3892 to control the exported API functions; however, two new macros, PNGCBAPI
3893 and PNGCAPI, are used instead for callback functions (PNGCBAPI) and
3894 (PNGCAPI) for functions that must match a C library prototype (currently
3895 only png_longjmp_ptr, which must match the C longjmp function.)  The new
3896 approach is documented in pngconf.h
3897
3898 Despite these changes libpng 1.5.0 only supports the native C function
3899 calling standard on those platforms tested so far (__cdecl on Microsoft
3900 Windows).  This is because the support requirements for alternative
3901 calling conventions seem to no longer exist.  Developers who find it
3902 necessary to set PNG_API_RULE to 1 should advise the mailing list
3903 (png-mng-implement) of this and library builders who use Openwatcom and
3904 therefore set PNG_API_RULE to 2 should also contact the mailing list.
3905
3906 A new test program, pngvalid, is provided in addition to pngtest.
3907 pngvalid validates the arithmetic accuracy of the gamma correction
3908 calculations and includes a number of validations of the file format.
3909 A subset of the full range of tests is run when "make check" is done
3910 (in the 'configure' build.)  pngvalid also allows total allocated memory
3911 usage to be evaluated and performs additional memory overwrite validation.
3912
3913 Many changes to individual feature macros have been made. The following
3914 are the changes most likely to be noticed by library builders who
3915 configure libpng:
3916
3917 1) All feature macros now have consistent naming:
3918
3919 #define PNG_NO_feature turns the feature off
3920 #define PNG_feature_SUPPORTED turns the feature on
3921
3922 pnglibconf.h contains one line for each feature macro which is either:
3923
3924 #define PNG_feature_SUPPORTED
3925
3926 if the feature is supported or:
3927
3928 /*#undef PNG_feature_SUPPORTED*/
3929
3930 if it is not.  Library code consistently checks for the 'SUPPORTED' macro.
3931 It does not, and should not, check for the 'NO' macro which will not
3932 normally be defined even if the feature is not supported.
3933
3934 Compatibility with the old names is provided as follows:
3935
3936 PNG_INCH_CONVERSIONS turns on PNG_INCH_CONVERSIONS_SUPPORTED
3937
3938 And the following definitions disable the corresponding feature:
3939
3940 PNG_SETJMP_NOT_SUPPORTED disables SETJMP
3941 PNG_READ_TRANSFORMS_NOT_SUPPORTED disables READ_TRANSFORMS
3942 PNG_NO_READ_COMPOSITED_NODIV disables READ_COMPOSITE_NODIV
3943 PNG_WRITE_TRANSFORMS_NOT_SUPPORTED disables WRITE_TRANSFORMS
3944 PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED disables READ_ANCILLARY_CHUNKS
3945 PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED disables WRITE_ANCILLARY_CHUNKS
3946
3947 Library builders should remove use of the above, inconsistent, names.
3948
3949 2) Warning and error message formatting was previously conditional on
3950 the STDIO feature. The library has been changed to use the
3951 CONSOLE_IO feature instead. This means that if CONSOLE_IO is disabled
3952 the library no longer uses the printf(3) functions, even though the
3953 default read/write implementations use (FILE) style stdio.h functions.
3954
3955 3) Three feature macros now control the fixed/floating point decisions:
3956
3957 PNG_FLOATING_POINT_SUPPORTED enables the floating point APIs
3958
3959 PNG_FIXED_POINT_SUPPORTED enables the fixed point APIs; however, in
3960 practice these are normally required internally anyway (because the PNG
3961 file format is fixed point), therefore in most cases PNG_NO_FIXED_POINT
3962 merely stops the function from being exported.
3963
3964 PNG_FLOATING_ARITHMETIC_SUPPORTED chooses between the internal floating
3965 point implementation or the fixed point one.  Typically the fixed point
3966 implementation is larger and slower than the floating point implementation
3967 on a system that supports floating point, however it may be faster on a
3968 system which lacks floating point hardware and therefore uses a software
3969 emulation.
3970
3971 4) Added PNG_{READ,WRITE}_INT_FUNCTIONS_SUPPORTED.  This allows the
3972 functions to read and write ints to be disabled independently of
3973 PNG_USE_READ_MACROS, which allows libpng to be built with the functions
3974 even though the default is to use the macros - this allows applications
3975 to choose at app buildtime whether or not to use macros (previously
3976 impossible because the functions weren't in the default build.)
3977
3978 B.2 Changes to the configuration mechanism
3979
3980 Prior to libpng-1.5.0 library builders who needed to configure libpng
3981 had either to modify the exported pngconf.h header file to add system
3982 specific configuration or had to write feature selection macros into
3983 pngusr.h and cause this to be included into pngconf.h by defining
3984 PNG_USER_CONFIG. The latter mechanism had the disadvantage that an
3985 application built without PNG_USER_CONFIG defined would see the
3986 unmodified, default, libpng API and thus would probably fail to link.
3987
3988 These mechanisms still work in the configure build and in any makefile
3989 build that builds pnglibconf.h although the feature selection macros
3990 have changed somewhat as described above.  In 1.5.0, however, pngusr.h is
3991 processed only once, when the exported header file pnglibconf.h is built.
3992 pngconf.h no longer includes pngusr.h, therefore it is ignored after the
3993 build of pnglibconf.h and it is never included in an application build.
3994
3995 The rarely used alternative of adding a list of feature macros to the
3996 CFLAGS setting in the build also still works, however the macros will be
3997 copied to pnglibconf.h and this may produce macro redefinition warnings
3998 when the individual C files are compiled.
3999
4000 All configuration now only works if pnglibconf.h is built from
4001 scripts/pnglibconf.dfa.  This requires the program awk.  Brian Kernighan
4002 (the original author of awk) maintains C source code of that awk and this
4003 and all known later implementations (often called by subtly different
4004 names - nawk and gawk for example) are adequate to build pnglibconf.h.
4005 The Sun Microsystems (now Oracle) program 'awk' is an earlier version
4006 and does not work, this may also apply to other systems that have a
4007 functioning awk called 'nawk'.
4008
4009 Configuration options are now documented in scripts/pnglibconf.dfa.  This
4010 file also includes dependency information that ensures a configuration is
4011 consistent; that is, if a feature is switched off dependent features are
4012 also removed.  As a recommended alternative to using feature macros in
4013 pngusr.h a system builder may also define equivalent options in pngusr.dfa
4014 (or, indeed, any file) and add that to the configuration by setting
4015 DFA_XTRA to the file name.  The makefiles in contrib/pngminim illustrate
4016 how to do this, and a case where pngusr.h is still required.
4017
4018 XI. Detecting libpng
4019
4020 The png_get_io_ptr() function has been present since libpng-0.88, has never
4021 changed, and is unaffected by conditional compilation macros.  It is the
4022 best choice for use in configure scripts for detecting the presence of any
4023 libpng version since 0.88.  In an autoconf "configure.in" you could use
4024
4025     AC_CHECK_LIB(png, png_get_io_ptr, ...
4026
4027 XII. Source code repository
4028
4029 Since about February 2009, version 1.2.34, libpng has been under "git" source
4030 control.  The git repository was built from old libpng-x.y.z.tar.gz files
4031 going back to version 0.70.  You can access the git repository (read only)
4032 at
4033
4034     git://libpng.git.sourceforge.net/gitroot/libpng
4035
4036 or you can browse it via "gitweb" at
4037
4038     http://libpng.git.sourceforge.net/git/gitweb.cgi?p=libpng
4039
4040 Patches can be sent to glennrp at users.sourceforge.net or to
4041 png-mng-implement at lists.sourceforge.net or you can upload them to
4042 the libpng bug tracker at
4043
4044     http://libpng.sourceforge.net
4045
4046 We also accept patches built from the tar or zip distributions, and
4047 simple verbal discriptions of bug fixes, reported either to the
4048 SourceForge bug tracker or to the png-mng-implement at lists.sf.net
4049 mailing list.
4050
4051 XIII. Coding style
4052
4053 Our coding style is similar to the "Allman" style, with curly
4054 braces on separate lines:
4055
4056     if (condition)
4057     {
4058        action;
4059     }
4060
4061     else if (another condition)
4062     {
4063        another action;
4064     }
4065
4066 The braces can be omitted from simple one-line actions:
4067
4068     if (condition)
4069        return (0);
4070
4071 We use 3-space indentation, except for continued statements which
4072 are usually indented the same as the first line of the statement
4073 plus four more spaces.
4074
4075 For macro definitions we use 2-space indentation, always leaving the "#"
4076 in the first column.
4077
4078     #ifndef PNG_NO_FEATURE
4079     #  ifndef PNG_FEATURE_SUPPORTED
4080     #    define PNG_FEATURE_SUPPORTED
4081     #  endif
4082     #endif
4083
4084 Comments appear with the leading "/*" at the same indentation as
4085 the statement that follows the comment:
4086
4087     /* Single-line comment */
4088     statement;
4089
4090     /* This is a multiple-line
4091      * comment.
4092      */
4093     statement;
4094
4095 Very short comments can be placed after the end of the statement
4096 to which they pertain:
4097
4098     statement;    /* comment */
4099
4100 We don't use C++ style ("//") comments. We have, however,
4101 used them in the past in some now-abandoned MMX assembler
4102 code.
4103
4104 Functions and their curly braces are not indented, and
4105 exported functions are marked with PNGAPI:
4106
4107  /* This is a public function that is visible to
4108   * application programmers. It does thus-and-so.
4109   */
4110  void PNGAPI
4111  png_exported_function(png_ptr, png_info, foo)
4112  {
4113     body;
4114  }
4115
4116 The prototypes for all exported functions appear in png.h,
4117 above the comment that says
4118
4119     /* Maintainer: Put new public prototypes here ... */
4120
4121 We mark all non-exported functions with "/* PRIVATE */"":
4122
4123  void /* PRIVATE */
4124  png_non_exported_function(png_ptr, png_info, foo)
4125  {
4126     body;
4127  }
4128
4129 The prototypes for non-exported functions (except for those in
4130 pngtest) appear in
4131 pngpriv.h
4132 above the comment that says
4133
4134   /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
4135
4136 To avoid polluting the global namespace, the names of all exported
4137 functions and variables begin with  "png_", and all publicly visible C
4138 preprocessor macros begin with "PNG_".  We request that applications that
4139 use libpng *not* begin any of their own symbols with either of these strings.
4140
4141 We put a space after each comma and after each semicolon
4142 in "for" statements, and we put spaces before and after each
4143 C binary operator and after "for" or "while", and before
4144 "?".  We don't put a space between a typecast and the expression
4145 being cast, nor do we put one between a function name and the
4146 left parenthesis that follows it:
4147
4148     for (i = 2; i > 0; --i)
4149        y[i] = a(x) + (int)b;
4150
4151 We prefer #ifdef and #ifndef to #if defined() and if !defined()
4152 when there is only one macro being tested.
4153
4154 We do not use the TAB character for indentation in the C sources.
4155
4156 Lines do not exceed 80 characters.
4157
4158 Other rules can be inferred by inspecting the libpng source.
4159
4160 XIV. Y2K Compliance in libpng
4161
4162 March 31, 2011
4163
4164 Since the PNG Development group is an ad-hoc body, we can't make
4165 an official declaration.
4166
4167 This is your unofficial assurance that libpng from version 0.71 and
4168 upward through 1.5.2 are Y2K compliant.  It is my belief that earlier
4169 versions were also Y2K compliant.
4170
4171 Libpng only has three year fields.  One is a 2-byte unsigned integer that
4172 will hold years up to 65535.  The other two hold the date in text
4173 format, and will hold years up to 9999.
4174
4175 The integer is
4176     "png_uint_16 year" in png_time_struct.
4177
4178 The strings are
4179     "png_charp time_buffer" in png_struct and
4180     "near_time_buffer", which is a local character string in png.c.
4181
4182 There are seven time-related functions:
4183
4184     png_convert_to_rfc_1123() in png.c
4185       (formerly png_convert_to_rfc_1152() in error)
4186     png_convert_from_struct_tm() in pngwrite.c, called
4187       in pngwrite.c
4188     png_convert_from_time_t() in pngwrite.c
4189     png_get_tIME() in pngget.c
4190     png_handle_tIME() in pngrutil.c, called in pngread.c
4191     png_set_tIME() in pngset.c
4192     png_write_tIME() in pngwutil.c, called in pngwrite.c
4193
4194 All appear to handle dates properly in a Y2K environment.  The
4195 png_convert_from_time_t() function calls gmtime() to convert from system
4196 clock time, which returns (year - 1900), which we properly convert to
4197 the full 4-digit year.  There is a possibility that applications using
4198 libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
4199 function, or that they are incorrectly passing only a 2-digit year
4200 instead of "year - 1900" into the png_convert_from_struct_tm() function,
4201 but this is not under our control.  The libpng documentation has always
4202 stated that it works with 4-digit years, and the APIs have been
4203 documented as such.
4204
4205 The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
4206 integer to hold the year, and can hold years as large as 65535.
4207
4208 zlib, upon which libpng depends, is also Y2K compliant.  It contains
4209 no date-related code.
4210
4211
4212    Glenn Randers-Pehrson
4213    libpng maintainer
4214    PNG Development Group