Coverage Report

Created: 2018-09-25 14:53

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