Bumping manifests a=b2g-bump
[gecko.git] / media / libpng / pngwrite.c
blob40f2818325e1f54ddee5c001aa0ec553ee596d58
2 /* pngwrite.c - general routines to write a PNG file
4 * Last changed in libpng 1.6.15 [November 20, 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.)
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
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)
27 if (info_ptr->unknown_chunks_num != 0)
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) != 0)
38 /* If per-chunk unknown chunk handling is enabled use it, otherwise
39 * just write the chunks the application has set.
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.
51 * The default handling is also slightly weird - it is not possible to
52 * stop the writing of all unsafe-to-copy chunks!
54 * TODO: REVIEW: this would seem to be a bug.
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
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);
72 #endif /* WRITE_UNKNOWN_CHUNKS */
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.
83 void PNGAPI
84 png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
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) == 0)
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) != 0 && \
98 png_ptr->mng_features_permitted != 0)
100 png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
101 png_ptr->mng_features_permitted = 0;
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
113 #endif
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.
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.)
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.
130 #ifdef PNG_WRITE_APNG_SUPPORTED
131 if ((info_ptr->valid & PNG_INFO_acTL) != 0)
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) == 0 &&
137 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 &&
138 (info_ptr->valid & PNG_INFO_gAMA) != 0)
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.
147 # ifdef PNG_WRITE_iCCP_SUPPORTED
148 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
149 (info_ptr->valid & PNG_INFO_iCCP) != 0)
151 # ifdef PNG_WRITE_sRGB_SUPPORTED
152 if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
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);
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) == 0 &&
167 (info_ptr->valid & PNG_INFO_sRGB) != 0)
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) != 0)
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) == 0 &&
180 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
181 (info_ptr->valid & PNG_INFO_cHRM) != 0)
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;
194 void PNGAPI
195 png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
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) != 0)
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) !=0)
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) !=0)
218 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
219 /* Invert the alpha channel (in tRNS) */
220 if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
221 info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
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]);
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);
232 #endif
233 #ifdef PNG_WRITE_bKGD_SUPPORTED
234 if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
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) != 0)
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) != 0)
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) != 0)
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) != 0)
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) != 0)
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) != 0)
271 png_write_tIME(png_ptr, &(info_ptr->mod_time));
272 png_ptr->mode |= PNG_WROTE_tIME;
274 #endif /* tIME */
276 #ifdef PNG_WRITE_sPLT_SUPPORTED
277 if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
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++)
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)
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 /* Mark this chunk as written */
300 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
301 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
302 else
303 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
304 #else
305 png_warning(png_ptr, "Unable to write international text");
306 #endif
309 /* If we want a compressed text chunk */
310 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
312 #ifdef PNG_WRITE_zTXt_SUPPORTED
313 /* Write compressed chunk */
314 png_write_zTXt(png_ptr, info_ptr->text[i].key,
315 info_ptr->text[i].text, info_ptr->text[i].compression);
316 /* Mark this chunk as written */
317 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
318 #else
319 png_warning(png_ptr, "Unable to write compressed text");
320 #endif
323 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
325 #ifdef PNG_WRITE_tEXt_SUPPORTED
326 /* Write uncompressed chunk */
327 png_write_tEXt(png_ptr, info_ptr->text[i].key,
328 info_ptr->text[i].text,
330 /* Mark this chunk as written */
331 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
332 #else
333 /* Can't get here */
334 png_warning(png_ptr, "Unable to write uncompressed text");
335 #endif
338 #endif /* tEXt */
340 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
341 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
342 #endif
345 /* Writes the end of the PNG file. If you don't want to write comments or
346 * time information, you can pass NULL for info. If you already wrote these
347 * in png_write_info(), do not write them again here. If you have long
348 * comments, I suggest writing them here, and compressing them.
350 void PNGAPI
351 png_write_end(png_structrp png_ptr, png_inforp info_ptr)
353 png_debug(1, "in png_write_end");
355 if (png_ptr == NULL)
356 return;
358 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
359 png_error(png_ptr, "No IDATs written into file");
361 #ifdef PNG_WRITE_APNG_SUPPORTED
362 if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
363 png_error(png_ptr, "Not enough frames written");
364 #endif
366 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
367 if (png_ptr->num_palette_max > png_ptr->num_palette)
368 png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
369 #endif
371 /* See if user wants us to write information chunks */
372 if (info_ptr != NULL)
374 #ifdef PNG_WRITE_TEXT_SUPPORTED
375 int i; /* local index variable */
376 #endif
377 #ifdef PNG_WRITE_tIME_SUPPORTED
378 /* Check to see if user has supplied a time chunk */
379 if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
380 (png_ptr->mode & PNG_WROTE_tIME) == 0)
381 png_write_tIME(png_ptr, &(info_ptr->mod_time));
383 #endif
384 #ifdef PNG_WRITE_TEXT_SUPPORTED
385 /* Loop through comment chunks */
386 for (i = 0; i < info_ptr->num_text; i++)
388 png_debug2(2, "Writing trailer text chunk %d, type %d", i,
389 info_ptr->text[i].compression);
390 /* An internationalized chunk? */
391 if (info_ptr->text[i].compression > 0)
393 #ifdef PNG_WRITE_iTXt_SUPPORTED
394 /* Write international chunk */
395 png_write_iTXt(png_ptr,
396 info_ptr->text[i].compression,
397 info_ptr->text[i].key,
398 info_ptr->text[i].lang,
399 info_ptr->text[i].lang_key,
400 info_ptr->text[i].text);
401 /* Mark this chunk as written */
402 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
403 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
404 else
405 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
406 #else
407 png_warning(png_ptr, "Unable to write international text");
408 #endif
411 else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
413 #ifdef PNG_WRITE_zTXt_SUPPORTED
414 /* Write compressed chunk */
415 png_write_zTXt(png_ptr, info_ptr->text[i].key,
416 info_ptr->text[i].text, info_ptr->text[i].compression);
417 /* Mark this chunk as written */
418 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
419 #else
420 png_warning(png_ptr, "Unable to write compressed text");
421 #endif
424 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
426 #ifdef PNG_WRITE_tEXt_SUPPORTED
427 /* Write uncompressed chunk */
428 png_write_tEXt(png_ptr, info_ptr->text[i].key,
429 info_ptr->text[i].text, 0);
430 /* Mark this chunk as written */
431 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
432 #else
433 png_warning(png_ptr, "Unable to write uncompressed text");
434 #endif
437 #endif
438 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
439 write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
440 #endif
443 png_ptr->mode |= PNG_AFTER_IDAT;
445 /* Write end of PNG file */
446 png_write_IEND(png_ptr);
448 /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
449 * and restored again in libpng-1.2.30, may cause some applications that
450 * do not set png_ptr->output_flush_fn to crash. If your application
451 * experiences a problem, please try building libpng with
452 * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
453 * png-mng-implement at lists.sf.net .
455 #ifdef PNG_WRITE_FLUSH_SUPPORTED
456 # ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
457 png_flush(png_ptr);
458 # endif
459 #endif
462 #ifdef PNG_CONVERT_tIME_SUPPORTED
463 void PNGAPI
464 png_convert_from_struct_tm(png_timep ptime, PNG_CONST struct tm * ttime)
466 png_debug(1, "in png_convert_from_struct_tm");
468 ptime->year = (png_uint_16)(1900 + ttime->tm_year);
469 ptime->month = (png_byte)(ttime->tm_mon + 1);
470 ptime->day = (png_byte)ttime->tm_mday;
471 ptime->hour = (png_byte)ttime->tm_hour;
472 ptime->minute = (png_byte)ttime->tm_min;
473 ptime->second = (png_byte)ttime->tm_sec;
476 void PNGAPI
477 png_convert_from_time_t(png_timep ptime, time_t ttime)
479 struct tm *tbuf;
481 png_debug(1, "in png_convert_from_time_t");
483 tbuf = gmtime(&ttime);
484 png_convert_from_struct_tm(ptime, tbuf);
486 #endif
488 /* Initialize png_ptr structure, and allocate any memory needed */
489 PNG_FUNCTION(png_structp,PNGAPI
490 png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
491 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
493 #ifndef PNG_USER_MEM_SUPPORTED
494 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
495 error_fn, warn_fn, NULL, NULL, NULL);
496 #else
497 return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
498 warn_fn, NULL, NULL, NULL);
501 /* Alternate initialize png_ptr structure, and allocate any memory needed */
502 PNG_FUNCTION(png_structp,PNGAPI
503 png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
504 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
505 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
507 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
508 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
509 #endif /* USER_MEM */
510 if (png_ptr != NULL)
512 /* Set the zlib control values to defaults; they can be overridden by the
513 * application after the struct has been created.
515 png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
517 /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
518 * pngwutil.c defaults it according to whether or not filters will be
519 * used, and ignores this setting.
521 png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
522 png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
523 png_ptr->zlib_mem_level = 8;
524 png_ptr->zlib_window_bits = 15;
525 png_ptr->zlib_method = 8;
527 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
528 png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
529 png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
530 png_ptr->zlib_text_mem_level = 8;
531 png_ptr->zlib_text_window_bits = 15;
532 png_ptr->zlib_text_method = 8;
533 #endif /* WRITE_COMPRESSED_TEXT */
535 /* This is a highly dubious configuration option; by default it is off,
536 * but it may be appropriate for private builds that are testing
537 * extensions not conformant to the current specification, or of
538 * applications that must not fail to write at all costs!
540 #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
541 /* In stable builds only warn if an application error can be completely
542 * handled.
544 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
545 #endif
547 /* App warnings are warnings in release (or release candidate) builds but
548 * are errors during development.
550 #if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
551 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
552 #endif
554 /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
555 * do it itself) avoiding setting the default function if it is not
556 * required.
558 png_set_write_fn(png_ptr, NULL, NULL, NULL);
561 return png_ptr;
565 /* Write a few rows of image data. If the image is interlaced,
566 * either you will have to write the 7 sub images, or, if you
567 * have called png_set_interlace_handling(), you will have to
568 * "write" the image seven times.
570 void PNGAPI
571 png_write_rows(png_structrp png_ptr, png_bytepp row,
572 png_uint_32 num_rows)
574 png_uint_32 i; /* row counter */
575 png_bytepp rp; /* row pointer */
577 png_debug(1, "in png_write_rows");
579 if (png_ptr == NULL)
580 return;
582 /* Loop through the rows */
583 for (i = 0, rp = row; i < num_rows; i++, rp++)
585 png_write_row(png_ptr, *rp);
589 /* Write the image. You only need to call this function once, even
590 * if you are writing an interlaced image.
592 void PNGAPI
593 png_write_image(png_structrp png_ptr, png_bytepp image)
595 png_uint_32 i; /* row index */
596 int pass, num_pass; /* pass variables */
597 png_bytepp rp; /* points to current row */
599 if (png_ptr == NULL)
600 return;
602 png_debug(1, "in png_write_image");
604 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
605 /* Initialize interlace handling. If image is not interlaced,
606 * this will set pass to 1
608 num_pass = png_set_interlace_handling(png_ptr);
609 #else
610 num_pass = 1;
611 #endif
612 /* Loop through passes */
613 for (pass = 0; pass < num_pass; pass++)
615 /* Loop through image */
616 for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
618 png_write_row(png_ptr, *rp);
623 #ifdef PNG_MNG_FEATURES_SUPPORTED
624 /* Performs intrapixel differencing */
625 static void
626 png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
628 png_debug(1, "in png_do_write_intrapixel");
630 if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
632 int bytes_per_pixel;
633 png_uint_32 row_width = row_info->width;
634 if (row_info->bit_depth == 8)
636 png_bytep rp;
637 png_uint_32 i;
639 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
640 bytes_per_pixel = 3;
642 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
643 bytes_per_pixel = 4;
645 else
646 return;
648 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
650 *(rp) = (png_byte)((*rp - *(rp + 1)) & 0xff);
651 *(rp + 2) = (png_byte)((*(rp + 2) - *(rp + 1)) & 0xff);
655 #ifdef PNG_WRITE_16BIT_SUPPORTED
656 else if (row_info->bit_depth == 16)
658 png_bytep rp;
659 png_uint_32 i;
661 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
662 bytes_per_pixel = 6;
664 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
665 bytes_per_pixel = 8;
667 else
668 return;
670 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
672 png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1);
673 png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3);
674 png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5);
675 png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
676 png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
677 *(rp ) = (png_byte)((red >> 8) & 0xff);
678 *(rp + 1) = (png_byte)(red & 0xff);
679 *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
680 *(rp + 5) = (png_byte)(blue & 0xff);
683 #endif /* WRITE_16BIT */
686 #endif /* MNG_FEATURES */
688 /* Called by user to write a row of image data */
689 void PNGAPI
690 png_write_row(png_structrp png_ptr, png_const_bytep row)
692 /* 1.5.6: moved from png_struct to be a local structure: */
693 png_row_info row_info;
695 if (png_ptr == NULL)
696 return;
698 png_debug2(1, "in png_write_row (row %u, pass %d)",
699 png_ptr->row_number, png_ptr->pass);
701 /* Initialize transformations and other stuff if first time */
702 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
704 /* Make sure we wrote the header info */
705 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
706 png_error(png_ptr,
707 "png_write_info was never called before png_write_row");
709 /* Check for transforms that have been set but were defined out */
710 #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
711 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
712 png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
713 #endif
715 #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
716 if ((png_ptr->transformations & PNG_FILLER) != 0)
717 png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
718 #endif
719 #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
720 defined(PNG_READ_PACKSWAP_SUPPORTED)
721 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
722 png_warning(png_ptr,
723 "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
724 #endif
726 #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
727 if ((png_ptr->transformations & PNG_PACK) != 0)
728 png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
729 #endif
731 #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
732 if ((png_ptr->transformations & PNG_SHIFT) != 0)
733 png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
734 #endif
736 #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
737 if ((png_ptr->transformations & PNG_BGR) != 0)
738 png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
739 #endif
741 #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
742 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
743 png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
744 #endif
746 png_write_start_row(png_ptr);
749 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
750 /* If interlaced and not interested in row, return */
751 if (png_ptr->interlaced != 0 &&
752 (png_ptr->transformations & PNG_INTERLACE) != 0)
754 switch (png_ptr->pass)
756 case 0:
757 if ((png_ptr->row_number & 0x07) != 0)
759 png_write_finish_row(png_ptr);
760 return;
762 break;
764 case 1:
765 if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
767 png_write_finish_row(png_ptr);
768 return;
770 break;
772 case 2:
773 if ((png_ptr->row_number & 0x07) != 4)
775 png_write_finish_row(png_ptr);
776 return;
778 break;
780 case 3:
781 if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
783 png_write_finish_row(png_ptr);
784 return;
786 break;
788 case 4:
789 if ((png_ptr->row_number & 0x03) != 2)
791 png_write_finish_row(png_ptr);
792 return;
794 break;
796 case 5:
797 if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
799 png_write_finish_row(png_ptr);
800 return;
802 break;
804 case 6:
805 if ((png_ptr->row_number & 0x01) == 0)
807 png_write_finish_row(png_ptr);
808 return;
810 break;
812 default: /* error: ignore it */
813 break;
816 #endif
818 /* Set up row info for transformations */
819 row_info.color_type = png_ptr->color_type;
820 row_info.width = png_ptr->usr_width;
821 row_info.channels = png_ptr->usr_channels;
822 row_info.bit_depth = png_ptr->usr_bit_depth;
823 row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
824 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
826 png_debug1(3, "row_info->color_type = %d", row_info.color_type);
827 png_debug1(3, "row_info->width = %u", row_info.width);
828 png_debug1(3, "row_info->channels = %d", row_info.channels);
829 png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
830 png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
831 png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
833 /* Copy user's row into buffer, leaving room for filter byte. */
834 memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
836 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
837 /* Handle interlacing */
838 if (png_ptr->interlaced && png_ptr->pass < 6 &&
839 (png_ptr->transformations & PNG_INTERLACE) != 0)
841 png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
842 /* This should always get caught above, but still ... */
843 if (row_info.width == 0)
845 png_write_finish_row(png_ptr);
846 return;
849 #endif
851 #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
852 /* Handle other transformations */
853 if (png_ptr->transformations != 0)
854 png_do_write_transformations(png_ptr, &row_info);
855 #endif
857 /* At this point the row_info pixel depth must match the 'transformed' depth,
858 * which is also the output depth.
860 if (row_info.pixel_depth != png_ptr->pixel_depth ||
861 row_info.pixel_depth != png_ptr->transformed_pixel_depth)
862 png_error(png_ptr, "internal write transform logic error");
864 #ifdef PNG_MNG_FEATURES_SUPPORTED
865 /* Write filter_method 64 (intrapixel differencing) only if
866 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
867 * 2. Libpng did not write a PNG signature (this filter_method is only
868 * used in PNG datastreams that are embedded in MNG datastreams) and
869 * 3. The application called png_permit_mng_features with a mask that
870 * included PNG_FLAG_MNG_FILTER_64 and
871 * 4. The filter_method is 64 and
872 * 5. The color_type is RGB or RGBA
874 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
875 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
877 /* Intrapixel differencing */
878 png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
880 #endif
882 /* Added at libpng-1.5.10 */
883 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
884 /* Check for out-of-range palette index */
885 if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
886 png_ptr->num_palette_max >= 0)
887 png_do_check_palette_indexes(png_ptr, &row_info);
888 #endif
890 /* Find a filter if necessary, filter the row and write it out. */
891 png_write_find_filter(png_ptr, &row_info);
893 if (png_ptr->write_row_fn != NULL)
894 (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
897 #ifdef PNG_WRITE_FLUSH_SUPPORTED
898 /* Set the automatic flush interval or 0 to turn flushing off */
899 void PNGAPI
900 png_set_flush(png_structrp png_ptr, int nrows)
902 png_debug(1, "in png_set_flush");
904 if (png_ptr == NULL)
905 return;
907 png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
910 /* Flush the current output buffers now */
911 void PNGAPI
912 png_write_flush(png_structrp png_ptr)
914 png_debug(1, "in png_write_flush");
916 if (png_ptr == NULL)
917 return;
919 /* We have already written out all of the data */
920 if (png_ptr->row_number >= png_ptr->num_rows)
921 return;
923 png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
924 png_ptr->flush_rows = 0;
925 png_flush(png_ptr);
927 #endif /* WRITE_FLUSH */
929 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
930 static void png_reset_filter_heuristics(png_structrp png_ptr);/* forward decl */
931 #endif
933 /* Free any memory used in png_ptr struct without freeing the struct itself. */
934 static void
935 png_write_destroy(png_structrp png_ptr)
937 png_debug(1, "in png_write_destroy");
939 /* Free any memory zlib uses */
940 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
941 deflateEnd(&png_ptr->zstream);
943 /* Free our memory. png_free checks NULL for us. */
944 png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
945 png_free(png_ptr, png_ptr->row_buf);
946 png_ptr->row_buf = NULL;
947 #ifdef PNG_WRITE_FILTER_SUPPORTED
948 png_free(png_ptr, png_ptr->prev_row);
949 png_free(png_ptr, png_ptr->sub_row);
950 png_free(png_ptr, png_ptr->up_row);
951 png_free(png_ptr, png_ptr->avg_row);
952 png_free(png_ptr, png_ptr->paeth_row);
953 png_ptr->prev_row = NULL;
954 png_ptr->sub_row = NULL;
955 png_ptr->up_row = NULL;
956 png_ptr->avg_row = NULL;
957 png_ptr->paeth_row = NULL;
958 #endif
960 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
961 /* Use this to save a little code space, it doesn't free the filter_costs */
962 png_reset_filter_heuristics(png_ptr);
963 png_free(png_ptr, png_ptr->filter_costs);
964 png_free(png_ptr, png_ptr->inv_filter_costs);
965 png_ptr->filter_costs = NULL;
966 png_ptr->inv_filter_costs = NULL;
967 #endif
969 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
970 png_free(png_ptr, png_ptr->chunk_list);
971 png_ptr->chunk_list = NULL;
972 #endif
974 /* The error handling and memory handling information is left intact at this
975 * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
976 * for how this happens.
980 /* Free all memory used by the write.
981 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
982 * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
983 * the passed in info_structs but it would quietly fail to free any of the data
984 * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
985 * has no png_ptr.)
987 void PNGAPI
988 png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
990 png_debug(1, "in png_destroy_write_struct");
992 if (png_ptr_ptr != NULL)
994 png_structrp png_ptr = *png_ptr_ptr;
996 if (png_ptr != NULL) /* added in libpng 1.6.0 */
998 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1000 *png_ptr_ptr = NULL;
1001 png_write_destroy(png_ptr);
1002 png_destroy_png_struct(png_ptr);
1007 /* Allow the application to select one or more row filters to use. */
1008 void PNGAPI
1009 png_set_filter(png_structrp png_ptr, int method, int filters)
1011 png_debug(1, "in png_set_filter");
1013 if (png_ptr == NULL)
1014 return;
1016 #ifdef PNG_MNG_FEATURES_SUPPORTED
1017 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1018 (method == PNG_INTRAPIXEL_DIFFERENCING))
1019 method = PNG_FILTER_TYPE_BASE;
1021 #endif
1022 if (method == PNG_FILTER_TYPE_BASE)
1024 switch (filters & (PNG_ALL_FILTERS | 0x07))
1026 #ifdef PNG_WRITE_FILTER_SUPPORTED
1027 case 5:
1028 case 6:
1029 case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1030 /* FALL THROUGH */
1031 #endif /* WRITE_FILTER */
1032 case PNG_FILTER_VALUE_NONE:
1033 png_ptr->do_filter = PNG_FILTER_NONE; break;
1035 #ifdef PNG_WRITE_FILTER_SUPPORTED
1036 case PNG_FILTER_VALUE_SUB:
1037 png_ptr->do_filter = PNG_FILTER_SUB; break;
1039 case PNG_FILTER_VALUE_UP:
1040 png_ptr->do_filter = PNG_FILTER_UP; break;
1042 case PNG_FILTER_VALUE_AVG:
1043 png_ptr->do_filter = PNG_FILTER_AVG; break;
1045 case PNG_FILTER_VALUE_PAETH:
1046 png_ptr->do_filter = PNG_FILTER_PAETH; break;
1048 default:
1049 png_ptr->do_filter = (png_byte)filters; break;
1050 #else
1051 default:
1052 png_app_error(png_ptr, "Unknown row filter for method 0");
1053 #endif /* WRITE_FILTER */
1056 /* If we have allocated the row_buf, this means we have already started
1057 * with the image and we should have allocated all of the filter buffers
1058 * that have been selected. If prev_row isn't already allocated, then
1059 * it is too late to start using the filters that need it, since we
1060 * will be missing the data in the previous row. If an application
1061 * wants to start and stop using particular filters during compression,
1062 * it should start out with all of the filters, and then add and
1063 * remove them after the start of compression.
1065 if (png_ptr->row_buf != NULL)
1067 #ifdef PNG_WRITE_FILTER_SUPPORTED
1068 if ((png_ptr->do_filter & PNG_FILTER_SUB) != 0 &&
1069 png_ptr->sub_row == NULL)
1071 png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
1072 (png_ptr->rowbytes + 1));
1073 png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
1076 if ((png_ptr->do_filter & PNG_FILTER_UP) != 0 &&
1077 png_ptr->up_row == NULL)
1079 if (png_ptr->prev_row == NULL)
1081 png_warning(png_ptr, "Can't add Up filter after starting");
1082 png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
1083 ~PNG_FILTER_UP);
1086 else
1088 png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1089 (png_ptr->rowbytes + 1));
1090 png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
1094 if ((png_ptr->do_filter & PNG_FILTER_AVG) != 0 &&
1095 png_ptr->avg_row == NULL)
1097 if (png_ptr->prev_row == NULL)
1099 png_warning(png_ptr, "Can't add Average filter after starting");
1100 png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
1101 ~PNG_FILTER_AVG);
1104 else
1106 png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1107 (png_ptr->rowbytes + 1));
1108 png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
1112 if ((png_ptr->do_filter & PNG_FILTER_PAETH) != 0 &&
1113 png_ptr->paeth_row == NULL)
1115 if (png_ptr->prev_row == NULL)
1117 png_warning(png_ptr, "Can't add Paeth filter after starting");
1118 png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
1121 else
1123 png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1124 (png_ptr->rowbytes + 1));
1125 png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
1129 if (png_ptr->do_filter == PNG_NO_FILTERS)
1130 #endif /* WRITE_FILTER */
1131 png_ptr->do_filter = PNG_FILTER_NONE;
1134 else
1135 png_error(png_ptr, "Unknown custom filter method");
1138 /* This allows us to influence the way in which libpng chooses the "best"
1139 * filter for the current scanline. While the "minimum-sum-of-absolute-
1140 * differences metric is relatively fast and effective, there is some
1141 * question as to whether it can be improved upon by trying to keep the
1142 * filtered data going to zlib more consistent, hopefully resulting in
1143 * better compression.
1145 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* GRR 970116 */
1146 /* Convenience reset API. */
1147 static void
1148 png_reset_filter_heuristics(png_structrp png_ptr)
1150 /* Clear out any old values in the 'weights' - this must be done because if
1151 * the app calls set_filter_heuristics multiple times with different
1152 * 'num_weights' values we would otherwise potentially have wrong sized
1153 * arrays.
1155 png_ptr->num_prev_filters = 0;
1156 png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
1157 if (png_ptr->prev_filters != NULL)
1159 png_bytep old = png_ptr->prev_filters;
1160 png_ptr->prev_filters = NULL;
1161 png_free(png_ptr, old);
1163 if (png_ptr->filter_weights != NULL)
1165 png_uint_16p old = png_ptr->filter_weights;
1166 png_ptr->filter_weights = NULL;
1167 png_free(png_ptr, old);
1170 if (png_ptr->inv_filter_weights != NULL)
1172 png_uint_16p old = png_ptr->inv_filter_weights;
1173 png_ptr->inv_filter_weights = NULL;
1174 png_free(png_ptr, old);
1177 /* Leave the filter_costs - this array is fixed size. */
1180 static int
1181 png_init_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1182 int num_weights)
1184 if (png_ptr == NULL)
1185 return 0;
1187 /* Clear out the arrays */
1188 png_reset_filter_heuristics(png_ptr);
1190 /* Check arguments; the 'reset' function makes the correct settings for the
1191 * unweighted case, but we must handle the weight case by initializing the
1192 * arrays for the caller.
1194 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1196 int i;
1198 if (num_weights > 0)
1200 png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
1201 (png_uint_32)((sizeof (png_byte)) * num_weights));
1203 /* To make sure that the weighting starts out fairly */
1204 for (i = 0; i < num_weights; i++)
1206 png_ptr->prev_filters[i] = 255;
1209 png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
1210 (png_uint_32)((sizeof (png_uint_16)) * num_weights));
1212 png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
1213 (png_uint_32)((sizeof (png_uint_16)) * num_weights));
1215 for (i = 0; i < num_weights; i++)
1217 png_ptr->inv_filter_weights[i] =
1218 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1221 /* Safe to set this now */
1222 png_ptr->num_prev_filters = (png_byte)num_weights;
1225 /* If, in the future, there are other filter methods, this would
1226 * need to be based on png_ptr->filter.
1228 if (png_ptr->filter_costs == NULL)
1230 png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
1231 (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
1233 png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
1234 (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
1237 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
1239 png_ptr->inv_filter_costs[i] =
1240 png_ptr->filter_costs[i] = PNG_COST_FACTOR;
1243 /* All the arrays are inited, safe to set this: */
1244 png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_WEIGHTED;
1246 /* Return the 'ok' code. */
1247 return 1;
1249 else if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT ||
1250 heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
1252 return 1;
1254 else
1256 png_warning(png_ptr, "Unknown filter heuristic method");
1257 return 0;
1261 /* Provide floating and fixed point APIs */
1262 #ifdef PNG_FLOATING_POINT_SUPPORTED
1263 void PNGAPI
1264 png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1265 int num_weights, png_const_doublep filter_weights,
1266 png_const_doublep filter_costs)
1268 png_debug(1, "in png_set_filter_heuristics");
1270 /* The internal API allocates all the arrays and ensures that the elements of
1271 * those arrays are set to the default value.
1273 if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0)
1274 return;
1276 /* If using the weighted method copy in the weights. */
1277 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1279 int i;
1280 for (i = 0; i < num_weights; i++)
1282 if (filter_weights[i] <= 0.0)
1284 png_ptr->inv_filter_weights[i] =
1285 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1288 else
1290 png_ptr->inv_filter_weights[i] =
1291 (png_uint_16)(PNG_WEIGHT_FACTOR*filter_weights[i]+.5);
1293 png_ptr->filter_weights[i] =
1294 (png_uint_16)(PNG_WEIGHT_FACTOR/filter_weights[i]+.5);
1298 /* Here is where we set the relative costs of the different filters. We
1299 * should take the desired compression level into account when setting
1300 * the costs, so that Paeth, for instance, has a high relative cost at low
1301 * compression levels, while it has a lower relative cost at higher
1302 * compression settings. The filter types are in order of increasing
1303 * relative cost, so it would be possible to do this with an algorithm.
1305 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) if (filter_costs[i] >= 1.0)
1307 png_ptr->inv_filter_costs[i] =
1308 (png_uint_16)(PNG_COST_FACTOR / filter_costs[i] + .5);
1310 png_ptr->filter_costs[i] =
1311 (png_uint_16)(PNG_COST_FACTOR * filter_costs[i] + .5);
1315 #endif /* FLOATING_POINT */
1317 #ifdef PNG_FIXED_POINT_SUPPORTED
1318 void PNGAPI
1319 png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1320 int num_weights, png_const_fixed_point_p filter_weights,
1321 png_const_fixed_point_p filter_costs)
1323 png_debug(1, "in png_set_filter_heuristics_fixed");
1325 /* The internal API allocates all the arrays and ensures that the elements of
1326 * those arrays are set to the default value.
1328 if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0)
1329 return;
1331 /* If using the weighted method copy in the weights. */
1332 if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
1334 int i;
1335 for (i = 0; i < num_weights; i++)
1337 if (filter_weights[i] <= 0)
1339 png_ptr->inv_filter_weights[i] =
1340 png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
1343 else
1345 png_ptr->inv_filter_weights[i] = (png_uint_16)
1346 ((PNG_WEIGHT_FACTOR*filter_weights[i]+PNG_FP_HALF)/PNG_FP_1);
1348 png_ptr->filter_weights[i] = (png_uint_16)((PNG_WEIGHT_FACTOR*
1349 PNG_FP_1+(filter_weights[i]/2))/filter_weights[i]);
1353 /* Here is where we set the relative costs of the different filters. We
1354 * should take the desired compression level into account when setting
1355 * the costs, so that Paeth, for instance, has a high relative cost at low
1356 * compression levels, while it has a lower relative cost at higher
1357 * compression settings. The filter types are in order of increasing
1358 * relative cost, so it would be possible to do this with an algorithm.
1360 for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
1361 if (filter_costs[i] >= PNG_FP_1)
1363 png_uint_32 tmp;
1365 /* Use a 32 bit unsigned temporary here because otherwise the
1366 * intermediate value will be a 32 bit *signed* integer (ANSI rules)
1367 * and this will get the wrong answer on division.
1369 tmp = PNG_COST_FACTOR*PNG_FP_1 + (filter_costs[i]/2);
1370 tmp /= filter_costs[i];
1372 png_ptr->inv_filter_costs[i] = (png_uint_16)tmp;
1374 tmp = PNG_COST_FACTOR * filter_costs[i] + PNG_FP_HALF;
1375 tmp /= PNG_FP_1;
1377 png_ptr->filter_costs[i] = (png_uint_16)tmp;
1381 #endif /* FIXED_POINT */
1382 #endif /* WRITE_WEIGHTED_FILTER */
1384 void PNGAPI
1385 png_set_compression_level(png_structrp png_ptr, int level)
1387 png_debug(1, "in png_set_compression_level");
1389 if (png_ptr == NULL)
1390 return;
1392 png_ptr->zlib_level = level;
1395 void PNGAPI
1396 png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1398 png_debug(1, "in png_set_compression_mem_level");
1400 if (png_ptr == NULL)
1401 return;
1403 png_ptr->zlib_mem_level = mem_level;
1406 void PNGAPI
1407 png_set_compression_strategy(png_structrp png_ptr, int strategy)
1409 png_debug(1, "in png_set_compression_strategy");
1411 if (png_ptr == NULL)
1412 return;
1414 /* The flag setting here prevents the libpng dynamic selection of strategy.
1416 png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1417 png_ptr->zlib_strategy = strategy;
1420 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1421 * smaller value of window_bits if it can do so safely.
1423 void PNGAPI
1424 png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1426 if (png_ptr == NULL)
1427 return;
1429 /* Prior to 1.6.0 this would warn but then set the window_bits value, this
1430 * meant that negative window bits values could be selected which would cause
1431 * libpng to write a non-standard PNG file with raw deflate or gzip
1432 * compressed IDAT or ancillary chunks. Such files can be read and there is
1433 * no warning on read, so this seems like a very bad idea.
1435 if (window_bits > 15)
1437 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1438 window_bits = 15;
1441 else if (window_bits < 8)
1443 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1444 window_bits = 8;
1447 png_ptr->zlib_window_bits = window_bits;
1450 void PNGAPI
1451 png_set_compression_method(png_structrp png_ptr, int method)
1453 png_debug(1, "in png_set_compression_method");
1455 if (png_ptr == NULL)
1456 return;
1458 /* This would produce an invalid PNG file if it worked, but it doesn't and
1459 * deflate will fault it, so it is harmless to just warn here.
1461 if (method != 8)
1462 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1464 png_ptr->zlib_method = method;
1467 /* The following were added to libpng-1.5.4 */
1468 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1469 void PNGAPI
1470 png_set_text_compression_level(png_structrp png_ptr, int level)
1472 png_debug(1, "in png_set_text_compression_level");
1474 if (png_ptr == NULL)
1475 return;
1477 png_ptr->zlib_text_level = level;
1480 void PNGAPI
1481 png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1483 png_debug(1, "in png_set_text_compression_mem_level");
1485 if (png_ptr == NULL)
1486 return;
1488 png_ptr->zlib_text_mem_level = mem_level;
1491 void PNGAPI
1492 png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1494 png_debug(1, "in png_set_text_compression_strategy");
1496 if (png_ptr == NULL)
1497 return;
1499 png_ptr->zlib_text_strategy = strategy;
1502 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1503 * smaller value of window_bits if it can do so safely.
1505 void PNGAPI
1506 png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1508 if (png_ptr == NULL)
1509 return;
1511 if (window_bits > 15)
1513 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1514 window_bits = 15;
1517 else if (window_bits < 8)
1519 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1520 window_bits = 8;
1523 png_ptr->zlib_text_window_bits = window_bits;
1526 void PNGAPI
1527 png_set_text_compression_method(png_structrp png_ptr, int method)
1529 png_debug(1, "in png_set_text_compression_method");
1531 if (png_ptr == NULL)
1532 return;
1534 if (method != 8)
1535 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1537 png_ptr->zlib_text_method = method;
1539 #endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1540 /* end of API added to libpng-1.5.4 */
1542 void PNGAPI
1543 png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1545 if (png_ptr == NULL)
1546 return;
1548 png_ptr->write_row_fn = write_row_fn;
1551 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1552 void PNGAPI
1553 png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1554 write_user_transform_fn)
1556 png_debug(1, "in png_set_write_user_transform_fn");
1558 if (png_ptr == NULL)
1559 return;
1561 png_ptr->transformations |= PNG_USER_TRANSFORM;
1562 png_ptr->write_user_transform_fn = write_user_transform_fn;
1564 #endif
1567 #ifdef PNG_INFO_IMAGE_SUPPORTED
1568 void PNGAPI
1569 png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1570 int transforms, voidp params)
1572 if (png_ptr == NULL || info_ptr == NULL)
1573 return;
1575 if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1577 png_app_error(png_ptr, "no rows for png_write_image to write");
1578 return;
1581 /* Write the file header information. */
1582 png_write_info(png_ptr, info_ptr);
1584 /* ------ these transformations don't touch the info structure ------- */
1586 /* Invert monochrome pixels */
1587 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1588 #ifdef PNG_WRITE_INVERT_SUPPORTED
1589 png_set_invert_mono(png_ptr);
1590 #else
1591 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1592 #endif
1594 /* Shift the pixels up to a legal bit depth and fill in
1595 * as appropriate to correctly scale the image.
1597 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1598 #ifdef PNG_WRITE_SHIFT_SUPPORTED
1599 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1600 png_set_shift(png_ptr, &info_ptr->sig_bit);
1601 #else
1602 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1603 #endif
1605 /* Pack pixels into bytes */
1606 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1607 #ifdef PNG_WRITE_PACK_SUPPORTED
1608 png_set_packing(png_ptr);
1609 #else
1610 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1611 #endif
1613 /* Swap location of alpha bytes from ARGB to RGBA */
1614 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1615 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1616 png_set_swap_alpha(png_ptr);
1617 #else
1618 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1619 #endif
1621 /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1622 * RGB, note that the code expects the input color type to be G or RGB; no
1623 * alpha channel.
1625 if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1626 PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1628 #ifdef PNG_WRITE_FILLER_SUPPORTED
1629 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1631 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1632 png_app_error(png_ptr,
1633 "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1635 /* Continue if ignored - this is the pre-1.6.10 behavior */
1636 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1639 else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1640 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1641 #else
1642 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1643 #endif
1646 /* Flip BGR pixels to RGB */
1647 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1648 #ifdef PNG_WRITE_BGR_SUPPORTED
1649 png_set_bgr(png_ptr);
1650 #else
1651 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1652 #endif
1654 /* Swap bytes of 16-bit files to most significant byte first */
1655 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1656 #ifdef PNG_WRITE_SWAP_SUPPORTED
1657 png_set_swap(png_ptr);
1658 #else
1659 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1660 #endif
1662 /* Swap bits of 1, 2, 4 bit packed pixel formats */
1663 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1664 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1665 png_set_packswap(png_ptr);
1666 #else
1667 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1668 #endif
1670 /* Invert the alpha channel from opacity to transparency */
1671 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1672 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1673 png_set_invert_alpha(png_ptr);
1674 #else
1675 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1676 #endif
1678 /* ----------------------- end of transformations ------------------- */
1680 /* Write the bits */
1681 png_write_image(png_ptr, info_ptr->row_pointers);
1683 /* It is REQUIRED to call this to finish writing the rest of the file */
1684 png_write_end(png_ptr, info_ptr);
1686 PNG_UNUSED(params)
1688 #endif
1691 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1692 #ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */
1693 /* Initialize the write structure - general purpose utility. */
1694 static int
1695 png_image_write_init(png_imagep image)
1697 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1698 png_safe_error, png_safe_warning);
1700 if (png_ptr != NULL)
1702 png_infop info_ptr = png_create_info_struct(png_ptr);
1704 if (info_ptr != NULL)
1706 png_controlp control = png_voidcast(png_controlp,
1707 png_malloc_warn(png_ptr, (sizeof *control)));
1709 if (control != NULL)
1711 memset(control, 0, (sizeof *control));
1713 control->png_ptr = png_ptr;
1714 control->info_ptr = info_ptr;
1715 control->for_write = 1;
1717 image->opaque = control;
1718 return 1;
1721 /* Error clean up */
1722 png_destroy_info_struct(png_ptr, &info_ptr);
1725 png_destroy_write_struct(&png_ptr, NULL);
1728 return png_image_error(image, "png_image_write_: out of memory");
1731 /* Arguments to png_image_write_main: */
1732 typedef struct
1734 /* Arguments: */
1735 png_imagep image;
1736 png_const_voidp buffer;
1737 png_int_32 row_stride;
1738 png_const_voidp colormap;
1739 int convert_to_8bit;
1740 /* Local variables: */
1741 png_const_voidp first_row;
1742 ptrdiff_t row_bytes;
1743 png_voidp local_row;
1744 } png_image_write_control;
1746 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1747 * do any necessary byte swapping. The component order is defined by the
1748 * png_image format value.
1750 static int
1751 png_write_image_16bit(png_voidp argument)
1753 png_image_write_control *display = png_voidcast(png_image_write_control*,
1754 argument);
1755 png_imagep image = display->image;
1756 png_structrp png_ptr = image->opaque->png_ptr;
1758 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1759 display->first_row);
1760 png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1761 png_uint_16p row_end;
1762 const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
1763 int aindex = 0;
1764 png_uint_32 y = image->height;
1766 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1768 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1769 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1771 aindex = -1;
1772 ++input_row; /* To point to the first component */
1773 ++output_row;
1776 else
1777 # endif
1778 aindex = channels;
1781 else
1782 png_error(png_ptr, "png_write_image: internal call error");
1784 /* Work out the output row end and count over this, note that the increment
1785 * above to 'row' means that row_end can actually be beyond the end of the
1786 * row; this is correct.
1788 row_end = output_row + image->width * (channels+1);
1790 while (y-- > 0)
1792 png_const_uint_16p in_ptr = input_row;
1793 png_uint_16p out_ptr = output_row;
1795 while (out_ptr < row_end)
1797 const png_uint_16 alpha = in_ptr[aindex];
1798 png_uint_32 reciprocal = 0;
1799 int c;
1801 out_ptr[aindex] = alpha;
1803 /* Calculate a reciprocal. The correct calculation is simply
1804 * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1805 * allows correct rounding by adding .5 before the shift. 'reciprocal'
1806 * is only initialized when required.
1808 if (alpha > 0 && alpha < 65535)
1809 reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1811 c = channels;
1812 do /* always at least one channel */
1814 png_uint_16 component = *in_ptr++;
1816 /* The following gives 65535 for an alpha of 0, which is fine,
1817 * otherwise if 0/0 is represented as some other value there is more
1818 * likely to be a discontinuity which will probably damage
1819 * compression when moving from a fully transparent area to a
1820 * nearly transparent one. (The assumption here is that opaque
1821 * areas tend not to be 0 intensity.)
1823 if (component >= alpha)
1824 component = 65535;
1826 /* component<alpha, so component/alpha is less than one and
1827 * component*reciprocal is less than 2^31.
1829 else if (component > 0 && alpha < 65535)
1831 png_uint_32 calc = component * reciprocal;
1832 calc += 16384; /* round to nearest */
1833 component = (png_uint_16)(calc >> 15);
1836 *out_ptr++ = component;
1838 while (--c > 0);
1840 /* Skip to next component (skip the intervening alpha channel) */
1841 ++in_ptr;
1842 ++out_ptr;
1845 png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1846 input_row += display->row_bytes/(sizeof (png_uint_16));
1849 return 1;
1852 /* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
1853 * is present it must be removed from the components, the components are then
1854 * written in sRGB encoding. No components are added or removed.
1856 * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
1857 * calculation can be done to 15 bits of accuracy; however, the output needs to
1858 * be scaled in the range 0..255*65535, so include that scaling here.
1860 #define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+(alpha>>1))/alpha)
1862 static png_byte
1863 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1864 png_uint_32 reciprocal/*from the above macro*/)
1866 /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1867 * is represented as some other value there is more likely to be a
1868 * discontinuity which will probably damage compression when moving from a
1869 * fully transparent area to a nearly transparent one. (The assumption here
1870 * is that opaque areas tend not to be 0 intensity.)
1872 * There is a rounding problem here; if alpha is less than 128 it will end up
1873 * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
1874 * output change for this too.
1876 if (component >= alpha || alpha < 128)
1877 return 255;
1879 /* component<alpha, so component/alpha is less than one and
1880 * component*reciprocal is less than 2^31.
1882 else if (component > 0)
1884 /* The test is that alpha/257 (rounded) is less than 255, the first value
1885 * that becomes 255 is 65407.
1886 * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1887 * be exact!) [Could also test reciprocal != 0]
1889 if (alpha < 65407)
1891 component *= reciprocal;
1892 component += 64; /* round to nearest */
1893 component >>= 7;
1896 else
1897 component *= 255;
1899 /* Convert the component to sRGB. */
1900 return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1903 else
1904 return 0;
1907 static int
1908 png_write_image_8bit(png_voidp argument)
1910 png_image_write_control *display = png_voidcast(png_image_write_control*,
1911 argument);
1912 png_imagep image = display->image;
1913 png_structrp png_ptr = image->opaque->png_ptr;
1915 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1916 display->first_row);
1917 png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1918 png_uint_32 y = image->height;
1919 const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
1921 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1923 png_bytep row_end;
1924 int aindex;
1926 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1927 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1929 aindex = -1;
1930 ++input_row; /* To point to the first component */
1931 ++output_row;
1934 else
1935 # endif
1936 aindex = channels;
1938 /* Use row_end in place of a loop counter: */
1939 row_end = output_row + image->width * (channels+1);
1941 while (y-- > 0)
1943 png_const_uint_16p in_ptr = input_row;
1944 png_bytep out_ptr = output_row;
1946 while (out_ptr < row_end)
1948 png_uint_16 alpha = in_ptr[aindex];
1949 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1950 png_uint_32 reciprocal = 0;
1951 int c;
1953 /* Scale and write the alpha channel. */
1954 out_ptr[aindex] = alphabyte;
1956 if (alphabyte > 0 && alphabyte < 255)
1957 reciprocal = UNP_RECIPROCAL(alpha);
1959 c = channels;
1960 do /* always at least one channel */
1961 *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1962 while (--c > 0);
1964 /* Skip to next component (skip the intervening alpha channel) */
1965 ++in_ptr;
1966 ++out_ptr;
1967 } /* while out_ptr < row_end */
1969 png_write_row(png_ptr, png_voidcast(png_const_bytep,
1970 display->local_row));
1971 input_row += display->row_bytes/(sizeof (png_uint_16));
1972 } /* while y */
1975 else
1977 /* No alpha channel, so the row_end really is the end of the row and it
1978 * is sufficient to loop over the components one by one.
1980 png_bytep row_end = output_row + image->width * channels;
1982 while (y-- > 0)
1984 png_const_uint_16p in_ptr = input_row;
1985 png_bytep out_ptr = output_row;
1987 while (out_ptr < row_end)
1989 png_uint_32 component = *in_ptr++;
1991 component *= 255;
1992 *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1995 png_write_row(png_ptr, output_row);
1996 input_row += display->row_bytes/(sizeof (png_uint_16));
2000 return 1;
2003 static void
2004 png_image_set_PLTE(png_image_write_control *display)
2006 const png_imagep image = display->image;
2007 const void *cmap = display->colormap;
2008 const int entries = image->colormap_entries > 256 ? 256 :
2009 (int)image->colormap_entries;
2011 /* NOTE: the caller must check for cmap != NULL and entries != 0 */
2012 const png_uint_32 format = image->format;
2013 const int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
2015 # if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
2016 defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
2017 const int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
2018 (format & PNG_FORMAT_FLAG_ALPHA) != 0;
2019 # else
2020 # define afirst 0
2021 # endif
2023 # ifdef PNG_FORMAT_BGR_SUPPORTED
2024 const int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
2025 # else
2026 # define bgr 0
2027 # endif
2029 int i, num_trans;
2030 png_color palette[256];
2031 png_byte tRNS[256];
2033 memset(tRNS, 255, (sizeof tRNS));
2034 memset(palette, 0, (sizeof palette));
2036 for (i=num_trans=0; i<entries; ++i)
2038 /* This gets automatically converted to sRGB with reversal of the
2039 * pre-multiplication if the color-map has an alpha channel.
2041 if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
2043 png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
2045 entry += i * channels;
2047 if ((channels & 1) != 0) /* no alpha */
2049 if (channels >= 3) /* RGB */
2051 palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
2052 entry[(2 ^ bgr)]);
2053 palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
2054 entry[1]);
2055 palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
2056 entry[bgr]);
2059 else /* Gray */
2060 palette[i].blue = palette[i].red = palette[i].green =
2061 (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
2064 else /* alpha */
2066 png_uint_16 alpha = entry[afirst ? 0 : channels-1];
2067 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
2068 png_uint_32 reciprocal = 0;
2070 /* Calculate a reciprocal, as in the png_write_image_8bit code above
2071 * this is designed to produce a value scaled to 255*65535 when
2072 * divided by 128 (i.e. asr 7).
2074 if (alphabyte > 0 && alphabyte < 255)
2075 reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
2077 tRNS[i] = alphabyte;
2078 if (alphabyte < 255)
2079 num_trans = i+1;
2081 if (channels >= 3) /* RGB */
2083 palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
2084 alpha, reciprocal);
2085 palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
2086 reciprocal);
2087 palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
2088 reciprocal);
2091 else /* gray */
2092 palette[i].blue = palette[i].red = palette[i].green =
2093 png_unpremultiply(entry[afirst], alpha, reciprocal);
2097 else /* Color-map has sRGB values */
2099 png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
2101 entry += i * channels;
2103 switch (channels)
2105 case 4:
2106 tRNS[i] = entry[afirst ? 0 : 3];
2107 if (tRNS[i] < 255)
2108 num_trans = i+1;
2109 /* FALL THROUGH */
2110 case 3:
2111 palette[i].blue = entry[afirst + (2 ^ bgr)];
2112 palette[i].green = entry[afirst + 1];
2113 palette[i].red = entry[afirst + bgr];
2114 break;
2116 case 2:
2117 tRNS[i] = entry[1 ^ afirst];
2118 if (tRNS[i] < 255)
2119 num_trans = i+1;
2120 /* FALL THROUGH */
2121 case 1:
2122 palette[i].blue = palette[i].red = palette[i].green =
2123 entry[afirst];
2124 break;
2126 default:
2127 break;
2132 # ifdef afirst
2133 # undef afirst
2134 # endif
2135 # ifdef bgr
2136 # undef bgr
2137 # endif
2139 png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
2140 entries);
2142 if (num_trans > 0)
2143 png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
2144 num_trans, NULL);
2146 image->colormap_entries = entries;
2149 static int
2150 png_image_write_main(png_voidp argument)
2152 png_image_write_control *display = png_voidcast(png_image_write_control*,
2153 argument);
2154 png_imagep image = display->image;
2155 png_structrp png_ptr = image->opaque->png_ptr;
2156 png_inforp info_ptr = image->opaque->info_ptr;
2157 png_uint_32 format = image->format;
2159 /* The following four ints are actually booleans */
2160 int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
2161 int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
2162 int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
2163 int write_16bit = linear && !colormap && (display->convert_to_8bit == 0);
2165 # ifdef PNG_BENIGN_ERRORS_SUPPORTED
2166 /* Make sure we error out on any bad situation */
2167 png_set_benign_errors(png_ptr, 0/*error*/);
2168 # endif
2170 /* Default the 'row_stride' parameter if required. */
2171 if (display->row_stride == 0)
2172 display->row_stride = PNG_IMAGE_ROW_STRIDE(*image);
2174 /* Set the required transforms then write the rows in the correct order. */
2175 if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
2177 if (display->colormap != NULL && image->colormap_entries > 0)
2179 png_uint_32 entries = image->colormap_entries;
2181 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2182 entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2183 PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2184 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2186 png_image_set_PLTE(display);
2189 else
2190 png_error(image->opaque->png_ptr,
2191 "no color-map for color-mapped image");
2194 else
2195 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2196 write_16bit ? 16 : 8,
2197 ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2198 ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2199 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2201 /* Counter-intuitively the data transformations must be called *after*
2202 * png_write_info, not before as in the read code, but the 'set' functions
2203 * must still be called before. Just set the color space information, never
2204 * write an interlaced image.
2207 if (write_16bit != 0)
2209 /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2210 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2212 if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2213 png_set_cHRM_fixed(png_ptr, info_ptr,
2214 /* color x y */
2215 /* white */ 31270, 32900,
2216 /* red */ 64000, 33000,
2217 /* green */ 30000, 60000,
2218 /* blue */ 15000, 6000
2222 else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2223 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2225 /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2226 * space must still be gamma encoded.
2228 else
2229 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2231 /* Write the file header. */
2232 png_write_info(png_ptr, info_ptr);
2234 /* Now set up the data transformations (*after* the header is written),
2235 * remove the handled transformations from the 'format' flags for checking.
2237 * First check for a little endian system if writing 16 bit files.
2239 if (write_16bit != 0)
2241 PNG_CONST png_uint_16 le = 0x0001;
2243 if ((*(png_const_bytep) & le) != 0)
2244 png_set_swap(png_ptr);
2247 # ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2248 if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2250 if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2251 png_set_bgr(png_ptr);
2252 format &= ~PNG_FORMAT_FLAG_BGR;
2254 # endif
2256 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2257 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2259 if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2260 png_set_swap_alpha(png_ptr);
2261 format &= ~PNG_FORMAT_FLAG_AFIRST;
2263 # endif
2265 /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2266 * above, but the application data is still byte packed.
2268 if (colormap != 0 && image->colormap_entries <= 16)
2269 png_set_packing(png_ptr);
2271 /* That should have handled all (both) the transforms. */
2272 if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2273 PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2274 png_error(png_ptr, "png_write_image: unsupported transformation");
2277 png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2278 ptrdiff_t row_bytes = display->row_stride;
2280 if (linear != 0)
2281 row_bytes *= (sizeof (png_uint_16));
2283 if (row_bytes < 0)
2284 row += (image->height-1) * (-row_bytes);
2286 display->first_row = row;
2287 display->row_bytes = row_bytes;
2290 /* Apply 'fast' options if the flag is set. */
2291 if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2293 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2294 /* NOTE: determined by experiment using pngstest, this reflects some
2295 * balance between the time to write the image once and the time to read
2296 * it about 50 times. The speed-up in pngstest was about 10-20% of the
2297 * total (user) time on a heavily loaded system.
2299 png_set_compression_level(png_ptr, 3);
2302 /* Check for the cases that currently require a pre-transform on the row
2303 * before it is written. This only applies when the input is 16-bit and
2304 * either there is an alpha channel or it is converted to 8-bit.
2306 if ((linear != 0 && alpha != 0 ) ||
2307 (colormap == 0 && display->convert_to_8bit != 0))
2309 png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2310 png_get_rowbytes(png_ptr, info_ptr)));
2311 int result;
2313 display->local_row = row;
2314 if (write_16bit != 0)
2315 result = png_safe_execute(image, png_write_image_16bit, display);
2316 else
2317 result = png_safe_execute(image, png_write_image_8bit, display);
2318 display->local_row = NULL;
2320 png_free(png_ptr, row);
2322 /* Skip the 'write_end' on error: */
2323 if (result == 0)
2324 return 0;
2327 /* Otherwise this is the case where the input is in a format currently
2328 * supported by the rest of the libpng write code; call it directly.
2330 else
2332 png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2333 ptrdiff_t row_bytes = display->row_bytes;
2334 png_uint_32 y = image->height;
2336 while (y-- > 0)
2338 png_write_row(png_ptr, row);
2339 row += row_bytes;
2343 png_write_end(png_ptr, info_ptr);
2344 return 1;
2347 int PNGAPI
2348 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2349 const void *buffer, png_int_32 row_stride, const void *colormap)
2351 /* Write the image to the given (FILE*). */
2352 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2354 if (file != NULL)
2356 if (png_image_write_init(image) != 0)
2358 png_image_write_control display;
2359 int result;
2361 /* This is slightly evil, but png_init_io doesn't do anything other
2362 * than this and we haven't changed the standard IO functions so
2363 * this saves a 'safe' function.
2365 image->opaque->png_ptr->io_ptr = file;
2367 memset(&display, 0, (sizeof display));
2368 display.image = image;
2369 display.buffer = buffer;
2370 display.row_stride = row_stride;
2371 display.colormap = colormap;
2372 display.convert_to_8bit = convert_to_8bit;
2374 result = png_safe_execute(image, png_image_write_main, &display);
2375 png_image_free(image);
2376 return result;
2379 else
2380 return 0;
2383 else
2384 return png_image_error(image,
2385 "png_image_write_to_stdio: invalid argument");
2388 else if (image != NULL)
2389 return png_image_error(image,
2390 "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2392 else
2393 return 0;
2396 int PNGAPI
2397 png_image_write_to_file(png_imagep image, const char *file_name,
2398 int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2399 const void *colormap)
2401 /* Write the image to the named file. */
2402 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2404 if (file_name != NULL)
2406 FILE *fp = fopen(file_name, "wb");
2408 if (fp != NULL)
2410 if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2411 row_stride, colormap) != 0)
2413 int error; /* from fflush/fclose */
2415 /* Make sure the file is flushed correctly. */
2416 if (fflush(fp) == 0 && ferror(fp) == 0)
2418 if (fclose(fp) == 0)
2419 return 1;
2421 error = errno; /* from fclose */
2424 else
2426 error = errno; /* from fflush or ferror */
2427 (void)fclose(fp);
2430 (void)remove(file_name);
2431 /* The image has already been cleaned up; this is just used to
2432 * set the error (because the original write succeeded).
2434 return png_image_error(image, strerror(error));
2437 else
2439 /* Clean up: just the opened file. */
2440 (void)fclose(fp);
2441 (void)remove(file_name);
2442 return 0;
2446 else
2447 return png_image_error(image, strerror(errno));
2450 else
2451 return png_image_error(image,
2452 "png_image_write_to_file: invalid argument");
2455 else if (image != NULL)
2456 return png_image_error(image,
2457 "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2459 else
2460 return 0;
2462 #endif /* STDIO */
2463 #endif /* SIMPLIFIED_WRITE */
2465 #ifdef PNG_WRITE_APNG_SUPPORTED
2466 void PNGAPI
2467 png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
2468 png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
2469 png_uint_32 x_offset, png_uint_32 y_offset,
2470 png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
2471 png_byte blend_op)
2473 png_debug(1, "in png_write_frame_head");
2475 /* there is a chance this has been set after png_write_info was called,
2476 * so it would be set but not written. is there a way to be sure? */
2477 if ((info_ptr->valid & PNG_INFO_acTL) == 0)
2478 png_error(png_ptr, "png_write_frame_head(): acTL not set");
2480 png_write_reset(png_ptr);
2482 png_write_reinit(png_ptr, info_ptr, width, height);
2484 if ((png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN) == 0 ||
2485 png_ptr->num_frames_written != 0)
2486 png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
2487 delay_num, delay_den, dispose_op, blend_op);
2489 PNG_UNUSED(row_pointers)
2492 void PNGAPI
2493 png_write_frame_tail(png_structp png_ptr, png_infop info_ptr)
2495 png_debug(1, "in png_write_frame_tail");
2497 png_ptr->num_frames_written++;
2499 PNG_UNUSED(info_ptr)
2501 #endif /* WRITE_APNG */
2502 #endif /* WRITE */