output-png.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Copyright (C) 2004-2023 Artifex Software, Inc.
  2. //
  3. // This file is part of MuPDF.
  4. //
  5. // MuPDF is free software: you can redistribute it and/or modify it under the
  6. // terms of the GNU Affero General Public License as published by the Free
  7. // Software Foundation, either version 3 of the License, or (at your option)
  8. // any later version.
  9. //
  10. // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
  11. // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  13. // details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
  17. //
  18. // Alternative licensing terms are available from the licensor.
  19. // For commercial licensing, see <https://www.artifex.com/> or contact
  20. // Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
  21. // CA 94129, USA, for further information.
  22. #include "mupdf/fitz.h"
  23. #include "z-imp.h"
  24. #include <string.h>
  25. static inline void big32(unsigned char *buf, unsigned int v)
  26. {
  27. buf[0] = (v >> 24) & 0xff;
  28. buf[1] = (v >> 16) & 0xff;
  29. buf[2] = (v >> 8) & 0xff;
  30. buf[3] = (v) & 0xff;
  31. }
  32. static void putchunk(fz_context *ctx, fz_output *out, char *tag, unsigned char *data, size_t size)
  33. {
  34. unsigned int sum;
  35. if ((uint32_t)size != size)
  36. fz_throw(ctx, FZ_ERROR_LIMIT, "PNG chunk too large");
  37. fz_write_int32_be(ctx, out, (int)size);
  38. fz_write_data(ctx, out, tag, 4);
  39. fz_write_data(ctx, out, data, size);
  40. sum = crc32(0, NULL, 0);
  41. sum = crc32(sum, (unsigned char*)tag, 4);
  42. sum = crc32(sum, data, (unsigned int)size);
  43. fz_write_int32_be(ctx, out, sum);
  44. }
  45. void
  46. fz_save_pixmap_as_png(fz_context *ctx, fz_pixmap *pixmap, const char *filename)
  47. {
  48. fz_output *out = fz_new_output_with_path(ctx, filename, 0);
  49. fz_band_writer *writer = NULL;
  50. fz_var(writer);
  51. fz_try(ctx)
  52. {
  53. writer = fz_new_png_band_writer(ctx, out);
  54. fz_write_header(ctx, writer, pixmap->w, pixmap->h, pixmap->n, pixmap->alpha, pixmap->xres, pixmap->yres, 0, pixmap->colorspace, pixmap->seps);
  55. fz_write_band(ctx, writer, pixmap->stride, pixmap->h, pixmap->samples);
  56. fz_close_band_writer(ctx, writer);
  57. fz_close_output(ctx, out);
  58. }
  59. fz_always(ctx)
  60. {
  61. fz_drop_band_writer(ctx, writer);
  62. fz_drop_output(ctx, out);
  63. }
  64. fz_catch(ctx)
  65. {
  66. fz_rethrow(ctx);
  67. }
  68. }
  69. void
  70. fz_write_pixmap_as_png(fz_context *ctx, fz_output *out, const fz_pixmap *pixmap)
  71. {
  72. fz_band_writer *writer;
  73. if (!out)
  74. return;
  75. writer = fz_new_png_band_writer(ctx, out);
  76. fz_try(ctx)
  77. {
  78. fz_write_header(ctx, writer, pixmap->w, pixmap->h, pixmap->n, pixmap->alpha, pixmap->xres, pixmap->yres, 0, pixmap->colorspace, pixmap->seps);
  79. fz_write_band(ctx, writer, pixmap->stride, pixmap->h, pixmap->samples);
  80. fz_close_band_writer(ctx, writer);
  81. }
  82. fz_always(ctx)
  83. {
  84. fz_drop_band_writer(ctx, writer);
  85. }
  86. fz_catch(ctx)
  87. {
  88. fz_rethrow(ctx);
  89. }
  90. }
  91. typedef struct png_band_writer_s
  92. {
  93. fz_band_writer super;
  94. unsigned char *udata;
  95. unsigned char *cdata;
  96. size_t usize, csize;
  97. z_stream stream;
  98. int stream_started;
  99. int stream_ended;
  100. } png_band_writer;
  101. static void
  102. png_write_icc(fz_context *ctx, png_band_writer *writer, fz_colorspace *cs)
  103. {
  104. #if FZ_ENABLE_ICC
  105. if (cs && !(cs->flags & FZ_COLORSPACE_IS_DEVICE) && (cs->flags & FZ_COLORSPACE_IS_ICC) && cs->u.icc.buffer)
  106. {
  107. fz_output *out = writer->super.out;
  108. size_t size, csize;
  109. fz_buffer *buffer = cs->u.icc.buffer;
  110. unsigned char *pos, *cdata, *chunk = NULL;
  111. const char *name;
  112. /* Deflate the profile */
  113. cdata = fz_new_deflated_data_from_buffer(ctx, &csize, buffer, FZ_DEFLATE_DEFAULT);
  114. if (!cdata)
  115. return;
  116. name = cs->name;
  117. size = csize + strlen(name) + 2;
  118. fz_try(ctx)
  119. {
  120. chunk = fz_calloc(ctx, size, 1);
  121. pos = chunk;
  122. memcpy(chunk, name, strlen(name));
  123. pos += strlen(name) + 2;
  124. memcpy(pos, cdata, csize);
  125. putchunk(ctx, out, "iCCP", chunk, size);
  126. }
  127. fz_always(ctx)
  128. {
  129. fz_free(ctx, cdata);
  130. fz_free(ctx, chunk);
  131. }
  132. fz_catch(ctx)
  133. {
  134. fz_rethrow(ctx);
  135. }
  136. }
  137. #endif
  138. }
  139. static void
  140. png_write_header(fz_context *ctx, fz_band_writer *writer_, fz_colorspace *cs)
  141. {
  142. png_band_writer *writer = (png_band_writer *)(void *)writer_;
  143. fz_output *out = writer->super.out;
  144. int w = writer->super.w;
  145. int h = writer->super.h;
  146. int n = writer->super.n;
  147. int alpha = writer->super.alpha;
  148. static const unsigned char pngsig[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  149. unsigned char head[13];
  150. int color;
  151. if (writer->super.s != 0)
  152. fz_throw(ctx, FZ_ERROR_ARGUMENT, "PNGs cannot contain spot colors");
  153. if (fz_colorspace_type(ctx, cs) == FZ_COLORSPACE_BGR)
  154. fz_throw(ctx, FZ_ERROR_ARGUMENT, "pixmap can not be bgr");
  155. if (cs && !fz_colorspace_is_gray(ctx, cs) && !fz_colorspace_is_rgb(ctx, cs))
  156. fz_throw(ctx, FZ_ERROR_ARGUMENT, "pixmap must be grayscale or rgb to write as png");
  157. /* Treat alpha only as greyscale */
  158. if (n == 1 && alpha)
  159. alpha = 0;
  160. n -= alpha;
  161. switch (n)
  162. {
  163. case 1: color = (alpha ? 4 : 0); break; /* 0 = Greyscale, 4 = Greyscale + Alpha */
  164. case 3: color = (alpha ? 6 : 2); break; /* 2 = RGB, 6 = RGBA */
  165. default:
  166. fz_throw(ctx, FZ_ERROR_ARGUMENT, "pixmap must be grayscale or rgb to write as png");
  167. }
  168. big32(head+0, w);
  169. big32(head+4, h);
  170. head[8] = 8; /* depth */
  171. head[9] = color;
  172. head[10] = 0; /* compression */
  173. head[11] = 0; /* filter */
  174. head[12] = 0; /* interlace */
  175. fz_write_data(ctx, out, pngsig, 8);
  176. putchunk(ctx, out, "IHDR", head, 13);
  177. big32(head+0, writer->super.xres * 100/2.54f + 0.5f);
  178. big32(head+4, writer->super.yres * 100/2.54f + 0.5f);
  179. head[8] = 1; /* metre */
  180. putchunk(ctx, out, "pHYs", head, 9);
  181. png_write_icc(ctx, writer, cs);
  182. }
  183. static void
  184. png_write_band(fz_context *ctx, fz_band_writer *writer_, int stride, int band_start, int band_height, const unsigned char *sp)
  185. {
  186. png_band_writer *writer = (png_band_writer *)(void *)writer_;
  187. fz_output *out = writer->super.out;
  188. unsigned char *dp;
  189. int y, x, k, err, finalband;
  190. int w, h, n;
  191. size_t remain;
  192. if (!out)
  193. return;
  194. w = writer->super.w;
  195. h = writer->super.h;
  196. n = writer->super.n;
  197. finalband = (band_start+band_height >= h);
  198. if (finalband)
  199. band_height = h - band_start;
  200. if (writer->udata == NULL)
  201. {
  202. size_t usize = w;
  203. if (usize > SIZE_MAX / n - 1)
  204. fz_throw(ctx, FZ_ERROR_LIMIT, "png data too large.");
  205. usize = usize * n + 1;
  206. if (usize > SIZE_MAX / band_height)
  207. fz_throw(ctx, FZ_ERROR_LIMIT, "png data too large.");
  208. usize *= band_height;
  209. writer->stream.opaque = ctx;
  210. writer->stream.zalloc = fz_zlib_alloc;
  211. writer->stream.zfree = fz_zlib_free;
  212. writer->stream_started = 1;
  213. err = deflateInit(&writer->stream, Z_DEFAULT_COMPRESSION);
  214. if (err != Z_OK)
  215. fz_throw(ctx, FZ_ERROR_LIBRARY, "compression error %d", err);
  216. writer->usize = usize;
  217. /* Now figure out how large a buffer we need to compress into.
  218. * deflateBound always expands a bit, and it's limited by being
  219. * a uLong rather than a size_t. */
  220. writer->csize = writer->usize >= UINT32_MAX ? UINT32_MAX : deflateBound(&writer->stream, (uLong)writer->usize);
  221. if (writer->csize < writer->usize || writer->csize > UINT32_MAX) /* Check for overflow */
  222. writer->csize = UINT32_MAX;
  223. writer->udata = Memento_label(fz_malloc(ctx, writer->usize), "png_write_udata");
  224. writer->cdata = Memento_label(fz_malloc(ctx, writer->csize), "png_write_cdata");
  225. }
  226. dp = writer->udata;
  227. stride -= w*n;
  228. if (writer->super.alpha)
  229. {
  230. /* Unpremultiply data */
  231. for (y = 0; y < band_height; y++)
  232. {
  233. *dp++ = 0; /* none prediction filter */
  234. for (x = 0; x < w; x++)
  235. {
  236. int a = sp[n-1];
  237. int inva = a ? 256*255/a : 0;
  238. for (k = 0; k < n-1; k++)
  239. dp[k] = (sp[k] * inva + 128)>>8;
  240. dp[k] = a;
  241. sp += n;
  242. dp += n;
  243. }
  244. sp += stride;
  245. }
  246. }
  247. else
  248. {
  249. for (y = 0; y < band_height; y++)
  250. {
  251. *dp++ = 0; /* none prediction filter */
  252. for (x = 0; x < w; x++)
  253. {
  254. for (k = 0; k < n; k++)
  255. dp[k] = sp[k];
  256. sp += n;
  257. dp += n;
  258. }
  259. sp += stride;
  260. }
  261. }
  262. remain = dp - writer->udata;
  263. dp = writer->udata;
  264. do
  265. {
  266. size_t eaten;
  267. writer->stream.next_in = dp;
  268. writer->stream.avail_in = (uInt)(remain <= UINT32_MAX ? remain : UINT32_MAX);
  269. writer->stream.next_out = writer->cdata;
  270. writer->stream.avail_out = writer->csize <= UINT32_MAX ? (uInt)writer->csize : UINT32_MAX;
  271. err = deflate(&writer->stream, (finalband && remain == writer->stream.avail_in) ? Z_FINISH : Z_NO_FLUSH);
  272. if (err != Z_OK && err != Z_STREAM_END)
  273. fz_throw(ctx, FZ_ERROR_LIBRARY, "compression error %d", err);
  274. /* We are guaranteed that writer->stream.next_in will have been updated for the
  275. * data that has been eaten. */
  276. eaten = (writer->stream.next_in - dp);
  277. remain -= eaten;
  278. dp += eaten;
  279. /* We are guaranteed that writer->stream.next_out will have been updated for the
  280. * data that has been written. */
  281. if (writer->stream.next_out != writer->cdata)
  282. putchunk(ctx, out, "IDAT", writer->cdata, writer->stream.next_out - writer->cdata);
  283. /* Zlib only guarantees to have finished when we have no more data to feed in, and
  284. * the last call to deflate did not return with avail_out == 0. (i.e. no more is
  285. * buffered internally.) */
  286. }
  287. while (remain != 0 || writer->stream.avail_out == 0);
  288. }
  289. static void
  290. png_write_trailer(fz_context *ctx, fz_band_writer *writer_)
  291. {
  292. png_band_writer *writer = (png_band_writer *)(void *)writer_;
  293. fz_output *out = writer->super.out;
  294. unsigned char block[1];
  295. int err;
  296. writer->stream_ended = 1;
  297. err = deflateEnd(&writer->stream);
  298. if (err != Z_OK)
  299. fz_throw(ctx, FZ_ERROR_LIBRARY, "compression error %d", err);
  300. putchunk(ctx, out, "IEND", block, 0);
  301. }
  302. static void
  303. png_drop_band_writer(fz_context *ctx, fz_band_writer *writer_)
  304. {
  305. png_band_writer *writer = (png_band_writer *)(void *)writer_;
  306. if (writer->stream_started && !writer->stream_ended)
  307. {
  308. int err = deflateEnd(&writer->stream);
  309. if (err != Z_OK)
  310. fz_warn(ctx, "ignoring compression error %d", err);
  311. }
  312. fz_free(ctx, writer->cdata);
  313. fz_free(ctx, writer->udata);
  314. }
  315. fz_band_writer *fz_new_png_band_writer(fz_context *ctx, fz_output *out)
  316. {
  317. png_band_writer *writer = fz_new_band_writer(ctx, png_band_writer, out);
  318. writer->super.header = png_write_header;
  319. writer->super.band = png_write_band;
  320. writer->super.trailer = png_write_trailer;
  321. writer->super.drop = png_drop_band_writer;
  322. return &writer->super;
  323. }
  324. /* We use an auxiliary function to do pixmap_as_png, as it can enable us to
  325. * drop pix early in the case where we have to convert, potentially saving
  326. * us having to have 2 copies of the pixmap and a buffer open at once. */
  327. static fz_buffer *
  328. png_from_pixmap(fz_context *ctx, fz_pixmap *pix, fz_color_params color_params, int drop)
  329. {
  330. fz_buffer *buf = NULL;
  331. fz_output *out = NULL;
  332. fz_pixmap *pix2 = NULL;
  333. fz_var(buf);
  334. fz_var(out);
  335. fz_var(pix2);
  336. if (pix->w == 0 || pix->h == 0)
  337. {
  338. if (drop)
  339. fz_drop_pixmap(ctx, pix);
  340. return NULL;
  341. }
  342. fz_try(ctx)
  343. {
  344. if (pix->colorspace && pix->colorspace != fz_device_gray(ctx) && pix->colorspace != fz_device_rgb(ctx))
  345. {
  346. pix2 = fz_convert_pixmap(ctx, pix, fz_device_rgb(ctx), NULL, NULL, color_params, 1);
  347. if (drop)
  348. fz_drop_pixmap(ctx, pix);
  349. pix = pix2;
  350. }
  351. buf = fz_new_buffer(ctx, 1024);
  352. out = fz_new_output_with_buffer(ctx, buf);
  353. fz_write_pixmap_as_png(ctx, out, pix);
  354. fz_close_output(ctx, out);
  355. }
  356. fz_always(ctx)
  357. {
  358. fz_drop_pixmap(ctx, drop ? pix : pix2);
  359. fz_drop_output(ctx, out);
  360. }
  361. fz_catch(ctx)
  362. {
  363. fz_drop_buffer(ctx, buf);
  364. fz_rethrow(ctx);
  365. }
  366. return buf;
  367. }
  368. fz_buffer *
  369. fz_new_buffer_from_image_as_png(fz_context *ctx, fz_image *image, fz_color_params color_params)
  370. {
  371. fz_pixmap *pix = fz_get_pixmap_from_image(ctx, image, NULL, NULL, NULL, NULL);
  372. return png_from_pixmap(ctx, pix, color_params, 1);
  373. }
  374. fz_buffer *
  375. fz_new_buffer_from_pixmap_as_png(fz_context *ctx, fz_pixmap *pix, fz_color_params color_params)
  376. {
  377. return png_from_pixmap(ctx, pix, color_params, 0);
  378. }