xref: /plan9/sys/src/cmd/gs/src/gdevpdfk.c (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
1 /* Copyright (C) 2001 Aladdin Enterprises.  All rights reserved.
2 
3   This software is provided AS-IS with no warranty, either express or
4   implied.
5 
6   This software is distributed under license and may not be copied,
7   modified or distributed except as expressly authorized under the terms
8   of the license contained in the file LICENSE in this distribution.
9 
10   For more information about licensing, please refer to
11   http://www.ghostscript.com/licensing/. For information on
12   commercial licensing, go to http://www.artifex.com/licensing/ or
13   contact Artifex Software, Inc., 101 Lucas Valley Road #110,
14   San Rafael, CA  94903, U.S.A., +1(415)492-9861.
15 */
16 
17 /* $Id: gdevpdfk.c,v 1.10 2005/02/25 07:58:50 igor Exp $ */
18 /* Lab and ICCBased color space writing */
19 #include "math_.h"
20 #include "memory_.h"
21 #include "gx.h"
22 #include "gxcspace.h"
23 #include "stream.h"
24 #include "gsicc.h"
25 #include "gserrors.h"
26 #include "gxcie.h"
27 #include "gdevpdfx.h"
28 #include "gdevpdfg.h"
29 #include "gdevpdfc.h"
30 #include "gdevpdfo.h"
31 #include "strimpl.h"
32 
33 /* ------ CIE space synthesis ------ */
34 
35 /* Add a /Range entry to a CIE-based color space dictionary. */
36 private int
pdf_cie_add_ranges(cos_dict_t * pcd,const gs_range * prange,int n,bool clamp)37 pdf_cie_add_ranges(cos_dict_t *pcd, const gs_range *prange, int n, bool clamp)
38 {
39     cos_array_t *pca = cos_array_alloc(pcd->pdev, "pdf_cie_add_ranges");
40     int code = 0, i;
41 
42     if (pca == 0)
43 	return_error(gs_error_VMerror);
44     for (i = 0; i < n; ++i) {
45 	floatp rmin = prange[i].rmin, rmax = prange[i].rmax;
46 
47 	if (clamp) {
48 	    if (rmin < 0) rmin = 0;
49 	    if (rmax > 1) rmax = 1;
50 	}
51 	if ((code = cos_array_add_real(pca, rmin)) < 0 ||
52 	    (code = cos_array_add_real(pca, rmax)) < 0
53 	    )
54 	    break;
55     }
56     if (code >= 0)
57 	code = cos_dict_put_c_key_object(pcd, "/Range", COS_OBJECT(pca));
58     if (code < 0)
59 	COS_FREE(pca, "pdf_cie_add_ranges");
60     return code;
61 }
62 
63 /* Transform a CIEBased color to XYZ. */
64 private int
cie_to_xyz(const double * in,double out[3],const gs_color_space * pcs,const gs_imager_state * pis)65 cie_to_xyz(const double *in, double out[3], const gs_color_space *pcs,
66 	   const gs_imager_state *pis)
67 {
68     gs_client_color cc;
69     frac xyz[3];
70     int ncomp = gs_color_space_num_components(pcs);
71     int i;
72 
73     for (i = 0; i < ncomp; ++i)
74 	cc.paint.values[i] = in[i];
75     cs_concretize_color(&cc, pcs, xyz, pis);
76     out[0] = frac2float(xyz[0]);
77     out[1] = frac2float(xyz[1]);
78     out[2] = frac2float(xyz[2]);
79     return 0;
80 }
81 
82 /* ------ Lab space writing and synthesis ------ */
83 
84 /* Transform XYZ values to Lab. */
85 private double
lab_g_inverse(double v)86 lab_g_inverse(double v)
87 {
88     if (v >= (6.0 * 6.0 * 6.0) / (29 * 29 * 29))
89 	return pow(v, 1.0 / 3);	/* use cbrt if available? */
90     else
91 	return (v * (841.0 / 108) + 4.0 / 29);
92 }
93 private void
xyz_to_lab(const double xyz[3],double lab[3],const gs_cie_common * pciec)94 xyz_to_lab(const double xyz[3], double lab[3], const gs_cie_common *pciec)
95 {
96     const gs_vector3 *const pWhitePoint = &pciec->points.WhitePoint;
97     double L, lunit;
98 
99     /* Calculate L* first. */
100     L = lab_g_inverse(xyz[1] / pWhitePoint->v) * 116 - 16;
101     /* Clamp L* to the PDF range [0..100]. */
102     if (L < 0)
103 	L = 0;
104     else if (L > 100)
105 	L = 100;
106     lab[1] = L;
107     lunit = (L + 16) / 116;
108 
109     /* Calculate a* and b*. */
110     lab[0] = (lab_g_inverse(xyz[0] / pWhitePoint->u) - lunit) * 500;
111     lab[2] = (lab_g_inverse(xyz[2] / pWhitePoint->w) - lunit) * -200;
112 }
113 
114 /* Create a PDF Lab color space corresponding to a CIEBased color space. */
115 private int
lab_range(gs_range range_out[3],const gs_color_space * pcs,const gs_cie_common * pciec,const gs_range * ranges,gs_memory_t * mem)116 lab_range(gs_range range_out[3] /* only [1] and [2] used */,
117 	  const gs_color_space *pcs, const gs_cie_common *pciec,
118 	  const gs_range *ranges, gs_memory_t *mem)
119 {
120     /*
121      * Determine the range of a* and b* by evaluating the color space
122      * mapping at all of its extrema.
123      */
124     int ncomp = gs_color_space_num_components(pcs);
125     gs_imager_state *pis;
126     int code = gx_cie_to_xyz_alloc(&pis, pcs, mem);
127     int i, j;
128 
129     if (code < 0)
130 	return code;
131     for (j = 1; j < 3; ++j)
132 	range_out[j].rmin = 1000.0, range_out[j].rmax = -1000.0;
133     for (i = 0; i < 1 << ncomp; ++i) {
134 	double in[4], xyz[3];
135 
136 	for (j = 0; j < ncomp; ++j)
137 	    in[j] = (i & (1 << j) ? ranges[j].rmax : ranges[j].rmin);
138 	if (cie_to_xyz(in, xyz, pcs, pis) >= 0) {
139 	    double lab[3];
140 
141 	    xyz_to_lab(xyz, lab, pciec);
142 	    for (j = 1; j < 3; ++j) {
143 		range_out[j].rmin = min(range_out[j].rmin, lab[j]);
144 		range_out[j].rmax = max(range_out[j].rmax, lab[j]);
145 	    }
146 	}
147     }
148     gx_cie_to_xyz_free(pis);
149     return 0;
150 }
151 /*
152  * Create a Lab color space object.
153  * This procedure is exported for Lab color spaces in gdevpdfc.c.
154  */
155 int
pdf_put_lab_color_space(cos_array_t * pca,cos_dict_t * pcd,const gs_range ranges[3])156 pdf_put_lab_color_space(cos_array_t *pca, cos_dict_t *pcd,
157 			const gs_range ranges[3] /* only [1] and [2] used */)
158 {
159     int code;
160     cos_value_t v;
161 
162     if ((code = cos_array_add(pca, cos_c_string_value(&v, "/Lab"))) >= 0)
163 	code = pdf_cie_add_ranges(pcd, ranges + 1, 2, false);
164     return code;
165 }
166 
167 /*
168  * Create a Lab color space for a CIEBased space that can't be represented
169  * directly as a Calxxx or Lab space.
170  */
171 private int
pdf_convert_cie_to_lab(gx_device_pdf * pdev,cos_array_t * pca,const gs_color_space * pcs,const gs_cie_common * pciec,const gs_range * prange)172 pdf_convert_cie_to_lab(gx_device_pdf *pdev, cos_array_t *pca,
173 		       const gs_color_space *pcs,
174 		       const gs_cie_common *pciec, const gs_range *prange)
175 {
176     cos_dict_t *pcd;
177     gs_range ranges[3];
178     int code;
179 
180     /****** NOT IMPLEMENTED YET, REQUIRES TRANSFORMING VALUES ******/
181     if (1) return_error(gs_error_rangecheck);
182     pcd = cos_dict_alloc(pdev, "pdf_convert_cie_to_lab(dict)");
183     if (pcd == 0)
184 	return_error(gs_error_VMerror);
185     if ((code = lab_range(ranges, pcs, pciec, prange, pdev->pdf_memory)) < 0 ||
186 	(code = pdf_put_lab_color_space(pca, pcd, ranges)) < 0 ||
187 	(code = pdf_finish_cie_space(pca, pcd, pciec)) < 0
188 	)
189 	COS_FREE(pcd, "pdf_convert_cie_to_lab(dict)");
190     return code;
191 }
192 
193 /* ------ ICCBased space writing and synthesis ------ */
194 
195 /*
196  * Create an ICCBased color space object (internal).  The client must write
197  * the profile data on *ppcstrm.
198  */
199 private int
pdf_make_iccbased(gx_device_pdf * pdev,cos_array_t * pca,int ncomps,const gs_range * prange,const gs_color_space * pcs_alt,cos_stream_t ** ppcstrm,const gs_range_t ** pprange)200 pdf_make_iccbased(gx_device_pdf *pdev, cos_array_t *pca, int ncomps,
201 		  const gs_range *prange /*[4]*/,
202 		  const gs_color_space *pcs_alt,
203 		  cos_stream_t **ppcstrm,
204 		  const gs_range_t **pprange /* if scaling is needed */)
205 
206 {
207     cos_value_t v;
208     int code;
209     cos_stream_t * pcstrm = 0;
210     cos_array_t * prngca = 0;
211     bool std_ranges = true;
212     bool scale_inputs = false;
213     int i;
214 
215     /* Check the ranges. */
216     if (pprange)
217 	*pprange = 0;
218     for (i = 0; i < ncomps; ++i) {
219 	double rmin = prange[i].rmin, rmax = prange[i].rmax;
220 
221 	if (rmin < 0.0 || rmax > 1.0) {
222 	    /* We'll have to scale the inputs.  :-( */
223 	    if (pprange == 0)
224 		return_error(gs_error_rangecheck); /* scaling not allowed */
225 	    *pprange = prange;
226 	    scale_inputs = true;
227 	}
228 	else if (rmin > 0.0 || rmax < 1.0)
229 	    std_ranges = false;
230     }
231 
232     /* ICCBased color spaces are essentially copied to the output. */
233     if ((code = cos_array_add(pca, cos_c_string_value(&v, "/ICCBased"))) < 0)
234 	return code;
235 
236     /* Create a stream for the output. */
237     if ((pcstrm = cos_stream_alloc(pdev, "pdf_make_iccbased(stream)")) == 0) {
238 	code = gs_note_error(gs_error_VMerror);
239 	goto fail;
240     }
241 
242     /* Indicate the number of components. */
243     code = cos_dict_put_c_key_int(cos_stream_dict(pcstrm), "/N", ncomps);
244     if (code < 0)
245 	goto fail;
246 
247     /* Indicate the range, if needed. */
248     if (!std_ranges && !scale_inputs) {
249 	code = pdf_cie_add_ranges(cos_stream_dict(pcstrm), prange, ncomps, true);
250 	if (code < 0)
251 	    goto fail;
252     }
253 
254     /* Output the alternate color space, if necessary. */
255     switch (gs_color_space_get_index(pcs_alt)) {
256     case gs_color_space_index_DeviceGray:
257     case gs_color_space_index_DeviceRGB:
258     case gs_color_space_index_DeviceCMYK:
259 	break;			/* implicit (default) */
260     default:
261 	if ((code = pdf_color_space(pdev, &v, NULL, pcs_alt,
262 				    &pdf_color_space_names, false)) < 0 ||
263 	    (code = cos_dict_put_c_key(cos_stream_dict(pcstrm), "/Alternate",
264 				       &v)) < 0
265 	    )
266 	    goto fail;
267     }
268 
269     /* Wrap up. */
270     if ((code = cos_array_add_object(pca, COS_OBJECT(pcstrm))) < 0)
271 	goto fail;
272     *ppcstrm = pcstrm;
273     return code;
274  fail:
275     if (prngca)
276 	COS_FREE(prngca, "pdf_make_iccbased(Range)");
277     if (pcstrm)
278 	COS_FREE(pcstrm, "pdf_make_iccbased(stream)");
279     return code;
280 }
281 /*
282  * Finish writing the data stream for an ICCBased color space object.
283  */
284 private int
pdf_finish_iccbased(cos_stream_t * pcstrm)285 pdf_finish_iccbased(cos_stream_t *pcstrm)
286 {
287     /*
288      * The stream must be an indirect object.  Assign an ID, and write the
289      * object out now.
290      */
291     gx_device_pdf *pdev = pcstrm->pdev;
292 
293     pcstrm->id = pdf_obj_ref(pdev);
294     return cos_write_object(COS_OBJECT(pcstrm), pdev);
295 }
296 
297 /*
298  * Create an ICCBased color space for a CIEBased space that can't be
299  * represented directly as a Calxxx or Lab space.
300  */
301 
302 typedef struct profile_table_s profile_table_t;
303 struct profile_table_s {
304     const char *tag;
305     const byte *data;
306     uint length;
307     uint data_length;		/* may be < length if write != 0 */
308     int (*write)(cos_stream_t *, const profile_table_t *, gs_memory_t *);
309     const void *write_data;
310     const gs_range_t *ranges;
311 };
312 private profile_table_t *
add_table(profile_table_t ** ppnt,const char * tag,const byte * data,uint length)313 add_table(profile_table_t **ppnt, const char *tag, const byte *data,
314 	  uint length)
315 {
316     profile_table_t *pnt = (*ppnt)++;
317 
318     pnt->tag = tag, pnt->data = data, pnt->length = length;
319     pnt->data_length = length;
320     pnt->write = NULL;
321     /* write_data not set */
322     pnt->ranges = NULL;
323     return pnt;
324 }
325 private void
set_uint32(byte bytes[4],uint value)326 set_uint32(byte bytes[4], uint value)
327 {
328     bytes[0] = (byte)(value >> 24);
329     bytes[1] = (byte)(value >> 16);
330     bytes[2] = (byte)(value >> 8);
331     bytes[3] = (byte)value;
332 }
333 private void
set_XYZ(byte bytes[4],floatp value)334 set_XYZ(byte bytes[4], floatp value)
335 {
336     set_uint32(bytes, (uint)(int)(value * 65536));
337 }
338 private void
add_table_xyz3(profile_table_t ** ppnt,const char * tag,byte bytes[20],const gs_vector3 * pv)339 add_table_xyz3(profile_table_t **ppnt, const char *tag, byte bytes[20],
340 	       const gs_vector3 *pv)
341 {
342     memcpy(bytes, "XYZ \000\000\000\000", 8);
343     set_XYZ(bytes + 8, pv->u);
344     set_XYZ(bytes + 12, pv->v);
345     set_XYZ(bytes + 16, pv->w);
346     DISCARD(add_table(ppnt, tag, bytes, 20));
347 }
348 private void
set_sample16(byte * p,floatp v)349 set_sample16(byte *p, floatp v)
350 {
351     int value = (int)(v * 65535);
352 
353     if (value < 0)
354 	value = 0;
355     else if (value > 65535)
356 	value = 65535;
357     p[0] = (byte)(value >> 8);
358     p[1] = (byte)value;
359 }
360 /* Create and write a TRC curve table. */
361 private int write_trc_abc(cos_stream_t *, const profile_table_t *, gs_memory_t *);
362 private int write_trc_lmn(cos_stream_t *, const profile_table_t *, gs_memory_t *);
363 private profile_table_t *
add_trc(profile_table_t ** ppnt,const char * tag,byte bytes[12],const gs_cie_common * pciec,cie_cache_one_step_t one_step)364 add_trc(profile_table_t **ppnt, const char *tag, byte bytes[12],
365 	const gs_cie_common *pciec, cie_cache_one_step_t one_step)
366 {
367     const int count = gx_cie_cache_size;
368     profile_table_t *pnt;
369 
370     memcpy(bytes, "curv\000\000\000\000", 8);
371     set_uint32(bytes + 8, count);
372     pnt = add_table(ppnt, tag, bytes, 12);
373     pnt->length += count * 2;
374     pnt->write = (one_step == ONE_STEP_ABC ? write_trc_abc : write_trc_lmn);
375     pnt->write_data = (const gs_cie_abc *)pciec;
376     return pnt;
377 }
378 private int
rgb_to_index(const profile_table_t * pnt)379 rgb_to_index(const profile_table_t *pnt)
380 {
381     switch (pnt->tag[0]) {
382     case 'r': return 0;
383     case 'g': return 1;
384     case 'b': default: /* others can't happen */ return 2;
385     }
386 }
387 private double
cache_arg(int i,int denom,const gs_range_t * range)388 cache_arg(int i, int denom, const gs_range_t *range)
389 {
390     double arg = i / (double)denom;
391 
392     if (range) {
393 	/* Sample over the range [range->rmin .. range->rmax]. */
394 	arg = arg * (range->rmax - range->rmin) + range->rmin;
395     }
396     return arg;
397 }
398 
399 private int
write_trc_abc(cos_stream_t * pcstrm,const profile_table_t * pnt,gs_memory_t * ignore_mem)400 write_trc_abc(cos_stream_t *pcstrm, const profile_table_t *pnt,
401 	      gs_memory_t *ignore_mem)
402 {
403     /* Write the curve table from DecodeABC. */
404     const gs_cie_abc *pabc = pnt->write_data;
405     int ci = rgb_to_index(pnt);
406     gs_cie_abc_proc proc = pabc->DecodeABC.procs[ci];
407     byte samples[gx_cie_cache_size * 2];
408     byte *p = samples;
409     int i;
410 
411     for (i = 0; i < gx_cie_cache_size; ++i, p += 2)
412 	set_sample16(p, proc(cache_arg(i, gx_cie_cache_size - 1, pnt->ranges),
413 			     pabc));
414     return cos_stream_add_bytes(pcstrm, samples, gx_cie_cache_size * 2);
415 }
416 private int
write_trc_lmn(cos_stream_t * pcstrm,const profile_table_t * pnt,gs_memory_t * ignore_mem)417 write_trc_lmn(cos_stream_t *pcstrm, const profile_table_t *pnt,
418 	      gs_memory_t *ignore_mem)
419 {
420     const gs_cie_common *pciec = pnt->write_data;
421     int ci = rgb_to_index(pnt);
422     gs_cie_common_proc proc = pciec->DecodeLMN.procs[ci];
423     byte samples[gx_cie_cache_size * 2];
424     byte *p = samples;
425     int i;
426 
427     /* Write the curve table from DecodeLMN. */
428     for (i = 0; i < gx_cie_cache_size; ++i, p += 2)
429 	set_sample16(p, proc(cache_arg(i, gx_cie_cache_size - 1, pnt->ranges),
430 			     pciec));
431     return cos_stream_add_bytes(pcstrm, samples, gx_cie_cache_size * 2);
432 }
433 /* Create and write an a2b0 lookup table. */
434 #define NUM_IN_ENTRIES 2	/* assume linear interpolation */
435 #define NUM_OUT_ENTRIES 2	/* ibid. */
436 #define MAX_CLUT_ENTRIES 2500	/* enough for 7^4 */
437 typedef struct icc_a2b0_s {
438     byte header[52];
439     const gs_color_space *pcs;
440     int num_points;		/* on each axis of LUT */
441     int count;			/* total # of entries in LUT */
442 } icc_a2b0_t;
443 private int write_a2b0(cos_stream_t *, const profile_table_t *, gs_memory_t *);
444 private profile_table_t *
add_a2b0(profile_table_t ** ppnt,icc_a2b0_t * pa2b,int ncomps,const gs_color_space * pcs)445 add_a2b0(profile_table_t **ppnt, icc_a2b0_t *pa2b, int ncomps,
446 	 const gs_color_space *pcs)
447 {
448     static const byte a2b0_data[sizeof(pa2b->header)] = {
449 	'm', 'f', 't', '2',		/* type signature */
450 	0, 0, 0, 0,			/* reserved, 0 */
451 	0,				/* # of input channels **VARIABLE** */
452 	3,				/* # of output channels */
453 	0,				/* # of CLUT points **VARIABLE** */
454 	0,				/* reserved, padding */
455 	0, 1, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, /* matrix column 0 */
456 	0, 0, 0, 0,  0, 1, 0, 0,  0, 0, 0, 0, /* matrix column 1 */
457 	0, 0, 0, 0,  0, 0, 0, 0,  0, 1, 0, 0, /* matrix column 2 */
458 	0, NUM_IN_ENTRIES,		/* # of input table entries */
459 	0, NUM_OUT_ENTRIES		/* # of output table entries */
460     };
461     int num_points = (int)floor(pow(MAX_CLUT_ENTRIES, 1.0 / ncomps));
462     profile_table_t *pnt;
463 
464     num_points = min(num_points, 255);
465     memcpy(pa2b->header, a2b0_data, sizeof(a2b0_data));
466     pa2b->header[8] = ncomps;
467     pa2b->header[10] = num_points;
468     pa2b->pcs = pcs;
469     pa2b->num_points = num_points;
470     pa2b->count = (int)pow(num_points, ncomps);
471     pnt = add_table(ppnt, "A2B0", pa2b->header,
472 		    sizeof(pa2b->header) +
473 		    ncomps * 2 * NUM_IN_ENTRIES + /* in */
474 		    pa2b->count * (3 * 2) + /* clut: XYZ, 16-bit values */
475 		    3 * 2 * NUM_OUT_ENTRIES /* out */
476 		    );
477     pnt->data_length = sizeof(pa2b->header); /* only write fixed part */
478     pnt->write = write_a2b0;
479     pnt->write_data = pa2b;
480     return pnt;
481 }
482 private int
write_a2b0(cos_stream_t * pcstrm,const profile_table_t * pnt,gs_memory_t * mem)483 write_a2b0(cos_stream_t *pcstrm, const profile_table_t *pnt,
484 	   gs_memory_t *mem)
485 {
486     const icc_a2b0_t *pa2b = pnt->write_data;
487     const gs_color_space *pcs = pa2b->pcs;
488     int ncomps = pa2b->header[8];
489     int num_points = pa2b->num_points;
490     int i;
491 #define MAX_NCOMPS 4		/* CIEBasedDEFG */
492     static const byte v01[MAX_NCOMPS * 2 * 2] = {
493 	0,0, 255,255,   0,0, 255,255,   0,0, 255,255,   0,0, 255,255
494     };
495     gs_imager_state *pis;
496     int code;
497 
498     /* Write the input table. */
499 
500     if ((code = cos_stream_add_bytes(pcstrm, v01, ncomps * 4)) < 0
501 	)
502 	return code;
503 
504     /* Write the lookup table. */
505 
506     code = gx_cie_to_xyz_alloc(&pis, pcs, mem);
507     if (code < 0)
508 	return code;
509     for (i = 0; i < pa2b->count; ++i) {
510 	double in[MAX_NCOMPS], xyz[3];
511 	byte entry[3 * 2];
512 	byte *p = entry;
513 	int n, j;
514 
515 	for (n = i, j = ncomps - 1; j >= 0; --j, n /= num_points)
516 	    in[j] = cache_arg(n % num_points, num_points - 1,
517 			      (pnt->ranges ? pnt->ranges + j : NULL));
518 	cie_to_xyz(in, xyz, pcs, pis);
519 	/*
520 	 * NOTE: Due to an obscure provision of the ICC Profile
521 	 * specification, values in a2b0 lookup tables do *not* represent
522 	 * the range [0 .. 1], but rather the range [0
523 	 * .. MAX_ICC_XYZ_VALUE].  This caused us a lot of grief before we
524 	 * figured it out!
525 	 */
526 #define MAX_ICC_XYZ_VALUE (1 + 32767.0/32768)
527 	for (j = 0; j < 3; ++j, p += 2)
528 	    set_sample16(p, xyz[j] / MAX_ICC_XYZ_VALUE);
529 #undef MAX_ICC_XYZ_VALUE
530 	if ((code = cos_stream_add_bytes(pcstrm, entry, sizeof(entry))) < 0)
531 	    break;
532     }
533     gx_cie_to_xyz_free(pis);
534     if (code < 0)
535 	return code;
536 
537     /* Write the output table. */
538 
539     return cos_stream_add_bytes(pcstrm, v01, 3 * 4);
540 }
541 private int
pdf_convert_cie_to_iccbased(gx_device_pdf * pdev,cos_array_t * pca,const gs_color_space * pcs,const char * dcsname,const gs_cie_common * pciec,const gs_range * prange,cie_cache_one_step_t one_step,const gs_matrix3 * pmat,const gs_range_t ** pprange)542 pdf_convert_cie_to_iccbased(gx_device_pdf *pdev, cos_array_t *pca,
543 			    const gs_color_space *pcs, const char *dcsname,
544 			    const gs_cie_common *pciec, const gs_range *prange,
545 			    cie_cache_one_step_t one_step,
546 			    const gs_matrix3 *pmat, const gs_range_t **pprange)
547 {
548     /*
549      * We have two options for creating an ICCBased color space to represent
550      * a CIEBased space.  For CIEBasedABC spaces using only a single
551      * Decode step followed by a single Matrix step, we can use [rgb]TRC
552      * and [rgb]XYZ; for CIEBasedA spaces using only DecodeA, we could use
553      * kTRC (but don't); otherwise, we must use a mft2 LUT.
554      */
555     int code;
556     int ncomps = gs_color_space_num_components(pcs);
557     gs_color_space alt_space;
558     cos_stream_t *pcstrm;
559 
560     /*
561      * Even though Ghostscript includes icclib, icclib is unusable here,
562      * because it requires random access to the output stream.
563      * Instead, we construct the ICC profile by hand.
564      */
565     /* Header */
566     byte header[128];
567     static const byte header_data[] = {
568 	0, 0, 0, 0,			/* profile size **VARIABLE** */
569 	0, 0, 0, 0,			/* CMM type signature */
570 	0x02, 0x20, 0, 0,		/* profile version number */
571 	's', 'c', 'n', 'r',		/* profile class signature */
572 	0, 0, 0, 0,			/* data color space **VARIABLE** */
573 	'X', 'Y', 'Z', ' ',		/* connection color space */
574 	2002 / 256, 2002 % 256, 0, 1, 0, 1, /* date (1/1/2002) */
575 	0, 0, 0, 0, 0, 0,		/* time */
576 	'a', 'c', 's', 'p',		/* profile file signature */
577 	0, 0, 0, 0,			/* primary platform signature */
578 	0, 0, 0, 3,			/* profile flags (embedded use only) */
579 	0, 0, 0, 0, 0, 0, 0, 0,		/* device manufacturer */
580 	0, 0, 0, 0,			/* device model */
581 	0, 0, 0, 0, 0, 0, 0, 2		/* device attributes */
582 	/* Remaining fields are zero or variable. */
583 	/* [4] */			/* rendering intent */
584 	/* 3 * [4] */			/* illuminant */
585     };
586     /* Description */
587 #define DESC_LENGTH 5		/* "adhoc" */
588     byte desc[12 + DESC_LENGTH + 1 + 11 + 67];
589     static const byte desc_data[] = {
590 	'd', 'e', 's', 'c',		/* type signature */
591 	0, 0, 0, 0,			/* reserved, 0 */
592 	0, 0, 0, DESC_LENGTH + 1,	/* ASCII description length */
593 	'a', 'd', 'h', 'o', 'c', 0,	/* ASCII description */
594 	/* Remaining fields are zero. */
595     };
596     /* White point */
597     byte wtpt[20];
598     /* Copyright (useless, but required by icclib) */
599     static const byte cprt_data[] = {
600 	't', 'e', 'x', 't',	/* type signature */
601 	0, 0, 0, 0,		/* reserved, 0 */
602 	'n', 'o', 'n', 'e', 0	/* must be null-terminated (!) */
603     };
604     /* Lookup table */
605     icc_a2b0_t a2b0;
606     /* [rgb]TRC */
607     byte rTRC[12], gTRC[12], bTRC[12];
608     /* [rgb]XYZ */
609     byte rXYZ[20], gXYZ[20], bXYZ[20];
610     /* Table structures */
611 #define MAX_NUM_TABLES 9	/* desc, [rgb]TRC, [rgb]xYZ, wtpt, cprt */
612     profile_table_t tables[MAX_NUM_TABLES];
613     profile_table_t *next_table = tables;
614 
615     pdf_cspace_init_Device(pdev->memory, &alt_space, ncomps);	/* can't fail */
616     code = pdf_make_iccbased(pdev, pca, ncomps, prange, &alt_space,
617 			     &pcstrm, pprange);
618     if (code < 0)
619 	return code;
620 
621     /* Fill in most of the header, except for the total size. */
622 
623     memset(header, 0, sizeof(header));
624     memcpy(header, header_data, sizeof(header_data));
625     memcpy(header + 16, dcsname, 4);
626 
627     /* Construct the tables. */
628 
629     /* desc */
630     memset(desc, 0, sizeof(desc));
631     memcpy(desc, desc_data, sizeof(desc_data));
632     DISCARD(add_table(&next_table, "desc", desc, sizeof(desc)));
633 
634     /* wtpt */
635     add_table_xyz3(&next_table, "wtpt", wtpt, &pciec->points.WhitePoint);
636     memcpy(header + 68, wtpt + 8, 12); /* illuminant = white point */
637 
638     /* cprt */
639     /* (We have no use for this tag, but icclib requires it.) */
640     DISCARD(add_table(&next_table, "cprt", cprt_data, sizeof(cprt_data)));
641 
642     /* Use TRC + XYZ if possible, otherwise AToB. */
643     if ((one_step == ONE_STEP_ABC || one_step == ONE_STEP_LMN) && pmat != 0) {
644 	/* Use TRC + XYZ. */
645 	profile_table_t *tr =
646 	    add_trc(&next_table, "rTRC", rTRC, pciec, one_step);
647 	profile_table_t *tg =
648 	    add_trc(&next_table, "gTRC", gTRC, pciec, one_step);
649 	profile_table_t *tb =
650 	    add_trc(&next_table, "bTRC", bTRC, pciec, one_step);
651 
652 	if (*pprange) {
653 	    tr->ranges = *pprange;
654 	    tg->ranges = *pprange + 1;
655 	    tb->ranges = *pprange + 2;
656 	}
657 	add_table_xyz3(&next_table, "rXYZ", rXYZ, &pmat->cu);
658 	add_table_xyz3(&next_table, "gXYZ", gXYZ, &pmat->cv);
659 	add_table_xyz3(&next_table, "bXYZ", bXYZ, &pmat->cw);
660     } else {
661 	/* General case, use a lookup table. */
662 	/* AToB (mft2) */
663 	profile_table_t *pnt = add_a2b0(&next_table, &a2b0, ncomps, pcs);
664 
665 	pnt->ranges = *pprange;
666     }
667 
668     /* Write the profile. */
669     {
670 	byte bytes[4 + MAX_NUM_TABLES * 12];
671 	int num_tables = next_table - tables;
672 	int i;
673 	byte *p;
674 	uint table_size = 4 + num_tables * 12;
675 	uint offset = sizeof(header) + table_size;
676 
677 	set_uint32(bytes, next_table - tables);
678 	for (i = 0, p = bytes + 4; i < num_tables; ++i, p += 12) {
679 	    memcpy(p, tables[i].tag, 4);
680 	    set_uint32(p + 4, offset);
681 	    set_uint32(p + 8, tables[i].length);
682 	    offset += round_up(tables[i].length, 4);
683 	}
684 	set_uint32(header, offset);
685 	if ((code = cos_stream_add_bytes(pcstrm, header, sizeof(header))) < 0 ||
686 	    (code = cos_stream_add_bytes(pcstrm, bytes, table_size)) < 0
687 	    )
688 	    return code;
689 	for (i = 0; i < num_tables; ++i) {
690 	    uint len = tables[i].data_length;
691 	    static const byte pad[3] = {0, 0, 0};
692 
693 	    if ((code = cos_stream_add_bytes(pcstrm, tables[i].data, len)) < 0 ||
694 		(tables[i].write != 0 &&
695 		 (code = tables[i].write(pcstrm, &tables[i], pdev->pdf_memory)) < 0) ||
696 		(code = cos_stream_add_bytes(pcstrm, pad,
697 			-(int)(tables[i].length) & 3)) < 0
698 		)
699 		return code;
700 	}
701     }
702 
703     return pdf_finish_iccbased(pcstrm);
704 }
705 
706 /* ------ Entry points (from gdevpdfc.c) ------ */
707 
708 /*
709  * Create an ICCBased color space.  This is a single-use procedure,
710  * broken out only for readability.
711  */
712 int
pdf_iccbased_color_space(gx_device_pdf * pdev,cos_value_t * pvalue,const gs_color_space * pcs,cos_array_t * pca)713 pdf_iccbased_color_space(gx_device_pdf *pdev, cos_value_t *pvalue,
714 			 const gs_color_space *pcs, cos_array_t *pca)
715 {
716     /*
717      * This would arise only in a pdf ==> pdf translation, but we
718      * should allow for it anyway.
719      */
720     const gs_icc_params * picc_params = &pcs->params.icc;
721     const gs_cie_icc * picc_info = picc_params->picc_info;
722     cos_stream_t * pcstrm;
723     int code =
724 	pdf_make_iccbased(pdev, pca, picc_info->num_components,
725 			  picc_info->Range.ranges,
726 			  (const gs_color_space *)&picc_params->alt_space,
727 			  &pcstrm, NULL);
728 
729     if (code < 0)
730 	return code;
731 
732     /* Transfer the profile stream. */
733     code = cos_stream_add_stream_contents(pcstrm, picc_info->instrp);
734     if (code >= 0)
735 	code = pdf_finish_iccbased(pcstrm);
736     /*
737      * The stream has been added to the array: in case of failure, the
738      * caller will free the array, so there is no need to free the stream
739      * explicitly here.
740      */
741     return code;
742 }
743 
744 /* Convert a CIEBased space to Lab or ICCBased. */
745 int
pdf_convert_cie_space(gx_device_pdf * pdev,cos_array_t * pca,const gs_color_space * pcs,const char * dcsname,const gs_cie_common * pciec,const gs_range * prange,cie_cache_one_step_t one_step,const gs_matrix3 * pmat,const gs_range_t ** pprange)746 pdf_convert_cie_space(gx_device_pdf *pdev, cos_array_t *pca,
747 		      const gs_color_space *pcs, const char *dcsname,
748 		      const gs_cie_common *pciec, const gs_range *prange,
749 		      cie_cache_one_step_t one_step, const gs_matrix3 *pmat,
750 		      const gs_range_t **pprange)
751 {
752     return (pdev->CompatibilityLevel < 1.3 ?
753 	    /* PDF 1.2 or earlier, use a Lab space. */
754 	    pdf_convert_cie_to_lab(pdev, pca, pcs, pciec, prange) :
755 	    /* PDF 1.3 or later, use an ICCBased space. */
756 	    pdf_convert_cie_to_iccbased(pdev, pca, pcs, dcsname, pciec, prange,
757 					one_step, pmat, pprange)
758 	    );
759 }
760