Coverage Report

Created: 2026-03-31 11:00

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