1 /* Copyright (C) 2001-2006 Artifex Software, Inc.
2    All Rights Reserved.
3 
4    This software is provided AS-IS with no warranty, either express or
5    implied.
6 
7    This software is distributed under license and may not be copied, modified
8    or distributed except as expressly authorized under the terms of that
9    license.  Refer to licensing information at http://www.artifex.com/
10    or contact Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134,
11    San Rafael, CA  94903, U.S.A., +1(415)492-9861, for further information.
12 */
13 
14 /* $Id: gdevpng.c 8846 2008-07-17 02:34:01Z giles $ */
15 /* PNG (Portable Network Graphics) Format.  Pronounced "ping". */
16 /* lpd 1999-09-24: changes PNG_NO_STDIO to PNG_NO_CONSOLE_IO for libpng
17    versions 1.0.3 and later. */
18 /* lpd 1999-07-01: replaced remaining uses of gs_malloc and gs_free with
19    gs_alloc_bytes and gs_free_object. */
20 /* lpd 1999-03-08: changed png.h to png_.h to allow compiling with only
21    headers in /usr/include, no source code. */
22 /* lpd 1997-07-20: changed from using gs_malloc/png_xxx_int to png_create_xxx
23  * for allocating structures, and from gs_free to png_write_destroy for
24  * freeing them. */
25 /* lpd 1997-5-7: added PNG_LIBPNG_VER conditional for operand types of
26  * dummy png_push_fill_buffer. */
27 /* lpd 1997-4-13: Added PNG_NO_STDIO to remove library access to stderr. */
28 /* lpd 1997-3-14: Added resolution (pHYs) to output. */
29 /* lpd 1996-6-24: Added #ifdef for compatibility with old libpng versions. */
30 /* lpd 1996-6-11: Edited to remove unnecessary color mapping code. */
31 /* lpd (L. Peter Deutsch) 1996-4-7: Modified for libpng 0.88. */
32 /* Original version by Russell Lang 1995-07-04 */
33 
34 #include "gdevprn.h"
35 #include "gdevmem.h"
36 #include "gdevpccm.h"
37 #include "gscdefs.h"
38 
39 #define PNG_INTERNAL
40 /*
41  * libpng versions 1.0.3 and later allow disabling access to the stdxxx
42  * files while retaining support for FILE * I/O.
43  */
44 #define PNG_NO_CONSOLE_IO
45 /*
46  * Earlier libpng versions require disabling FILE * I/O altogether.
47  * This produces a compiler warning about no prototype for png_init_io.
48  * The right thing will happen at link time, since the library itself
49  * is compiled with stdio support.  Unfortunately, we can't do this
50  * conditionally depending on PNG_LIBPNG_VER, because this is defined
51  * in png.h.
52  */
53 /*#define PNG_NO_STDIO*/
54 #include "png_.h"
55 
56 /* ------ The device descriptors ------ */
57 
58 /*
59  * Default X and Y resolution.
60  */
61 #define X_DPI 72
62 #define Y_DPI 72
63 
64 static dev_proc_print_page(png_print_page);
65 static dev_proc_open_device(pngalpha_open);
66 static dev_proc_encode_color(pngalpha_encode_color);
67 static dev_proc_decode_color(pngalpha_decode_color);
68 static dev_proc_copy_alpha(pngalpha_copy_alpha);
69 static dev_proc_fill_rectangle(pngalpha_fill_rectangle);
70 static dev_proc_get_params(pngalpha_get_params);
71 static dev_proc_put_params(pngalpha_put_params);
72 static dev_proc_create_buf_device(pngalpha_create_buf_device);
73 
74 /* Monochrome. */
75 
76 const gx_device_printer gs_pngmono_device =
77 prn_device(prn_std_procs, "pngmono",
78 	   DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
79 	   X_DPI, Y_DPI,
80 	   0, 0, 0, 0,		/* margins */
81 	   1, png_print_page);
82 
83 /* 4-bit planar (EGA/VGA-style) color. */
84 
85 static const gx_device_procs png16_procs =
86 prn_color_procs(gdev_prn_open, gdev_prn_output_page, gdev_prn_close,
87 		pc_4bit_map_rgb_color, pc_4bit_map_color_rgb);
88 const gx_device_printer gs_png16_device = {
89   prn_device_body(gx_device_printer, png16_procs, "png16",
90 	   DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
91 	   X_DPI, Y_DPI,
92 	   0, 0, 0, 0,		/* margins */
93 	   3, 4, 1, 1, 2, 2, png_print_page)
94 };
95 
96 /* 8-bit (SuperVGA-style) color. */
97 /* (Uses a fixed palette of 3,3,2 bits.) */
98 
99 static const gx_device_procs png256_procs =
100 prn_color_procs(gdev_prn_open, gdev_prn_output_page, gdev_prn_close,
101 		pc_8bit_map_rgb_color, pc_8bit_map_color_rgb);
102 const gx_device_printer gs_png256_device = {
103   prn_device_body(gx_device_printer, png256_procs, "png256",
104 	   DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
105 	   X_DPI, Y_DPI,
106 	   0, 0, 0, 0,		/* margins */
107 	   3, 8, 5, 5, 6, 6, png_print_page)
108 };
109 
110 /* 8-bit gray */
111 
112 static const gx_device_procs pnggray_procs =
113 prn_color_procs(gdev_prn_open, gdev_prn_output_page, gdev_prn_close,
114 	      gx_default_gray_map_rgb_color, gx_default_gray_map_color_rgb);
115 const gx_device_printer gs_pnggray_device =
116 {prn_device_body(gx_device_printer, pnggray_procs, "pnggray",
117 		 DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
118 		 X_DPI, Y_DPI,
119 		 0, 0, 0, 0,	/* margins */
120 		 1, 8, 255, 0, 256, 0, png_print_page)
121 };
122 
123 /* 24-bit color. */
124 
125 static const gx_device_procs png16m_procs =
126 prn_color_procs(gdev_prn_open, gdev_prn_output_page, gdev_prn_close,
127 		gx_default_rgb_map_rgb_color, gx_default_rgb_map_color_rgb);
128 const gx_device_printer gs_png16m_device =
129 prn_device(png16m_procs, "png16m",
130 	   DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
131 	   X_DPI, Y_DPI,
132 	   0, 0, 0, 0,		/* margins */
133 	   24, png_print_page);
134 
135 /* 48 bit color. */
136 
137 static const gx_device_procs png48_procs =
138 prn_color_procs(gdev_prn_open, gdev_prn_output_page, gdev_prn_close,
139 		gx_default_rgb_map_rgb_color, gx_default_rgb_map_color_rgb);
140 const gx_device_printer gs_png48_device =
141 prn_device(png48_procs, "png48",
142 	   DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
143 	   X_DPI, Y_DPI,
144 	   0, 0, 0, 0,		/* margins */
145 	   48, png_print_page);
146 
147 
148 /* 32-bit RGBA */
149 /* pngalpha device is 32-bit RGBA, with the alpha channel
150  * indicating pixel coverage, not true transparency.
151  * Anti-aliasing is enabled by default.
152  * An erasepage will erase to transparent, not white.
153  * It is intended to be used for creating web graphics with
154  * a transparent background.
155  */
156 typedef struct gx_device_pngalpha_s gx_device_pngalpha;
157 struct gx_device_pngalpha_s {
158     gx_device_common;
159     gx_prn_device_common;
160     dev_t_proc_fill_rectangle((*orig_fill_rectangle), gx_device);
161     int background;
162 };
163 static const gx_device_procs pngalpha_procs =
164 {
165 	pngalpha_open,
166 	NULL,	/* get_initial_matrix */
167 	NULL,	/* sync_output */
168 	gdev_prn_output_page,
169 	gdev_prn_close,
170 	pngalpha_encode_color,	/* map_rgb_color */
171 	pngalpha_decode_color,  /* map_color_rgb */
172 	pngalpha_fill_rectangle,
173 	NULL,	/* tile_rectangle */
174 	NULL,	/* copy_mono */
175 	NULL,	/* copy_color */
176 	NULL,	/* draw_line */
177 	NULL,	/* get_bits */
178 	pngalpha_get_params,
179 	pngalpha_put_params,
180 	NULL,	/* map_cmyk_color */
181 	NULL,	/* get_xfont_procs */
182 	NULL,	/* get_xfont_device */
183 	NULL,	/* map_rgb_alpha_color */
184 	gx_page_device_get_page_device,
185 	NULL,	/* get_alpha_bits */
186 	pngalpha_copy_alpha,
187 	NULL,	/* get_band */
188 	NULL,	/* copy_rop */
189 	NULL,	/* fill_path */
190 	NULL,	/* stroke_path */
191 	NULL,	/* fill_mask */
192 	NULL,	/* fill_trapezoid */
193 	NULL,	/* fill_parallelogram */
194 	NULL,	/* fill_triangle */
195 	NULL,	/* draw_thin_line */
196 	NULL,	/* begin_image */
197 	NULL,	/* image_data */
198 	NULL,	/* end_image */
199 	NULL,	/* strip_tile_rectangle */
200 	NULL,	/* strip_copy_rop, */
201 	NULL,	/* get_clipping_box */
202 	NULL,	/* begin_typed_image */
203 	NULL,	/* get_bits_rectangle */
204 	NULL,	/* map_color_rgb_alpha */
205 	NULL,	/* create_compositor */
206 	NULL,	/* get_hardware_params */
207 	NULL,	/* text_begin */
208 	NULL,	/* finish_copydevice */
209 	NULL, 	/* begin_transparency_group */
210 	NULL, 	/* end_transparency_group */
211 	NULL, 	/* begin_transparency_mask */
212 	NULL, 	/* end_transparency_mask */
213 	NULL, 	/* discard_transparency_layer */
214 	gx_default_DevRGB_get_color_mapping_procs,
215 	gx_default_DevRGB_get_color_comp_index,
216 	pngalpha_encode_color,
217 	pngalpha_decode_color
218 };
219 
220 const gx_device_pngalpha gs_pngalpha_device = {
221 	std_device_part1_(gx_device_pngalpha, &pngalpha_procs, "pngalpha",
222 		&st_device_printer, open_init_closed),
223 	/* color_info */
224 	{3 /* max components */,
225 	 3 /* number components */,
226 	 GX_CINFO_POLARITY_ADDITIVE /* polarity */,
227 	 32 /* depth */,
228 	 -1 /* gray index */,
229 	 255 /* max gray */,
230 	 255 /* max color */,
231 	 256 /* dither grays */,
232 	 256 /* dither colors */,
233 	 { 4, 4 } /* antialias info text, graphics */,
234 	 GX_CINFO_SEP_LIN_NONE /* separable_and_linear */,
235 	 { 0 } /* component shift */,
236 	 { 0 } /* component bits */,
237 	 { 0 } /* component mask */,
238 	 "DeviceRGB" /* process color name */,
239 	 GX_CINFO_OPMODE_UNKNOWN /* opmode */,
240 	 0 /* process_cmps */
241 	},
242 	std_device_part2_(
243 	  (int)((float)(DEFAULT_WIDTH_10THS) * (X_DPI) / 10 + 0.5),
244 	  (int)((float)(DEFAULT_HEIGHT_10THS) * (Y_DPI) / 10 + 0.5),
245 	   X_DPI, Y_DPI),
246 	offset_margin_values(0, 0, 0, 0, 0, 0),
247 	std_device_part3_(),
248 	prn_device_body_rest_(png_print_page),
249 	NULL,
250 	0xffffff	/* white background */
251 };
252 
253 
254 /* ------ Private definitions ------ */
255 
256 /* Write out a page in PNG format. */
257 /* This routine is used for all formats. */
258 static int
png_print_page(gx_device_printer * pdev,FILE * file)259 png_print_page(gx_device_printer * pdev, FILE * file)
260 {
261     gs_memory_t *mem = pdev->memory;
262     int raster = gdev_prn_raster(pdev);
263 
264     /* PNG structures */
265     byte *row = gs_alloc_bytes(mem, raster, "png raster buffer");
266     png_struct *png_ptr =
267     png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
268     png_info *info_ptr =
269     png_create_info_struct(png_ptr);
270     int height = pdev->height;
271     int depth = pdev->color_info.depth;
272     int y;
273     int code;			/* return code */
274     char software_key[80];
275     char software_text[256];
276     png_text text_png;
277 
278     if (row == 0 || png_ptr == 0 || info_ptr == 0) {
279 	code = gs_note_error(gs_error_VMerror);
280 	goto done;
281     }
282     /* set error handling */
283     if (setjmp(png_ptr->jmpbuf)) {
284 	/* If we get here, we had a problem reading the file */
285 	code = gs_note_error(gs_error_VMerror);
286 	goto done;
287     }
288     code = 0;			/* for normal path */
289     /* set up the output control */
290     png_init_io(png_ptr, file);
291 
292     /* set the file information here */
293     info_ptr->width = pdev->width;
294     info_ptr->height = pdev->height;
295     /* resolution is in pixels per meter vs. dpi */
296     info_ptr->x_pixels_per_unit =
297 	(png_uint_32) (pdev->HWResolution[0] * (100.0 / 2.54));
298     info_ptr->y_pixels_per_unit =
299 	(png_uint_32) (pdev->HWResolution[1] * (100.0 / 2.54));
300     info_ptr->phys_unit_type = PNG_RESOLUTION_METER;
301     info_ptr->valid |= PNG_INFO_pHYs;
302     switch (depth) {
303 	case 32:
304 	    info_ptr->bit_depth = 8;
305 	    info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
306 	    png_set_invert_alpha(png_ptr);
307 	    {   gx_device_pngalpha *ppdev = (gx_device_pngalpha *)pdev;
308 		png_color_16 background;
309 		background.index = 0;
310 		background.red =   (ppdev->background >> 16) & 0xff;
311 		background.green = (ppdev->background >> 8)  & 0xff;
312 		background.blue =  (ppdev->background)       & 0xff;
313 		background.gray = 0;
314 		png_set_bKGD(png_ptr, info_ptr, &background);
315 	    }
316 	    break;
317 	case 48:
318 	    info_ptr->bit_depth = 16;
319 	    info_ptr->color_type = PNG_COLOR_TYPE_RGB;
320 #if defined(ARCH_IS_BIG_ENDIAN) && (!ARCH_IS_BIG_ENDIAN)
321 	    png_set_swap(png_ptr);
322 #endif
323 	    break;
324 	case 24:
325 	    info_ptr->bit_depth = 8;
326 	    info_ptr->color_type = PNG_COLOR_TYPE_RGB;
327 	    break;
328 	case 8:
329 	    info_ptr->bit_depth = 8;
330 	    if (gx_device_has_color(pdev))
331 		info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
332 	    else
333 		info_ptr->color_type = PNG_COLOR_TYPE_GRAY;
334 	    break;
335 	case 4:
336 	    info_ptr->bit_depth = 4;
337 	    info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
338 	    break;
339 	case 1:
340 	    info_ptr->bit_depth = 1;
341 	    info_ptr->color_type = PNG_COLOR_TYPE_GRAY;
342 	    /* invert monocrome pixels */
343 	    png_set_invert_mono(png_ptr);
344 	    break;
345     }
346 
347     /* set the palette if there is one */
348     if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) {
349 	int i;
350 	int num_colors = 1 << depth;
351 	gx_color_value rgb[3];
352 
353 	info_ptr->palette =
354 	    (void *)gs_alloc_bytes(mem, 256 * sizeof(png_color),
355 				   "png palette");
356 	if (info_ptr->palette == 0) {
357 	    code = gs_note_error(gs_error_VMerror);
358 	    goto done;
359 	}
360 	info_ptr->num_palette = num_colors;
361 	info_ptr->valid |= PNG_INFO_PLTE;
362 	for (i = 0; i < num_colors; i++) {
363 	    (*dev_proc(pdev, map_color_rgb)) ((gx_device *) pdev,
364 					      (gx_color_index) i, rgb);
365 	    info_ptr->palette[i].red = gx_color_value_to_byte(rgb[0]);
366 	    info_ptr->palette[i].green = gx_color_value_to_byte(rgb[1]);
367 	    info_ptr->palette[i].blue = gx_color_value_to_byte(rgb[2]);
368 	}
369     }
370     /* add comment */
371     strncpy(software_key, "Software", sizeof(software_key));
372     sprintf(software_text, "%s %d.%02d", gs_product,
373 	    (int)(gs_revision / 100), (int)(gs_revision % 100));
374     text_png.compression = -1;	/* uncompressed */
375     text_png.key = software_key;
376     text_png.text = software_text;
377     text_png.text_length = strlen(software_text);
378     info_ptr->text = &text_png;
379     info_ptr->num_text = 1;
380 
381     /* write the file information */
382     png_write_info(png_ptr, info_ptr);
383 
384     /* don't write the comments twice */
385     info_ptr->num_text = 0;
386     info_ptr->text = NULL;
387 
388     /* Write the contents of the image. */
389     for (y = 0; y < height; y++) {
390 	gdev_prn_copy_scan_lines(pdev, y, row, raster);
391 	png_write_rows(png_ptr, &row, 1);
392     }
393 
394     /* write the rest of the file */
395     png_write_end(png_ptr, info_ptr);
396 
397     /* if you alloced the palette, free it here */
398     gs_free_object(mem, info_ptr->palette, "png palette");
399 
400   done:
401     /* free the structures */
402     png_destroy_write_struct(&png_ptr, &info_ptr);
403     gs_free_object(mem, row, "png raster buffer");
404 
405     return code;
406 }
407 
408 /*
409  * Patch around a static reference to a never-used procedure.
410  * This could be avoided if we were willing to edit pngconf.h to
411  *      #undef PNG_PROGRESSIVE_READ_SUPPORTED
412  */
413 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
414 #  if PNG_LIBPNG_VER >= 95
415 #    define PPFB_LENGTH_T png_size_t
416 #  else
417 #    define PPFB_LENGTH_T png_uint_32
418 #  endif
419 void
png_push_fill_buffer(png_structp png_ptr,png_bytep buffer,PPFB_LENGTH_T length)420 png_push_fill_buffer(png_structp png_ptr, png_bytep buffer,
421 		     PPFB_LENGTH_T length)
422 {
423 }
424 #endif
425 
426 static int
pngalpha_open(gx_device * pdev)427 pngalpha_open(gx_device * pdev)
428 {
429     gx_device_pngalpha *ppdev = (gx_device_pngalpha *)pdev;
430     int code;
431     /* We replace create_buf_device so we can replace copy_alpha
432      * for memory device, but not clist.
433      */
434     ppdev->printer_procs.buf_procs.create_buf_device =
435 	pngalpha_create_buf_device;
436     code = gdev_prn_open(pdev);
437     /* We intercept fill_rectangle to translate "fill page with white"
438      * into "fill page with transparent".  We then call the original
439      * implementation of fill_page.
440      */
441     if ((ppdev->procs.fill_rectangle != pngalpha_fill_rectangle) &&
442 	(ppdev->procs.fill_rectangle != NULL)) {
443 	ppdev->orig_fill_rectangle = ppdev->procs.fill_rectangle;
444         ppdev->procs.fill_rectangle = pngalpha_fill_rectangle;
445     }
446     return code;
447 }
448 
449 static int
pngalpha_create_buf_device(gx_device ** pbdev,gx_device * target,int y,const gx_render_plane_t * render_plane,gs_memory_t * mem,gx_band_complexity_t * band_complexity)450 pngalpha_create_buf_device(gx_device **pbdev, gx_device *target, int y,
451    const gx_render_plane_t *render_plane, gs_memory_t *mem,
452    gx_band_complexity_t *band_complexity)
453 {
454     gx_device_printer *ptarget = (gx_device_printer *)target;
455     int code = gx_default_create_buf_device(pbdev, target, y,
456 	render_plane, mem, band_complexity);
457     /* Now set copy_alpha to one that handles RGBA */
458     set_dev_proc(*pbdev, copy_alpha, ptarget->orig_procs.copy_alpha);
459     return code;
460 }
461 
462 static int
pngalpha_put_params(gx_device * pdev,gs_param_list * plist)463 pngalpha_put_params(gx_device * pdev, gs_param_list * plist)
464 {
465     gx_device_pngalpha *ppdev = (gx_device_pngalpha *)pdev;
466     int background;
467     int code;
468 
469     /* BackgroundColor in format 16#RRGGBB is used for bKGD chunk */
470     switch(code = param_read_int(plist, "BackgroundColor", &background)) {
471 	case 0:
472 	    ppdev->background = background & 0xffffff;
473 	    break;
474 	case 1:		/* not found */
475 	    code = 0;
476 	    break;
477 	default:
478 	    param_signal_error(plist, "BackgroundColor", code);
479 	    break;
480     }
481 
482     if (code == 0) {
483 	code = gdev_prn_put_params(pdev, plist);
484 	if ((ppdev->procs.fill_rectangle != pngalpha_fill_rectangle) &&
485 	    (ppdev->procs.fill_rectangle != NULL)) {
486 	    /* Get current implementation of fill_rectangle and restore ours.
487 	     * Implementation is either clist or memory and can change
488 	     * during put_params.
489 	     */
490 	    ppdev->orig_fill_rectangle = ppdev->procs.fill_rectangle;
491 	    ppdev->procs.fill_rectangle = pngalpha_fill_rectangle;
492 	}
493     }
494     return code;
495 }
496 
497 /* Get device parameters */
498 static int
pngalpha_get_params(gx_device * pdev,gs_param_list * plist)499 pngalpha_get_params(gx_device * pdev, gs_param_list * plist)
500 {
501     gx_device_pngalpha *ppdev = (gx_device_pngalpha *)pdev;
502     int code = gdev_prn_get_params(pdev, plist);
503     if (code >= 0)
504 	code = param_write_int(plist, "BackgroundColor",
505 				&(ppdev->background));
506     return code;
507 }
508 
509 
510 /* RGB mapping for 32-bit RGBA color devices */
511 
512 static gx_color_index
pngalpha_encode_color(gx_device * dev,const gx_color_value cv[])513 pngalpha_encode_color(gx_device * dev, const gx_color_value cv[])
514 {
515     /* bits 0-7 are alpha, stored inverted to avoid white/opaque
516      * being 0xffffffff which is also gx_no_color_index.
517      * So 0xff is transparent and 0x00 is opaque.
518      * We always return opaque colors (bits 0-7 = 0).
519      * Return value is 0xRRGGBB00.
520      */
521     return
522 	((uint) gx_color_value_to_byte(cv[2]) << 8) +
523 	((ulong) gx_color_value_to_byte(cv[1]) << 16) +
524 	((ulong) gx_color_value_to_byte(cv[0]) << 24);
525 }
526 
527 /* Map a color index to a r-g-b color. */
528 static int
pngalpha_decode_color(gx_device * dev,gx_color_index color,gx_color_value prgb[3])529 pngalpha_decode_color(gx_device * dev, gx_color_index color,
530 			     gx_color_value prgb[3])
531 {
532     prgb[0] = gx_color_value_from_byte((color >> 24) & 0xff);
533     prgb[1] = gx_color_value_from_byte((color >> 16) & 0xff);
534     prgb[2] = gx_color_value_from_byte((color >> 8)  & 0xff);
535     return 0;
536 }
537 
538 static int
pngalpha_fill_rectangle(gx_device * dev,int x,int y,int w,int h,gx_color_index color)539 pngalpha_fill_rectangle(gx_device * dev, int x, int y, int w, int h,
540 		  gx_color_index color)
541 {
542     gx_device_pngalpha *pdev = (gx_device_pngalpha *)dev;
543     if ((color == 0xffffff00) && (x==0) && (y==0)
544 	&& (w==dev->width) && (h==dev->height)) {
545 	/* If filling whole page with white, make it transparent */
546         return pdev->orig_fill_rectangle(dev, x, y, w, h, 0xffffffff);
547     }
548     return pdev->orig_fill_rectangle(dev, x, y, w, h, color);
549 }
550 
551 /* Implementation for 32-bit RGBA in a memory buffer */
552 /* Derived from gx_default_copy_alpha, but now maintains alpha channel. */
553 static int
pngalpha_copy_alpha(gx_device * dev,const byte * data,int data_x,int raster,gx_bitmap_id id,int x,int y,int width,int height,gx_color_index color,int depth)554 pngalpha_copy_alpha(gx_device * dev, const byte * data, int data_x,
555 	   int raster, gx_bitmap_id id, int x, int y, int width, int height,
556 		      gx_color_index color, int depth)
557 {				/* This might be called with depth = 1.... */
558     if (depth == 1)
559 	return (*dev_proc(dev, copy_mono)) (dev, data, data_x, raster, id,
560 					    x, y, width, height,
561 					    gx_no_color_index, color);
562     /*
563      * Simulate alpha by weighted averaging of RGB values.
564      * This is very slow, but functionally correct.
565      */
566     {
567 	const byte *row;
568 	gs_memory_t *mem = dev->memory;
569 	int bpp = dev->color_info.depth;
570 	int ncomps = dev->color_info.num_components;
571 	uint in_size = gx_device_raster(dev, false);
572 	byte *lin;
573 	uint out_size;
574 	byte *lout;
575 	int code = 0;
576 	gx_color_value color_cv[GX_DEVICE_COLOR_MAX_COMPONENTS];
577 	int ry;
578 
579 	fit_copy(dev, data, data_x, raster, id, x, y, width, height);
580 	row = data;
581 	out_size = bitmap_raster(width * bpp);
582 	lin = gs_alloc_bytes(mem, in_size, "copy_alpha(lin)");
583 	lout = gs_alloc_bytes(mem, out_size, "copy_alpha(lout)");
584 	if (lin == 0 || lout == 0) {
585 	    code = gs_note_error(gs_error_VMerror);
586 	    goto out;
587 	}
588 	(*dev_proc(dev, decode_color)) (dev, color, color_cv);
589 	for (ry = y; ry < y + height; row += raster, ++ry) {
590 	    byte *line;
591 	    int sx, rx;
592 
593 	    DECLARE_LINE_ACCUM_COPY(lout, bpp, x);
594 
595 	    code = (*dev_proc(dev, get_bits)) (dev, ry, lin, &line);
596 	    if (code < 0)
597 		break;
598 	    for (sx = data_x, rx = x; sx < data_x + width; ++sx, ++rx) {
599 		gx_color_index previous = gx_no_color_index;
600 		gx_color_index composite;
601 		int alpha2, alpha;
602 
603 		if (depth == 2)	/* map 0 - 3 to 0 - 15 */
604 		    alpha = ((row[sx >> 2] >> ((3 - (sx & 3)) << 1)) & 3) * 5;
605 		else
606 		    alpha2 = row[sx >> 1],
607 			alpha = (sx & 1 ? alpha2 & 0xf : alpha2 >> 4);
608 		if (alpha == 15) {	/* Just write the new color. */
609 		    composite = color;
610 		} else {
611 		    if (previous == gx_no_color_index) {	/* Extract the old color. */
612 			const byte *src = line + (rx * (bpp >> 3));
613 			previous = 0;
614 			previous += (gx_color_index) * src++ << 24;
615 			previous += (gx_color_index) * src++ << 16;
616 			previous += (gx_color_index) * src++ << 8;
617 			previous += *src++;
618 		    }
619 		    if (alpha == 0) {	/* Just write the old color. */
620 			composite = previous;
621 		    } else {	/* Blend values. */
622 			gx_color_value cv[GX_DEVICE_COLOR_MAX_COMPONENTS];
623 			int i;
624 			int old_coverage;
625 			int new_coverage;
626 
627 			(*dev_proc(dev, decode_color)) (dev, previous, cv);
628 			/* decode color doesn't give us coverage */
629 			cv[3] = previous & 0xff;
630 			old_coverage = 255 - cv[3];
631 			new_coverage =
632 			    (255 * alpha + old_coverage * (15 - alpha)) / 15;
633 			for (i=0; i<ncomps; i++)
634 			    cv[i] = min(((255 * alpha * color_cv[i]) +
635 				(old_coverage * (15 - alpha ) * cv[i]))
636 				/ (new_coverage * 15), gx_max_color_value);
637 			composite =
638 			    (*dev_proc(dev, encode_color)) (dev, cv);
639 			/* encode color doesn't include coverage */
640 			composite |= (255 - new_coverage) & 0xff;
641 
642 			/* composite can never be gx_no_color_index
643 			 * because pixel is never completely transparent
644 			 * (low byte != 0xff).
645 			 */
646 		    }
647 		}
648 		LINE_ACCUM(composite, bpp);
649 	    }
650 	    LINE_ACCUM_COPY(dev, lout, bpp, x, rx, raster, ry);
651 	}
652       out:gs_free_object(mem, lout, "copy_alpha(lout)");
653 	gs_free_object(mem, lin, "copy_alpha(lin)");
654 	return code;
655     }
656 }
657 
658