Coverage Report

Created: 2026-03-31 06:56

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