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