Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2332 lines
75KB

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