Coverage Report

Created: 2025-06-24 07:01

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