Coverage Report

Created: 2022-10-31 07:00

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