Coverage Report

Created: 2025-11-14 07:32

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-2025 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.14k
{
26
7.14k
   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.14k
}
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.76k
{
85
4.76k
   png_debug(1, "in png_write_info_before_PLTE");
86
87
4.76k
   if (png_ptr == NULL || info_ptr == NULL)
88
0
      return;
89
90
4.76k
   if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
91
2.38k
   {
92
      /* Write PNG signature */
93
2.38k
      png_write_sig(png_ptr);
94
95
2.38k
#ifdef PNG_MNG_FEATURES_SUPPORTED
96
2.38k
      if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
97
1.96k
          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.38k
#endif
104
105
      /* Write IHDR information. */
106
2.38k
      png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
107
2.38k
          info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
108
2.38k
          info_ptr->filter_type,
109
2.38k
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
110
2.38k
          info_ptr->interlace_type
111
#else
112
          0
113
#endif
114
2.38k
         );
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.38k
#ifdef PNG_WRITE_APNG_SUPPORTED
131
2.38k
         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.38k
#endif
134
135
2.38k
#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.38k
         write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
146
2.38k
#endif
147
148
2.38k
#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.38k
         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.38k
#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 chunkgs 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.38k
#ifdef PNG_WRITE_cLLI_SUPPORTED
172
2.38k
   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.38k
#endif
177
2.38k
#ifdef PNG_WRITE_mDCV_SUPPORTED
178
2.38k
   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.38k
#endif
188
189
2.38k
#  ifdef PNG_WRITE_cICP_SUPPORTED /* Priority 4 */
190
2.38k
   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.38k
#  endif
199
200
2.38k
#  ifdef PNG_WRITE_iCCP_SUPPORTED /* Priority 3 */
201
2.38k
         if ((info_ptr->valid & PNG_INFO_iCCP) != 0)
202
18
         {
203
18
            png_write_iCCP(png_ptr, info_ptr->iccp_name,
204
18
                info_ptr->iccp_profile, info_ptr->iccp_proflen);
205
18
         }
206
2.38k
#  endif
207
208
2.38k
#  ifdef PNG_WRITE_sRGB_SUPPORTED /* Priority 2 */
209
2.38k
         if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
210
0
            png_write_sRGB(png_ptr, info_ptr->rendering_intent);
211
2.38k
#  endif /* WRITE_sRGB */
212
213
2.38k
#  ifdef PNG_WRITE_gAMA_SUPPORTED /* Priority 1 */
214
2.38k
      if ((info_ptr->valid & PNG_INFO_gAMA) != 0)
215
0
         png_write_gAMA_fixed(png_ptr, info_ptr->gamma);
216
2.38k
#  endif
217
218
2.38k
#  ifdef PNG_WRITE_cHRM_SUPPORTED /* Also priority 1 */
219
2.38k
         if ((info_ptr->valid & PNG_INFO_cHRM) != 0)
220
783
            png_write_cHRM_fixed(png_ptr, &info_ptr->cHRM);
221
2.38k
#  endif
222
223
2.38k
      png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
224
2.38k
   }
225
4.76k
}
226
227
void
228
png_write_info(png_struct *png_ptr, const png_info *info_ptr)
229
2.38k
{
230
2.38k
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
231
2.38k
   int i;
232
2.38k
#endif
233
234
2.38k
   png_debug(1, "in png_write_info");
235
236
2.38k
   if (png_ptr == NULL || info_ptr == NULL)
237
0
      return;
238
239
2.38k
   png_write_info_before_PLTE(png_ptr, info_ptr);
240
241
2.38k
   if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
242
486
      png_write_PLTE(png_ptr, info_ptr->palette,
243
486
          (png_uint_32)info_ptr->num_palette);
244
245
1.89k
   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.38k
#ifdef PNG_WRITE_tRNS_SUPPORTED
249
2.38k
   if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
250
157
   {
251
157
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
252
      /* Invert the alpha channel (in tRNS) */
253
157
      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
157
#endif
267
157
      png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
268
157
          info_ptr->num_trans, info_ptr->color_type);
269
157
   }
270
2.38k
#endif
271
2.38k
#ifdef PNG_WRITE_bKGD_SUPPORTED
272
2.38k
   if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
273
1.73k
      png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
274
2.38k
#endif
275
276
2.38k
#ifdef PNG_WRITE_eXIf_SUPPORTED
277
2.38k
   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.38k
#endif
283
284
2.38k
#ifdef PNG_WRITE_hIST_SUPPORTED
285
2.38k
   if ((info_ptr->valid & PNG_INFO_hIST) != 0)
286
0
      png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
287
2.38k
#endif
288
289
2.38k
#ifdef PNG_WRITE_oFFs_SUPPORTED
290
2.38k
   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.38k
#endif
294
295
2.38k
#ifdef PNG_WRITE_pCAL_SUPPORTED
296
2.38k
   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.38k
#endif
301
302
2.38k
#ifdef PNG_WRITE_sCAL_SUPPORTED
303
2.38k
   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.38k
#endif /* sCAL */
307
308
2.38k
#ifdef PNG_WRITE_pHYs_SUPPORTED
309
2.38k
   if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
310
83
      png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
311
83
          info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
312
2.38k
#endif /* pHYs */
313
314
2.38k
#ifdef PNG_WRITE_tIME_SUPPORTED
315
2.38k
   if ((info_ptr->valid & PNG_INFO_tIME) != 0)
316
1.79k
   {
317
1.79k
      png_write_tIME(png_ptr, &(info_ptr->mod_time));
318
1.79k
      png_ptr->mode |= PNG_WROTE_tIME;
319
1.79k
   }
320
2.38k
#endif /* tIME */
321
322
2.38k
#ifdef PNG_WRITE_sPLT_SUPPORTED
323
2.38k
   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.38k
#endif /* sPLT */
327
328
2.38k
#ifdef PNG_WRITE_TEXT_SUPPORTED
329
   /* Check to see if we need to write text chunks */
330
8.93k
   for (i = 0; i < info_ptr->num_text; i++)
331
6.55k
   {
332
6.55k
      png_debug2(2, "Writing header text chunk %d, type %d", i,
333
6.55k
          info_ptr->text[i].compression);
334
      /* An internationalized chunk? */
335
6.55k
      if (info_ptr->text[i].compression > 0)
336
54
      {
337
54
#ifdef PNG_WRITE_iTXt_SUPPORTED
338
         /* Write international chunk */
339
54
         png_write_iTXt(png_ptr,
340
54
             info_ptr->text[i].compression,
341
54
             info_ptr->text[i].key,
342
54
             info_ptr->text[i].lang,
343
54
             info_ptr->text[i].lang_key,
344
54
             info_ptr->text[i].text);
345
         /* Mark this chunk as written */
346
54
         if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
347
0
            info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
348
54
         else
349
54
            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
54
      }
354
355
      /* If we want a compressed text chunk */
356
6.50k
      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
357
55
      {
358
55
#ifdef PNG_WRITE_zTXt_SUPPORTED
359
         /* Write compressed chunk */
360
55
         png_write_zTXt(png_ptr, info_ptr->text[i].key,
361
55
             info_ptr->text[i].text, info_ptr->text[i].compression);
362
         /* Mark this chunk as written */
363
55
         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
55
      }
368
369
6.44k
      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
370
6.44k
      {
371
6.44k
#ifdef PNG_WRITE_tEXt_SUPPORTED
372
         /* Write uncompressed chunk */
373
6.44k
         png_write_tEXt(png_ptr, info_ptr->text[i].key,
374
6.44k
             info_ptr->text[i].text,
375
6.44k
             0);
376
         /* Mark this chunk as written */
377
6.44k
         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.44k
      }
383
6.55k
   }
384
2.38k
#endif /* tEXt */
385
386
2.38k
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
387
2.38k
   write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
388
2.38k
#endif
389
2.38k
}
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.38k
{
399
2.38k
   png_debug(1, "in png_write_end");
400
401
2.38k
   if (png_ptr == NULL)
402
0
      return;
403
404
2.38k
   if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
405
0
      png_error(png_ptr, "No IDATs written into file");
406
407
2.38k
#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
408
2.38k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
409
486
       png_ptr->num_palette_max >= png_ptr->num_palette)
410
0
      png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
411
2.38k
#endif
412
413
2.38k
#ifdef PNG_WRITE_APNG_SUPPORTED
414
2.38k
   if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
415
0
      png_error(png_ptr, "Not enough frames written");
416
2.38k
#endif
417
418
   /* See if user wants us to write information chunks */
419
2.38k
   if (info_ptr != NULL)
420
2.38k
   {
421
2.38k
#ifdef PNG_WRITE_TEXT_SUPPORTED
422
2.38k
      int i; /* local index variable */
423
2.38k
#endif
424
2.38k
#ifdef PNG_WRITE_tIME_SUPPORTED
425
      /* Check to see if user has supplied a time chunk */
426
2.38k
      if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
427
1.79k
          (png_ptr->mode & PNG_WROTE_tIME) == 0)
428
0
         png_write_tIME(png_ptr, &(info_ptr->mod_time));
429
430
2.38k
#endif
431
2.38k
#ifdef PNG_WRITE_TEXT_SUPPORTED
432
      /* Loop through comment chunks */
433
8.93k
      for (i = 0; i < info_ptr->num_text; i++)
434
6.55k
      {
435
6.55k
         png_debug2(2, "Writing trailer text chunk %d, type %d", i,
436
6.55k
             info_ptr->text[i].compression);
437
         /* An internationalized chunk? */
438
6.55k
         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.55k
         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.55k
         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.55k
      }
484
2.38k
#endif
485
486
2.38k
#ifdef PNG_WRITE_eXIf_SUPPORTED
487
2.38k
      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.38k
#endif
491
492
2.38k
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
493
2.38k
      write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
494
2.38k
#endif
495
2.38k
   }
496
497
2.38k
   png_ptr->mode |= PNG_AFTER_IDAT;
498
499
   /* Write end of PNG file */
500
2.38k
   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.38k
#ifdef PNG_WRITE_FLUSH_SUPPORTED
510
#  ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
511
   png_flush(png_ptr);
512
#  endif
513
2.38k
#endif
514
2.38k
}
515
516
#ifdef PNG_CONVERT_tIME_SUPPORTED
517
void
518
png_convert_from_struct_tm(png_time *ptime, const struct tm * ttime)
519
1.79k
{
520
1.79k
   png_debug(1, "in png_convert_from_struct_tm");
521
522
1.79k
   ptime->year = (png_uint_16)(1900 + ttime->tm_year);
523
1.79k
   ptime->month = (png_byte)(ttime->tm_mon + 1);
524
1.79k
   ptime->day = (png_byte)ttime->tm_mday;
525
1.79k
   ptime->hour = (png_byte)ttime->tm_hour;
526
1.79k
   ptime->minute = (png_byte)ttime->tm_min;
527
1.79k
   ptime->second = (png_byte)ttime->tm_sec;
528
1.79k
}
529
530
void
531
png_convert_from_time_t(png_time *ptime, time_t ttime)
532
1.79k
{
533
1.79k
   struct tm *tbuf;
534
535
1.79k
   png_debug(1, "in png_convert_from_time_t");
536
537
1.79k
   tbuf = gmtime(&ttime);
538
1.79k
   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.79k
   png_convert_from_struct_tm(ptime, tbuf);
549
1.79k
}
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.38k
{
573
2.38k
   png_struct *png_ptr = png_create_png_struct(user_png_ver, error_ptr,
574
2.38k
       error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
575
2.38k
#endif /* USER_MEM */
576
2.38k
   if (png_ptr != NULL)
577
2.38k
   {
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.38k
      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.38k
      png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
588
2.38k
      png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
589
2.38k
      png_ptr->zlib_mem_level = 8;
590
2.38k
      png_ptr->zlib_window_bits = 15;
591
2.38k
      png_ptr->zlib_method = 8;
592
593
2.38k
#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
594
2.38k
      png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
595
2.38k
      png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
596
2.38k
      png_ptr->zlib_text_mem_level = 8;
597
2.38k
      png_ptr->zlib_text_window_bits = 15;
598
2.38k
      png_ptr->zlib_text_method = 8;
599
2.38k
#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.38k
      png_set_write_fn(png_ptr, NULL, NULL, NULL);
625
2.38k
   }
626
627
2.38k
   return png_ptr;
628
2.38k
}
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
288k
{
758
   /* 1.5.6: moved from png_struct to be a local structure: */
759
288k
   png_row_info row_info;
760
761
288k
   png_debug2(1, "in png_write_row (row %u, pass %d)",
762
288k
       png_ptr->row_number, png_ptr->pass);
763
764
288k
   if (png_ptr == NULL)
765
0
      return;
766
767
   /* Initialize transformations and other stuff if first time */
768
288k
   if (png_ptr->row_number == 0 && png_ptr->pass == 0)
769
2.38k
   {
770
      /* Make sure we wrote the header info */
771
2.38k
      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.38k
      png_write_start_row(png_ptr);
813
2.38k
   }
814
815
288k
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
816
   /* If interlaced and not interested in row, return */
817
288k
   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
288k
#endif
883
884
   /* Set up row info for transformations */
885
288k
   row_info.color_type = png_ptr->color_type;
886
288k
   row_info.width = png_ptr->usr_width;
887
288k
   row_info.channels = png_ptr->usr_channels;
888
288k
   row_info.bit_depth = png_ptr->usr_bit_depth;
889
288k
   row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
890
288k
   row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
891
892
288k
   png_debug1(3, "row_info->color_type = %d", row_info.color_type);
893
288k
   png_debug1(3, "row_info->width = %u", row_info.width);
894
288k
   png_debug1(3, "row_info->channels = %d", row_info.channels);
895
288k
   png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
896
288k
   png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
897
288k
   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
288k
   memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
901
902
288k
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
903
   /* Handle interlacing */
904
288k
   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
288k
#endif
916
917
288k
#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
918
   /* Handle other transformations */
919
288k
   if (png_ptr->transformations != 0)
920
131k
      png_do_write_transformations(png_ptr, &row_info);
921
288k
#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
288k
   if (row_info.pixel_depth != png_ptr->pixel_depth ||
927
288k
       row_info.pixel_depth != png_ptr->transformed_pixel_depth)
928
0
      png_error(png_ptr, "internal write transform logic error");
929
930
288k
#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
288k
   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
941
222k
       (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
288k
#endif
947
948
/* Added at libpng-1.5.10 */
949
288k
#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
950
   /* Check for out-of-range palette index */
951
288k
   if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
952
22.3k
       png_ptr->num_palette_max >= 0)
953
17.3k
      png_do_check_palette_indexes(png_ptr, &row_info);
954
288k
#endif
955
956
   /* Find a filter if necessary, filter the row and write it out. */
957
288k
   png_write_find_filter(png_ptr, &row_info);
958
959
288k
   if (png_ptr->write_row_fn != NULL)
960
0
      (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
961
288k
}
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.38k
{
999
2.38k
   png_debug(1, "in png_write_destroy");
1000
1001
   /* Free any memory zlib uses */
1002
2.38k
   if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
1003
2.38k
      deflateEnd(&png_ptr->zstream);
1004
1005
   /* Free our memory.  png_free checks NULL for us. */
1006
2.38k
   png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
1007
2.38k
   png_free(png_ptr, png_ptr->row_buf);
1008
2.38k
   png_ptr->row_buf = NULL;
1009
2.38k
#ifdef PNG_WRITE_FILTER_SUPPORTED
1010
2.38k
   png_free(png_ptr, png_ptr->prev_row);
1011
2.38k
   png_free(png_ptr, png_ptr->try_row);
1012
2.38k
   png_free(png_ptr, png_ptr->tst_row);
1013
2.38k
   png_ptr->prev_row = NULL;
1014
2.38k
   png_ptr->try_row = NULL;
1015
2.38k
   png_ptr->tst_row = NULL;
1016
2.38k
#endif
1017
1018
2.38k
#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
1019
2.38k
   png_free(png_ptr, png_ptr->chunk_list);
1020
2.38k
   png_ptr->chunk_list = NULL;
1021
2.38k
#endif
1022
1023
   /* The error handling and memory handling information is left intact at this
1024
    * point: the jmp_buf may still have to be freed.  See png_destroy_png_struct
1025
    * for how this happens.
1026
    */
1027
2.38k
}
1028
1029
/* Free all memory used by the write.
1030
 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
1031
 * *png_ptr_ptr.  Prior to 1.6.0 it would accept such a value and it would free
1032
 * the passed in info_structs but it would quietly fail to free any of the data
1033
 * inside them.  In 1.6.0 it quietly does nothing (it has to be quiet because it
1034
 * has no png_ptr.)
1035
 */
1036
void
1037
png_destroy_write_struct(png_struct **png_ptr_ptr, png_info **info_ptr_ptr)
1038
2.38k
{
1039
2.38k
   png_debug(1, "in png_destroy_write_struct");
1040
1041
2.38k
   if (png_ptr_ptr != NULL)
1042
2.38k
   {
1043
2.38k
      png_struct *png_ptr = *png_ptr_ptr;
1044
1045
2.38k
      if (png_ptr != NULL) /* added in libpng 1.6.0 */
1046
2.38k
      {
1047
2.38k
         png_destroy_info_struct(png_ptr, info_ptr_ptr);
1048
1049
2.38k
         *png_ptr_ptr = NULL;
1050
2.38k
         png_write_destroy(png_ptr);
1051
2.38k
         png_destroy_png_struct(png_ptr);
1052
2.38k
      }
1053
2.38k
   }
1054
2.38k
}
1055
1056
/* Allow the application to select one or more row filters to use. */
1057
void
1058
png_set_filter(png_struct *png_ptr, int method, int filters)
1059
2.38k
{
1060
2.38k
   png_debug(1, "in png_set_filter");
1061
1062
2.38k
   if (png_ptr == NULL)
1063
0
      return;
1064
1065
2.38k
#ifdef PNG_MNG_FEATURES_SUPPORTED
1066
2.38k
   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1067
413
       (method == PNG_INTRAPIXEL_DIFFERENCING))
1068
0
      method = PNG_FILTER_TYPE_BASE;
1069
1070
2.38k
#endif
1071
2.38k
   if (method == PNG_FILTER_TYPE_BASE)
1072
2.38k
   {
1073
2.38k
      switch (filters & (PNG_ALL_FILTERS | 0x07))
1074
2.38k
      {
1075
0
#ifdef PNG_WRITE_FILTER_SUPPORTED
1076
0
         case 5:
1077
0
         case 6:
1078
0
         case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1079
0
#endif /* WRITE_FILTER */
1080
            /* FALLTHROUGH */
1081
1.02k
         case PNG_FILTER_VALUE_NONE:
1082
1.02k
            png_ptr->do_filter = PNG_FILTER_NONE; break;
1083
1084
0
#ifdef PNG_WRITE_FILTER_SUPPORTED
1085
0
         case PNG_FILTER_VALUE_SUB:
1086
0
            png_ptr->do_filter = PNG_FILTER_SUB; break;
1087
1088
0
         case PNG_FILTER_VALUE_UP:
1089
0
            png_ptr->do_filter = PNG_FILTER_UP; break;
1090
1091
0
         case PNG_FILTER_VALUE_AVG:
1092
0
            png_ptr->do_filter = PNG_FILTER_AVG; break;
1093
1094
0
         case PNG_FILTER_VALUE_PAETH:
1095
0
            png_ptr->do_filter = PNG_FILTER_PAETH; break;
1096
1097
1.35k
         default:
1098
1.35k
            png_ptr->do_filter = (png_byte)filters; break;
1099
#else
1100
         default:
1101
            png_app_error(png_ptr, "Unknown row filter for method 0");
1102
#endif /* WRITE_FILTER */
1103
2.38k
      }
1104
1105
2.38k
#ifdef PNG_WRITE_FILTER_SUPPORTED
1106
      /* If we have allocated the row_buf, this means we have already started
1107
       * with the image and we should have allocated all of the filter buffers
1108
       * that have been selected.  If prev_row isn't already allocated, then
1109
       * it is too late to start using the filters that need it, since we
1110
       * will be missing the data in the previous row.  If an application
1111
       * wants to start and stop using particular filters during compression,
1112
       * it should start out with all of the filters, and then remove them
1113
       * or add them back after the start of compression.
1114
       *
1115
       * NOTE: this is a nasty constraint on the code, because it means that the
1116
       * prev_row buffer must be maintained even if there are currently no
1117
       * 'prev_row' requiring filters active.
1118
       */
1119
2.38k
      if (png_ptr->row_buf != NULL)
1120
0
      {
1121
0
         int num_filters;
1122
0
         png_alloc_size_t buf_size;
1123
1124
         /* Repeat the checks in png_write_start_row; 1 pixel high or wide
1125
          * images cannot benefit from certain filters.  If this isn't done here
1126
          * the check below will fire on 1 pixel high images.
1127
          */
1128
0
         if (png_ptr->height == 1)
1129
0
            filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1130
1131
0
         if (png_ptr->width == 1)
1132
0
            filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1133
1134
0
         if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
1135
0
            && png_ptr->prev_row == NULL)
1136
0
         {
1137
            /* This is the error case, however it is benign - the previous row
1138
             * is not available so the filter can't be used.  Just warn here.
1139
             */
1140
0
            png_app_warning(png_ptr,
1141
0
                "png_set_filter: UP/AVG/PAETH cannot be added after start");
1142
0
            filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1143
0
         }
1144
1145
0
         num_filters = 0;
1146
1147
0
         if (filters & PNG_FILTER_SUB)
1148
0
            num_filters++;
1149
1150
0
         if (filters & PNG_FILTER_UP)
1151
0
            num_filters++;
1152
1153
0
         if (filters & PNG_FILTER_AVG)
1154
0
            num_filters++;
1155
1156
0
         if (filters & PNG_FILTER_PAETH)
1157
0
            num_filters++;
1158
1159
         /* Allocate needed row buffers if they have not already been
1160
          * allocated.
1161
          */
1162
0
         buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
1163
0
             png_ptr->width) + 1;
1164
1165
0
         if (png_ptr->try_row == NULL)
1166
0
            png_ptr->try_row = png_voidcast(png_byte *,
1167
0
                png_malloc(png_ptr, buf_size));
1168
1169
0
         if (num_filters > 1)
1170
0
         {
1171
0
            if (png_ptr->tst_row == NULL)
1172
0
               png_ptr->tst_row = png_voidcast(png_byte *,
1173
0
                   png_malloc(png_ptr, buf_size));
1174
0
         }
1175
0
      }
1176
2.38k
      png_ptr->do_filter = (png_byte)filters;
1177
2.38k
#endif
1178
2.38k
   }
1179
0
   else
1180
0
      png_error(png_ptr, "Unknown custom filter method");
1181
2.38k
}
1182
1183
#ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
1184
void
1185
png_set_compression_level(png_struct *png_ptr, int level)
1186
2.38k
{
1187
2.38k
   png_debug(1, "in png_set_compression_level");
1188
1189
2.38k
   if (png_ptr == NULL)
1190
0
      return;
1191
1192
2.38k
   png_ptr->zlib_level = level;
1193
2.38k
}
1194
1195
void
1196
png_set_compression_mem_level(png_struct *png_ptr, int mem_level)
1197
2.38k
{
1198
2.38k
   png_debug(1, "in png_set_compression_mem_level");
1199
1200
2.38k
   if (png_ptr == NULL)
1201
0
      return;
1202
1203
2.38k
   png_ptr->zlib_mem_level = mem_level;
1204
2.38k
}
1205
1206
void
1207
png_set_compression_strategy(png_struct *png_ptr, int strategy)
1208
0
{
1209
0
   png_debug(1, "in png_set_compression_strategy");
1210
1211
0
   if (png_ptr == NULL)
1212
0
      return;
1213
1214
   /* The flag setting here prevents the libpng dynamic selection of strategy.
1215
    */
1216
0
   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1217
0
   png_ptr->zlib_strategy = strategy;
1218
0
}
1219
1220
/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1221
 * smaller value of window_bits if it can do so safely.
1222
 */
1223
void
1224
png_set_compression_window_bits(png_struct *png_ptr, int window_bits)
1225
0
{
1226
0
   png_debug(1, "in png_set_compression_window_bits");
1227
1228
0
   if (png_ptr == NULL)
1229
0
      return;
1230
1231
   /* Prior to 1.6.0 this would warn but then set the window_bits value. This
1232
    * meant that negative window bits values could be selected that would cause
1233
    * libpng to write a non-standard PNG file with raw deflate or gzip
1234
    * compressed IDAT or ancillary chunks.  Such files can be read and there is
1235
    * no warning on read, so this seems like a very bad idea.
1236
    */
1237
0
   if (window_bits > 15)
1238
0
   {
1239
0
      png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1240
0
      window_bits = 15;
1241
0
   }
1242
1243
0
   else if (window_bits < 8)
1244
0
   {
1245
0
      png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1246
0
      window_bits = 8;
1247
0
   }
1248
1249
0
   png_ptr->zlib_window_bits = window_bits;
1250
0
}
1251
1252
void
1253
png_set_compression_method(png_struct *png_ptr, int method)
1254
0
{
1255
0
   png_debug(1, "in png_set_compression_method");
1256
1257
0
   if (png_ptr == NULL)
1258
0
      return;
1259
1260
   /* This would produce an invalid PNG file if it worked, but it doesn't and
1261
    * deflate will fault it, so it is harmless to just warn here.
1262
    */
1263
0
   if (method != 8)
1264
0
      png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1265
1266
0
   png_ptr->zlib_method = method;
1267
0
}
1268
#endif /* WRITE_CUSTOMIZE_COMPRESSION */
1269
1270
/* The following were added to libpng-1.5.4 */
1271
#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1272
void
1273
png_set_text_compression_level(png_struct *png_ptr, int level)
1274
0
{
1275
0
   png_debug(1, "in png_set_text_compression_level");
1276
1277
0
   if (png_ptr == NULL)
1278
0
      return;
1279
1280
0
   png_ptr->zlib_text_level = level;
1281
0
}
1282
1283
void
1284
png_set_text_compression_mem_level(png_struct *png_ptr, int mem_level)
1285
0
{
1286
0
   png_debug(1, "in png_set_text_compression_mem_level");
1287
1288
0
   if (png_ptr == NULL)
1289
0
      return;
1290
1291
0
   png_ptr->zlib_text_mem_level = mem_level;
1292
0
}
1293
1294
void
1295
png_set_text_compression_strategy(png_struct *png_ptr, int strategy)
1296
0
{
1297
0
   png_debug(1, "in png_set_text_compression_strategy");
1298
1299
0
   if (png_ptr == NULL)
1300
0
      return;
1301
1302
0
   png_ptr->zlib_text_strategy = strategy;
1303
0
}
1304
1305
/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1306
 * smaller value of window_bits if it can do so safely.
1307
 */
1308
void
1309
png_set_text_compression_window_bits(png_struct *png_ptr, int window_bits)
1310
0
{
1311
0
   png_debug(1, "in png_set_text_compression_window_bits");
1312
1313
0
   if (png_ptr == NULL)
1314
0
      return;
1315
1316
0
   if (window_bits > 15)
1317
0
   {
1318
0
      png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1319
0
      window_bits = 15;
1320
0
   }
1321
1322
0
   else if (window_bits < 8)
1323
0
   {
1324
0
      png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1325
0
      window_bits = 8;
1326
0
   }
1327
1328
0
   png_ptr->zlib_text_window_bits = window_bits;
1329
0
}
1330
1331
void
1332
png_set_text_compression_method(png_struct *png_ptr, int method)
1333
0
{
1334
0
   png_debug(1, "in png_set_text_compression_method");
1335
1336
0
   if (png_ptr == NULL)
1337
0
      return;
1338
1339
0
   if (method != 8)
1340
0
      png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1341
1342
0
   png_ptr->zlib_text_method = method;
1343
0
}
1344
#endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1345
/* end of API added to libpng-1.5.4 */
1346
1347
void
1348
png_set_write_status_fn(png_struct *png_ptr, png_write_status_ptr write_row_fn)
1349
0
{
1350
0
   png_debug(1, "in png_set_write_status_fn");
1351
1352
0
   if (png_ptr == NULL)
1353
0
      return;
1354
1355
0
   png_ptr->write_row_fn = write_row_fn;
1356
0
}
1357
1358
#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1359
void
1360
png_set_write_user_transform_fn(png_struct *png_ptr,
1361
    png_user_transform_ptr write_user_transform_fn)
1362
0
{
1363
0
   png_debug(1, "in png_set_write_user_transform_fn");
1364
1365
0
   if (png_ptr == NULL)
1366
0
      return;
1367
1368
0
   png_ptr->transformations |= PNG_USER_TRANSFORM;
1369
0
   png_ptr->write_user_transform_fn = write_user_transform_fn;
1370
0
}
1371
#endif
1372
1373
1374
#ifdef PNG_INFO_IMAGE_SUPPORTED
1375
void
1376
png_write_png(png_struct *png_ptr, png_info *info_ptr,
1377
    int transforms, void *params)
1378
0
{
1379
0
   png_debug(1, "in png_write_png");
1380
1381
0
   if (png_ptr == NULL || info_ptr == NULL)
1382
0
      return;
1383
1384
0
   if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1385
0
   {
1386
0
      png_app_error(png_ptr, "no rows for png_write_image to write");
1387
0
      return;
1388
0
   }
1389
1390
   /* Write the file header information. */
1391
0
   png_write_info(png_ptr, info_ptr);
1392
1393
   /* ------ these transformations don't touch the info structure ------- */
1394
1395
   /* Invert monochrome pixels */
1396
0
   if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1397
0
#ifdef PNG_WRITE_INVERT_SUPPORTED
1398
0
      png_set_invert_mono(png_ptr);
1399
#else
1400
      png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1401
#endif
1402
1403
   /* Shift the pixels up to a legal bit depth and fill in
1404
    * as appropriate to correctly scale the image.
1405
    */
1406
0
   if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1407
0
#ifdef PNG_WRITE_SHIFT_SUPPORTED
1408
0
      if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1409
0
         png_set_shift(png_ptr, &info_ptr->sig_bit);
1410
#else
1411
      png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1412
#endif
1413
1414
   /* Pack pixels into bytes */
1415
0
   if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1416
0
#ifdef PNG_WRITE_PACK_SUPPORTED
1417
0
      png_set_packing(png_ptr);
1418
#else
1419
      png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1420
#endif
1421
1422
   /* Swap location of alpha bytes from ARGB to RGBA */
1423
0
   if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1424
0
#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1425
0
      png_set_swap_alpha(png_ptr);
1426
#else
1427
      png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1428
#endif
1429
1430
   /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1431
    * RGB, note that the code expects the input color type to be G or RGB; no
1432
    * alpha channel.
1433
    */
1434
0
   if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1435
0
       PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1436
0
   {
1437
0
#ifdef PNG_WRITE_FILLER_SUPPORTED
1438
0
      if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1439
0
      {
1440
0
         if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1441
0
            png_app_error(png_ptr,
1442
0
                "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1443
1444
         /* Continue if ignored - this is the pre-1.6.10 behavior */
1445
0
         png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1446
0
      }
1447
1448
0
      else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1449
0
         png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1450
#else
1451
      png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1452
#endif
1453
0
   }
1454
1455
   /* Flip BGR pixels to RGB */
1456
0
   if ((transforms & PNG_TRANSFORM_BGR) != 0)
1457
0
#ifdef PNG_WRITE_BGR_SUPPORTED
1458
0
      png_set_bgr(png_ptr);
1459
#else
1460
      png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1461
#endif
1462
1463
   /* Swap bytes of 16-bit files to most significant byte first */
1464
0
   if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1465
0
#ifdef PNG_WRITE_SWAP_SUPPORTED
1466
0
      png_set_swap(png_ptr);
1467
#else
1468
      png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1469
#endif
1470
1471
   /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
1472
0
   if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1473
0
#ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1474
0
      png_set_packswap(png_ptr);
1475
#else
1476
      png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1477
#endif
1478
1479
   /* Invert the alpha channel from opacity to transparency */
1480
0
   if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1481
0
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1482
0
      png_set_invert_alpha(png_ptr);
1483
#else
1484
      png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1485
#endif
1486
1487
   /* ----------------------- end of transformations ------------------- */
1488
1489
   /* Write the bits */
1490
0
   png_write_image(png_ptr, info_ptr->row_pointers);
1491
1492
   /* It is REQUIRED to call this to finish writing the rest of the file */
1493
0
   png_write_end(png_ptr, info_ptr);
1494
1495
0
   PNG_UNUSED(params)
1496
0
}
1497
#endif
1498
1499
#ifdef PNG_WRITE_APNG_SUPPORTED
1500
void PNGAPI
1501
png_write_frame_head(png_struct *png_ptr, png_info *info_ptr,
1502
                     png_byte **row_pointers,
1503
                     png_uint_32 width, png_uint_32 height,
1504
                     png_uint_32 x_offset, png_uint_32 y_offset,
1505
                     png_uint_16 delay_num, png_uint_16 delay_den,
1506
                     png_byte dispose_op, png_byte blend_op)
1507
0
{
1508
0
   png_debug(1, "in png_write_frame_head");
1509
1510
   /* There is a chance this has been set after png_write_info was called,
1511
    * so it would be set but not written. Is there a way to be sure?
1512
    */
1513
0
   if (!(info_ptr->valid & PNG_INFO_acTL))
1514
0
      png_error(png_ptr, "Cannot write APNG frame: missing acTL");
1515
1516
0
   png_write_reset(png_ptr);
1517
1518
0
   png_write_reinit(png_ptr, info_ptr, width, height);
1519
1520
0
   if (!(png_ptr->num_frames_written == 0 &&
1521
0
         (png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN)))
1522
0
      png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
1523
0
                     delay_num, delay_den, dispose_op, blend_op);
1524
1525
0
   PNG_UNUSED(row_pointers)
1526
0
}
1527
1528
void PNGAPI
1529
png_write_frame_tail(png_struct *png_ptr, png_info *info_ptr)
1530
0
{
1531
0
   png_debug(1, "in png_write_frame_tail");
1532
1533
0
   png_ptr->num_frames_written++;
1534
1535
0
   PNG_UNUSED(info_ptr)
1536
0
}
1537
#endif /* PNG_WRITE_APNG_SUPPORTED */
1538
1539
#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1540
/* Initialize the write structure - general purpose utility. */
1541
static int
1542
png_image_write_init(png_image *image)
1543
0
{
1544
0
   png_struct *png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1545
0
       png_safe_error, png_safe_warning);
1546
1547
0
   if (png_ptr != NULL)
1548
0
   {
1549
0
      png_info *info_ptr = png_create_info_struct(png_ptr);
1550
1551
0
      if (info_ptr != NULL)
1552
0
      {
1553
0
         png_control *control = png_voidcast(png_control *,
1554
0
             png_malloc_warn(png_ptr, (sizeof *control)));
1555
1556
0
         if (control != NULL)
1557
0
         {
1558
0
            memset(control, 0, (sizeof *control));
1559
1560
0
            control->png_ptr = png_ptr;
1561
0
            control->info_ptr = info_ptr;
1562
0
            control->for_write = 1;
1563
1564
0
            image->opaque = control;
1565
0
            return 1;
1566
0
         }
1567
1568
         /* Error clean up */
1569
0
         png_destroy_info_struct(png_ptr, &info_ptr);
1570
0
      }
1571
1572
0
      png_destroy_write_struct(&png_ptr, NULL);
1573
0
   }
1574
1575
0
   return png_image_error(image, "png_image_write_: out of memory");
1576
0
}
1577
1578
/* Arguments to png_image_write_main: */
1579
typedef struct
1580
{
1581
   /* Arguments: */
1582
   png_image *image;
1583
   const void *buffer;
1584
   png_int_32 row_stride;
1585
   const void *colormap;
1586
   int convert_to_8bit;
1587
   /* Local variables: */
1588
   const void *first_row;
1589
   ptrdiff_t row_bytes;
1590
   void *local_row;
1591
   /* Byte count for memory writing */
1592
   png_byte *memory;
1593
   png_alloc_size_t memory_bytes; /* not used for STDIO */
1594
   png_alloc_size_t output_bytes; /* running total */
1595
} png_image_write_control;
1596
1597
/* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1598
 * do any necessary byte swapping.  The component order is defined by the
1599
 * png_image format value.
1600
 */
1601
static int
1602
png_write_image_16bit(void *argument)
1603
0
{
1604
0
   png_image_write_control *display = png_voidcast(png_image_write_control*,
1605
0
       argument);
1606
0
   png_image *image = display->image;
1607
0
   png_struct *png_ptr = image->opaque->png_ptr;
1608
1609
0
   const png_uint_16 *input_row = png_voidcast(const png_uint_16 *,
1610
0
       display->first_row);
1611
0
   png_uint_16 *output_row = png_voidcast(png_uint_16 *, display->local_row);
1612
0
   png_uint_16 *row_end;
1613
0
   unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1614
0
       3 : 1;
1615
0
   int aindex = 0;
1616
0
   png_uint_32 y = image->height;
1617
1618
0
   if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1619
0
   {
1620
0
#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1621
0
      if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1622
0
      {
1623
0
         aindex = -1;
1624
0
         ++input_row; /* To point to the first component */
1625
0
         ++output_row;
1626
0
      }
1627
0
         else
1628
0
            aindex = (int)channels;
1629
#     else
1630
         aindex = (int)channels;
1631
#     endif
1632
0
   }
1633
1634
0
   else
1635
0
      png_error(png_ptr, "png_write_image: internal call error");
1636
1637
   /* Work out the output row end and count over this, note that the increment
1638
    * above to 'row' means that row_end can actually be beyond the end of the
1639
    * row; this is correct.
1640
    */
1641
0
   row_end = output_row + image->width * (channels+1);
1642
1643
0
   for (; y > 0; --y)
1644
0
   {
1645
0
      const png_uint_16 *in_ptr = input_row;
1646
0
      png_uint_16 *out_ptr = output_row;
1647
1648
0
      while (out_ptr < row_end)
1649
0
      {
1650
0
         png_uint_16 alpha = in_ptr[aindex];
1651
0
         png_uint_32 reciprocal = 0;
1652
0
         int c;
1653
1654
0
         out_ptr[aindex] = alpha;
1655
1656
         /* Calculate a reciprocal.  The correct calculation is simply
1657
          * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1658
          * allows correct rounding by adding .5 before the shift.  'reciprocal'
1659
          * is only initialized when required.
1660
          */
1661
0
         if (alpha > 0 && alpha < 65535)
1662
0
            reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1663
1664
0
         c = (int)channels;
1665
0
         do /* always at least one channel */
1666
0
         {
1667
0
            png_uint_16 component = *in_ptr++;
1668
1669
            /* The following gives 65535 for an alpha of 0, which is fine,
1670
             * otherwise if 0/0 is represented as some other value there is more
1671
             * likely to be a discontinuity which will probably damage
1672
             * compression when moving from a fully transparent area to a
1673
             * nearly transparent one.  (The assumption here is that opaque
1674
             * areas tend not to be 0 intensity.)
1675
             */
1676
0
            if (component >= alpha)
1677
0
               component = 65535;
1678
1679
            /* component<alpha, so component/alpha is less than one and
1680
             * component*reciprocal is less than 2^31.
1681
             */
1682
0
            else if (component > 0 && alpha < 65535)
1683
0
            {
1684
0
               png_uint_32 calc = component * reciprocal;
1685
0
               calc += 16384; /* round to nearest */
1686
0
               component = (png_uint_16)(calc >> 15);
1687
0
            }
1688
1689
0
            *out_ptr++ = component;
1690
0
         }
1691
0
         while (--c > 0);
1692
1693
         /* Skip to next component (skip the intervening alpha channel) */
1694
0
         ++in_ptr;
1695
0
         ++out_ptr;
1696
0
      }
1697
1698
0
      png_write_row(png_ptr,
1699
0
          png_voidcast(const png_byte *, display->local_row));
1700
0
      input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1701
0
   }
1702
1703
0
   return 1;
1704
0
}
1705
1706
/* Given 16-bit input (1 to 4 channels) write 8-bit output.  If an alpha channel
1707
 * is present it must be removed from the components, the components are then
1708
 * written in sRGB encoding.  No components are added or removed.
1709
 *
1710
 * Calculate an alpha reciprocal to reverse pre-multiplication.  As above the
1711
 * calculation can be done to 15 bits of accuracy; however, the output needs to
1712
 * be scaled in the range 0..255*65535, so include that scaling here.
1713
 */
1714
0
#   define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
1715
1716
static png_byte
1717
png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1718
    png_uint_32 reciprocal/*from the above macro*/)
1719
0
{
1720
   /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1721
    * is represented as some other value there is more likely to be a
1722
    * discontinuity which will probably damage compression when moving from a
1723
    * fully transparent area to a nearly transparent one.  (The assumption here
1724
    * is that opaque areas tend not to be 0 intensity.)
1725
    *
1726
    * There is a rounding problem here; if alpha is less than 128 it will end up
1727
    * as 0 when scaled to 8 bits.  To avoid introducing spurious colors into the
1728
    * output change for this too.
1729
    */
1730
0
   if (component >= alpha || alpha < 128)
1731
0
      return 255;
1732
1733
   /* component<alpha, so component/alpha is less than one and
1734
    * component*reciprocal is less than 2^31.
1735
    */
1736
0
   else if (component > 0)
1737
0
   {
1738
      /* The test is that alpha/257 (rounded) is less than 255, the first value
1739
       * that becomes 255 is 65407.
1740
       * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1741
       * be exact!)  [Could also test reciprocal != 0]
1742
       */
1743
0
      if (alpha < 65407)
1744
0
      {
1745
0
         component *= reciprocal;
1746
0
         component += 64; /* round to nearest */
1747
0
         component >>= 7;
1748
0
      }
1749
1750
0
      else
1751
0
         component *= 255;
1752
1753
      /* Convert the component to sRGB. */
1754
0
      return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1755
0
   }
1756
1757
0
   else
1758
0
      return 0;
1759
0
}
1760
1761
static int
1762
png_write_image_8bit(void *argument)
1763
0
{
1764
0
   png_image_write_control *display = png_voidcast(png_image_write_control*,
1765
0
       argument);
1766
0
   png_image *image = display->image;
1767
0
   png_struct *png_ptr = image->opaque->png_ptr;
1768
1769
0
   const png_uint_16 *input_row = png_voidcast(const png_uint_16 *,
1770
0
       display->first_row);
1771
0
   png_byte *output_row = png_voidcast(png_byte *, display->local_row);
1772
0
   png_uint_32 y = image->height;
1773
0
   unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1774
0
       3 : 1;
1775
1776
0
   if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1777
0
   {
1778
0
      png_byte *row_end;
1779
0
      int aindex;
1780
1781
0
#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1782
0
      if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1783
0
      {
1784
0
         aindex = -1;
1785
0
         ++input_row; /* To point to the first component */
1786
0
         ++output_row;
1787
0
      }
1788
1789
0
      else
1790
0
#   endif
1791
0
      aindex = (int)channels;
1792
1793
      /* Use row_end in place of a loop counter: */
1794
0
      row_end = output_row + image->width * (channels+1);
1795
1796
0
      for (; y > 0; --y)
1797
0
      {
1798
0
         const png_uint_16 *in_ptr = input_row;
1799
0
         png_byte *out_ptr = output_row;
1800
1801
0
         while (out_ptr < row_end)
1802
0
         {
1803
0
            png_uint_16 alpha = in_ptr[aindex];
1804
0
            png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1805
0
            png_uint_32 reciprocal = 0;
1806
0
            int c;
1807
1808
            /* Scale and write the alpha channel. */
1809
0
            out_ptr[aindex] = alphabyte;
1810
1811
0
            if (alphabyte > 0 && alphabyte < 255)
1812
0
               reciprocal = UNP_RECIPROCAL(alpha);
1813
1814
0
            c = (int)channels;
1815
0
            do /* always at least one channel */
1816
0
               *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1817
0
            while (--c > 0);
1818
1819
            /* Skip to next component (skip the intervening alpha channel) */
1820
0
            ++in_ptr;
1821
0
            ++out_ptr;
1822
0
         } /* while out_ptr < row_end */
1823
1824
0
         png_write_row(png_ptr, png_voidcast(const png_byte *,
1825
0
             display->local_row));
1826
0
         input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1827
0
      } /* while y */
1828
0
   }
1829
1830
0
   else
1831
0
   {
1832
      /* No alpha channel, so the row_end really is the end of the row and it
1833
       * is sufficient to loop over the components one by one.
1834
       */
1835
0
      png_byte *row_end = output_row + image->width * channels;
1836
1837
0
      for (; y > 0; --y)
1838
0
      {
1839
0
         const png_uint_16 *in_ptr = input_row;
1840
0
         png_byte *out_ptr = output_row;
1841
1842
0
         while (out_ptr < row_end)
1843
0
         {
1844
0
            png_uint_32 component = *in_ptr++;
1845
1846
0
            component *= 255;
1847
0
            *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1848
0
         }
1849
1850
0
         png_write_row(png_ptr, output_row);
1851
0
         input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1852
0
      }
1853
0
   }
1854
1855
0
   return 1;
1856
0
}
1857
1858
static void
1859
png_image_set_PLTE(png_image_write_control *display)
1860
0
{
1861
0
   png_image *image = display->image;
1862
0
   const void *cmap = display->colormap;
1863
0
   int entries = image->colormap_entries > 256 ? 256 :
1864
0
       (int)image->colormap_entries;
1865
1866
   /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1867
0
   png_uint_32 format = image->format;
1868
0
   unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1869
1870
0
#   if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
1871
0
      defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
1872
0
      int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1873
0
          (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1874
#   else
1875
#     define afirst 0
1876
#   endif
1877
1878
0
#   ifdef PNG_FORMAT_BGR_SUPPORTED
1879
0
      int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1880
#   else
1881
#     define bgr 0
1882
#   endif
1883
1884
0
   int i, num_trans;
1885
0
   png_color palette[256];
1886
0
   png_byte tRNS[256];
1887
1888
0
   memset(tRNS, 255, (sizeof tRNS));
1889
0
   memset(palette, 0, (sizeof palette));
1890
1891
0
   for (i=num_trans=0; i<entries; ++i)
1892
0
   {
1893
      /* This gets automatically converted to sRGB with reversal of the
1894
       * pre-multiplication if the color-map has an alpha channel.
1895
       */
1896
0
      if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
1897
0
      {
1898
0
         const png_uint_16 *entry = png_voidcast(const png_uint_16 *, cmap);
1899
1900
0
         entry += (unsigned int)i * channels;
1901
1902
0
         if ((channels & 1) != 0) /* no alpha */
1903
0
         {
1904
0
            if (channels >= 3) /* RGB */
1905
0
            {
1906
0
               palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1907
0
                   entry[(2 ^ bgr)]);
1908
0
               palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1909
0
                   entry[1]);
1910
0
               palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1911
0
                   entry[bgr]);
1912
0
            }
1913
1914
0
            else /* Gray */
1915
0
               palette[i].blue = palette[i].red = palette[i].green =
1916
0
                  (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1917
0
         }
1918
1919
0
         else /* alpha */
1920
0
         {
1921
0
            png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1922
0
            png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1923
0
            png_uint_32 reciprocal = 0;
1924
1925
            /* Calculate a reciprocal, as in the png_write_image_8bit code above
1926
             * this is designed to produce a value scaled to 255*65535 when
1927
             * divided by 128 (i.e. asr 7).
1928
             */
1929
0
            if (alphabyte > 0 && alphabyte < 255)
1930
0
               reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1931
1932
0
            tRNS[i] = alphabyte;
1933
0
            if (alphabyte < 255)
1934
0
               num_trans = i+1;
1935
1936
0
            if (channels >= 3) /* RGB */
1937
0
            {
1938
0
               palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1939
0
                   alpha, reciprocal);
1940
0
               palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1941
0
                   reciprocal);
1942
0
               palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1943
0
                   reciprocal);
1944
0
            }
1945
1946
0
            else /* gray */
1947
0
               palette[i].blue = palette[i].red = palette[i].green =
1948
0
                   png_unpremultiply(entry[afirst], alpha, reciprocal);
1949
0
         }
1950
0
      }
1951
1952
0
      else /* Color-map has sRGB values */
1953
0
      {
1954
0
         const png_byte *entry = png_voidcast(const png_byte *, cmap);
1955
1956
0
         entry += (unsigned int)i * channels;
1957
1958
0
         switch (channels)
1959
0
         {
1960
0
            case 4:
1961
0
               tRNS[i] = entry[afirst ? 0 : 3];
1962
0
               if (tRNS[i] < 255)
1963
0
                  num_trans = i+1;
1964
               /* FALLTHROUGH */
1965
0
            case 3:
1966
0
               palette[i].blue = entry[afirst + (2 ^ bgr)];
1967
0
               palette[i].green = entry[afirst + 1];
1968
0
               palette[i].red = entry[afirst + bgr];
1969
0
               break;
1970
1971
0
            case 2:
1972
0
               tRNS[i] = entry[1 ^ afirst];
1973
0
               if (tRNS[i] < 255)
1974
0
                  num_trans = i+1;
1975
               /* FALLTHROUGH */
1976
0
            case 1:
1977
0
               palette[i].blue = palette[i].red = palette[i].green =
1978
0
                  entry[afirst];
1979
0
               break;
1980
1981
0
            default:
1982
0
               break;
1983
0
         }
1984
0
      }
1985
0
   }
1986
1987
#   ifdef afirst
1988
#     undef afirst
1989
#   endif
1990
#   ifdef bgr
1991
#     undef bgr
1992
#   endif
1993
1994
0
   png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
1995
0
       entries);
1996
1997
0
   if (num_trans > 0)
1998
0
      png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
1999
0
          num_trans, NULL);
2000
2001
0
   image->colormap_entries = (png_uint_32)entries;
2002
0
}
2003
2004
static int
2005
png_image_write_main(void *argument)
2006
0
{
2007
0
   png_image_write_control *display = png_voidcast(png_image_write_control*,
2008
0
       argument);
2009
0
   png_image *image = display->image;
2010
0
   png_struct *png_ptr = image->opaque->png_ptr;
2011
0
   png_info *info_ptr = image->opaque->info_ptr;
2012
0
   png_uint_32 format = image->format;
2013
2014
   /* The following four ints are actually booleans */
2015
0
   int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
2016
0
   int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
2017
0
   int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
2018
0
   int write_16bit = linear && (display->convert_to_8bit == 0);
2019
2020
0
#   ifdef PNG_BENIGN_ERRORS_SUPPORTED
2021
      /* Make sure we error out on any bad situation */
2022
0
      png_set_benign_errors(png_ptr, 0/*error*/);
2023
0
#   endif
2024
2025
   /* Default the 'row_stride' parameter if required, also check the row stride
2026
    * and total image size to ensure that they are within the system limits.
2027
    */
2028
0
   {
2029
0
      unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
2030
2031
0
      if (image->width <= 0x7fffffffU/channels) /* no overflow */
2032
0
      {
2033
0
         png_uint_32 check;
2034
0
         png_uint_32 png_row_stride = image->width * channels;
2035
2036
0
         if (display->row_stride == 0)
2037
0
            display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
2038
2039
0
         if (display->row_stride < 0)
2040
0
            check = (png_uint_32)(-display->row_stride);
2041
2042
0
         else
2043
0
            check = (png_uint_32)display->row_stride;
2044
2045
0
         if (check >= png_row_stride)
2046
0
         {
2047
            /* Now check for overflow of the image buffer calculation; this
2048
             * limits the whole image size to 32 bits for API compatibility with
2049
             * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
2050
             */
2051
0
            if (image->height > 0xffffffffU/png_row_stride)
2052
0
               png_error(image->opaque->png_ptr, "memory image too large");
2053
0
         }
2054
2055
0
         else
2056
0
            png_error(image->opaque->png_ptr, "supplied row stride too small");
2057
0
      }
2058
2059
0
      else
2060
0
         png_error(image->opaque->png_ptr, "image row stride too large");
2061
0
   }
2062
2063
   /* Set the required transforms then write the rows in the correct order. */
2064
0
   if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
2065
0
   {
2066
0
      if (display->colormap != NULL && image->colormap_entries > 0)
2067
0
      {
2068
0
         png_uint_32 entries = image->colormap_entries;
2069
2070
0
         png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2071
0
             entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2072
0
             PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2073
0
             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2074
2075
0
         png_image_set_PLTE(display);
2076
0
      }
2077
2078
0
      else
2079
0
         png_error(image->opaque->png_ptr,
2080
0
             "no color-map for color-mapped image");
2081
0
   }
2082
2083
0
   else
2084
0
      png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2085
0
          write_16bit ? 16 : 8,
2086
0
          ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2087
0
          ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2088
0
          PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2089
2090
   /* Counter-intuitively the data transformations must be called *after*
2091
    * png_write_info, not before as in the read code, but the 'set' functions
2092
    * must still be called before.  Just set the color space information, never
2093
    * write an interlaced image.
2094
    */
2095
2096
0
   if (write_16bit != 0)
2097
0
   {
2098
      /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2099
0
      png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2100
2101
0
      if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2102
0
         png_set_cHRM_fixed(png_ptr, info_ptr,
2103
             /* color      x       y */
2104
0
             /* white */ 31270, 32900,
2105
0
             /* red   */ 64000, 33000,
2106
0
             /* green */ 30000, 60000,
2107
0
             /* blue  */ 15000,  6000
2108
0
         );
2109
0
   }
2110
2111
0
   else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2112
0
      png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2113
2114
   /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2115
    * space must still be gamma encoded.
2116
    */
2117
0
   else
2118
0
      png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2119
2120
   /* Write the file header. */
2121
0
   png_write_info(png_ptr, info_ptr);
2122
2123
   /* Now set up the data transformations (*after* the header is written),
2124
    * remove the handled transformations from the 'format' flags for checking.
2125
    *
2126
    * First check for a little endian system if writing 16-bit files.
2127
    */
2128
0
   if (write_16bit != 0)
2129
0
   {
2130
0
      png_uint_16 le = 0x0001;
2131
2132
0
      if ((*(const png_byte *) & le) != 0)
2133
0
         png_set_swap(png_ptr);
2134
0
   }
2135
2136
0
#   ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2137
0
      if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2138
0
      {
2139
0
         if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2140
0
            png_set_bgr(png_ptr);
2141
0
         format &= ~PNG_FORMAT_FLAG_BGR;
2142
0
      }
2143
0
#   endif
2144
2145
0
#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2146
0
      if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2147
0
      {
2148
0
         if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2149
0
            png_set_swap_alpha(png_ptr);
2150
0
         format &= ~PNG_FORMAT_FLAG_AFIRST;
2151
0
      }
2152
0
#   endif
2153
2154
   /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2155
    * above, but the application data is still byte packed.
2156
    */
2157
0
   if (colormap != 0 && image->colormap_entries <= 16)
2158
0
      png_set_packing(png_ptr);
2159
2160
   /* That should have handled all (both) the transforms. */
2161
0
   if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2162
0
         PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2163
0
      png_error(png_ptr, "png_write_image: unsupported transformation");
2164
2165
0
   {
2166
0
      const png_byte *row = png_voidcast(const png_byte *, display->buffer);
2167
0
      ptrdiff_t row_bytes = display->row_stride;
2168
2169
0
      if (linear != 0)
2170
0
         row_bytes *= (sizeof (png_uint_16));
2171
2172
0
      if (row_bytes < 0)
2173
0
         row += (image->height-1) * (-row_bytes);
2174
2175
0
      display->first_row = row;
2176
0
      display->row_bytes = row_bytes;
2177
0
   }
2178
2179
   /* Apply 'fast' options if the flag is set. */
2180
0
   if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2181
0
   {
2182
0
      png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2183
      /* NOTE: determined by experiment using pngstest, this reflects some
2184
       * balance between the time to write the image once and the time to read
2185
       * it about 50 times.  The speed-up in pngstest was about 10-20% of the
2186
       * total (user) time on a heavily loaded system.
2187
       */
2188
0
#   ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
2189
0
      png_set_compression_level(png_ptr, 3);
2190
0
#   endif
2191
0
   }
2192
2193
   /* Check for the cases that currently require a pre-transform on the row
2194
    * before it is written.  This only applies when the input is 16-bit and
2195
    * either there is an alpha channel or it is converted to 8-bit.
2196
    */
2197
0
   if ((linear != 0 && alpha != 0 ) ||
2198
0
       (colormap == 0 && display->convert_to_8bit != 0))
2199
0
   {
2200
0
      png_byte *row = png_voidcast(png_byte *, png_malloc(png_ptr,
2201
0
          png_get_rowbytes(png_ptr, info_ptr)));
2202
0
      int result;
2203
2204
0
      display->local_row = row;
2205
0
      if (write_16bit != 0)
2206
0
         result = png_safe_execute(image, png_write_image_16bit, display);
2207
0
      else
2208
0
         result = png_safe_execute(image, png_write_image_8bit, display);
2209
0
      display->local_row = NULL;
2210
2211
0
      png_free(png_ptr, row);
2212
2213
      /* Skip the 'write_end' on error: */
2214
0
      if (result == 0)
2215
0
         return 0;
2216
0
   }
2217
2218
   /* Otherwise this is the case where the input is in a format currently
2219
    * supported by the rest of the libpng write code; call it directly.
2220
    */
2221
0
   else
2222
0
   {
2223
0
      const png_byte *row = png_voidcast(const png_byte *, display->first_row);
2224
0
      ptrdiff_t row_bytes = display->row_bytes;
2225
0
      png_uint_32 y = image->height;
2226
2227
0
      for (; y > 0; --y)
2228
0
      {
2229
0
         png_write_row(png_ptr, row);
2230
0
         row += row_bytes;
2231
0
      }
2232
0
   }
2233
2234
0
   png_write_end(png_ptr, info_ptr);
2235
0
   return 1;
2236
0
}
2237
2238
static void
2239
image_memory_write(png_struct *png_ptr, png_byte *data, size_t size)
2240
0
{
2241
0
   png_image_write_control *display = png_voidcast(png_image_write_control*,
2242
0
       png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
2243
0
   png_alloc_size_t ob = display->output_bytes;
2244
2245
   /* Check for overflow; this should never happen: */
2246
0
   if (size <= ((png_alloc_size_t)-1) - ob)
2247
0
   {
2248
      /* I don't think libpng ever does this, but just in case: */
2249
0
      if (size > 0)
2250
0
      {
2251
0
         if (display->memory_bytes >= ob+size) /* writing */
2252
0
            memcpy(display->memory+ob, data, size);
2253
2254
         /* Always update the size: */
2255
0
         display->output_bytes = ob+size;
2256
0
      }
2257
0
   }
2258
2259
0
   else
2260
0
      png_error(png_ptr, "png_image_write_to_memory: PNG too big");
2261
0
}
2262
2263
static void
2264
image_memory_flush(png_struct *png_ptr)
2265
0
{
2266
0
   PNG_UNUSED(png_ptr)
2267
0
}
2268
2269
static int
2270
png_image_write_memory(void *argument)
2271
0
{
2272
0
   png_image_write_control *display = png_voidcast(png_image_write_control*,
2273
0
       argument);
2274
2275
   /* The rest of the memory-specific init and write_main in an error protected
2276
    * environment.  This case needs to use callbacks for the write operations
2277
    * since libpng has no built in support for writing to memory.
2278
    */
2279
0
   png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
2280
0
       image_memory_write, image_memory_flush);
2281
2282
0
   return png_image_write_main(display);
2283
0
}
2284
2285
int
2286
png_image_write_to_memory(png_image *image, void *memory,
2287
    png_alloc_size_t *memory_bytes, int convert_to_8bit, const void *buffer,
2288
    png_int_32 row_stride, const void *colormap)
2289
0
{
2290
   /* Write the image to the given buffer, or count the bytes if it is NULL */
2291
0
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
2292
0
   {
2293
0
      if (memory_bytes != NULL && buffer != NULL)
2294
0
      {
2295
         /* This is to give the caller an easier error detection in the NULL
2296
          * case and guard against uninitialized variable problems:
2297
          */
2298
0
         if (memory == NULL)
2299
0
            *memory_bytes = 0;
2300
2301
0
         if (png_image_write_init(image) != 0)
2302
0
         {
2303
0
            png_image_write_control display;
2304
0
            int result;
2305
2306
0
            memset(&display, 0, (sizeof display));
2307
0
            display.image = image;
2308
0
            display.buffer = buffer;
2309
0
            display.row_stride = row_stride;
2310
0
            display.colormap = colormap;
2311
0
            display.convert_to_8bit = convert_to_8bit;
2312
0
            display.memory = png_voidcast(png_byte *, memory);
2313
0
            display.memory_bytes = *memory_bytes;
2314
0
            display.output_bytes = 0;
2315
2316
0
            result = png_safe_execute(image, png_image_write_memory, &display);
2317
0
            png_image_free(image);
2318
2319
            /* write_memory returns true even if we ran out of buffer. */
2320
0
            if (result)
2321
0
            {
2322
               /* On out-of-buffer this function returns '0' but still updates
2323
                * memory_bytes:
2324
                */
2325
0
               if (memory != NULL && display.output_bytes > *memory_bytes)
2326
0
                  result = 0;
2327
2328
0
               *memory_bytes = display.output_bytes;
2329
0
            }
2330
2331
0
            return result;
2332
0
         }
2333
2334
0
         else
2335
0
            return 0;
2336
0
      }
2337
2338
0
      else
2339
0
         return png_image_error(image,
2340
0
             "png_image_write_to_memory: invalid argument");
2341
0
   }
2342
2343
0
   else if (image != NULL)
2344
0
      return png_image_error(image,
2345
0
          "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
2346
2347
0
   else
2348
0
      return 0;
2349
0
}
2350
2351
#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
2352
int
2353
png_image_write_to_stdio(png_image *image, FILE *file, int convert_to_8bit,
2354
    const void *buffer, png_int_32 row_stride, const void *colormap)
2355
0
{
2356
   /* Write the image to the given FILE object. */
2357
0
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
2358
0
   {
2359
0
      if (file != NULL && buffer != NULL)
2360
0
      {
2361
0
         if (png_image_write_init(image) != 0)
2362
0
         {
2363
0
            png_image_write_control display;
2364
0
            int result;
2365
2366
            /* This is slightly evil, but png_init_io doesn't do anything other
2367
             * than this and we haven't changed the standard IO functions so
2368
             * this saves a 'safe' function.
2369
             */
2370
0
            image->opaque->png_ptr->io_ptr = file;
2371
2372
0
            memset(&display, 0, (sizeof display));
2373
0
            display.image = image;
2374
0
            display.buffer = buffer;
2375
0
            display.row_stride = row_stride;
2376
0
            display.colormap = colormap;
2377
0
            display.convert_to_8bit = convert_to_8bit;
2378
2379
0
            result = png_safe_execute(image, png_image_write_main, &display);
2380
0
            png_image_free(image);
2381
0
            return result;
2382
0
         }
2383
2384
0
         else
2385
0
            return 0;
2386
0
      }
2387
2388
0
      else
2389
0
         return png_image_error(image,
2390
0
             "png_image_write_to_stdio: invalid argument");
2391
0
   }
2392
2393
0
   else if (image != NULL)
2394
0
      return png_image_error(image,
2395
0
          "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2396
2397
0
   else
2398
0
      return 0;
2399
0
}
2400
2401
int
2402
png_image_write_to_file(png_image *image, const char *file_name,
2403
    int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2404
    const void *colormap)
2405
0
{
2406
   /* Write the image to the named file. */
2407
0
   if (image != NULL && image->version == PNG_IMAGE_VERSION)
2408
0
   {
2409
0
      if (file_name != NULL && buffer != NULL)
2410
0
      {
2411
0
         FILE *fp = fopen(file_name, "wb");
2412
2413
0
         if (fp != NULL)
2414
0
         {
2415
0
            if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2416
0
                row_stride, colormap) != 0)
2417
0
            {
2418
0
               int error; /* from fflush/fclose */
2419
2420
               /* Make sure the file is flushed correctly. */
2421
0
               if (fflush(fp) == 0 && ferror(fp) == 0)
2422
0
               {
2423
0
                  if (fclose(fp) == 0)
2424
0
                     return 1;
2425
2426
0
                  error = errno; /* from fclose */
2427
0
               }
2428
2429
0
               else
2430
0
               {
2431
0
                  error = errno; /* from fflush or ferror */
2432
0
                  (void)fclose(fp);
2433
0
               }
2434
2435
0
               (void)remove(file_name);
2436
               /* The image has already been cleaned up; this is just used to
2437
                * set the error (because the original write succeeded).
2438
                */
2439
0
               return png_image_error(image, strerror(error));
2440
0
            }
2441
2442
0
            else
2443
0
            {
2444
               /* Clean up: just the opened file. */
2445
0
               (void)fclose(fp);
2446
0
               (void)remove(file_name);
2447
0
               return 0;
2448
0
            }
2449
0
         }
2450
2451
0
         else
2452
0
            return png_image_error(image, strerror(errno));
2453
0
      }
2454
2455
0
      else
2456
0
         return png_image_error(image,
2457
0
             "png_image_write_to_file: invalid argument");
2458
0
   }
2459
2460
0
   else if (image != NULL)
2461
0
      return png_image_error(image,
2462
0
          "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2463
2464
0
   else
2465
0
      return 0;
2466
0
}
2467
#endif /* SIMPLIFIED_WRITE_STDIO */
2468
#endif /* SIMPLIFIED_WRITE */
2469
#endif /* WRITE */