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