1 /* Copyright (C) 2001-2012 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,
8    modified or distributed except as expressly authorized under the terms
9    of the license contained in the file LICENSE in this distribution.
10 
11    Refer to licensing information at http://www.artifex.com or contact
12    Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134, San Rafael,
13    CA  94903, U.S.A., +1(415)492-9861, for further information.
14 */
15 
16 
17 /* Image handling for PDF-writing driver */
18 #include "memory_.h"
19 #include "math_.h"
20 #include "gx.h"
21 #include "gserrors.h"
22 #include "gsdevice.h"
23 #include "gsflip.h"
24 #include "gsstate.h"
25 #include "gscolor2.h"
26 #include "gdevpdfx.h"
27 #include "gdevpdfg.h"
28 #include "gdevpdfo.h"		/* for data stream */
29 #include "gxcspace.h"
30 #include "gximage3.h"
31 #include "gximag3x.h"
32 #include "gsiparm4.h"
33 #include "gxdcolor.h"
34 #include "gxpcolor.h"
35 #include "gxcolor2.h"
36 #include "gxhldevc.h"
37 #include "gxdevsop.h"
38 #include "gsicc_manage.h"
39 
40 /* Forward references */
41 static image_enum_proc_plane_data(pdf_image_plane_data);
42 static image_enum_proc_end_image(pdf_image_end_image);
43 static image_enum_proc_end_image(pdf_image_end_image_object);
44 static image_enum_proc_end_image(pdf_image_end_image_object2);
45 static image_enum_proc_end_image(pdf_image_end_image_cvd);
46 static IMAGE3_MAKE_MID_PROC(pdf_image3_make_mid);
47 static IMAGE3_MAKE_MCDE_PROC(pdf_image3_make_mcde);
48 static IMAGE3X_MAKE_MID_PROC(pdf_image3x_make_mid);
49 static IMAGE3X_MAKE_MCDE_PROC(pdf_image3x_make_mcde);
50 
51 static const gx_image_enum_procs_t pdf_image_enum_procs = {
52     pdf_image_plane_data,
53     pdf_image_end_image
54 };
55 static const gx_image_enum_procs_t pdf_image_object_enum_procs = {
56     pdf_image_plane_data,
57     pdf_image_end_image_object
58 };
59 static const gx_image_enum_procs_t pdf_image_object_enum_procs2 = {
60     pdf_image_plane_data,
61     pdf_image_end_image_object2
62 };
63 static const gx_image_enum_procs_t pdf_image_cvd_enum_procs = {
64     gx_image1_plane_data,
65     pdf_image_end_image_cvd,
66     gx_image1_flush
67 };
68 
69 /* ---------------- Driver procedures ---------------- */
70 
71 /* Define the structure for keeping track of progress through an image. */
72 typedef struct pdf_image_enum_s {
73     gx_image_enum_common;
74     int width;
75     int bits_per_pixel;		/* bits per pixel (per plane) */
76     int rows_left;
77     pdf_image_writer writer;
78     gs_matrix mat;
79 } pdf_image_enum;
80 gs_private_st_composite(st_pdf_image_enum, pdf_image_enum, "pdf_image_enum",
81   pdf_image_enum_enum_ptrs, pdf_image_enum_reloc_ptrs);
82 /* GC procedures */
83 static ENUM_PTRS_WITH(pdf_image_enum_enum_ptrs, pdf_image_enum *pie)
84     if (index < pdf_image_writer_max_ptrs) {
85         gs_ptr_type_t ret =
86             ENUM_USING(st_pdf_image_writer, &pie->writer, sizeof(pie->writer),
87                        index);
88 
89         if (ret == 0)		/* don't stop early */
90             ENUM_RETURN(0);
91         return ret;
92     }
93     return ENUM_USING_PREFIX(st_gx_image_enum_common,
94                              pdf_image_writer_max_ptrs);
95 ENUM_PTRS_END
RELOC_PTRS_WITH(pdf_image_enum_reloc_ptrs,pdf_image_enum * pie)96 static RELOC_PTRS_WITH(pdf_image_enum_reloc_ptrs, pdf_image_enum *pie)
97 {
98     RELOC_USING(st_pdf_image_writer, &pie->writer, sizeof(pie->writer));
99     RELOC_USING(st_gx_image_enum_common, vptr, size);
100 }
101 RELOC_PTRS_END
102 
103 /*
104  * Test whether we can write an image in-line.  This is always true,
105  * because we only support PDF 1.2 and later.
106  */
107 static bool
can_write_image_in_line(const gx_device_pdf * pdev,const gs_image_t * pim)108 can_write_image_in_line(const gx_device_pdf *pdev, const gs_image_t *pim)
109 {
110     return true;
111 }
112 
113 /*
114  * Convert a Type 4 image to a Type 1 masked image if possible.
115  * Type 1 masked images are more compact, and are supported in all PDF
116  * versions, whereas general masked images require PDF 1.3 or higher.
117  * Also, Acrobat 5 for Windows has a bug that causes an error for images
118  * with a color-key mask, at least for 1-bit-deep images using an Indexed
119  * color space.
120  */
121 static int
color_is_black_or_white(gx_device * dev,const gx_drawing_color * pdcolor)122 color_is_black_or_white(gx_device *dev, const gx_drawing_color *pdcolor)
123 {
124     return (!color_is_pure(pdcolor) ? -1 :
125             gx_dc_pure_color(pdcolor) == gx_device_black(dev) ? 0 :
126             gx_dc_pure_color(pdcolor) == gx_device_white(dev) ? 1 : -1);
127 }
128 static int
pdf_convert_image4_to_image1(gx_device_pdf * pdev,const gs_imager_state * pis,const gx_drawing_color * pbcolor,const gs_image4_t * pim4,gs_image_t * pim1,gx_drawing_color * pdcolor)129 pdf_convert_image4_to_image1(gx_device_pdf *pdev,
130                              const gs_imager_state *pis,
131                              const gx_drawing_color *pbcolor,
132                              const gs_image4_t *pim4, gs_image_t *pim1,
133                              gx_drawing_color *pdcolor)
134 {
135     if (pim4->BitsPerComponent == 1 &&
136         pim4->ColorSpace->type->num_components(pim4->ColorSpace) == 1 &&
137         (pim4->MaskColor_is_range ?
138          pim4->MaskColor[0] | pim4->MaskColor[1] :
139          pim4->MaskColor[0]) <= 1
140         ) {
141         gx_device *const dev = (gx_device *)pdev;
142         const gs_color_space *pcs = pim4->ColorSpace;
143         bool write_1s = !pim4->MaskColor[0];
144         gs_client_color cc;
145         int code;
146 
147         /*
148          * Prepare the drawing color.  (pdf_prepare_imagemask will set it.)
149          * This is the other color in the image (the one that isn't the
150          * mask key), taking Decode into account.
151          */
152 
153         cc.paint.values[0] = pim4->Decode[(int)write_1s];
154         cc.pattern = 0;
155         code = pcs->type->remap_color(&cc, pcs, pdcolor, pis, dev,
156                                       gs_color_select_texture);
157         if (code < 0)
158             return code;
159 
160         /*
161          * The PDF imaging model doesn't support RasterOp.  We can convert a
162          * Type 4 image to a Type 1 imagemask only if the effective RasterOp
163          * passes through the source color unchanged.  "Effective" means we
164          * take into account CombineWithColor, and whether the source and/or
165          * texture are black, white, or neither.
166          */
167         {
168             gs_logical_operation_t lop = pis->log_op;
169             int black_or_white = color_is_black_or_white(dev, pdcolor);
170 
171             switch (black_or_white) {
172             case 0: lop = lop_know_S_0(lop); break;
173             case 1: lop = lop_know_S_1(lop); break;
174             default: DO_NOTHING;
175             }
176             if (pim4->CombineWithColor)
177                 switch (color_is_black_or_white(dev, pbcolor)) {
178                 case 0: lop = lop_know_T_0(lop); break;
179                 case 1: lop = lop_know_T_1(lop); break;
180                 default: DO_NOTHING;
181                 }
182             else
183                 lop = lop_know_T_0(lop);
184             switch (lop_rop(lop)) {
185             case rop3_0:
186                 if (black_or_white != 0)
187                     return -1;
188                 break;
189             case rop3_1:
190                 if (black_or_white != 1)
191                     return -1;
192                 break;
193             case rop3_S:
194                 break;
195             default:
196                 return -1;
197             }
198             if ((lop & lop_S_transparent) && black_or_white == 1)
199                 return -1;
200         }
201 
202         /* All conditions are met.  Convert to a masked image. */
203 
204         gs_image_t_init_mask_adjust(pim1, write_1s, false);
205 #define COPY_ELEMENT(e) pim1->e = pim4->e
206         COPY_ELEMENT(ImageMatrix);
207         COPY_ELEMENT(Width);
208         COPY_ELEMENT(Height);
209         pim1->BitsPerComponent = 1;
210         /* not Decode */
211         COPY_ELEMENT(Interpolate);
212         pim1->format = gs_image_format_chunky; /* BPC = 1, doesn't matter */
213 #undef COPY_ELEMENT
214         return 0;
215     }
216     return -1;			/* arbitrary <0 */
217 }
218 
219 static int
pdf_begin_image_data_decoded(gx_device_pdf * pdev,int num_components,const gs_range_t * pranges,int i,gs_pixel_image_t * pi,cos_value_t * cs_value,pdf_image_enum * pie)220 pdf_begin_image_data_decoded(gx_device_pdf *pdev, int num_components, const gs_range_t *pranges, int i,
221                              gs_pixel_image_t *pi, cos_value_t *cs_value, pdf_image_enum *pie)
222 {
223 
224     if (pranges) {
225         /* Rescale the Decode values for the image data. */
226         const gs_range_t *pr = pranges;
227         float *decode = pi->Decode;
228         int j;
229 
230         for (j = 0; j < num_components; ++j, ++pr, decode += 2) {
231             double vmin = decode[0], vmax = decode[1];
232             double base = pr->rmin, factor = pr->rmax - base;
233 
234             decode[1] = (vmax - vmin) / factor + (vmin - base);
235             decode[0] = vmin - base;
236         }
237     }
238     return pdf_begin_image_data(pdev, &pie->writer, pi, cs_value, i);
239 }
240 
241 static int
make_device_color_space(gx_device_pdf * pdev,gs_color_space_index output_cspace_index,gs_color_space ** ppcs)242 make_device_color_space(gx_device_pdf *pdev,
243                         gs_color_space_index output_cspace_index,
244                         gs_color_space **ppcs)
245 {
246     gs_color_space *cs;
247     gs_memory_t *mem = pdev->v_memory;
248 
249     switch (output_cspace_index) {
250         case gs_color_space_index_DeviceGray:
251             cs = gs_cspace_new_DeviceGray(mem);
252             break;
253         case gs_color_space_index_DeviceRGB:
254             cs = gs_cspace_new_DeviceRGB(mem);
255             break;
256         case gs_color_space_index_DeviceCMYK:
257             cs = gs_cspace_new_DeviceCMYK(mem);
258             break;
259         default:
260             /* Notify the user and terminate.
261                Don't emit rangecheck becuause it would fall back
262                to a default implementation (rasterisation).
263              */
264             emprintf(mem, "Unsupported ProcessColorModel");
265             return_error(gs_error_undefined);
266     }
267     if (cs == NULL)
268         return_error(gs_error_VMerror);
269     *ppcs = cs;
270     return 0;
271 }
272 
273 static bool
check_image_color_space(gs_pixel_image_t * pim,gs_color_space_index index)274 check_image_color_space(gs_pixel_image_t * pim, gs_color_space_index index)
275 {
276     if (pim->ColorSpace->type->index == index)
277         return true;
278     if (pim->ColorSpace->type->index == gs_color_space_index_Indexed)
279         if (pim->ColorSpace->base_space->type->index == index)
280             return true;
281     return false;
282 }
283 
284 /*
285  * Start processing an image.  This procedure takes extra arguments because
286  * it has to do something slightly different for the parts of an ImageType 3
287  * image.
288  */
289 typedef enum {
290     PDF_IMAGE_DEFAULT,
291     PDF_IMAGE_TYPE3_MASK,	/* no in-line, don't render */
292     PDF_IMAGE_TYPE3_DATA	/* no in-line */
293 } pdf_typed_image_context_t;
294 
295 /*
296  * We define this union because psdf_setup_image_filters may alter the
297  * gs_pixel_image_t part, but pdf_begin_image_data must also have access
298  * to the type-specific parameters.
299  */
300 typedef union image_union_s {
301     gs_pixel_image_t pixel;	/* we may change some components */
302     gs_image1_t type1;
303     gs_image3_t type3;
304     gs_image3x_t type3x;
305     gs_image4_t type4;
306 } image_union_t;
307 
308 static int pdf_begin_typed_image(gx_device_pdf *pdev,
309     const gs_imager_state * pis, const gs_matrix *pmat,
310     const gs_image_common_t *pic, const gs_int_rect * prect,
311     const gx_drawing_color * pdcolor, const gx_clip_path * pcpath,
312     gs_memory_t * mem, gx_image_enum_common_t ** pinfo,
313     pdf_typed_image_context_t context);
314 
315 static int
pdf_begin_typed_image_impl(gx_device_pdf * pdev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo,pdf_typed_image_context_t context,image_union_t * image)316 pdf_begin_typed_image_impl(gx_device_pdf *pdev, const gs_imager_state * pis,
317                       const gs_matrix *pmat, const gs_image_common_t *pic,
318                       const gs_int_rect * prect,
319                       const gx_drawing_color * pdcolor,
320                       const gx_clip_path * pcpath, gs_memory_t * mem,
321                       gx_image_enum_common_t ** pinfo,
322                       pdf_typed_image_context_t context,
323                       image_union_t *image)
324 {
325     cos_dict_t *pnamed = 0;
326     const gs_pixel_image_t *pim;
327     int code, i;
328     pdf_image_enum *pie;
329     gs_image_format_t format;
330     const gs_color_space *pcs;
331     cos_value_t cs_value;
332     int num_components;
333     bool is_mask = false, in_line = false;
334     gs_int_rect rect;
335     int width, height;
336     const gs_range_t *pranges = 0;
337     const pdf_color_space_names_t *names;
338     bool convert_to_process_colors = false;
339     gs_color_space *pcs_device = NULL;
340     gs_color_space *pcs_orig = NULL;
341     pdf_lcvd_t *cvd = NULL;
342     bool force_lossless = false;
343 
344     /*
345      * Pop the image name from the NI stack.  We must do this, to keep the
346      * stack in sync, even if it turns out we can't handle the image.
347      */
348     {
349         cos_value_t ni_value;
350 
351         if (cos_array_unadd(pdev->NI_stack, &ni_value) >= 0)
352             pnamed = (cos_dict_t *)ni_value.contents.object;
353     }
354 
355     /* An initialization for pdf_end_and_do_image :
356        We need to delay adding the "Mask" entry into a type 3 image dictionary
357        until the mask is completed due to equal image merging. */
358     pdev->image_mask_id = gs_no_id;
359 
360     /* Check for the image types we can handle. */
361     switch (pic->type->index) {
362     case 1: {
363         const gs_image_t *pim1 = (const gs_image_t *)pic;
364 
365         if (pim1->Alpha != gs_image_alpha_none)
366             goto nyi;
367         is_mask = pim1->ImageMask;
368         if (is_mask) {
369             /* If parameters are invalid, use the default implementation. */
370             if (!(gx_dc_is_pattern1_color(pdcolor)))
371                 if (pim1->BitsPerComponent != 1 ||
372                     !((pim1->Decode[0] == 0.0 && pim1->Decode[1] == 1.0) ||
373                       (pim1->Decode[0] == 1.0 && pim1->Decode[1] == 0.0))
374                     )
375                     goto nyi;
376         }
377         /* If image is not type 3X and we can write in-line then make it so */
378 
379          in_line = context == PDF_IMAGE_DEFAULT &&
380             can_write_image_in_line(pdev, pim1);
381 
382         image[0].type1 = *pim1;
383         break;
384     }
385     case 3: {
386         const gs_image3_t *pim3 = (const gs_image3_t *)pic;
387         gs_image3_t pim3a;
388         const gs_image_common_t *pic1 = pic;
389         gs_matrix m, mi;
390         const gs_matrix *pmat1 = pmat;
391 
392         pdev->image_mask_is_SMask = false;
393         if (pdev->CompatibilityLevel < 1.2)
394             goto nyi;
395         if (prect && !(prect->p.x == 0 && prect->p.y == 0 &&
396                        prect->q.x == pim3->Width &&
397                        prect->q.y == pim3->Height))
398             goto nyi;
399         if (pdev->CompatibilityLevel < 1.3 && !pdev->PatternImagemask) {
400             if (pdf_must_put_clip_path(pdev, pcpath))
401                 code = pdf_unclip(pdev);
402             else
403                 code = pdf_open_page(pdev, PDF_IN_STREAM);
404             if (code < 0)
405                 return code;
406             code = pdf_put_clip_path(pdev, pcpath);
407             if (code < 0)
408                 return code;
409             gs_make_identity(&m);
410             pmat1 = &m;
411             m.tx = floor(pis->ctm.tx + 0.5); /* Round the origin against the image size distorsions */
412             m.ty = floor(pis->ctm.ty + 0.5);
413             pim3a = *pim3;
414             gs_matrix_invert(&pim3a.ImageMatrix, &mi);
415             gs_make_identity(&pim3a.ImageMatrix);
416             if (pim3a.Width < pim3a.MaskDict.Width && pim3a.Width > 0) {
417                 int sx = (pim3a.MaskDict.Width + pim3a.Width - 1) / pim3a.Width;
418 
419                 gs_matrix_scale(&mi, 1.0 / sx, 1, &mi);
420                 gs_matrix_scale(&pim3a.ImageMatrix, 1.0 / sx, 1, &pim3a.ImageMatrix);
421             }
422             if (pim3a.Height < pim3a.MaskDict.Height && pim3a.Height > 0) {
423                 int sy = (pim3a.MaskDict.Height + pim3a.Height - 1) / pim3a.Height;
424 
425                 gs_matrix_scale(&mi, 1, 1.0 / sy, &mi);
426                 gs_matrix_scale(&pim3a.ImageMatrix, 1, 1.0 / sy, &pim3a.ImageMatrix);
427             }
428             gs_matrix_multiply(&mi, &pim3a.MaskDict.ImageMatrix, &pim3a.MaskDict.ImageMatrix);
429             pic1 = (gs_image_common_t *)&pim3a;
430             /* Setting pdev->converting_image_matrix to communicate with pdf_image3_make_mcde. */
431             gs_matrix_multiply(&mi, &ctm_only(pis), &pdev->converting_image_matrix);
432         }
433         /*
434          * We handle ImageType 3 images in a completely different way:
435          * the default implementation sets up the enumerator.
436          */
437         return gx_begin_image3_generic((gx_device *)pdev, pis, pmat1, pic1,
438                                        prect, pdcolor, pcpath, mem,
439                                        pdf_image3_make_mid,
440                                        pdf_image3_make_mcde, pinfo);
441     }
442     case IMAGE3X_IMAGETYPE: {
443         /* See ImageType3 above for more information. */
444         const gs_image3x_t *pim3x = (const gs_image3x_t *)pic;
445 
446         if (pdev->CompatibilityLevel < 1.4)
447             goto nyi;
448         if (prect && !(prect->p.x == 0 && prect->p.y == 0 &&
449                        prect->q.x == pim3x->Width &&
450                        prect->q.y == pim3x->Height))
451             goto nyi;
452         pdev->image_mask_is_SMask = true;
453         return gx_begin_image3x_generic((gx_device *)pdev, pis, pmat, pic,
454                                         prect, pdcolor, pcpath, mem,
455                                         pdf_image3x_make_mid,
456                                         pdf_image3x_make_mcde, pinfo);
457     }
458     case 4: {
459         /* Try to convert the image to a plain masked image. */
460         gx_drawing_color icolor;
461 
462         pdev->image_mask_is_SMask = false;
463         if (pdf_convert_image4_to_image1(pdev, pis, pdcolor,
464                                          (const gs_image4_t *)pic,
465                                          &image[0].type1, &icolor) >= 0) {
466             gs_state *pgs = (gs_state *)gx_hld_get_gstate_ptr(pis);
467 
468             if (pgs == NULL)
469                 return_error(gs_error_unregistered); /* Must not happen. */
470 
471             /* Undo the pop of the NI stack if necessary. */
472             if (pnamed)
473                 cos_array_add_object(pdev->NI_stack, COS_OBJECT(pnamed));
474             /* HACK: temporary patch the color space, to allow
475                pdf_prepare_imagemask to write the right color for the imagemask. */
476             code = gs_gsave(pgs);
477             if (code < 0)
478                 return code;
479             /* {csrc}: const cast warning */
480             code = gs_setcolorspace(pgs, ((const gs_image4_t *)pic)->ColorSpace);
481             if (code < 0)
482                 return code;
483             code = pdf_begin_typed_image(pdev, pis, pmat,
484                                          (gs_image_common_t *)&image[0].type1,
485                                          prect, &icolor, pcpath, mem,
486                                          pinfo, context);
487             if (code < 0)
488                 return code;
489             return gs_grestore(pgs);
490         }
491         /* No luck.  Masked images require PDF 1.3 or higher. */
492         if (pdev->CompatibilityLevel < 1.2)
493             goto nyi;
494         if (pdev->CompatibilityLevel < 1.3 && !pdev->PatternImagemask) {
495             gs_matrix m, m1, mi;
496             gs_image4_t pi4 = *(const gs_image4_t *)pic;
497 
498             if (pdf_must_put_clip_path(pdev, pcpath))
499                 code = pdf_unclip(pdev);
500             else
501                 code = pdf_open_page(pdev, PDF_IN_STREAM);
502             if (code < 0)
503                 return code;
504             code = pdf_put_clip_path(pdev, pcpath);
505             if (code < 0)
506                 return code;
507             gs_make_identity(&m1);
508             gs_matrix_invert(&pic->ImageMatrix, &mi);
509             gs_matrix_multiply(&mi, &ctm_only(pis), &m);
510             code = pdf_setup_masked_image_converter(pdev, mem, &m, &cvd,
511                                  true, 0, 0, pi4.Width, pi4.Height, false);
512             if (code < 0)
513                 return code;
514             cvd->mdev.is_open = true; /* fixme: same as above. */
515             cvd->mask->is_open = true; /* fixme: same as above. */
516             cvd->mask_is_empty = false;
517             code = (*dev_proc(cvd->mask, fill_rectangle))((gx_device *)cvd->mask,
518                         0, 0, cvd->mask->width, cvd->mask->height, (gx_color_index)0);
519             if (code < 0)
520                 return code;
521             gx_device_retain((gx_device *)cvd, true);
522             gx_device_retain((gx_device *)cvd->mask, true);
523             gs_make_identity(&pi4.ImageMatrix);
524             code = gx_default_begin_typed_image((gx_device *)cvd,
525                 pis, &m1, (gs_image_common_t *)&pi4, prect, pdcolor, NULL, mem, pinfo);
526             if (code < 0)
527                 return code;
528             (*pinfo)->procs = &pdf_image_cvd_enum_procs;
529             return 0;
530         }
531         image[0].type4 = *(const gs_image4_t *)pic;
532         break;
533     }
534     default:
535         goto nyi;
536     }
537     pim = (const gs_pixel_image_t *)pic;
538     format = pim->format;
539     switch (format) {
540     case gs_image_format_chunky:
541     case gs_image_format_component_planar:
542         break;
543     default:
544         goto nyi;
545     }
546     /* AR5 on Windows doesn't support 0-size images. Skipping. */
547     if (pim->Width == 0 || pim->Height == 0)
548         goto nyi;
549     /* PDF doesn't support images with more than 8 bits per component. */
550     switch (pim->BitsPerComponent) {
551         case 1:
552         case 2:
553         case 4:
554         case 8:
555             break;
556         case 12:
557         case 16:
558             goto nyi;
559         default:
560             return_error(gs_error_rangecheck);
561     }
562     pcs = pim->ColorSpace;
563     num_components = (is_mask ? 1 : gs_color_space_num_components(pcs));
564 
565     if (pdf_must_put_clip_path(pdev, pcpath))
566         code = pdf_unclip(pdev);
567     else
568         code = pdf_open_page(pdev, PDF_IN_STREAM);
569     if (code < 0)
570         return code;
571     if (context == PDF_IMAGE_TYPE3_MASK) {
572         /*
573          * The soft mask for an ImageType 3x image uses a DevicePixel
574          * color space, which pdf_color_space() can't handle.  Patch it
575          * to DeviceGray here.
576          */
577         /* {csrc} make sure this gets freed */
578         pcs = gs_cspace_new_DeviceGray(pdev->memory);
579     } else if (is_mask)
580         code = pdf_prepare_imagemask(pdev, pis, pdcolor);
581     else
582         code = pdf_prepare_image(pdev, pis);
583     if (code < 0)
584         goto nyi;
585     if (prect)
586         rect = *prect;
587     else {
588         rect.p.x = rect.p.y = 0;
589         rect.q.x = pim->Width, rect.q.y = pim->Height;
590     }
591     pie = gs_alloc_struct(mem, pdf_image_enum, &st_pdf_image_enum,
592                         "pdf_begin_image");
593     if (pie == 0)
594         return_error(gs_error_VMerror);
595     memset(pie, 0, sizeof(*pie)); /* cleanup entirely for GC to work in all cases. */
596     *pinfo = (gx_image_enum_common_t *) pie;
597     gx_image_enum_common_init(*pinfo, (const gs_data_image_t *) pim,
598                     ((pdev->CompatibilityLevel >= 1.3) ?
599                             (context == PDF_IMAGE_TYPE3_MASK ?
600                             &pdf_image_object_enum_procs :
601                             &pdf_image_enum_procs) :
602                             context == PDF_IMAGE_TYPE3_MASK ?
603                             &pdf_image_object_enum_procs :
604                             context == PDF_IMAGE_TYPE3_DATA ?
605                             &pdf_image_object_enum_procs2 :
606                             &pdf_image_enum_procs),
607                         (gx_device *)pdev, num_components, format);
608     pie->memory = mem;
609     width = rect.q.x - rect.p.x;
610     pie->width = width;
611     height = rect.q.y - rect.p.y;
612     pie->bits_per_pixel =
613         pim->BitsPerComponent * num_components / pie->num_planes;
614     pie->rows_left = height;
615     if (pnamed != 0) /* Don't in-line the image if it is named. */
616         in_line = false;
617     else {
618         double nbytes = (double)(((ulong) pie->width * pie->bits_per_pixel + 7) >> 3) *
619             pie->num_planes * pie->rows_left;
620 
621         in_line &= (nbytes < pdev->MaxInlineImageSize);
622     }
623     if (rect.p.x != 0 || rect.p.y != 0 ||
624         rect.q.x != pim->Width || rect.q.y != pim->Height ||
625         (is_mask && pim->CombineWithColor)
626         /* Color space setup used to be done here: see SRZB comment below. */
627         ) {
628         gs_free_object(mem, pie, "pdf_begin_image");
629         goto nyi;
630     }
631     if (pmat == 0)
632         pmat = &ctm_only(pis);
633     {
634         gs_matrix mat;
635         gs_matrix bmat;
636         int code;
637 
638         pdf_make_bitmap_matrix(&bmat, -rect.p.x, -rect.p.y,
639                                pim->Width, pim->Height, height);
640         if ((code = gs_matrix_invert(&pim->ImageMatrix, &mat)) < 0 ||
641             (code = gs_matrix_multiply(&bmat, &mat, &mat)) < 0 ||
642             (code = gs_matrix_multiply(&mat, pmat, &pie->mat)) < 0
643             ) {
644             gs_free_object(mem, pie, "pdf_begin_image");
645             return code;
646         }
647         /* AR3,AR4 show no image when CTM is singular; AR5 reports an error */
648         if (pie->mat.xx * pie->mat.yy == pie->mat.xy * pie->mat.yx) {
649             gs_free_object(mem, pie, "pdf_begin_image");
650             goto nyi;
651         }
652     }
653     code = pdf_put_clip_path(pdev, pcpath);
654     if (code < 0)
655         return code;
656     pdf_image_writer_init(&pie->writer);
657     pie->writer.alt_writer_count = (in_line ||
658                                     (pim->Width <= 64 && pim->Height <= 64)
659                                     ? 1 : 2);
660     if ((image[0].pixel.ColorSpace != NULL &&
661         image[0].pixel.ColorSpace->type->index == gs_color_space_index_Indexed
662         && pdev->params.ColorImage.DownsampleType != ds_Subsample) ||
663         pdev->transfer_not_identity)
664         force_lossless = true;
665 
666     image[1] = image[0];
667     names = (in_line ? &pdf_color_space_names_short : &pdf_color_space_names);
668     if (!is_mask) {
669         if (psdf_is_converting_image_to_RGB((gx_device_psdf *)pdev, pis, pim)) {
670             /* psdf_setup_image_filters may change the color space
671              * (in case of pdev->params.ConvertCMYKImagesToRGB == true).
672              * Account it here.
673              */
674             cos_c_string_value(&cs_value, names->DeviceRGB);
675         } else {
676             /* A minor hack to deal with CIELAB images. */
677             if (pcs->cmm_icc_profile_data != NULL &&
678                 pcs->cmm_icc_profile_data->islab) {
679                     gscms_set_icc_range((cmm_profile_t **)&(pcs->cmm_icc_profile_data));
680             }
681             code = pdf_convert_ICC(pdev, pcs, &cs_value, names);
682             if (code == 0) {
683                 code = pdf_color_space_named(pdev, &cs_value, &pranges, pcs, names,
684                                          in_line, NULL, 0);
685             }
686             if (pcs->cmm_icc_profile_data != NULL &&
687                 pcs->cmm_icc_profile_data->islab) {
688                 gsicc_setrange_lab(pcs->cmm_icc_profile_data);
689             }
690             if (code < 0)
691                 convert_to_process_colors = true;
692         }
693     }
694     if (image[0].pixel.ColorSpace != NULL && !(context == PDF_IMAGE_TYPE3_MASK)) {
695         /* Not an imagemask. Also not a SMask, we carefully made a Gray space
696          * for SMasks above, do not destroy it now!
697          */
698         if ((pdev->params.ColorConversionStrategy == ccs_Gray &&
699              !check_image_color_space(&image[0].pixel, gs_color_space_index_DeviceGray)) ||
700             (pdev->params.ColorConversionStrategy == ccs_sRGB &&
701              !psdf_is_converting_image_to_RGB((const gx_device_psdf *)pdev, pis, &image[0].pixel) &&
702              !check_image_color_space(&image[0].pixel, gs_color_space_index_DeviceGray) &&
703              !check_image_color_space(&image[0].pixel, gs_color_space_index_DeviceRGB)) ||
704             (pdev->params.ColorConversionStrategy == ccs_CMYK &&
705              !check_image_color_space(&image[0].pixel, gs_color_space_index_DeviceGray) &&
706              !check_image_color_space(&image[0].pixel, gs_color_space_index_DeviceCMYK))) {
707             /* fixme : as a rudiment of old code,
708                 the case psdf_is_converting_image_to_RGB
709                 is handled with the 'cmyk_to_rgb' branch
710                 in psdf_setup_image_filters. */
711             if ((pdev->params.ColorConversionStrategy == ccs_CMYK &&
712                  strcmp(pdev->color_info.cm_name, "DeviceCMYK")) ||
713                 (pdev->params.ColorConversionStrategy == ccs_sRGB &&
714                  strcmp(pdev->color_info.cm_name, "DeviceRGB")) ||
715                 (pdev->params.ColorConversionStrategy == ccs_Gray &&
716                  strcmp(pdev->color_info.cm_name, "DeviceGray"))) {
717                 emprintf(pdev->memory, "ColorConversionStrategy isn't "
718                          "compatible to ProcessColorModel.");
719                 return_error(gs_error_rangecheck);
720             }
721             convert_to_process_colors = true;
722         }
723     }
724     if (convert_to_process_colors) {
725         const char *sname;
726 
727         switch (pdev->pcm_color_info_index) {
728             case gs_color_space_index_DeviceGray: sname = names->DeviceGray; break;
729             case gs_color_space_index_DeviceRGB:  sname = names->DeviceRGB;  break;
730             case gs_color_space_index_DeviceCMYK: sname = names->DeviceCMYK; break;
731             default:
732                 emprintf(pdev->memory, "Unsupported ProcessColorModel.");
733                 return_error(gs_error_undefined);
734         }
735         cos_c_string_value(&cs_value, sname);
736         pcs_orig = image[0].pixel.ColorSpace;
737         code = make_device_color_space(pdev, pdev->pcm_color_info_index, &pcs_device);
738         if (code < 0)
739             goto fail;
740         image[0].pixel.ColorSpace = pcs_device;
741     }
742     pdev->ParamCompatibilityLevel = pdev->CompatibilityLevel;
743 
744     /* This is rather hacky. the gs_image_pixel_t union has copies of the image
745      * information, including the ColorSpace, but it does not increment the
746      * reference counts of the counted objects (teh ColorSpace) when it makes
747      * copies. However, if psdf_setup_image_filters() should change the colour
748      * space into DeviceCMYK because it converts the image, it will decrement
749      * the reference count of the original space. There is at least one place
750      * where it is called with the original space, so we can't simply remove
751      * the decrement. Handling this properly would entail incrementing the
752      * reference count when we make the copy, and correctly decrementing it
753      * in all the error conditions. Its easier to isolate the changes to
754      * this piece of code.
755      */
756     rc_increment_cs(image[0].pixel.ColorSpace);
757     code = pdf_begin_write_image(pdev, &pie->writer, gs_no_id, width,
758                     height, pnamed, in_line);
759     if (code < 0)
760         goto fail;
761     if (pie->writer.alt_writer_count == 1)
762         code = psdf_setup_lossless_filters((gx_device_psdf *) pdev,
763                                              &pie->writer.binary[0],
764                                              &image[0].pixel, in_line);
765     else {
766         if (force_lossless) {
767             /*
768              * Some regrettable PostScript code (such as LanguageLevel 1 output
769              * from Microsoft's PSCRIPT.DLL driver) misuses the transfer
770              * function to accomplish the equivalent of indexed color.
771              * Downsampling (well, only averaging) or JPEG compression are not
772              * compatible with this.  Play it safe by using only lossless
773              * filters if the transfer function(s) is/are other than the
774              * identity and by setting the downsample type to Subsample..
775              */
776             int saved_downsample = pdev->params.ColorImage.DownsampleType;
777 
778             pdev->params.ColorImage.DownsampleType = ds_Subsample;
779             code = psdf_setup_image_filters((gx_device_psdf *) pdev,
780                                           &pie->writer.binary[0], &image[0].pixel,
781                                           pmat, pis, true, in_line);
782             pdev->params.ColorImage.DownsampleType = saved_downsample;
783         } else {
784             code = psdf_setup_image_filters((gx_device_psdf *) pdev,
785                                           &pie->writer.binary[0], &image[0].pixel,
786                                           pmat, pis, true, in_line);
787         }
788     }
789     if (code < 0) {
790         if (image[0].pixel.ColorSpace == pim->ColorSpace)
791             rc_decrement_only_cs(pim->ColorSpace, "psdf_setup_image_filters");
792         goto fail;
793     }
794 
795     if (convert_to_process_colors) {
796         image[0].pixel.ColorSpace = pcs_orig;
797         code = psdf_setup_image_colors_filter(&pie->writer.binary[0],
798                     (gx_device_psdf *)pdev, &image[0].pixel, pis);
799         if (code < 0)
800             goto fail;
801         image[0].pixel.ColorSpace = pcs_device;
802     }
803 
804     /* See the comment above about reference counting of the colour space */
805     rc_increment_cs(image[1].pixel.ColorSpace);
806     if (pie->writer.alt_writer_count > 1) {
807         code = pdf_make_alt_stream(pdev, &pie->writer.binary[1]);
808         if (code)
809             goto fail;
810         if (convert_to_process_colors)
811             image[1].pixel.ColorSpace = pcs_device;
812         code = psdf_setup_image_filters((gx_device_psdf *) pdev,
813                                   &pie->writer.binary[1], &image[1].pixel,
814                                   pmat, pis, force_lossless, in_line);
815         if (code == gs_error_rangecheck) {
816 
817             for (i=1;i < pie->writer.alt_writer_count; i++) {
818                 stream *s = pie->writer.binary[i].strm;
819                 cos_stream_t *pcos = cos_stream_from_pipeline(pie->writer.binary[i].strm);
820                 s_close_filters(&s, NULL);
821                 gs_free_object(pdev->pdf_memory, s, "compressed image stream");
822                 pcos->cos_procs->release((cos_object_t *)pcos, "pdf_begin_typed_image_impl");
823                 gs_free_object(pdev->pdf_memory, pcos, "compressed image cos_stream");
824             }
825             /* setup_image_compression rejected the alternative compression. */
826             pie->writer.alt_writer_count = 1;
827             memset(pie->writer.binary + 1, 0, sizeof(pie->writer.binary[1]));
828             memset(pie->writer.binary + 2, 0, sizeof(pie->writer.binary[1]));
829         } else if (code) {
830             if (image[1].pixel.ColorSpace == pim->ColorSpace)
831                 rc_decrement_only_cs(pim->ColorSpace, "psdf_setup_image_filters");
832             goto fail;
833         }
834         else if (convert_to_process_colors) {
835             image[1].pixel.ColorSpace = pcs_orig;
836             code = psdf_setup_image_colors_filter(&pie->writer.binary[1],
837                     (gx_device_psdf *)pdev, &image[1].pixel, pis);
838             if (code < 0) {
839                 if (image[1].pixel.ColorSpace == pim->ColorSpace)
840                     rc_decrement_only_cs(pim->ColorSpace, "psdf_setup_image_filters");
841                 goto fail;
842             }
843             image[1].pixel.ColorSpace = pcs_device;
844         }
845     }
846     if (image[1].pixel.ColorSpace == pim->ColorSpace)
847         rc_decrement_only_cs(pim->ColorSpace, "psdf_setup_image_filters");
848 
849     for (i = 0; i < pie->writer.alt_writer_count; i++) {
850         code = pdf_begin_image_data_decoded(pdev, num_components, pranges, i,
851                              &image[i].pixel, &cs_value, pie);
852         if (code < 0)
853             goto fail;
854     }
855     if (pie->writer.alt_writer_count == 2) {
856         psdf_setup_compression_chooser(&pie->writer.binary[2],
857              (gx_device_psdf *)pdev, pim->Width, pim->Height,
858              num_components, pim->BitsPerComponent);
859         pie->writer.alt_writer_count = 3;
860     }
861     if (pic->type->index == 4 && pdev->CompatibilityLevel < 1.3) {
862         int i;
863 
864         /* Create a stream for writing the mask. */
865         i = pie->writer.alt_writer_count;
866         gs_image_t_init_mask_adjust((gs_image_t *)&image[i].type1, true, false);
867         image[i].type1.Width = image[0].pixel.Width;
868         image[i].type1.Height = image[0].pixel.Height;
869         /* Won't use image[2]. */
870         code = pdf_begin_write_image(pdev, &pie->writer, gs_no_id, width,
871                     height, NULL, false);
872         if (code)
873             goto fail;
874         code = psdf_setup_image_filters((gx_device_psdf *) pdev,
875                                   &pie->writer.binary[i], &image[i].pixel,
876                                   pmat, pis, force_lossless, in_line);
877         if (code < 0)
878             goto fail;
879         psdf_setup_image_to_mask_filter(&pie->writer.binary[i],
880              (gx_device_psdf *)pdev, pim->Width, pim->Height,
881              num_components, pim->BitsPerComponent, image[i].type4.MaskColor);
882         code = pdf_begin_image_data_decoded(pdev, num_components, pranges, i,
883                              &image[i].pixel, &cs_value, pie);
884         if (code < 0)
885             goto fail;
886         ++pie->writer.alt_writer_count;
887         /* Note : Possible values for alt_writer_count are 1,2,3, 4.
888            1 means no alternative streams.
889            2 means the main image stream and a mask stream while converting
890                    an Image Type 4.
891            3 means the main image stream, alternative image compression stream,
892                    and the compression chooser.
893            4 meams 3 and a mask stream while convertingh an Image Type 4.
894          */
895     }
896     return 0;
897  fail:
898     /****** SHOULD FREE STRUCTURES AND CLEAN UP HERE ******/
899     /* Fall back to the default implementation. */
900  nyi:
901     return gx_default_begin_typed_image
902         ((gx_device *)pdev, pis, pmat, pic, prect, pdcolor, pcpath, mem,
903          pinfo);
904 }
905 
906 static int
pdf_begin_typed_image(gx_device_pdf * pdev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo,pdf_typed_image_context_t context)907 pdf_begin_typed_image(gx_device_pdf *pdev, const gs_imager_state * pis,
908                       const gs_matrix *pmat, const gs_image_common_t *pic,
909                       const gs_int_rect * prect,
910                       const gx_drawing_color * pdcolor,
911                       const gx_clip_path * pcpath, gs_memory_t * mem,
912                       gx_image_enum_common_t ** pinfo,
913                       pdf_typed_image_context_t context)
914 {
915   int code;
916   image_union_t *image = (image_union_t *)gs_malloc(mem->non_gc_memory, 4,
917                        sizeof(image_union_t), "pdf_begin_typed_image(image)");
918   if (image == 0)
919       return_error(gs_error_VMerror);
920   code = pdf_begin_typed_image_impl(pdev, pis, pmat, pic, prect,
921          pdcolor, pcpath, mem, pinfo, context, image);
922   gs_free(mem->non_gc_memory, image, 4, sizeof(image_union_t),
923                                               "pdf_begin_typed_image(image)");
924   return code;
925 }
926 
927 int
gdev_pdf_begin_typed_image(gx_device * dev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo)928 gdev_pdf_begin_typed_image(gx_device * dev, const gs_imager_state * pis,
929                            const gs_matrix *pmat, const gs_image_common_t *pic,
930                            const gs_int_rect * prect,
931                            const gx_drawing_color * pdcolor,
932                            const gx_clip_path * pcpath, gs_memory_t * mem,
933                            gx_image_enum_common_t ** pinfo)
934 {
935     return pdf_begin_typed_image((gx_device_pdf *)dev, pis, pmat, pic, prect,
936                                  pdcolor, pcpath, mem, pinfo,
937                                  PDF_IMAGE_DEFAULT);
938 }
939 
940 /* ---------------- All images ---------------- */
941 
942 /* Process the next piece of an image. */
943 static int
pdf_image_plane_data_alt(gx_image_enum_common_t * info,const gx_image_plane_t * planes,int height,int * rows_used,int alt_writer_index)944 pdf_image_plane_data_alt(gx_image_enum_common_t * info,
945                      const gx_image_plane_t * planes, int height,
946                      int *rows_used, int alt_writer_index)
947 {
948     pdf_image_enum *pie = (pdf_image_enum *) info;
949     int h = height;
950     int y;
951     /****** DOESN'T HANDLE IMAGES WITH VARYING WIDTH PER PLANE ******/
952     uint width_bits = pie->width * pie->plane_depths[0];
953     /****** DOESN'T HANDLE NON-ZERO data_x CORRECTLY ******/
954     uint bcount = (width_bits + 7) >> 3;
955     uint ignore;
956     int nplanes = pie->num_planes;
957     int status = 0;
958 
959     if (h > pie->rows_left)
960         h = pie->rows_left;
961     for (y = 0; y < h; ++y) {
962         if (nplanes > 1) {
963             /*
964              * We flip images in blocks, and each block except the last one
965              * must contain an integral number of pixels.  The easiest way
966              * to meet this condition is for all blocks except the last to
967              * be a multiple of 3 source bytes (guaranteeing an integral
968              * number of 1/2/4/8/12-bit samples), i.e., 3*nplanes flipped
969              * bytes.  This requires a buffer of at least
970              * 3*GS_IMAGE_MAX_COMPONENTS bytes.
971              */
972             int pi;
973             uint count = bcount;
974             uint offset = 0;
975 #define ROW_BYTES max(200 /*arbitrary*/, 3 * GS_IMAGE_MAX_COMPONENTS)
976             const byte *bit_planes[GS_IMAGE_MAX_COMPONENTS];
977             int block_bytes = ROW_BYTES / (3 * nplanes) * 3;
978             byte row[ROW_BYTES];
979 
980             for (pi = 0; pi < nplanes; ++pi)
981                 bit_planes[pi] = planes[pi].data + planes[pi].raster * y;
982             while (count) {
983                 uint flip_count;
984                 uint flipped_count;
985 
986                 if (count >= block_bytes) {
987                     flip_count = block_bytes;
988                     flipped_count = block_bytes * nplanes;
989                 } else {
990                     flip_count = count;
991                     flipped_count =
992                         (width_bits % (block_bytes * 8) * nplanes + 7) >> 3;
993                 }
994                 image_flip_planes(row, bit_planes, offset, flip_count,
995                                   nplanes, pie->plane_depths[0]);
996                 status = sputs(pie->writer.binary[alt_writer_index].strm, row,
997                                flipped_count, &ignore);
998                 if (status < 0)
999                     break;
1000                 offset += flip_count;
1001                 count -= flip_count;
1002             }
1003         } else {
1004             status = sputs(pie->writer.binary[alt_writer_index].strm,
1005                            planes[0].data + planes[0].raster * y, bcount,
1006                            &ignore);
1007         }
1008         if (status < 0)
1009             break;
1010     }
1011     *rows_used = h;
1012     if (status < 0)
1013         return_error(gs_error_ioerror);
1014     return !pie->rows_left;
1015 #undef ROW_BYTES
1016 }
1017 
1018 static int
pdf_image_plane_data(gx_image_enum_common_t * info,const gx_image_plane_t * planes,int height,int * rows_used)1019 pdf_image_plane_data(gx_image_enum_common_t * info,
1020                      const gx_image_plane_t * planes, int height,
1021                      int *rows_used)
1022 {
1023     pdf_image_enum *pie = (pdf_image_enum *) info;
1024     int i;
1025     for (i = 0; i < pie->writer.alt_writer_count; i++) {
1026         int code = pdf_image_plane_data_alt(info, planes, height, rows_used, i);
1027         if (code)
1028             return code;
1029     }
1030     pie->rows_left -= *rows_used;
1031     if (pie->writer.alt_writer_count > 2)
1032         pdf_choose_compression(&pie->writer, false);
1033     return !pie->rows_left;
1034 }
1035 
1036 static int
use_image_as_pattern(gx_device_pdf * pdev,pdf_resource_t * pres1,const gs_matrix * pmat,gs_id id)1037 use_image_as_pattern(gx_device_pdf *pdev, pdf_resource_t *pres1,
1038                      const gs_matrix *pmat, gs_id id)
1039 {   /* See also dump_image in gdevpdfd.c . */
1040     gs_imager_state s;
1041     gs_pattern1_instance_t inst;
1042     cos_value_t v;
1043     const pdf_resource_t *pres;
1044     int code;
1045 
1046     memset(&s, 0, sizeof(s));
1047     s.ctm.xx = pmat->xx;
1048     s.ctm.xy = pmat->xy;
1049     s.ctm.yx = pmat->yx;
1050     s.ctm.yy = pmat->yy;
1051     s.ctm.tx = pmat->tx;
1052     s.ctm.ty = pmat->ty;
1053     memset(&inst, 0, sizeof(inst));
1054     inst.saved = (gs_state *)&s; /* HACK : will use s.ctm only. */
1055     inst.templat.PaintType = 1;
1056     inst.templat.TilingType = 1;
1057     inst.templat.BBox.p.x = inst.templat.BBox.p.y = 0;
1058     inst.templat.BBox.q.x = 1;
1059     inst.templat.BBox.q.y = 1;
1060     inst.templat.XStep = 2; /* Set 2 times bigger step against artifacts. */
1061     inst.templat.YStep = 2;
1062     code = (*dev_proc(pdev, dev_spec_op))((gx_device *)pdev,
1063         gxdso_pattern_start_accum, &inst, id);
1064     if (code >= 0)
1065         pprintld1(pdev->strm, "/R%ld Do\n", pdf_resource_id(pres1));
1066     pres = pdev->accumulating_substream_resource;
1067     if (code >= 0)
1068         code = pdf_add_resource(pdev, pdev->substream_Resources, "/XObject", pres1);
1069     if (code >= 0)
1070         code = (*dev_proc(pdev, dev_spec_op))((gx_device *)pdev,
1071             gxdso_pattern_finish_accum, &inst, id);
1072     if (code >= 0)
1073         code = (*dev_proc(pdev, dev_spec_op))((gx_device *)pdev,
1074             gxdso_pattern_load, &inst, id);
1075     if (code >= 0) {
1076         stream_puts(pdev->strm, "q ");
1077         code = pdf_cs_Pattern_colored(pdev, &v);
1078     }
1079     if (code >= 0) {
1080         cos_value_write(&v, pdev);
1081         pprintld1(pdev->strm, " cs /R%ld scn ", pdf_resource_id(pres));
1082     }
1083     if (code >= 0) {
1084         /* The image offset weas broken in gx_begin_image3_generic,
1085            (see 'origin' in there).
1086            As a temporary hack use the offset of the image.
1087            fixme : This isn't generally correct,
1088            because the mask may be "transpozed" against the image. */
1089         gs_matrix m = pdev->converting_image_matrix;
1090 
1091         m.tx = pmat->tx;
1092         m.ty = pmat->ty;
1093         code = pdf_do_image_by_id(pdev, pdev->image_mask_scale,
1094              &m, true, pdev->image_mask_id);
1095         stream_puts(pdev->strm, "Q\n");
1096     }
1097     return code;
1098 }
1099 
1100 typedef enum {
1101     USE_AS_MASK,
1102     USE_AS_IMAGE,
1103     USE_AS_PATTERN
1104 } pdf_image_usage_t;
1105 
1106 /* Close PDF image and do it. */
1107 static int
pdf_end_and_do_image(gx_device_pdf * pdev,pdf_image_writer * piw,const gs_matrix * mat,gs_id ps_bitmap_id,pdf_image_usage_t do_image)1108 pdf_end_and_do_image(gx_device_pdf *pdev, pdf_image_writer *piw,
1109                      const gs_matrix *mat, gs_id ps_bitmap_id, pdf_image_usage_t do_image)
1110 {
1111     int code = pdf_end_write_image(pdev, piw);
1112     pdf_resource_t *pres = piw->pres;
1113 
1114     switch (code) {
1115     default:
1116         return code;	/* error */
1117     case 1:
1118         code = 0;
1119         break;
1120     case 0:
1121         if (do_image == USE_AS_IMAGE) {
1122             if (pdev->image_mask_id != gs_no_id) {
1123                 char buf[20];
1124 
1125                 sprintf(buf, "%ld 0 R", pdev->image_mask_id);
1126                 code = cos_dict_put_string_copy((cos_dict_t *)pres->object,
1127                         pdev->image_mask_is_SMask ? "/SMask" : "/Mask", buf);
1128                 if (code < 0)
1129                     return code;
1130             }
1131             if (pdev->image_mask_skip)
1132                 code = 0;
1133             else
1134                 code = pdf_do_image(pdev, pres, mat, true);
1135         } else if (do_image == USE_AS_MASK) {
1136             /* Provide data for pdf_do_image_by_id, which will be called through
1137                 use_image_as_pattern during the next call to this function.
1138                 See pdf_do_image about the meaning of 'scale'. */
1139             const pdf_x_object_t *const pxo = (const pdf_x_object_t *)pres;
1140 
1141             pdev->image_mask_scale = (double)pxo->data_height / pxo->height;
1142             pdev->image_mask_id = pdf_resource_id(pres);
1143             pdev->converting_image_matrix = *mat;
1144         } else if (do_image == USE_AS_PATTERN)
1145             code = use_image_as_pattern(pdev, pres, mat, ps_bitmap_id);
1146     }
1147     return code;
1148 }
1149 
1150 /* Clean up by releasing the buffers. */
1151 static int
pdf_image_end_image_data(gx_image_enum_common_t * info,bool draw_last,pdf_image_usage_t do_image)1152 pdf_image_end_image_data(gx_image_enum_common_t * info, bool draw_last,
1153                          pdf_image_usage_t do_image)
1154 {
1155     gx_device_pdf *pdev = (gx_device_pdf *)info->dev;
1156     pdf_image_enum *pie = (pdf_image_enum *)info;
1157     int height = pie->writer.height;
1158     int data_height = height - pie->rows_left;
1159     int code = 0;
1160 
1161     if (pie->writer.pres)
1162         ((pdf_x_object_t *)pie->writer.pres)->data_height = data_height;
1163     else if (data_height > 0)
1164         pdf_put_image_matrix(pdev, &pie->mat, (double)data_height / height);
1165     if (data_height > 0) {
1166         code = pdf_complete_image_data(pdev, &pie->writer, data_height,
1167                         pie->width, pie->bits_per_pixel);
1168         if (code < 0)
1169             return code;
1170         code = pdf_end_image_binary(pdev, &pie->writer, data_height);
1171         /* The call above possibly decreases pie->writer.alt_writer_count in 2. */
1172         if (code < 0)
1173             return code;
1174         if (pie->writer.alt_writer_count == 2) {
1175             /* We're converting a type 4 image into an imagemask with a pattern color. */
1176             /* Since the type 3 image writes the mask first, do so here. */
1177             pdf_image_writer writer = pie->writer;
1178 
1179             writer.binary[0] = pie->writer.binary[1];
1180             writer.pres = pie->writer.pres_mask;
1181             writer.alt_writer_count = 1;
1182             memset(&pie->writer.binary[1], 0, sizeof(pie->writer.binary[1]));
1183             pie->writer.alt_writer_count--; /* For GC. */
1184             pie->writer.pres_mask = 0; /* For GC. */
1185             code = pdf_end_image_binary(pdev, &writer, data_height);
1186             if (code < 0)
1187                 return code;
1188             code = pdf_end_and_do_image(pdev, &writer, &pie->mat, info->id, USE_AS_MASK);
1189             if (code < 0)
1190                 return code;
1191             code = pdf_end_and_do_image(pdev, &pie->writer, &pie->mat, info->id, USE_AS_PATTERN);
1192         } else
1193             code = pdf_end_and_do_image(pdev, &pie->writer, &pie->mat, info->id, do_image);
1194         pie->writer.alt_writer_count--; /* For GC. */
1195     }
1196     gx_image_free_enum(&info);
1197     return code;
1198 }
1199 
1200 /* End a normal image, drawing it. */
1201 static int
pdf_image_end_image(gx_image_enum_common_t * info,bool draw_last)1202 pdf_image_end_image(gx_image_enum_common_t * info, bool draw_last)
1203 {
1204     return pdf_image_end_image_data(info, draw_last, USE_AS_IMAGE);
1205 }
1206 
1207 /* End an image converted with pdf_lcvd_t. */
1208 static int
pdf_image_end_image_cvd(gx_image_enum_common_t * info,bool draw_last)1209 pdf_image_end_image_cvd(gx_image_enum_common_t * info, bool draw_last)
1210 {   pdf_lcvd_t *cvd = (pdf_lcvd_t *)info->dev;
1211     int code = pdf_dump_converted_image(cvd->pdev, cvd);
1212     int code1 = gx_image1_end_image(info, draw_last);
1213     int code2 = gs_closedevice((gx_device *)cvd->mask);
1214     int code3 = gs_closedevice((gx_device *)cvd);
1215 
1216     gs_free_object(cvd->mask->memory, (gx_device *)cvd->mask, "pdf_image_end_image_cvd");
1217     gs_free_object(cvd->mdev.memory, (gx_device *)cvd, "pdf_image_end_image_cvd");
1218     return code < 0 ? code : code1 < 0 ? code1 : code2 < 0 ? code2 : code3;
1219 }
1220 /* ---------------- Type 3/3x images ---------------- */
1221 
1222 /*
1223  * For both types of masked images, we create temporary dummy (null) devices
1224  * that forward the begin_typed_image call to the implementation above.
1225  */
1226 static int
pdf_make_mxd(gx_device ** pmxdev,gx_device * tdev,gs_memory_t * mem)1227 pdf_make_mxd(gx_device **pmxdev, gx_device *tdev, gs_memory_t *mem)
1228 {
1229     gx_device *fdev;
1230     int code = gs_copydevice(&fdev, (const gx_device *)&gs_null_device, mem);
1231 
1232     if (code < 0)
1233         return code;
1234     gx_device_set_target((gx_device_forward *)fdev, tdev);
1235     *pmxdev = fdev;
1236     return 0;
1237 }
1238 
1239 /* End the mask of an ImageType 3 image, not drawing it. */
1240 static int
pdf_image_end_image_object(gx_image_enum_common_t * info,bool draw_last)1241 pdf_image_end_image_object(gx_image_enum_common_t * info, bool draw_last)
1242 {
1243     return pdf_image_end_image_data(info, draw_last, USE_AS_MASK);
1244 }
1245 /* End the data of an ImageType 3 image, converting it into pattern. */
1246 static int
pdf_image_end_image_object2(gx_image_enum_common_t * info,bool draw_last)1247 pdf_image_end_image_object2(gx_image_enum_common_t * info, bool draw_last)
1248 {
1249     return pdf_image_end_image_data(info, draw_last, USE_AS_PATTERN);
1250 }
1251 
1252 /* ---------------- Type 3 images ---------------- */
1253 
1254 /* Implement the mask image device. */
1255 static dev_proc_begin_typed_image(pdf_mid_begin_typed_image);
1256 static int
pdf_image3_make_mid(gx_device ** pmidev,gx_device * dev,int width,int height,gs_memory_t * mem)1257 pdf_image3_make_mid(gx_device **pmidev, gx_device *dev, int width, int height,
1258                     gs_memory_t *mem)
1259 {
1260     gx_device_pdf *pdev = (gx_device_pdf *)dev;
1261 
1262     if (pdev->CompatibilityLevel < 1.3 && !pdev->PatternImagemask) {
1263         gs_matrix m;
1264         pdf_lcvd_t *cvd = NULL;
1265         int code;
1266 
1267         gs_make_identity(&m);
1268         code = pdf_setup_masked_image_converter(pdev, mem, &m, &cvd,
1269                                         true, 0, 0, width, height, true);
1270         if (code < 0)
1271             return code;
1272         cvd->mask->target = (gx_device *)cvd; /* Temporary, just to communicate with
1273                                          pdf_image3_make_mcde. The latter will reset it. */
1274         cvd->mask_is_empty = false;
1275         *pmidev = (gx_device *)cvd->mask;
1276         return 0;
1277     } else {
1278         int code = pdf_make_mxd(pmidev, dev, mem);
1279 
1280         if (code < 0)
1281             return code;
1282         set_dev_proc(*pmidev, begin_typed_image, pdf_mid_begin_typed_image);
1283         return 0;
1284     }
1285 }
1286 static int
pdf_mid_begin_typed_image(gx_device * dev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo)1287 pdf_mid_begin_typed_image(gx_device * dev, const gs_imager_state * pis,
1288                           const gs_matrix *pmat, const gs_image_common_t *pic,
1289                           const gs_int_rect * prect,
1290                           const gx_drawing_color * pdcolor,
1291                           const gx_clip_path * pcpath, gs_memory_t * mem,
1292                           gx_image_enum_common_t ** pinfo)
1293 {
1294     /* The target of the null device is the pdfwrite device. */
1295     gx_device_pdf *const pdev = (gx_device_pdf *)
1296         ((gx_device_null *)dev)->target;
1297     return pdf_begin_typed_image
1298         (pdev, pis, pmat, pic, prect, pdcolor, pcpath, mem, pinfo,
1299          PDF_IMAGE_TYPE3_MASK);
1300 }
1301 
1302 /* Implement the mask clip device. */
1303 static int
pdf_image3_make_mcde(gx_device * dev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo,gx_device ** pmcdev,gx_device * midev,gx_image_enum_common_t * pminfo,const gs_int_point * origin)1304 pdf_image3_make_mcde(gx_device *dev, const gs_imager_state *pis,
1305                      const gs_matrix *pmat, const gs_image_common_t *pic,
1306                      const gs_int_rect *prect, const gx_drawing_color *pdcolor,
1307                      const gx_clip_path *pcpath, gs_memory_t *mem,
1308                      gx_image_enum_common_t **pinfo,
1309                      gx_device **pmcdev, gx_device *midev,
1310                      gx_image_enum_common_t *pminfo,
1311                      const gs_int_point *origin)
1312 {
1313     int code;
1314     gx_device_pdf *pdev = (gx_device_pdf *)dev;
1315 
1316     if (pdev->CompatibilityLevel < 1.3 && !pdev->PatternImagemask) {
1317         /* pdf_image3_make_mid must set midev with a pdf_lcvd_t instance.*/
1318         pdf_lcvd_t *cvd = (pdf_lcvd_t *)((gx_device_memory *)midev)->target;
1319 
1320         ((gx_device_memory *)midev)->target = NULL;
1321         cvd->m = pdev->converting_image_matrix;
1322         cvd->mdev.mapped_x = origin->x;
1323         cvd->mdev.mapped_y = origin->y;
1324         *pmcdev = (gx_device *)&cvd->mdev;
1325         code = gx_default_begin_typed_image
1326             ((gx_device *)&cvd->mdev, pis, pmat, pic, prect, pdcolor, NULL, mem,
1327             pinfo);
1328         if (code < 0)
1329             return code;
1330     } else {
1331         code = pdf_make_mxd(pmcdev, midev, mem);
1332         if (code < 0)
1333             return code;
1334         code = pdf_begin_typed_image
1335             ((gx_device_pdf *)dev, pis, pmat, pic, prect, pdcolor, pcpath, mem,
1336             pinfo, PDF_IMAGE_TYPE3_DATA);
1337         if (code < 0)
1338             return code;
1339     }
1340     /* Due to equal image merging, we delay the adding of the "Mask" entry into
1341        a type 3 image dictionary until the mask is completed.
1342        Will do in pdf_end_and_do_image.*/
1343     return 0;
1344 }
1345 
1346 /* ---------------- Type 3x images ---------------- */
1347 
1348 /* Implement the mask image device. */
1349 static int
pdf_image3x_make_mid(gx_device ** pmidev,gx_device * dev,int width,int height,int depth,gs_memory_t * mem)1350 pdf_image3x_make_mid(gx_device **pmidev, gx_device *dev, int width, int height,
1351                      int depth, gs_memory_t *mem)
1352 {
1353     int code = pdf_make_mxd(pmidev, dev, mem);
1354 
1355     if (code < 0)
1356         return code;
1357     set_dev_proc(*pmidev, begin_typed_image, pdf_mid_begin_typed_image);
1358     return 0;
1359 }
1360 
1361 /* Implement the mask clip device. */
1362 static int
pdf_image3x_make_mcde(gx_device * dev,const gs_imager_state * pis,const gs_matrix * pmat,const gs_image_common_t * pic,const gs_int_rect * prect,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath,gs_memory_t * mem,gx_image_enum_common_t ** pinfo,gx_device ** pmcdev,gx_device * midev[2],gx_image_enum_common_t * pminfo[2],const gs_int_point origin[2],const gs_image3x_t * pim)1363 pdf_image3x_make_mcde(gx_device *dev, const gs_imager_state *pis,
1364                       const gs_matrix *pmat, const gs_image_common_t *pic,
1365                       const gs_int_rect *prect,
1366                       const gx_drawing_color *pdcolor,
1367                       const gx_clip_path *pcpath, gs_memory_t *mem,
1368                       gx_image_enum_common_t **pinfo,
1369                       gx_device **pmcdev, gx_device *midev[2],
1370                       gx_image_enum_common_t *pminfo[2],
1371                       const gs_int_point origin[2],
1372                       const gs_image3x_t *pim)
1373 {
1374     int code;
1375     pdf_image_enum *pmie;
1376     int i;
1377     const gs_image3x_mask_t *pixm;
1378 
1379     if (midev[0]) {
1380         if (midev[1])
1381             return_error(gs_error_rangecheck);
1382         i = 0, pixm = &pim->Opacity;
1383     } else if (midev[1])
1384         i = 1, pixm = &pim->Shape;
1385     else
1386         return_error(gs_error_rangecheck);
1387     code = pdf_make_mxd(pmcdev, midev[i], mem);
1388     if (code < 0)
1389         return code;
1390     code = pdf_begin_typed_image
1391         ((gx_device_pdf *)dev, pis, pmat, pic, prect, pdcolor, pcpath, mem,
1392          pinfo, PDF_IMAGE_TYPE3_DATA);
1393     if (code < 0)
1394         return code;
1395     if ((*pinfo)->procs != &pdf_image_enum_procs) {
1396         /* We couldn't handle the image.  Bail out. */
1397         gx_image_end(*pinfo, false);
1398         gs_free_object(mem, *pmcdev, "pdf_image3x_make_mcde");
1399         return_error(gs_error_rangecheck);
1400     }
1401     pmie = (pdf_image_enum *)pminfo[i];
1402     /*
1403      * Add the SMask entry to the image dictionary, and, if needed,
1404      * the Matte entry to the mask dictionary.
1405      */
1406     if (pixm->has_Matte) {
1407         int num_components =
1408             gs_color_space_num_components(pim->ColorSpace);
1409 
1410         code = cos_dict_put_c_key_floats(
1411                                 (cos_dict_t *)pmie->writer.pres->object,
1412                                 "/Matte", pixm->Matte,
1413                                 num_components);
1414         if (code < 0)
1415             return code;
1416     }
1417 /* Don't put SMask here because pmie->writer.pres->object may be substituted
1418  * after the image stream is accummulated. pdf_end_and_do_image will set
1419  * SMask with the right value. Bug 690345.
1420  */
1421     return 0;
1422 }
1423 
pdf_substitute_pattern(pdf_resource_t * pres)1424 pdf_resource_t *pdf_substitute_pattern(pdf_resource_t *pres)
1425 {
1426     pdf_pattern_t *ppat = (pdf_pattern_t *)pres;
1427 
1428     return (pdf_resource_t *)(ppat->substitute != 0 ? ppat->substitute : ppat);
1429 }
1430 
1431 static int
check_unsubstituted2(gx_device_pdf * pdev,pdf_resource_t * pres0,pdf_resource_t * pres1)1432 check_unsubstituted2(gx_device_pdf * pdev, pdf_resource_t *pres0, pdf_resource_t *pres1)
1433 {
1434     pdf_pattern_t *ppat0 = (pdf_pattern_t *)pres0;
1435     pdf_pattern_t *ppat1 = (pdf_pattern_t *)pres1;
1436 
1437     return (ppat0->substitute == NULL && ppat1->substitute == NULL);
1438 }
1439 
1440 static int
check_unsubstituted1(gx_device_pdf * pdev,pdf_resource_t * pres0)1441 check_unsubstituted1(gx_device_pdf * pdev, pdf_resource_t *pres0)
1442 {
1443     pdf_pattern_t *ppat = (pdf_pattern_t *)pres0;
1444 
1445     return ppat->substitute != NULL;
1446 }
1447 
1448 /*
1449    The device specific operations - just pattern management.
1450    See gxdevcli.h about return codes.
1451  */
1452 int
gdev_pdf_dev_spec_op(gx_device * pdev1,int dev_spec_op,void * data,int size)1453 gdev_pdf_dev_spec_op(gx_device *pdev1, int dev_spec_op, void *data, int size)
1454 {
1455     gx_device_pdf *pdev = (gx_device_pdf *)pdev1;
1456     int code;
1457     pdf_resource_t *pres, *pres1;
1458     gx_bitmap_id id = (gx_bitmap_id)size;
1459     gs_pattern1_instance_t *pinst = (gs_pattern1_instance_t *)data;
1460 
1461     switch (dev_spec_op) {
1462         case gxdso_pattern_can_accum:
1463             return 1;
1464         case gxdso_pattern_start_accum:
1465             code = pdf_enter_substream(pdev, resourcePattern, id, &pres, false,
1466                     pdev->CompressFonts/* Have no better switch.*/);
1467             if (code < 0)
1468                 return code;
1469             pres->rid = id;
1470             code = pdf_store_pattern1_params(pdev, pres, pinst);
1471             if (code < 0)
1472                 return code;
1473             /* Scale the coordinate system, because object handlers assume so. See none_to_stream. */
1474             pprintg2(pdev->strm, "%g 0 0 %g 0 0 cm\n",
1475                      72.0 / pdev->HWResolution[0], 72.0 / pdev->HWResolution[1]);
1476             pdev->PatternDepth++;
1477             return 1;
1478         case gxdso_pattern_finish_accum:
1479             code = pdf_add_procsets(pdev->substream_Resources, pdev->procsets);
1480             if (code < 0)
1481                 return code;
1482             pres = pres1 = pdev->accumulating_substream_resource;
1483             code = pdf_exit_substream(pdev);
1484             if (code < 0)
1485                 return code;
1486             if (pdev->substituted_pattern_count > 300 &&
1487                     pdev->substituted_pattern_drop_page != pdev->next_page) { /* arbitrary */
1488                 pdf_drop_resources(pdev, resourcePattern, check_unsubstituted1);
1489                 pdev->substituted_pattern_count = 0;
1490                 pdev->substituted_pattern_drop_page = pdev->next_page;
1491             }
1492             code = pdf_find_same_resource(pdev, resourcePattern, &pres, check_unsubstituted2);
1493             if (code < 0)
1494                 return code;
1495             if (code > 0) {
1496                 pdf_pattern_t *ppat = (pdf_pattern_t *)pres1;
1497 
1498                 code = pdf_cancel_resource(pdev, pres1, resourcePattern);
1499                 if (code < 0)
1500                     return code;
1501                 /* Do not remove pres1, because it keeps the substitution. */
1502                 ppat->substitute = (pdf_pattern_t *)pres;
1503                 pres->where_used |= pdev->used_mask;
1504                 pdev->substituted_pattern_count++;
1505             } else if (pres->object->id < 0)
1506                 pdf_reserve_object_id(pdev, pres, 0);
1507             pdev->PatternDepth--;
1508             return 1;
1509         case gxdso_pattern_load:
1510             pres = pdf_find_resource_by_gs_id(pdev, resourcePattern, id);
1511             if (pres == 0)
1512                 return gs_error_undefined;
1513             pres = pdf_substitute_pattern(pres);
1514             pres->where_used |= pdev->used_mask;
1515             code = pdf_add_resource(pdev, pdev->substream_Resources, "/Pattern", pres);
1516             if (code < 0)
1517                 return code;
1518             return 1;
1519         case gxdso_pattern_shading_area:
1520             return 0;
1521         case gxdso_pattern_is_cpath_accum:
1522             return 0;
1523         case gxdso_pattern_shfill_doesnt_need_path:
1524             return 0; /* gdev_pdf_fill_path still does need a path. */
1525         case gxdso_pattern_handles_clip_path:
1526             /* This is important when the default implementation of
1527                of fill_path is called due to a failure in setcolor
1528                or so, for example when a shading is incorrect.
1529                The test case is the unfixed (buggy) Genoa test 446-01.ps .
1530                In this case pdfwrite converts the object into rectangles,
1531                and the clipping device has to be set up. */
1532             return 0;
1533         case gxdso_supports_hlcolor:
1534             /* This is used due to some aliasing between the rect_hl color
1535                filling used by pdfwrite vs. that used by the planar device
1536                which is actually a devn vs. the pattern type for pdfwrite.
1537                We use this to distingush between the two */
1538             return 1;
1539     }
1540     return gx_default_dev_spec_op(pdev1, dev_spec_op, data, size);
1541 }
1542