Merge branch 'upstream' into tizen
[platform/upstream/libpng.git] / pngwrite.c
1
2 /* pngwrite.c - general routines to write a PNG file
3  *
4  * Copyright (c) 2018-2023 Cosmin Truta
5  * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6  * Copyright (c) 1996-1997 Andreas Dilger
7  * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
8  *
9  * This code is released under the libpng license.
10  * For conditions of distribution and use, see the disclaimer
11  * and license in png.h
12  */
13
14 #include "pngpriv.h"
15 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
16 #  include <errno.h>
17 #endif /* SIMPLIFIED_WRITE_STDIO */
18
19 #ifdef PNG_WRITE_SUPPORTED
20
21 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
22 /* Write out all the unknown chunks for the current given location */
23 static void
24 write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr,
25     unsigned int where)
26 {
27    if (info_ptr->unknown_chunks_num != 0)
28    {
29       png_const_unknown_chunkp up;
30
31       png_debug(5, "writing extra chunks");
32
33       for (up = info_ptr->unknown_chunks;
34            up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
35            ++up)
36          if ((up->location & where) != 0)
37       {
38          /* If per-chunk unknown chunk handling is enabled use it, otherwise
39           * just write the chunks the application has set.
40           */
41 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
42          int keep = png_handle_as_unknown(png_ptr, up->name);
43
44          /* NOTE: this code is radically different from the read side in the
45           * matter of handling an ancillary unknown chunk.  In the read side
46           * the default behavior is to discard it, in the code below the default
47           * behavior is to write it.  Critical chunks are, however, only
48           * written if explicitly listed or if the default is set to write all
49           * unknown chunks.
50           *
51           * The default handling is also slightly weird - it is not possible to
52           * stop the writing of all unsafe-to-copy chunks!
53           *
54           * TODO: REVIEW: this would seem to be a bug.
55           */
56          if (keep != PNG_HANDLE_CHUNK_NEVER &&
57              ((up->name[3] & 0x20) /* safe-to-copy overrides everything */ ||
58               keep == PNG_HANDLE_CHUNK_ALWAYS ||
59               (keep == PNG_HANDLE_CHUNK_AS_DEFAULT &&
60                png_ptr->unknown_default == PNG_HANDLE_CHUNK_ALWAYS)))
61 #endif
62          {
63             /* TODO: review, what is wrong with a zero length unknown chunk? */
64             if (up->size == 0)
65                png_warning(png_ptr, "Writing zero-length unknown chunk");
66
67             png_write_chunk(png_ptr, up->name, up->data, up->size);
68          }
69       }
70    }
71 }
72 #endif /* WRITE_UNKNOWN_CHUNKS */
73
74 /* Writes all the PNG information.  This is the suggested way to use the
75  * library.  If you have a new chunk to add, make a function to write it,
76  * and put it in the correct location here.  If you want the chunk written
77  * after the image data, put it in png_write_end().  I strongly encourage
78  * you to supply a PNG_INFO_<chunk> flag, and check info_ptr->valid before
79  * writing the chunk, as that will keep the code from breaking if you want
80  * to just write a plain PNG file.  If you have long comments, I suggest
81  * writing them in png_write_end(), and compressing them.
82  */
83 void PNGAPI
84 png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
85 {
86    png_debug(1, "in png_write_info_before_PLTE");
87
88    if (png_ptr == NULL || info_ptr == NULL)
89       return;
90
91    if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
92    {
93       /* Write PNG signature */
94       png_write_sig(png_ptr);
95
96 #ifdef PNG_MNG_FEATURES_SUPPORTED
97       if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
98           png_ptr->mng_features_permitted != 0)
99       {
100          png_warning(png_ptr,
101              "MNG features are not allowed in a PNG datastream");
102          png_ptr->mng_features_permitted = 0;
103       }
104 #endif
105
106       /* Write IHDR information. */
107       png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
108           info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
109           info_ptr->filter_type,
110 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
111           info_ptr->interlace_type
112 #else
113           0
114 #endif
115          );
116
117       /* The rest of these check to see if the valid field has the appropriate
118        * flag set, and if it does, writes the chunk.
119        *
120        * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
121        * the chunks will be written if the WRITE routine is there and
122        * information * is available in the COLORSPACE. (See
123        * png_colorspace_sync_info in png.c for where the valid flags get set.)
124        *
125        * Under certain circumstances the colorspace can be invalidated without
126        * syncing the info_struct 'valid' flags; this happens if libpng detects
127        * an error and calls png_error while the color space is being set, yet
128        * the application continues writing the PNG.  So check the 'invalid'
129        * flag here too.
130        */
131 #ifdef PNG_WRITE_APNG_SUPPORTED
132       if (info_ptr->valid & PNG_INFO_acTL)
133          png_write_acTL(png_ptr, info_ptr->num_frames, info_ptr->num_plays);
134 #endif
135 #ifdef PNG_GAMMA_SUPPORTED
136 #  ifdef PNG_WRITE_gAMA_SUPPORTED
137       if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
138           (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 &&
139           (info_ptr->valid & PNG_INFO_gAMA) != 0)
140          png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma);
141 #  endif
142 #endif
143
144 #ifdef PNG_COLORSPACE_SUPPORTED
145       /* Write only one of sRGB or an ICC profile.  If a profile was supplied
146        * and it matches one of the known sRGB ones issue a warning.
147        */
148 #  ifdef PNG_WRITE_iCCP_SUPPORTED
149          if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
150              (info_ptr->valid & PNG_INFO_iCCP) != 0)
151          {
152 #    ifdef PNG_WRITE_sRGB_SUPPORTED
153                if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
154                   png_app_warning(png_ptr,
155                       "profile matches sRGB but writing iCCP instead");
156 #     endif
157
158             png_write_iCCP(png_ptr, info_ptr->iccp_name,
159                 info_ptr->iccp_profile);
160          }
161 #     ifdef PNG_WRITE_sRGB_SUPPORTED
162          else
163 #     endif
164 #  endif
165
166 #  ifdef PNG_WRITE_sRGB_SUPPORTED
167          if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
168              (info_ptr->valid & PNG_INFO_sRGB) != 0)
169             png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
170 #  endif /* WRITE_sRGB */
171 #endif /* COLORSPACE */
172
173 #ifdef PNG_WRITE_sBIT_SUPPORTED
174          if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
175             png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
176 #endif
177
178 #ifdef PNG_COLORSPACE_SUPPORTED
179 #  ifdef PNG_WRITE_cHRM_SUPPORTED
180          if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
181              (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
182              (info_ptr->valid & PNG_INFO_cHRM) != 0)
183             png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
184 #  endif
185 #endif
186
187 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
188          write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
189 #endif
190
191       png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
192    }
193 }
194
195 void PNGAPI
196 png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
197 {
198 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
199    int i;
200 #endif
201
202    png_debug(1, "in png_write_info");
203
204    if (png_ptr == NULL || info_ptr == NULL)
205       return;
206
207    png_write_info_before_PLTE(png_ptr, info_ptr);
208
209    if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
210       png_write_PLTE(png_ptr, info_ptr->palette,
211           (png_uint_32)info_ptr->num_palette);
212
213    else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
214       png_error(png_ptr, "Valid palette required for paletted images");
215
216 #ifdef PNG_WRITE_tRNS_SUPPORTED
217    if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
218    {
219 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
220       /* Invert the alpha channel (in tRNS) */
221       if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
222           info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
223       {
224          int j, jend;
225
226          jend = info_ptr->num_trans;
227          if (jend > PNG_MAX_PALETTE_LENGTH)
228             jend = PNG_MAX_PALETTE_LENGTH;
229
230          for (j = 0; j<jend; ++j)
231             info_ptr->trans_alpha[j] =
232                (png_byte)(255 - info_ptr->trans_alpha[j]);
233       }
234 #endif
235       png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
236           info_ptr->num_trans, info_ptr->color_type);
237    }
238 #endif
239 #ifdef PNG_WRITE_bKGD_SUPPORTED
240    if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
241       png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
242 #endif
243
244 #ifdef PNG_WRITE_eXIf_SUPPORTED
245    if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
246    {
247       png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
248       png_ptr->mode |= PNG_WROTE_eXIf;
249    }
250 #endif
251
252 #ifdef PNG_WRITE_hIST_SUPPORTED
253    if ((info_ptr->valid & PNG_INFO_hIST) != 0)
254       png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
255 #endif
256
257 #ifdef PNG_WRITE_oFFs_SUPPORTED
258    if ((info_ptr->valid & PNG_INFO_oFFs) != 0)
259       png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
260           info_ptr->offset_unit_type);
261 #endif
262
263 #ifdef PNG_WRITE_pCAL_SUPPORTED
264    if ((info_ptr->valid & PNG_INFO_pCAL) != 0)
265       png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
266           info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
267           info_ptr->pcal_units, info_ptr->pcal_params);
268 #endif
269
270 #ifdef PNG_WRITE_sCAL_SUPPORTED
271    if ((info_ptr->valid & PNG_INFO_sCAL) != 0)
272       png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
273           info_ptr->scal_s_width, info_ptr->scal_s_height);
274 #endif /* sCAL */
275
276 #ifdef PNG_WRITE_pHYs_SUPPORTED
277    if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
278       png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
279           info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
280 #endif /* pHYs */
281
282 #ifdef PNG_WRITE_tIME_SUPPORTED
283    if ((info_ptr->valid & PNG_INFO_tIME) != 0)
284    {
285       png_write_tIME(png_ptr, &(info_ptr->mod_time));
286       png_ptr->mode |= PNG_WROTE_tIME;
287    }
288 #endif /* tIME */
289
290 #ifdef PNG_WRITE_sPLT_SUPPORTED
291    if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
292       for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
293          png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
294 #endif /* sPLT */
295
296 #ifdef PNG_WRITE_TEXT_SUPPORTED
297    /* Check to see if we need to write text chunks */
298    for (i = 0; i < info_ptr->num_text; i++)
299    {
300       png_debug2(2, "Writing header text chunk %d, type %d", i,
301           info_ptr->text[i].compression);
302       /* An internationalized chunk? */
303       if (info_ptr->text[i].compression > 0)
304       {
305 #ifdef PNG_WRITE_iTXt_SUPPORTED
306          /* Write international chunk */
307          png_write_iTXt(png_ptr,
308              info_ptr->text[i].compression,
309              info_ptr->text[i].key,
310              info_ptr->text[i].lang,
311              info_ptr->text[i].lang_key,
312              info_ptr->text[i].text);
313          /* Mark this chunk as written */
314          if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
315             info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
316          else
317             info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
318 #else
319          png_warning(png_ptr, "Unable to write international text");
320 #endif
321       }
322
323       /* If we want a compressed text chunk */
324       else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
325       {
326 #ifdef PNG_WRITE_zTXt_SUPPORTED
327          /* Write compressed chunk */
328          png_write_zTXt(png_ptr, info_ptr->text[i].key,
329              info_ptr->text[i].text, info_ptr->text[i].compression);
330          /* Mark this chunk as written */
331          info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
332 #else
333          png_warning(png_ptr, "Unable to write compressed text");
334 #endif
335       }
336
337       else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
338       {
339 #ifdef PNG_WRITE_tEXt_SUPPORTED
340          /* Write uncompressed chunk */
341          png_write_tEXt(png_ptr, info_ptr->text[i].key,
342              info_ptr->text[i].text,
343              0);
344          /* Mark this chunk as written */
345          info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
346 #else
347          /* Can't get here */
348          png_warning(png_ptr, "Unable to write uncompressed text");
349 #endif
350       }
351    }
352 #endif /* tEXt */
353
354 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
355    write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
356 #endif
357 }
358
359 /* Writes the end of the PNG file.  If you don't want to write comments or
360  * time information, you can pass NULL for info.  If you already wrote these
361  * in png_write_info(), do not write them again here.  If you have long
362  * comments, I suggest writing them here, and compressing them.
363  */
364 void PNGAPI
365 png_write_end(png_structrp png_ptr, png_inforp info_ptr)
366 {
367    png_debug(1, "in png_write_end");
368
369    if (png_ptr == NULL)
370       return;
371
372    if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
373       png_error(png_ptr, "No IDATs written into file");
374
375 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
376    if (png_ptr->num_palette_max > png_ptr->num_palette)
377       png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
378 #endif
379
380 #ifdef PNG_WRITE_APNG_SUPPORTED
381    if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
382       png_error(png_ptr, "Not enough frames written");
383 #endif
384
385    /* See if user wants us to write information chunks */
386    if (info_ptr != NULL)
387    {
388 #ifdef PNG_WRITE_TEXT_SUPPORTED
389       int i; /* local index variable */
390 #endif
391 #ifdef PNG_WRITE_tIME_SUPPORTED
392       /* Check to see if user has supplied a time chunk */
393       if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
394           (png_ptr->mode & PNG_WROTE_tIME) == 0)
395          png_write_tIME(png_ptr, &(info_ptr->mod_time));
396
397 #endif
398 #ifdef PNG_WRITE_TEXT_SUPPORTED
399       /* Loop through comment chunks */
400       for (i = 0; i < info_ptr->num_text; i++)
401       {
402          png_debug2(2, "Writing trailer text chunk %d, type %d", i,
403              info_ptr->text[i].compression);
404          /* An internationalized chunk? */
405          if (info_ptr->text[i].compression > 0)
406          {
407 #ifdef PNG_WRITE_iTXt_SUPPORTED
408             /* Write international chunk */
409             png_write_iTXt(png_ptr,
410                 info_ptr->text[i].compression,
411                 info_ptr->text[i].key,
412                 info_ptr->text[i].lang,
413                 info_ptr->text[i].lang_key,
414                 info_ptr->text[i].text);
415             /* Mark this chunk as written */
416             if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
417                info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
418             else
419                info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
420 #else
421             png_warning(png_ptr, "Unable to write international text");
422 #endif
423          }
424
425          else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
426          {
427 #ifdef PNG_WRITE_zTXt_SUPPORTED
428             /* Write compressed chunk */
429             png_write_zTXt(png_ptr, info_ptr->text[i].key,
430                 info_ptr->text[i].text, info_ptr->text[i].compression);
431             /* Mark this chunk as written */
432             info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
433 #else
434             png_warning(png_ptr, "Unable to write compressed text");
435 #endif
436          }
437
438          else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
439          {
440 #ifdef PNG_WRITE_tEXt_SUPPORTED
441             /* Write uncompressed chunk */
442             png_write_tEXt(png_ptr, info_ptr->text[i].key,
443                 info_ptr->text[i].text, 0);
444             /* Mark this chunk as written */
445             info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
446 #else
447             png_warning(png_ptr, "Unable to write uncompressed text");
448 #endif
449          }
450       }
451 #endif
452
453 #ifdef PNG_WRITE_eXIf_SUPPORTED
454       if ((info_ptr->valid & PNG_INFO_eXIf) != 0 &&
455           (png_ptr->mode & PNG_WROTE_eXIf) == 0)
456          png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
457 #endif
458
459 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
460       write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
461 #endif
462    }
463
464    png_ptr->mode |= PNG_AFTER_IDAT;
465
466    /* Write end of PNG file */
467    png_write_IEND(png_ptr);
468
469    /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
470     * and restored again in libpng-1.2.30, may cause some applications that
471     * do not set png_ptr->output_flush_fn to crash.  If your application
472     * experiences a problem, please try building libpng with
473     * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
474     * png-mng-implement at lists.sf.net .
475     */
476 #ifdef PNG_WRITE_FLUSH_SUPPORTED
477 #  ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
478    png_flush(png_ptr);
479 #  endif
480 #endif
481 }
482
483 #ifdef PNG_CONVERT_tIME_SUPPORTED
484 void PNGAPI
485 png_convert_from_struct_tm(png_timep ptime, const struct tm * ttime)
486 {
487    png_debug(1, "in png_convert_from_struct_tm");
488
489    ptime->year = (png_uint_16)(1900 + ttime->tm_year);
490    ptime->month = (png_byte)(ttime->tm_mon + 1);
491    ptime->day = (png_byte)ttime->tm_mday;
492    ptime->hour = (png_byte)ttime->tm_hour;
493    ptime->minute = (png_byte)ttime->tm_min;
494    ptime->second = (png_byte)ttime->tm_sec;
495 }
496
497 void PNGAPI
498 png_convert_from_time_t(png_timep ptime, time_t ttime)
499 {
500    struct tm *tbuf;
501
502    png_debug(1, "in png_convert_from_time_t");
503
504    tbuf = gmtime(&ttime);
505    if (tbuf == NULL)
506    {
507       /* TODO: add a safe function which takes a png_ptr argument and raises
508        * a png_error if the ttime argument is invalid and the call to gmtime
509        * fails as a consequence.
510        */
511       memset(ptime, 0, sizeof(*ptime));
512       return;
513    }
514
515    png_convert_from_struct_tm(ptime, tbuf);
516 }
517 #endif
518
519 /* Initialize png_ptr structure, and allocate any memory needed */
520 PNG_FUNCTION(png_structp,PNGAPI
521 png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
522     png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
523 {
524 #ifndef PNG_USER_MEM_SUPPORTED
525    png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
526        error_fn, warn_fn, NULL, NULL, NULL);
527 #else
528    return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
529        warn_fn, NULL, NULL, NULL);
530 }
531
532 /* Alternate initialize png_ptr structure, and allocate any memory needed */
533 PNG_FUNCTION(png_structp,PNGAPI
534 png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
535     png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
536     png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
537 {
538    png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
539        error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
540 #endif /* USER_MEM */
541    if (png_ptr != NULL)
542    {
543       /* Set the zlib control values to defaults; they can be overridden by the
544        * application after the struct has been created.
545        */
546       png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
547
548       /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
549        * pngwutil.c defaults it according to whether or not filters will be
550        * used, and ignores this setting.
551        */
552       png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
553       png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
554       png_ptr->zlib_mem_level = 8;
555       png_ptr->zlib_window_bits = 15;
556       png_ptr->zlib_method = 8;
557
558 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
559       png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
560       png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
561       png_ptr->zlib_text_mem_level = 8;
562       png_ptr->zlib_text_window_bits = 15;
563       png_ptr->zlib_text_method = 8;
564 #endif /* WRITE_COMPRESSED_TEXT */
565
566       /* This is a highly dubious configuration option; by default it is off,
567        * but it may be appropriate for private builds that are testing
568        * extensions not conformant to the current specification, or of
569        * applications that must not fail to write at all costs!
570        */
571 #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
572       /* In stable builds only warn if an application error can be completely
573        * handled.
574        */
575       png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
576 #endif
577
578       /* App warnings are warnings in release (or release candidate) builds but
579        * are errors during development.
580        */
581 #if PNG_RELEASE_BUILD
582       png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
583 #endif
584
585       /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
586        * do it itself) avoiding setting the default function if it is not
587        * required.
588        */
589       png_set_write_fn(png_ptr, NULL, NULL, NULL);
590    }
591
592    return png_ptr;
593 }
594
595
596 /* Write a few rows of image data.  If the image is interlaced,
597  * either you will have to write the 7 sub images, or, if you
598  * have called png_set_interlace_handling(), you will have to
599  * "write" the image seven times.
600  */
601 void PNGAPI
602 png_write_rows(png_structrp png_ptr, png_bytepp row,
603     png_uint_32 num_rows)
604 {
605    png_uint_32 i; /* row counter */
606    png_bytepp rp; /* row pointer */
607
608    png_debug(1, "in png_write_rows");
609
610    if (png_ptr == NULL)
611       return;
612
613    /* Loop through the rows */
614    for (i = 0, rp = row; i < num_rows; i++, rp++)
615    {
616       png_write_row(png_ptr, *rp);
617    }
618 }
619
620 /* Write the image.  You only need to call this function once, even
621  * if you are writing an interlaced image.
622  */
623 void PNGAPI
624 png_write_image(png_structrp png_ptr, png_bytepp image)
625 {
626    png_uint_32 i; /* row index */
627    int pass, num_pass; /* pass variables */
628    png_bytepp rp; /* points to current row */
629
630    if (png_ptr == NULL)
631       return;
632
633    png_debug(1, "in png_write_image");
634
635 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
636    /* Initialize interlace handling.  If image is not interlaced,
637     * this will set pass to 1
638     */
639    num_pass = png_set_interlace_handling(png_ptr);
640 #else
641    num_pass = 1;
642 #endif
643    /* Loop through passes */
644    for (pass = 0; pass < num_pass; pass++)
645    {
646       /* Loop through image */
647       for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
648       {
649          png_write_row(png_ptr, *rp);
650       }
651    }
652 }
653
654 #ifdef PNG_MNG_FEATURES_SUPPORTED
655 /* Performs intrapixel differencing  */
656 static void
657 png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
658 {
659    png_debug(1, "in png_do_write_intrapixel");
660
661    if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
662    {
663       int bytes_per_pixel;
664       png_uint_32 row_width = row_info->width;
665       if (row_info->bit_depth == 8)
666       {
667          png_bytep rp;
668          png_uint_32 i;
669
670          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
671             bytes_per_pixel = 3;
672
673          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
674             bytes_per_pixel = 4;
675
676          else
677             return;
678
679          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
680          {
681             *(rp)     = (png_byte)(*rp       - *(rp + 1));
682             *(rp + 2) = (png_byte)(*(rp + 2) - *(rp + 1));
683          }
684       }
685
686 #ifdef PNG_WRITE_16BIT_SUPPORTED
687       else if (row_info->bit_depth == 16)
688       {
689          png_bytep rp;
690          png_uint_32 i;
691
692          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
693             bytes_per_pixel = 6;
694
695          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
696             bytes_per_pixel = 8;
697
698          else
699             return;
700
701          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
702          {
703             png_uint_32 s0   = (png_uint_32)(*(rp    ) << 8) | *(rp + 1);
704             png_uint_32 s1   = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
705             png_uint_32 s2   = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
706             png_uint_32 red  = (png_uint_32)((s0 - s1) & 0xffffL);
707             png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
708             *(rp    ) = (png_byte)(red >> 8);
709             *(rp + 1) = (png_byte)red;
710             *(rp + 4) = (png_byte)(blue >> 8);
711             *(rp + 5) = (png_byte)blue;
712          }
713       }
714 #endif /* WRITE_16BIT */
715    }
716 }
717 #endif /* MNG_FEATURES */
718
719 /* Called by user to write a row of image data */
720 void PNGAPI
721 png_write_row(png_structrp png_ptr, png_const_bytep row)
722 {
723    /* 1.5.6: moved from png_struct to be a local structure: */
724    png_row_info row_info;
725
726    if (png_ptr == NULL)
727       return;
728
729    png_debug2(1, "in png_write_row (row %u, pass %d)",
730        png_ptr->row_number, png_ptr->pass);
731
732    /* Initialize transformations and other stuff if first time */
733    if (png_ptr->row_number == 0 && png_ptr->pass == 0)
734    {
735       /* Make sure we wrote the header info */
736       if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
737          png_error(png_ptr,
738              "png_write_info was never called before png_write_row");
739
740       /* Check for transforms that have been set but were defined out */
741 #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
742       if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
743          png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
744 #endif
745
746 #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
747       if ((png_ptr->transformations & PNG_FILLER) != 0)
748          png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
749 #endif
750 #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
751     defined(PNG_READ_PACKSWAP_SUPPORTED)
752       if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
753          png_warning(png_ptr,
754              "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
755 #endif
756
757 #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
758       if ((png_ptr->transformations & PNG_PACK) != 0)
759          png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
760 #endif
761
762 #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
763       if ((png_ptr->transformations & PNG_SHIFT) != 0)
764          png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
765 #endif
766
767 #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
768       if ((png_ptr->transformations & PNG_BGR) != 0)
769          png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
770 #endif
771
772 #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
773       if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
774          png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
775 #endif
776
777       png_write_start_row(png_ptr);
778    }
779
780 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
781    /* If interlaced and not interested in row, return */
782    if (png_ptr->interlaced != 0 &&
783        (png_ptr->transformations & PNG_INTERLACE) != 0)
784    {
785       switch (png_ptr->pass)
786       {
787          case 0:
788             if ((png_ptr->row_number & 0x07) != 0)
789             {
790                png_write_finish_row(png_ptr);
791                return;
792             }
793             break;
794
795          case 1:
796             if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
797             {
798                png_write_finish_row(png_ptr);
799                return;
800             }
801             break;
802
803          case 2:
804             if ((png_ptr->row_number & 0x07) != 4)
805             {
806                png_write_finish_row(png_ptr);
807                return;
808             }
809             break;
810
811          case 3:
812             if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
813             {
814                png_write_finish_row(png_ptr);
815                return;
816             }
817             break;
818
819          case 4:
820             if ((png_ptr->row_number & 0x03) != 2)
821             {
822                png_write_finish_row(png_ptr);
823                return;
824             }
825             break;
826
827          case 5:
828             if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
829             {
830                png_write_finish_row(png_ptr);
831                return;
832             }
833             break;
834
835          case 6:
836             if ((png_ptr->row_number & 0x01) == 0)
837             {
838                png_write_finish_row(png_ptr);
839                return;
840             }
841             break;
842
843          default: /* error: ignore it */
844             break;
845       }
846    }
847 #endif
848
849    /* Set up row info for transformations */
850    row_info.color_type = png_ptr->color_type;
851    row_info.width = png_ptr->usr_width;
852    row_info.channels = png_ptr->usr_channels;
853    row_info.bit_depth = png_ptr->usr_bit_depth;
854    row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
855    row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
856
857    png_debug1(3, "row_info->color_type = %d", row_info.color_type);
858    png_debug1(3, "row_info->width = %u", row_info.width);
859    png_debug1(3, "row_info->channels = %d", row_info.channels);
860    png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
861    png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
862    png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
863
864    /* Copy user's row into buffer, leaving room for filter byte. */
865    memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
866
867 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
868    /* Handle interlacing */
869    if (png_ptr->interlaced && png_ptr->pass < 6 &&
870        (png_ptr->transformations & PNG_INTERLACE) != 0)
871    {
872       png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
873       /* This should always get caught above, but still ... */
874       if (row_info.width == 0)
875       {
876          png_write_finish_row(png_ptr);
877          return;
878       }
879    }
880 #endif
881
882 #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
883    /* Handle other transformations */
884    if (png_ptr->transformations != 0)
885       png_do_write_transformations(png_ptr, &row_info);
886 #endif
887
888    /* At this point the row_info pixel depth must match the 'transformed' depth,
889     * which is also the output depth.
890     */
891    if (row_info.pixel_depth != png_ptr->pixel_depth ||
892        row_info.pixel_depth != png_ptr->transformed_pixel_depth)
893       png_error(png_ptr, "internal write transform logic error");
894
895 #ifdef PNG_MNG_FEATURES_SUPPORTED
896    /* Write filter_method 64 (intrapixel differencing) only if
897     * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
898     * 2. Libpng did not write a PNG signature (this filter_method is only
899     *    used in PNG datastreams that are embedded in MNG datastreams) and
900     * 3. The application called png_permit_mng_features with a mask that
901     *    included PNG_FLAG_MNG_FILTER_64 and
902     * 4. The filter_method is 64 and
903     * 5. The color_type is RGB or RGBA
904     */
905    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
906        (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
907    {
908       /* Intrapixel differencing */
909       png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
910    }
911 #endif
912
913 /* Added at libpng-1.5.10 */
914 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
915    /* Check for out-of-range palette index */
916    if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
917        png_ptr->num_palette_max >= 0)
918       png_do_check_palette_indexes(png_ptr, &row_info);
919 #endif
920
921    /* Find a filter if necessary, filter the row and write it out. */
922    png_write_find_filter(png_ptr, &row_info);
923
924    if (png_ptr->write_row_fn != NULL)
925       (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
926 }
927
928 #ifdef PNG_WRITE_FLUSH_SUPPORTED
929 /* Set the automatic flush interval or 0 to turn flushing off */
930 void PNGAPI
931 png_set_flush(png_structrp png_ptr, int nrows)
932 {
933    png_debug(1, "in png_set_flush");
934
935    if (png_ptr == NULL)
936       return;
937
938    png_ptr->flush_dist = (nrows < 0 ? 0 : (png_uint_32)nrows);
939 }
940
941 /* Flush the current output buffers now */
942 void PNGAPI
943 png_write_flush(png_structrp png_ptr)
944 {
945    png_debug(1, "in png_write_flush");
946
947    if (png_ptr == NULL)
948       return;
949
950    /* We have already written out all of the data */
951    if (png_ptr->row_number >= png_ptr->num_rows)
952       return;
953
954    png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
955    png_ptr->flush_rows = 0;
956    png_flush(png_ptr);
957 }
958 #endif /* WRITE_FLUSH */
959
960 /* Free any memory used in png_ptr struct without freeing the struct itself. */
961 static void
962 png_write_destroy(png_structrp png_ptr)
963 {
964    png_debug(1, "in png_write_destroy");
965
966    /* Free any memory zlib uses */
967    if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
968       deflateEnd(&png_ptr->zstream);
969
970    /* Free our memory.  png_free checks NULL for us. */
971    png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
972    png_free(png_ptr, png_ptr->row_buf);
973    png_ptr->row_buf = NULL;
974 #ifdef PNG_WRITE_FILTER_SUPPORTED
975    png_free(png_ptr, png_ptr->prev_row);
976    png_free(png_ptr, png_ptr->try_row);
977    png_free(png_ptr, png_ptr->tst_row);
978    png_ptr->prev_row = NULL;
979    png_ptr->try_row = NULL;
980    png_ptr->tst_row = NULL;
981 #endif
982
983 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
984    png_free(png_ptr, png_ptr->chunk_list);
985    png_ptr->chunk_list = NULL;
986 #endif
987
988    /* The error handling and memory handling information is left intact at this
989     * point: the jmp_buf may still have to be freed.  See png_destroy_png_struct
990     * for how this happens.
991     */
992 }
993
994 /* Free all memory used by the write.
995  * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
996  * *png_ptr_ptr.  Prior to 1.6.0 it would accept such a value and it would free
997  * the passed in info_structs but it would quietly fail to free any of the data
998  * inside them.  In 1.6.0 it quietly does nothing (it has to be quiet because it
999  * has no png_ptr.)
1000  */
1001 void PNGAPI
1002 png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
1003 {
1004    png_debug(1, "in png_destroy_write_struct");
1005
1006    if (png_ptr_ptr != NULL)
1007    {
1008       png_structrp png_ptr = *png_ptr_ptr;
1009
1010       if (png_ptr != NULL) /* added in libpng 1.6.0 */
1011       {
1012          png_destroy_info_struct(png_ptr, info_ptr_ptr);
1013
1014          *png_ptr_ptr = NULL;
1015          png_write_destroy(png_ptr);
1016          png_destroy_png_struct(png_ptr);
1017       }
1018    }
1019 }
1020
1021 /* Allow the application to select one or more row filters to use. */
1022 void PNGAPI
1023 png_set_filter(png_structrp png_ptr, int method, int filters)
1024 {
1025    png_debug(1, "in png_set_filter");
1026
1027    if (png_ptr == NULL)
1028       return;
1029
1030 #ifdef PNG_MNG_FEATURES_SUPPORTED
1031    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1032        (method == PNG_INTRAPIXEL_DIFFERENCING))
1033       method = PNG_FILTER_TYPE_BASE;
1034
1035 #endif
1036    if (method == PNG_FILTER_TYPE_BASE)
1037    {
1038       switch (filters & (PNG_ALL_FILTERS | 0x07))
1039       {
1040 #ifdef PNG_WRITE_FILTER_SUPPORTED
1041          case 5:
1042          case 6:
1043          case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1044 #endif /* WRITE_FILTER */
1045             /* FALLTHROUGH */
1046 #ifdef __TIZEN__
1047             /* 'switch ~ case' is dead code.
1048              * If filters is #PNG_FILTER_VALUE_NONE, #PNG_FILTER_VALUE_SUB ...,
1049              * filter flag will be assigned to 'png_ptr->do_filter'. But
1050              * 'png_ptr->do_filter' is overwritten as 'filters' at below code.
1051              * Issue code(#1155) is 'png_ptr->do_filter = (png_byte)filters;'.
1052              * So the result of 'switch ~ case' has been lost at the line.
1053              * To keep the value of 'switch ~ case', we fixed it to apply
1054              * the result into 'filters'.
1055              * It will be updated into 'png_ptr->do_filter' at #1155 line.
1056              */
1057          case PNG_FILTER_VALUE_NONE:
1058             filters = PNG_FILTER_NONE; break;
1059 #else
1060          case PNG_FILTER_VALUE_NONE:
1061             png_ptr->do_filter = PNG_FILTER_NONE; break;
1062 #endif /* __TIZEN__ */
1063
1064 #ifdef PNG_WRITE_FILTER_SUPPORTED
1065 #ifdef __TIZEN__
1066          case PNG_FILTER_VALUE_SUB:
1067             filters = PNG_FILTER_SUB; break;
1068
1069          case PNG_FILTER_VALUE_UP:
1070             filters = PNG_FILTER_UP; break;
1071
1072          case PNG_FILTER_VALUE_AVG:
1073             filters = PNG_FILTER_AVG; break;
1074
1075          case PNG_FILTER_VALUE_PAETH:
1076             filters = PNG_FILTER_PAETH; break;
1077 #else
1078          case PNG_FILTER_VALUE_SUB:
1079             png_ptr->do_filter = PNG_FILTER_SUB; break;
1080
1081          case PNG_FILTER_VALUE_UP:
1082             png_ptr->do_filter = PNG_FILTER_UP; break;
1083
1084          case PNG_FILTER_VALUE_AVG:
1085             png_ptr->do_filter = PNG_FILTER_AVG; break;
1086
1087          case PNG_FILTER_VALUE_PAETH:
1088             png_ptr->do_filter = PNG_FILTER_PAETH; break;
1089 #endif /* __TIZEN__ */
1090          default:
1091             png_ptr->do_filter = (png_byte)filters; break;
1092 #else
1093          default:
1094             png_app_error(png_ptr, "Unknown row filter for method 0");
1095 #endif /* WRITE_FILTER */
1096       }
1097
1098 #ifdef PNG_WRITE_FILTER_SUPPORTED
1099       /* If we have allocated the row_buf, this means we have already started
1100        * with the image and we should have allocated all of the filter buffers
1101        * that have been selected.  If prev_row isn't already allocated, then
1102        * it is too late to start using the filters that need it, since we
1103        * will be missing the data in the previous row.  If an application
1104        * wants to start and stop using particular filters during compression,
1105        * it should start out with all of the filters, and then remove them
1106        * or add them back after the start of compression.
1107        *
1108        * NOTE: this is a nasty constraint on the code, because it means that the
1109        * prev_row buffer must be maintained even if there are currently no
1110        * 'prev_row' requiring filters active.
1111        */
1112       if (png_ptr->row_buf != NULL)
1113       {
1114          int num_filters;
1115          png_alloc_size_t buf_size;
1116
1117          /* Repeat the checks in png_write_start_row; 1 pixel high or wide
1118           * images cannot benefit from certain filters.  If this isn't done here
1119           * the check below will fire on 1 pixel high images.
1120           */
1121          if (png_ptr->height == 1)
1122             filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1123
1124          if (png_ptr->width == 1)
1125             filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1126
1127          if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
1128             && png_ptr->prev_row == NULL)
1129          {
1130             /* This is the error case, however it is benign - the previous row
1131              * is not available so the filter can't be used.  Just warn here.
1132              */
1133             png_app_warning(png_ptr,
1134                 "png_set_filter: UP/AVG/PAETH cannot be added after start");
1135             filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1136          }
1137
1138          num_filters = 0;
1139
1140          if (filters & PNG_FILTER_SUB)
1141             num_filters++;
1142
1143          if (filters & PNG_FILTER_UP)
1144             num_filters++;
1145
1146          if (filters & PNG_FILTER_AVG)
1147             num_filters++;
1148
1149          if (filters & PNG_FILTER_PAETH)
1150             num_filters++;
1151
1152          /* Allocate needed row buffers if they have not already been
1153           * allocated.
1154           */
1155          buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
1156              png_ptr->width) + 1;
1157
1158          if (png_ptr->try_row == NULL)
1159             png_ptr->try_row = png_voidcast(png_bytep,
1160                 png_malloc(png_ptr, buf_size));
1161
1162          if (num_filters > 1)
1163          {
1164             if (png_ptr->tst_row == NULL)
1165                png_ptr->tst_row = png_voidcast(png_bytep,
1166                    png_malloc(png_ptr, buf_size));
1167          }
1168       }
1169       png_ptr->do_filter = (png_byte)filters;
1170 #endif
1171    }
1172    else
1173       png_error(png_ptr, "Unknown custom filter method");
1174 }
1175
1176 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
1177 /* Provide floating and fixed point APIs */
1178 #ifdef PNG_FLOATING_POINT_SUPPORTED
1179 void PNGAPI
1180 png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1181     int num_weights, png_const_doublep filter_weights,
1182     png_const_doublep filter_costs)
1183 {
1184    PNG_UNUSED(png_ptr)
1185    PNG_UNUSED(heuristic_method)
1186    PNG_UNUSED(num_weights)
1187    PNG_UNUSED(filter_weights)
1188    PNG_UNUSED(filter_costs)
1189 }
1190 #endif /* FLOATING_POINT */
1191
1192 #ifdef PNG_FIXED_POINT_SUPPORTED
1193 void PNGAPI
1194 png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1195     int num_weights, png_const_fixed_point_p filter_weights,
1196     png_const_fixed_point_p filter_costs)
1197 {
1198    PNG_UNUSED(png_ptr)
1199    PNG_UNUSED(heuristic_method)
1200    PNG_UNUSED(num_weights)
1201    PNG_UNUSED(filter_weights)
1202    PNG_UNUSED(filter_costs)
1203 }
1204 #endif /* FIXED_POINT */
1205 #endif /* WRITE_WEIGHTED_FILTER */
1206
1207 #ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
1208 void PNGAPI
1209 png_set_compression_level(png_structrp png_ptr, int level)
1210 {
1211    png_debug(1, "in png_set_compression_level");
1212
1213    if (png_ptr == NULL)
1214       return;
1215
1216    png_ptr->zlib_level = level;
1217 }
1218
1219 void PNGAPI
1220 png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1221 {
1222    png_debug(1, "in png_set_compression_mem_level");
1223
1224    if (png_ptr == NULL)
1225       return;
1226
1227    png_ptr->zlib_mem_level = mem_level;
1228 }
1229
1230 void PNGAPI
1231 png_set_compression_strategy(png_structrp png_ptr, int strategy)
1232 {
1233    png_debug(1, "in png_set_compression_strategy");
1234
1235    if (png_ptr == NULL)
1236       return;
1237
1238    /* The flag setting here prevents the libpng dynamic selection of strategy.
1239     */
1240    png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1241    png_ptr->zlib_strategy = strategy;
1242 }
1243
1244 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1245  * smaller value of window_bits if it can do so safely.
1246  */
1247 void PNGAPI
1248 png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1249 {
1250    if (png_ptr == NULL)
1251       return;
1252
1253    /* Prior to 1.6.0 this would warn but then set the window_bits value. This
1254     * meant that negative window bits values could be selected that would cause
1255     * libpng to write a non-standard PNG file with raw deflate or gzip
1256     * compressed IDAT or ancillary chunks.  Such files can be read and there is
1257     * no warning on read, so this seems like a very bad idea.
1258     */
1259    if (window_bits > 15)
1260    {
1261       png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1262       window_bits = 15;
1263    }
1264
1265    else if (window_bits < 8)
1266    {
1267       png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1268       window_bits = 8;
1269    }
1270
1271    png_ptr->zlib_window_bits = window_bits;
1272 }
1273
1274 void PNGAPI
1275 png_set_compression_method(png_structrp png_ptr, int method)
1276 {
1277    png_debug(1, "in png_set_compression_method");
1278
1279    if (png_ptr == NULL)
1280       return;
1281
1282    /* This would produce an invalid PNG file if it worked, but it doesn't and
1283     * deflate will fault it, so it is harmless to just warn here.
1284     */
1285    if (method != 8)
1286       png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1287
1288    png_ptr->zlib_method = method;
1289 }
1290 #endif /* WRITE_CUSTOMIZE_COMPRESSION */
1291
1292 /* The following were added to libpng-1.5.4 */
1293 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1294 void PNGAPI
1295 png_set_text_compression_level(png_structrp png_ptr, int level)
1296 {
1297    png_debug(1, "in png_set_text_compression_level");
1298
1299    if (png_ptr == NULL)
1300       return;
1301
1302    png_ptr->zlib_text_level = level;
1303 }
1304
1305 void PNGAPI
1306 png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1307 {
1308    png_debug(1, "in png_set_text_compression_mem_level");
1309
1310    if (png_ptr == NULL)
1311       return;
1312
1313    png_ptr->zlib_text_mem_level = mem_level;
1314 }
1315
1316 void PNGAPI
1317 png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1318 {
1319    png_debug(1, "in png_set_text_compression_strategy");
1320
1321    if (png_ptr == NULL)
1322       return;
1323
1324    png_ptr->zlib_text_strategy = strategy;
1325 }
1326
1327 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1328  * smaller value of window_bits if it can do so safely.
1329  */
1330 void PNGAPI
1331 png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1332 {
1333    if (png_ptr == NULL)
1334       return;
1335
1336    if (window_bits > 15)
1337    {
1338       png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1339       window_bits = 15;
1340    }
1341
1342    else if (window_bits < 8)
1343    {
1344       png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1345       window_bits = 8;
1346    }
1347
1348    png_ptr->zlib_text_window_bits = window_bits;
1349 }
1350
1351 void PNGAPI
1352 png_set_text_compression_method(png_structrp png_ptr, int method)
1353 {
1354    png_debug(1, "in png_set_text_compression_method");
1355
1356    if (png_ptr == NULL)
1357       return;
1358
1359    if (method != 8)
1360       png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1361
1362    png_ptr->zlib_text_method = method;
1363 }
1364 #endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1365 /* end of API added to libpng-1.5.4 */
1366
1367 void PNGAPI
1368 png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1369 {
1370    if (png_ptr == NULL)
1371       return;
1372
1373    png_ptr->write_row_fn = write_row_fn;
1374 }
1375
1376 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1377 void PNGAPI
1378 png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1379     write_user_transform_fn)
1380 {
1381    png_debug(1, "in png_set_write_user_transform_fn");
1382
1383    if (png_ptr == NULL)
1384       return;
1385
1386    png_ptr->transformations |= PNG_USER_TRANSFORM;
1387    png_ptr->write_user_transform_fn = write_user_transform_fn;
1388 }
1389 #endif
1390
1391
1392 #ifdef PNG_INFO_IMAGE_SUPPORTED
1393 void PNGAPI
1394 png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1395     int transforms, voidp params)
1396 {
1397    if (png_ptr == NULL || info_ptr == NULL)
1398       return;
1399
1400    if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1401    {
1402       png_app_error(png_ptr, "no rows for png_write_image to write");
1403       return;
1404    }
1405
1406    /* Write the file header information. */
1407    png_write_info(png_ptr, info_ptr);
1408
1409    /* ------ these transformations don't touch the info structure ------- */
1410
1411    /* Invert monochrome pixels */
1412    if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1413 #ifdef PNG_WRITE_INVERT_SUPPORTED
1414       png_set_invert_mono(png_ptr);
1415 #else
1416       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1417 #endif
1418
1419    /* Shift the pixels up to a legal bit depth and fill in
1420     * as appropriate to correctly scale the image.
1421     */
1422    if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1423 #ifdef PNG_WRITE_SHIFT_SUPPORTED
1424       if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1425          png_set_shift(png_ptr, &info_ptr->sig_bit);
1426 #else
1427       png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1428 #endif
1429
1430    /* Pack pixels into bytes */
1431    if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1432 #ifdef PNG_WRITE_PACK_SUPPORTED
1433       png_set_packing(png_ptr);
1434 #else
1435       png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1436 #endif
1437
1438    /* Swap location of alpha bytes from ARGB to RGBA */
1439    if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1440 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1441       png_set_swap_alpha(png_ptr);
1442 #else
1443       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1444 #endif
1445
1446    /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1447     * RGB, note that the code expects the input color type to be G or RGB; no
1448     * alpha channel.
1449     */
1450    if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1451        PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1452    {
1453 #ifdef PNG_WRITE_FILLER_SUPPORTED
1454       if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1455       {
1456          if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1457             png_app_error(png_ptr,
1458                 "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1459
1460          /* Continue if ignored - this is the pre-1.6.10 behavior */
1461          png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1462       }
1463
1464       else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1465          png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1466 #else
1467       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1468 #endif
1469    }
1470
1471    /* Flip BGR pixels to RGB */
1472    if ((transforms & PNG_TRANSFORM_BGR) != 0)
1473 #ifdef PNG_WRITE_BGR_SUPPORTED
1474       png_set_bgr(png_ptr);
1475 #else
1476       png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1477 #endif
1478
1479    /* Swap bytes of 16-bit files to most significant byte first */
1480    if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1481 #ifdef PNG_WRITE_SWAP_SUPPORTED
1482       png_set_swap(png_ptr);
1483 #else
1484       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1485 #endif
1486
1487    /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
1488    if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1489 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1490       png_set_packswap(png_ptr);
1491 #else
1492       png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1493 #endif
1494
1495    /* Invert the alpha channel from opacity to transparency */
1496    if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1497 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1498       png_set_invert_alpha(png_ptr);
1499 #else
1500       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1501 #endif
1502
1503    /* ----------------------- end of transformations ------------------- */
1504
1505    /* Write the bits */
1506    png_write_image(png_ptr, info_ptr->row_pointers);
1507
1508    /* It is REQUIRED to call this to finish writing the rest of the file */
1509    png_write_end(png_ptr, info_ptr);
1510
1511    PNG_UNUSED(params)
1512 }
1513 #endif
1514
1515 #ifdef PNG_WRITE_APNG_SUPPORTED
1516 void PNGAPI
1517 png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
1518     png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
1519     png_uint_32 x_offset, png_uint_32 y_offset,
1520     png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
1521     png_byte blend_op)
1522 {
1523     png_debug(1, "in png_write_frame_head");
1524
1525     /* there is a chance this has been set after png_write_info was called,
1526     * so it would be set but not written. is there a way to be sure? */
1527     if (!(info_ptr->valid & PNG_INFO_acTL))
1528         png_error(png_ptr, "png_write_frame_head(): acTL not set");
1529
1530     png_write_reset(png_ptr);
1531
1532     png_write_reinit(png_ptr, info_ptr, width, height);
1533
1534     if ( !(png_ptr->num_frames_written == 0 &&
1535            (png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN) ) )
1536         png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
1537                        delay_num, delay_den, dispose_op, blend_op);
1538
1539     PNG_UNUSED(row_pointers)
1540 }
1541
1542 void PNGAPI
1543 png_write_frame_tail(png_structp png_ptr, png_infop info_ptr)
1544 {
1545     png_debug(1, "in png_write_frame_tail");
1546
1547     png_ptr->num_frames_written++;
1548
1549     PNG_UNUSED(info_ptr)
1550 }
1551 #endif /* PNG_WRITE_APNG_SUPPORTED */
1552
1553 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1554 /* Initialize the write structure - general purpose utility. */
1555 static int
1556 png_image_write_init(png_imagep image)
1557 {
1558    png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1559        png_safe_error, png_safe_warning);
1560
1561    if (png_ptr != NULL)
1562    {
1563       png_infop info_ptr = png_create_info_struct(png_ptr);
1564
1565       if (info_ptr != NULL)
1566       {
1567          png_controlp control = png_voidcast(png_controlp,
1568              png_malloc_warn(png_ptr, (sizeof *control)));
1569
1570          if (control != NULL)
1571          {
1572             memset(control, 0, (sizeof *control));
1573
1574             control->png_ptr = png_ptr;
1575             control->info_ptr = info_ptr;
1576             control->for_write = 1;
1577
1578             image->opaque = control;
1579             return 1;
1580          }
1581
1582          /* Error clean up */
1583          png_destroy_info_struct(png_ptr, &info_ptr);
1584       }
1585
1586       png_destroy_write_struct(&png_ptr, NULL);
1587    }
1588
1589    return png_image_error(image, "png_image_write_: out of memory");
1590 }
1591
1592 /* Arguments to png_image_write_main: */
1593 typedef struct
1594 {
1595    /* Arguments: */
1596    png_imagep      image;
1597    png_const_voidp buffer;
1598    png_int_32      row_stride;
1599    png_const_voidp colormap;
1600    int             convert_to_8bit;
1601    /* Local variables: */
1602    png_const_voidp first_row;
1603    ptrdiff_t       row_bytes;
1604    png_voidp       local_row;
1605    /* Byte count for memory writing */
1606    png_bytep        memory;
1607    png_alloc_size_t memory_bytes; /* not used for STDIO */
1608    png_alloc_size_t output_bytes; /* running total */
1609 } png_image_write_control;
1610
1611 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1612  * do any necessary byte swapping.  The component order is defined by the
1613  * png_image format value.
1614  */
1615 static int
1616 png_write_image_16bit(png_voidp argument)
1617 {
1618    png_image_write_control *display = png_voidcast(png_image_write_control*,
1619        argument);
1620    png_imagep image = display->image;
1621    png_structrp png_ptr = image->opaque->png_ptr;
1622
1623    png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1624        display->first_row);
1625    png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1626    png_uint_16p row_end;
1627    unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1628        3 : 1;
1629    int aindex = 0;
1630    png_uint_32 y = image->height;
1631
1632    if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1633    {
1634 #   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1635       if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1636       {
1637          aindex = -1;
1638          ++input_row; /* To point to the first component */
1639          ++output_row;
1640       }
1641          else
1642             aindex = (int)channels;
1643 #     else
1644          aindex = (int)channels;
1645 #     endif
1646    }
1647
1648    else
1649       png_error(png_ptr, "png_write_image: internal call error");
1650
1651    /* Work out the output row end and count over this, note that the increment
1652     * above to 'row' means that row_end can actually be beyond the end of the
1653     * row; this is correct.
1654     */
1655    row_end = output_row + image->width * (channels+1);
1656
1657    for (; y > 0; --y)
1658    {
1659       png_const_uint_16p in_ptr = input_row;
1660       png_uint_16p out_ptr = output_row;
1661
1662       while (out_ptr < row_end)
1663       {
1664          png_uint_16 alpha = in_ptr[aindex];
1665          png_uint_32 reciprocal = 0;
1666          int c;
1667
1668          out_ptr[aindex] = alpha;
1669
1670          /* Calculate a reciprocal.  The correct calculation is simply
1671           * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1672           * allows correct rounding by adding .5 before the shift.  'reciprocal'
1673           * is only initialized when required.
1674           */
1675          if (alpha > 0 && alpha < 65535)
1676             reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1677
1678          c = (int)channels;
1679          do /* always at least one channel */
1680          {
1681             png_uint_16 component = *in_ptr++;
1682
1683             /* The following gives 65535 for an alpha of 0, which is fine,
1684              * otherwise if 0/0 is represented as some other value there is more
1685              * likely to be a discontinuity which will probably damage
1686              * compression when moving from a fully transparent area to a
1687              * nearly transparent one.  (The assumption here is that opaque
1688              * areas tend not to be 0 intensity.)
1689              */
1690             if (component >= alpha)
1691                component = 65535;
1692
1693             /* component<alpha, so component/alpha is less than one and
1694              * component*reciprocal is less than 2^31.
1695              */
1696             else if (component > 0 && alpha < 65535)
1697             {
1698                png_uint_32 calc = component * reciprocal;
1699                calc += 16384; /* round to nearest */
1700                component = (png_uint_16)(calc >> 15);
1701             }
1702
1703             *out_ptr++ = component;
1704          }
1705          while (--c > 0);
1706
1707          /* Skip to next component (skip the intervening alpha channel) */
1708          ++in_ptr;
1709          ++out_ptr;
1710       }
1711
1712       png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1713       input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1714    }
1715
1716    return 1;
1717 }
1718
1719 /* Given 16-bit input (1 to 4 channels) write 8-bit output.  If an alpha channel
1720  * is present it must be removed from the components, the components are then
1721  * written in sRGB encoding.  No components are added or removed.
1722  *
1723  * Calculate an alpha reciprocal to reverse pre-multiplication.  As above the
1724  * calculation can be done to 15 bits of accuracy; however, the output needs to
1725  * be scaled in the range 0..255*65535, so include that scaling here.
1726  */
1727 #   define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
1728
1729 static png_byte
1730 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1731     png_uint_32 reciprocal/*from the above macro*/)
1732 {
1733    /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1734     * is represented as some other value there is more likely to be a
1735     * discontinuity which will probably damage compression when moving from a
1736     * fully transparent area to a nearly transparent one.  (The assumption here
1737     * is that opaque areas tend not to be 0 intensity.)
1738     *
1739     * There is a rounding problem here; if alpha is less than 128 it will end up
1740     * as 0 when scaled to 8 bits.  To avoid introducing spurious colors into the
1741     * output change for this too.
1742     */
1743    if (component >= alpha || alpha < 128)
1744       return 255;
1745
1746    /* component<alpha, so component/alpha is less than one and
1747     * component*reciprocal is less than 2^31.
1748     */
1749    else if (component > 0)
1750    {
1751       /* The test is that alpha/257 (rounded) is less than 255, the first value
1752        * that becomes 255 is 65407.
1753        * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1754        * be exact!)  [Could also test reciprocal != 0]
1755        */
1756       if (alpha < 65407)
1757       {
1758          component *= reciprocal;
1759          component += 64; /* round to nearest */
1760          component >>= 7;
1761       }
1762
1763       else
1764          component *= 255;
1765
1766       /* Convert the component to sRGB. */
1767       return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1768    }
1769
1770    else
1771       return 0;
1772 }
1773
1774 static int
1775 png_write_image_8bit(png_voidp argument)
1776 {
1777    png_image_write_control *display = png_voidcast(png_image_write_control*,
1778        argument);
1779    png_imagep image = display->image;
1780    png_structrp png_ptr = image->opaque->png_ptr;
1781
1782    png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1783        display->first_row);
1784    png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1785    png_uint_32 y = image->height;
1786    unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1787        3 : 1;
1788
1789    if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1790    {
1791       png_bytep row_end;
1792       int aindex;
1793
1794 #   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1795       if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1796       {
1797          aindex = -1;
1798          ++input_row; /* To point to the first component */
1799          ++output_row;
1800       }
1801
1802       else
1803 #   endif
1804       aindex = (int)channels;
1805
1806       /* Use row_end in place of a loop counter: */
1807       row_end = output_row + image->width * (channels+1);
1808
1809       for (; y > 0; --y)
1810       {
1811          png_const_uint_16p in_ptr = input_row;
1812          png_bytep out_ptr = output_row;
1813
1814          while (out_ptr < row_end)
1815          {
1816             png_uint_16 alpha = in_ptr[aindex];
1817             png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1818             png_uint_32 reciprocal = 0;
1819             int c;
1820
1821             /* Scale and write the alpha channel. */
1822             out_ptr[aindex] = alphabyte;
1823
1824             if (alphabyte > 0 && alphabyte < 255)
1825                reciprocal = UNP_RECIPROCAL(alpha);
1826
1827             c = (int)channels;
1828             do /* always at least one channel */
1829                *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1830             while (--c > 0);
1831
1832             /* Skip to next component (skip the intervening alpha channel) */
1833             ++in_ptr;
1834             ++out_ptr;
1835          } /* while out_ptr < row_end */
1836
1837          png_write_row(png_ptr, png_voidcast(png_const_bytep,
1838              display->local_row));
1839          input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1840       } /* while y */
1841    }
1842
1843    else
1844    {
1845       /* No alpha channel, so the row_end really is the end of the row and it
1846        * is sufficient to loop over the components one by one.
1847        */
1848       png_bytep row_end = output_row + image->width * channels;
1849
1850       for (; y > 0; --y)
1851       {
1852          png_const_uint_16p in_ptr = input_row;
1853          png_bytep out_ptr = output_row;
1854
1855          while (out_ptr < row_end)
1856          {
1857             png_uint_32 component = *in_ptr++;
1858
1859             component *= 255;
1860             *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1861          }
1862
1863          png_write_row(png_ptr, output_row);
1864          input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1865       }
1866    }
1867
1868    return 1;
1869 }
1870
1871 static void
1872 png_image_set_PLTE(png_image_write_control *display)
1873 {
1874    png_imagep image = display->image;
1875    const void *cmap = display->colormap;
1876    int entries = image->colormap_entries > 256 ? 256 :
1877        (int)image->colormap_entries;
1878
1879    /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1880    png_uint_32 format = image->format;
1881    unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1882
1883 #   if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
1884       defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
1885       int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1886           (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1887 #   else
1888 #     define afirst 0
1889 #   endif
1890
1891 #   ifdef PNG_FORMAT_BGR_SUPPORTED
1892       int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1893 #   else
1894 #     define bgr 0
1895 #   endif
1896
1897    int i, num_trans;
1898    png_color palette[256];
1899    png_byte tRNS[256];
1900
1901    memset(tRNS, 255, (sizeof tRNS));
1902    memset(palette, 0, (sizeof palette));
1903
1904    for (i=num_trans=0; i<entries; ++i)
1905    {
1906       /* This gets automatically converted to sRGB with reversal of the
1907        * pre-multiplication if the color-map has an alpha channel.
1908        */
1909       if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
1910       {
1911          png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
1912
1913          entry += (unsigned int)i * channels;
1914
1915          if ((channels & 1) != 0) /* no alpha */
1916          {
1917             if (channels >= 3) /* RGB */
1918             {
1919                palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1920                    entry[(2 ^ bgr)]);
1921                palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1922                    entry[1]);
1923                palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1924                    entry[bgr]);
1925             }
1926
1927             else /* Gray */
1928                palette[i].blue = palette[i].red = palette[i].green =
1929                   (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1930          }
1931
1932          else /* alpha */
1933          {
1934             png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1935             png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1936             png_uint_32 reciprocal = 0;
1937
1938             /* Calculate a reciprocal, as in the png_write_image_8bit code above
1939              * this is designed to produce a value scaled to 255*65535 when
1940              * divided by 128 (i.e. asr 7).
1941              */
1942             if (alphabyte > 0 && alphabyte < 255)
1943                reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1944
1945             tRNS[i] = alphabyte;
1946             if (alphabyte < 255)
1947                num_trans = i+1;
1948
1949             if (channels >= 3) /* RGB */
1950             {
1951                palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1952                    alpha, reciprocal);
1953                palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1954                    reciprocal);
1955                palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1956                    reciprocal);
1957             }
1958
1959             else /* gray */
1960                palette[i].blue = palette[i].red = palette[i].green =
1961                    png_unpremultiply(entry[afirst], alpha, reciprocal);
1962          }
1963       }
1964
1965       else /* Color-map has sRGB values */
1966       {
1967          png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
1968
1969          entry += (unsigned int)i * channels;
1970
1971          switch (channels)
1972          {
1973             case 4:
1974                tRNS[i] = entry[afirst ? 0 : 3];
1975                if (tRNS[i] < 255)
1976                   num_trans = i+1;
1977                /* FALLTHROUGH */
1978             case 3:
1979                palette[i].blue = entry[afirst + (2 ^ bgr)];
1980                palette[i].green = entry[afirst + 1];
1981                palette[i].red = entry[afirst + bgr];
1982                break;
1983
1984             case 2:
1985                tRNS[i] = entry[1 ^ afirst];
1986                if (tRNS[i] < 255)
1987                   num_trans = i+1;
1988                /* FALLTHROUGH */
1989             case 1:
1990                palette[i].blue = palette[i].red = palette[i].green =
1991                   entry[afirst];
1992                break;
1993
1994             default:
1995                break;
1996          }
1997       }
1998    }
1999
2000 #   ifdef afirst
2001 #     undef afirst
2002 #   endif
2003 #   ifdef bgr
2004 #     undef bgr
2005 #   endif
2006
2007    png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
2008        entries);
2009
2010    if (num_trans > 0)
2011       png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
2012           num_trans, NULL);
2013
2014    image->colormap_entries = (png_uint_32)entries;
2015 }
2016
2017 static int
2018 png_image_write_main(png_voidp argument)
2019 {
2020    png_image_write_control *display = png_voidcast(png_image_write_control*,
2021        argument);
2022    png_imagep image = display->image;
2023    png_structrp png_ptr = image->opaque->png_ptr;
2024    png_inforp info_ptr = image->opaque->info_ptr;
2025    png_uint_32 format = image->format;
2026
2027    /* The following four ints are actually booleans */
2028    int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
2029    int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
2030    int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
2031    int write_16bit = linear && (display->convert_to_8bit == 0);
2032
2033 #   ifdef PNG_BENIGN_ERRORS_SUPPORTED
2034       /* Make sure we error out on any bad situation */
2035       png_set_benign_errors(png_ptr, 0/*error*/);
2036 #   endif
2037
2038    /* Default the 'row_stride' parameter if required, also check the row stride
2039     * and total image size to ensure that they are within the system limits.
2040     */
2041    {
2042       unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
2043
2044       if (image->width <= 0x7fffffffU/channels) /* no overflow */
2045       {
2046          png_uint_32 check;
2047          png_uint_32 png_row_stride = image->width * channels;
2048
2049          if (display->row_stride == 0)
2050             display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
2051
2052          if (display->row_stride < 0)
2053             check = (png_uint_32)(-display->row_stride);
2054
2055          else
2056             check = (png_uint_32)display->row_stride;
2057
2058          if (check >= png_row_stride)
2059          {
2060             /* Now check for overflow of the image buffer calculation; this
2061              * limits the whole image size to 32 bits for API compatibility with
2062              * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
2063              */
2064             if (image->height > 0xffffffffU/png_row_stride)
2065                png_error(image->opaque->png_ptr, "memory image too large");
2066          }
2067
2068          else
2069             png_error(image->opaque->png_ptr, "supplied row stride too small");
2070       }
2071
2072       else
2073          png_error(image->opaque->png_ptr, "image row stride too large");
2074    }
2075
2076    /* Set the required transforms then write the rows in the correct order. */
2077    if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
2078    {
2079       if (display->colormap != NULL && image->colormap_entries > 0)
2080       {
2081          png_uint_32 entries = image->colormap_entries;
2082
2083          png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2084              entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2085              PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2086              PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2087
2088          png_image_set_PLTE(display);
2089       }
2090
2091       else
2092          png_error(image->opaque->png_ptr,
2093              "no color-map for color-mapped image");
2094    }
2095
2096    else
2097       png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2098           write_16bit ? 16 : 8,
2099           ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2100           ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2101           PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2102
2103    /* Counter-intuitively the data transformations must be called *after*
2104     * png_write_info, not before as in the read code, but the 'set' functions
2105     * must still be called before.  Just set the color space information, never
2106     * write an interlaced image.
2107     */
2108
2109    if (write_16bit != 0)
2110    {
2111       /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2112       png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2113
2114       if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2115          png_set_cHRM_fixed(png_ptr, info_ptr,
2116              /* color      x       y */
2117              /* white */ 31270, 32900,
2118              /* red   */ 64000, 33000,
2119              /* green */ 30000, 60000,
2120              /* blue  */ 15000,  6000
2121          );
2122    }
2123
2124    else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2125       png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2126
2127    /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2128     * space must still be gamma encoded.
2129     */
2130    else
2131       png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2132
2133    /* Write the file header. */
2134    png_write_info(png_ptr, info_ptr);
2135
2136    /* Now set up the data transformations (*after* the header is written),
2137     * remove the handled transformations from the 'format' flags for checking.
2138     *
2139     * First check for a little endian system if writing 16-bit files.
2140     */
2141    if (write_16bit != 0)
2142    {
2143       png_uint_16 le = 0x0001;
2144
2145       if ((*(png_const_bytep) & le) != 0)
2146          png_set_swap(png_ptr);
2147    }
2148
2149 #   ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2150       if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2151       {
2152          if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2153             png_set_bgr(png_ptr);
2154          format &= ~PNG_FORMAT_FLAG_BGR;
2155       }
2156 #   endif
2157
2158 #   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2159       if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2160       {
2161          if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2162             png_set_swap_alpha(png_ptr);
2163          format &= ~PNG_FORMAT_FLAG_AFIRST;
2164       }
2165 #   endif
2166
2167    /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2168     * above, but the application data is still byte packed.
2169     */
2170    if (colormap != 0 && image->colormap_entries <= 16)
2171       png_set_packing(png_ptr);
2172
2173    /* That should have handled all (both) the transforms. */
2174    if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2175          PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2176       png_error(png_ptr, "png_write_image: unsupported transformation");
2177
2178    {
2179       png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2180       ptrdiff_t row_bytes = display->row_stride;
2181
2182       if (linear != 0)
2183          row_bytes *= (sizeof (png_uint_16));
2184
2185       if (row_bytes < 0)
2186          row += (image->height-1) * (-row_bytes);
2187
2188       display->first_row = row;
2189       display->row_bytes = row_bytes;
2190    }
2191
2192    /* Apply 'fast' options if the flag is set. */
2193    if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2194    {
2195       png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2196       /* NOTE: determined by experiment using pngstest, this reflects some
2197        * balance between the time to write the image once and the time to read
2198        * it about 50 times.  The speed-up in pngstest was about 10-20% of the
2199        * total (user) time on a heavily loaded system.
2200        */
2201 #   ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
2202       png_set_compression_level(png_ptr, 3);
2203 #   endif
2204    }
2205
2206    /* Check for the cases that currently require a pre-transform on the row
2207     * before it is written.  This only applies when the input is 16-bit and
2208     * either there is an alpha channel or it is converted to 8-bit.
2209     */
2210    if ((linear != 0 && alpha != 0 ) ||
2211        (colormap == 0 && display->convert_to_8bit != 0))
2212    {
2213       png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2214           png_get_rowbytes(png_ptr, info_ptr)));
2215       int result;
2216
2217       display->local_row = row;
2218       if (write_16bit != 0)
2219          result = png_safe_execute(image, png_write_image_16bit, display);
2220       else
2221          result = png_safe_execute(image, png_write_image_8bit, display);
2222       display->local_row = NULL;
2223
2224       png_free(png_ptr, row);
2225
2226       /* Skip the 'write_end' on error: */
2227       if (result == 0)
2228          return 0;
2229    }
2230
2231    /* Otherwise this is the case where the input is in a format currently
2232     * supported by the rest of the libpng write code; call it directly.
2233     */
2234    else
2235    {
2236       png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2237       ptrdiff_t row_bytes = display->row_bytes;
2238       png_uint_32 y = image->height;
2239
2240       for (; y > 0; --y)
2241       {
2242          png_write_row(png_ptr, row);
2243          row += row_bytes;
2244       }
2245    }
2246
2247    png_write_end(png_ptr, info_ptr);
2248    return 1;
2249 }
2250
2251
2252 static void (PNGCBAPI
2253 image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data, size_t size)
2254 {
2255    png_image_write_control *display = png_voidcast(png_image_write_control*,
2256        png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
2257    png_alloc_size_t ob = display->output_bytes;
2258
2259    /* Check for overflow; this should never happen: */
2260    if (size <= ((png_alloc_size_t)-1) - ob)
2261    {
2262       /* I don't think libpng ever does this, but just in case: */
2263       if (size > 0)
2264       {
2265          if (display->memory_bytes >= ob+size) /* writing */
2266             memcpy(display->memory+ob, data, size);
2267
2268          /* Always update the size: */
2269          display->output_bytes = ob+size;
2270       }
2271    }
2272
2273    else
2274       png_error(png_ptr, "png_image_write_to_memory: PNG too big");
2275 }
2276
2277 static void (PNGCBAPI
2278 image_memory_flush)(png_structp png_ptr)
2279 {
2280    PNG_UNUSED(png_ptr)
2281 }
2282
2283 static int
2284 png_image_write_memory(png_voidp argument)
2285 {
2286    png_image_write_control *display = png_voidcast(png_image_write_control*,
2287        argument);
2288
2289    /* The rest of the memory-specific init and write_main in an error protected
2290     * environment.  This case needs to use callbacks for the write operations
2291     * since libpng has no built in support for writing to memory.
2292     */
2293    png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
2294        image_memory_write, image_memory_flush);
2295
2296    return png_image_write_main(display);
2297 }
2298
2299 int PNGAPI
2300 png_image_write_to_memory(png_imagep image, void *memory,
2301     png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
2302     const void *buffer, png_int_32 row_stride, const void *colormap)
2303 {
2304    /* Write the image to the given buffer, or count the bytes if it is NULL */
2305    if (image != NULL && image->version == PNG_IMAGE_VERSION)
2306    {
2307       if (memory_bytes != NULL && buffer != NULL)
2308       {
2309          /* This is to give the caller an easier error detection in the NULL
2310           * case and guard against uninitialized variable problems:
2311           */
2312          if (memory == NULL)
2313             *memory_bytes = 0;
2314
2315          if (png_image_write_init(image) != 0)
2316          {
2317             png_image_write_control display;
2318             int result;
2319
2320             memset(&display, 0, (sizeof display));
2321             display.image = image;
2322             display.buffer = buffer;
2323             display.row_stride = row_stride;
2324             display.colormap = colormap;
2325             display.convert_to_8bit = convert_to_8bit;
2326             display.memory = png_voidcast(png_bytep, memory);
2327             display.memory_bytes = *memory_bytes;
2328             display.output_bytes = 0;
2329
2330             result = png_safe_execute(image, png_image_write_memory, &display);
2331             png_image_free(image);
2332
2333             /* write_memory returns true even if we ran out of buffer. */
2334             if (result)
2335             {
2336                /* On out-of-buffer this function returns '0' but still updates
2337                 * memory_bytes:
2338                 */
2339                if (memory != NULL && display.output_bytes > *memory_bytes)
2340                   result = 0;
2341
2342                *memory_bytes = display.output_bytes;
2343             }
2344
2345             return result;
2346          }
2347
2348          else
2349             return 0;
2350       }
2351
2352       else
2353          return png_image_error(image,
2354              "png_image_write_to_memory: invalid argument");
2355    }
2356
2357    else if (image != NULL)
2358       return png_image_error(image,
2359           "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
2360
2361    else
2362       return 0;
2363 }
2364
2365 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
2366 int PNGAPI
2367 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2368     const void *buffer, png_int_32 row_stride, const void *colormap)
2369 {
2370    /* Write the image to the given (FILE*). */
2371    if (image != NULL && image->version == PNG_IMAGE_VERSION)
2372    {
2373       if (file != NULL && buffer != NULL)
2374       {
2375          if (png_image_write_init(image) != 0)
2376          {
2377             png_image_write_control display;
2378             int result;
2379
2380             /* This is slightly evil, but png_init_io doesn't do anything other
2381              * than this and we haven't changed the standard IO functions so
2382              * this saves a 'safe' function.
2383              */
2384             image->opaque->png_ptr->io_ptr = file;
2385
2386             memset(&display, 0, (sizeof display));
2387             display.image = image;
2388             display.buffer = buffer;
2389             display.row_stride = row_stride;
2390             display.colormap = colormap;
2391             display.convert_to_8bit = convert_to_8bit;
2392
2393             result = png_safe_execute(image, png_image_write_main, &display);
2394             png_image_free(image);
2395             return result;
2396          }
2397
2398          else
2399             return 0;
2400       }
2401
2402       else
2403          return png_image_error(image,
2404              "png_image_write_to_stdio: invalid argument");
2405    }
2406
2407    else if (image != NULL)
2408       return png_image_error(image,
2409           "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2410
2411    else
2412       return 0;
2413 }
2414
2415 int PNGAPI
2416 png_image_write_to_file(png_imagep image, const char *file_name,
2417     int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2418     const void *colormap)
2419 {
2420    /* Write the image to the named file. */
2421    if (image != NULL && image->version == PNG_IMAGE_VERSION)
2422    {
2423       if (file_name != NULL && buffer != NULL)
2424       {
2425          FILE *fp = fopen(file_name, "wb");
2426
2427          if (fp != NULL)
2428          {
2429             if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2430                 row_stride, colormap) != 0)
2431             {
2432                int error; /* from fflush/fclose */
2433
2434                /* Make sure the file is flushed correctly. */
2435                if (fflush(fp) == 0 && ferror(fp) == 0)
2436                {
2437                   if (fclose(fp) == 0)
2438                      return 1;
2439
2440                   error = errno; /* from fclose */
2441                }
2442
2443                else
2444                {
2445                   error = errno; /* from fflush or ferror */
2446                   (void)fclose(fp);
2447                }
2448
2449                (void)remove(file_name);
2450                /* The image has already been cleaned up; this is just used to
2451                 * set the error (because the original write succeeded).
2452                 */
2453                return png_image_error(image, strerror(error));
2454             }
2455
2456             else
2457             {
2458                /* Clean up: just the opened file. */
2459                (void)fclose(fp);
2460                (void)remove(file_name);
2461                return 0;
2462             }
2463          }
2464
2465          else
2466             return png_image_error(image, strerror(errno));
2467       }
2468
2469       else
2470          return png_image_error(image,
2471              "png_image_write_to_file: invalid argument");
2472    }
2473
2474    else if (image != NULL)
2475       return png_image_error(image,
2476           "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2477
2478    else
2479       return 0;
2480 }
2481 #endif /* SIMPLIFIED_WRITE_STDIO */
2482 #endif /* SIMPLIFIED_WRITE */
2483 #endif /* WRITE */