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 /* Halftone rendering for imaging library */
18 #include "memory_.h"
19 #include "gx.h"
20 #include "gserrors.h"
21 #include "gsstruct.h"
22 #include "gsbitops.h"
23 #include "gsutil.h"		/* for gs_next_ids */
24 #include "gxdcolor.h"
25 #include "gxfixed.h"
26 #include "gxdevice.h"		/* for gzht.h */
27 #include "gxistate.h"
28 #include "gzht.h"
29 #include "gsserial.h"
30 
31 /* Define the binary halftone device color type. */
32 /* The type descriptor must be public for Pattern types. */
33 gs_public_st_composite(st_dc_ht_binary, gx_device_color, "dc_ht_binary",
34                        dc_ht_binary_enum_ptrs, dc_ht_binary_reloc_ptrs);
35 static dev_color_proc_save_dc(gx_dc_ht_binary_save_dc);
36 static dev_color_proc_get_dev_halftone(gx_dc_ht_binary_get_dev_halftone);
37 static dev_color_proc_load(gx_dc_ht_binary_load);
38 static dev_color_proc_fill_rectangle(gx_dc_ht_binary_fill_rectangle);
39 static dev_color_proc_fill_masked(gx_dc_ht_binary_fill_masked);
40 static dev_color_proc_equal(gx_dc_ht_binary_equal);
41 static dev_color_proc_write(gx_dc_ht_binary_write);
42 static dev_color_proc_read(gx_dc_ht_binary_read);
43 const gx_device_color_type_t
44       gx_dc_type_data_ht_binary =
45 {&st_dc_ht_binary,
46  gx_dc_ht_binary_save_dc, gx_dc_ht_binary_get_dev_halftone,
47  gx_dc_ht_get_phase,
48  gx_dc_ht_binary_load, gx_dc_ht_binary_fill_rectangle,
49  gx_dc_ht_binary_fill_masked, gx_dc_ht_binary_equal,
50  gx_dc_ht_binary_write, gx_dc_ht_binary_read,
51  gx_dc_ht_binary_get_nonzero_comps
52 };
53 
54 #undef gx_dc_type_ht_binary
55 const gx_device_color_type_t *const gx_dc_type_ht_binary =
56 &gx_dc_type_data_ht_binary;
57 
58 #define gx_dc_type_ht_binary (&gx_dc_type_data_ht_binary)
59 /* GC procedures */
60 static
61 ENUM_PTRS_WITH(dc_ht_binary_enum_ptrs, gx_device_color *cptr) return 0;
62 ENUM_PTR(0, gx_device_color, colors.binary.b_ht);
63 case 1:
64 {
65     gx_ht_tile *tile = cptr->colors.binary.b_tile;
66 
67     ENUM_RETURN(tile ? tile - tile->index : 0);
68 }
69 ENUM_PTRS_END
RELOC_PTRS_WITH(dc_ht_binary_reloc_ptrs,gx_device_color * cptr)70 static RELOC_PTRS_WITH(dc_ht_binary_reloc_ptrs, gx_device_color *cptr)
71 {
72     gx_ht_tile *tile = cptr->colors.binary.b_tile;
73     uint index = tile ? tile->index : 0;
74 
75     RELOC_PTR(gx_device_color, colors.binary.b_ht);
76     RELOC_TYPED_OFFSET_PTR(gx_device_color, colors.binary.b_tile, index);
77 }
78 RELOC_PTRS_END
79 #undef cptr
80 
81 /* Other GC procedures */
82 private_st_ht_tiles();
83 static
ENUM_PTRS_BEGIN_PROC(ht_tiles_enum_ptrs)84 ENUM_PTRS_BEGIN_PROC(ht_tiles_enum_ptrs)
85 {
86     return 0;
87 }
88 ENUM_PTRS_END_PROC
RELOC_PTRS_BEGIN(ht_tiles_reloc_ptrs)89 static RELOC_PTRS_BEGIN(ht_tiles_reloc_ptrs)
90 {
91     /* Reset the bitmap pointers in the tiles. */
92     /* We know the first tile points to the base of the bits. */
93     gx_ht_tile *ht_tiles = vptr;
94     byte *bits = ht_tiles->tiles.data;
95     uint diff;
96 
97     if (bits == 0)
98         return;
99     RELOC_VAR(bits);
100     if (size == size_of(gx_ht_tile)) {	/* only 1 tile */
101         ht_tiles->tiles.data = bits;
102         return;
103     }
104     diff = ht_tiles[1].tiles.data - ht_tiles[0].tiles.data;
105     for (; size; ht_tiles++, size -= size_of(gx_ht_tile), bits += diff) {
106         ht_tiles->tiles.data = bits;
107     }
108 }
109 RELOC_PTRS_END
110 private_st_ht_cache();
111 
112 /* Return the default sizes of the halftone cache. */
113 uint
gx_ht_cache_default_tiles(void)114 gx_ht_cache_default_tiles(void)
115 {
116 #ifdef DEBUG
117     return (gs_debug_c('.') ? max_ht_cached_tiles_SMALL :
118             max_ht_cached_tiles);
119 #else
120     return max_ht_cached_tiles;
121 #endif
122 }
123 uint
gx_ht_cache_default_bits_size(void)124 gx_ht_cache_default_bits_size(void)
125 {
126 #ifdef DEBUG
127     return (gs_debug_c('.') ? max_ht_cache_bits_size_SMALL :
128             max_ht_cache_bits_size);
129 #else
130     return max_ht_cache_bits_size;
131 #endif
132 }
133 
134 /* Allocate a halftone cache. max_bits_size is number of bytes */
135 gx_ht_cache *
gx_ht_alloc_cache(gs_memory_t * mem,uint max_tiles,uint max_bits_size)136 gx_ht_alloc_cache(gs_memory_t * mem, uint max_tiles, uint max_bits_size)
137 {
138     gx_ht_cache *pcache =
139     gs_alloc_struct(mem, gx_ht_cache, &st_ht_cache,
140                     "alloc_ht_cache(struct)");
141     byte *tbits =
142         gs_alloc_bytes(mem, max_bits_size, "alloc_ht_cache(bits)");
143     gx_ht_tile *ht_tiles =
144         gs_alloc_struct_array(mem, max_tiles, gx_ht_tile, &st_ht_tiles,
145                               "alloc_ht_cache(ht_tiles)");
146 
147     if (pcache == 0 || tbits == 0 || ht_tiles == 0) {
148         gs_free_object(mem, ht_tiles, "alloc_ht_cache(ht_tiles)");
149         gs_free_object(mem, tbits, "alloc_ht_cache(bits)");
150         gs_free_object(mem, pcache, "alloc_ht_cache(struct)");
151         return 0;
152     }
153     pcache->bits = tbits;
154     pcache->bits_size = max_bits_size;
155     pcache->ht_tiles = ht_tiles;
156     pcache->num_tiles = max_tiles;
157     pcache->order.cache = pcache;
158     pcache->order.transfer = 0;
159     gx_ht_clear_cache(pcache);
160     return pcache;
161 }
162 
163 /* Free a halftone cache. */
164 void
gx_ht_free_cache(gs_memory_t * mem,gx_ht_cache * pcache)165 gx_ht_free_cache(gs_memory_t * mem, gx_ht_cache * pcache)
166 {
167     gs_free_object(mem, pcache->ht_tiles, "free_ht_cache(ht_tiles)");
168     gs_free_object(mem, pcache->bits, "free_ht_cache(bits)");
169     gs_free_object(mem, pcache, "free_ht_cache(struct)");
170 }
171 
172 /* Render a given level into a halftone cache. */
173 static int render_ht(gx_ht_tile *, int, const gx_ht_order *,
174                       gx_bitmap_id);
175 static gx_ht_tile *
gx_render_ht_default(gx_ht_cache * pcache,int b_level)176 gx_render_ht_default(gx_ht_cache * pcache, int b_level)
177 {
178     const gx_ht_order *porder = &pcache->order;
179     int level = porder->levels[b_level];
180     gx_ht_tile *bt;
181 
182     if (pcache->num_cached < porder->num_levels )
183         bt = &pcache->ht_tiles[level / pcache->levels_per_tile];
184     else
185         bt =  &pcache->ht_tiles[b_level];	/* one tile per b_level */
186 
187     if (bt->level != level) {
188         int code = render_ht(bt, level, porder, pcache->base_id + b_level);
189 
190         if (code < 0)
191             return 0;
192     }
193     return bt;
194 }
195 
196 /* save information about the operand binary halftone color */
197 static void
gx_dc_ht_binary_save_dc(const gx_device_color * pdevc,gx_device_color_saved * psdc)198 gx_dc_ht_binary_save_dc(const gx_device_color * pdevc,
199                         gx_device_color_saved * psdc)
200 {
201     psdc->type = pdevc->type;
202     psdc->colors.binary.b_color[0] = pdevc->colors.binary.color[0];
203     psdc->colors.binary.b_color[1] = pdevc->colors.binary.color[1];
204     psdc->colors.binary.b_level = pdevc->colors.binary.b_level;
205     psdc->colors.binary.b_index = pdevc->colors.binary.b_index;
206     psdc->phase = pdevc->phase;
207 }
208 
209 /* get the halftone used for a binary halftone color */
210 static const gx_device_halftone *
gx_dc_ht_binary_get_dev_halftone(const gx_device_color * pdevc)211 gx_dc_ht_binary_get_dev_halftone(const gx_device_color * pdevc)
212 {
213     return pdevc->colors.binary.b_ht;
214 }
215 
216 /* Load the device color into the halftone cache if needed. */
217 static int
gx_dc_ht_binary_load(gx_device_color * pdevc,const gs_imager_state * pis,gx_device * dev,gs_color_select_t select)218 gx_dc_ht_binary_load(gx_device_color * pdevc, const gs_imager_state * pis,
219                      gx_device * dev, gs_color_select_t select)
220 {
221     int component_index = pdevc->colors.binary.b_index;
222     const gx_ht_order *porder =
223         (component_index < 0 ?
224          &pdevc->colors.binary.b_ht->order :
225          &pdevc->colors.binary.b_ht->components[component_index].corder);
226     gx_ht_cache *pcache = porder->cache;
227 
228     if (pcache->order.bit_data != porder->bit_data)
229         gx_ht_init_cache(pis->memory, pcache, porder);
230     /*
231      * We do not load the cache now.  Instead we wait until we are ready
232      * to actually render the color.  This allows multiple colors to be
233      * loaded without cache conflicts.  (Cache conflicts can occur when
234      * if two device colors use the same cache elements.  This can occur
235      * when the tile size is large enough that we do not have a separate
236      * tile for each half tone level.)  See gx_dc_ht_binary_load_cache.
237      */
238     pdevc->colors.binary.b_tile = NULL;
239     return 0;
240 }
241 
242 /*
243  * Load the half tone tile in the halftone cache.
244  */
245 static int
gx_dc_ht_binary_load_cache(const gx_device_color * pdevc)246 gx_dc_ht_binary_load_cache(const gx_device_color * pdevc)
247 {
248     int component_index = pdevc->colors.binary.b_index;
249     const gx_ht_order *porder =
250          &pdevc->colors.binary.b_ht->components[component_index].corder;
251     gx_ht_cache *pcache = porder->cache;
252     int b_level = pdevc->colors.binary.b_level;
253     int level = porder->levels[b_level];
254     gx_ht_tile *bt;
255 
256     if (pcache->num_cached < porder->num_levels )
257         bt = &pcache->ht_tiles[level / pcache->levels_per_tile];
258     else
259         bt =  &pcache->ht_tiles[b_level];	/* one tile per b_level */
260 
261     if (bt->level != level) {
262         int code = render_ht(bt, level, porder, pcache->base_id + b_level);
263 
264         if (code < 0)
265             return_error(gs_error_Fatal);
266     }
267     ((gx_device_color *)pdevc)->colors.binary.b_tile = bt;
268     return 0;
269 }
270 
271 /* Fill a rectangle with a binary halftone. */
272 /* Note that we treat this as "texture" for RasterOp. */
273 static int
gx_dc_ht_binary_fill_rectangle(const gx_device_color * pdevc,int x,int y,int w,int h,gx_device * dev,gs_logical_operation_t lop,const gx_rop_source_t * source)274 gx_dc_ht_binary_fill_rectangle(const gx_device_color * pdevc, int x, int y,
275                   int w, int h, gx_device * dev, gs_logical_operation_t lop,
276                                const gx_rop_source_t * source)
277 {
278     gx_rop_source_t no_source;
279 
280     /* Load the halftone cache for the color */
281     gx_dc_ht_binary_load_cache(pdevc);
282     /*
283      * Observation of H-P devices and documentation yields confusing
284      * evidence about whether white pixels in halftones are always
285      * opaque.  It appears that for black-and-white devices, these
286      * pixels are *not* opaque.
287      */
288     if (dev->color_info.depth > 1)
289         lop &= ~lop_T_transparent;
290     if (source == NULL && lop_no_S_is_T(lop))
291         return (*dev_proc(dev, strip_tile_rectangle)) (dev,
292                                         &pdevc->colors.binary.b_tile->tiles,
293                                   x, y, w, h, pdevc->colors.binary.color[0],
294                                               pdevc->colors.binary.color[1],
295                                             pdevc->phase.x, pdevc->phase.y);
296     /* Adjust the logical operation per transparent colors. */
297     if (pdevc->colors.binary.color[0] == gx_no_color_index)
298         lop = rop3_use_D_when_T_0(lop);
299     if (pdevc->colors.binary.color[1] == gx_no_color_index)
300         lop = rop3_use_D_when_T_1(lop);
301     if (source == NULL)
302         set_rop_no_source(source, no_source, dev);
303     if (source->planar_height == 0)
304         return (*dev_proc(dev, strip_copy_rop))
305                              (dev, source->sdata,
306                               source->sourcex, source->sraster, source->id,
307                               (source->use_scolors ? source->scolors : NULL),
308                               &pdevc->colors.binary.b_tile->tiles,
309                               pdevc->colors.binary.color,
310                               x, y, w, h, pdevc->phase.x, pdevc->phase.y,
311                               lop);
312     else
313         return (*dev_proc(dev, strip_copy_rop2))
314                              (dev, source->sdata,
315                               source->sourcex, source->sraster, source->id,
316                               (source->use_scolors ? source->scolors : NULL),
317                               &pdevc->colors.binary.b_tile->tiles,
318                               pdevc->colors.binary.color,
319                               x, y, w, h, pdevc->phase.x, pdevc->phase.y,
320                               lop, source->planar_height);
321 }
322 
323 static int
gx_dc_ht_binary_fill_masked(const gx_device_color * pdevc,const byte * data,int data_x,int raster,gx_bitmap_id id,int x,int y,int w,int h,gx_device * dev,gs_logical_operation_t lop,bool invert)324 gx_dc_ht_binary_fill_masked(const gx_device_color * pdevc, const byte * data,
325         int data_x, int raster, gx_bitmap_id id, int x, int y, int w, int h,
326                    gx_device * dev, gs_logical_operation_t lop, bool invert)
327 {
328     /*
329      * Load the halftone cache for the color.  We do not do it earlier
330      * because for small halftone caches, each cache tile may be used for
331      * for more than one halftone level.  This can cause conflicts if more
332      * than one device color has been set and they use the same cache
333      * entry.
334      */
335     int code = gx_dc_ht_binary_load_cache(pdevc);
336 
337     if (code < 0)
338         return code;
339     return gx_dc_default_fill_masked(pdevc, data, data_x, raster, id,
340                                         x, y, w, h, dev, lop, invert);
341 }
342 
343 /* Compare two binary halftones for equality. */
344 static bool
gx_dc_ht_binary_equal(const gx_device_color * pdevc1,const gx_device_color * pdevc2)345 gx_dc_ht_binary_equal(const gx_device_color * pdevc1,
346                       const gx_device_color * pdevc2)
347 {
348     return pdevc2->type == pdevc1->type &&
349         pdevc1->phase.x == pdevc2->phase.x &&
350         pdevc1->phase.y == pdevc2->phase.y &&
351         gx_dc_binary_color0(pdevc1) == gx_dc_binary_color0(pdevc2) &&
352         gx_dc_binary_color1(pdevc1) == gx_dc_binary_color1(pdevc2) &&
353         pdevc1->colors.binary.b_level == pdevc2->colors.binary.b_level;
354 }
355 
356 /*
357  * Flags to indicate the pieces of a binary halftone that are included
358  * in its string representation. The first byte of the string holds this
359  * set of flags.
360  *
361  * The binary halftone tile is never transmitted as part of the string
362  * representation, so there is also no flag bit for it.
363  */
364 static const int   dc_ht_binary_has_color0 = 0x01;
365 static const int   dc_ht_binary_has_color1 = 0x02;
366 static const int   dc_ht_binary_has_level = 0x04;
367 static const int   dc_ht_binary_has_index = 0x08;
368 
369 /*
370  * Serialize a binany halftone device color.
371  *
372  * Operands:
373  *
374  *  pdevc       pointer to device color to be serialized
375  *
376  *  psdc        pointer ot saved version of last serialized color (for
377  *              this band)
378  *
379  *  dev         pointer to the current device, used to retrieve process
380  *              color model information
381  *
382  *  pdata       pointer to buffer in which to write the data
383  *
384  *  psize       pointer to a location that, on entry, contains the size of
385  *              the buffer pointed to by pdata; on return, the size of
386  *              the data required or actually used will be written here.
387  *
388  * Returns:
389  *  1, with *psize set to 0, if *psdc and *pdevc represent the same color
390  *
391  *  0, with *psize set to the amount of data written, if everything OK
392  *
393  *  gs_error_rangecheck, with *psize set to the size of buffer required,
394  *  if *psize was not large enough
395  *
396  *  < 0, != gs_error_rangecheck, in the event of some other error; in this
397  *  case *psize is not changed.
398  */
399 static int
gx_dc_ht_binary_write(const gx_device_color * pdevc,const gx_device_color_saved * psdc0,const gx_device * dev,int64_t offset,byte * pdata,uint * psize)400 gx_dc_ht_binary_write(
401     const gx_device_color *         pdevc,
402     const gx_device_color_saved *   psdc0,
403     const gx_device *               dev,
404     int64_t			    offset,
405     byte *                          pdata,
406     uint *                          psize )
407 {
408     int                             req_size = 1;   /* flag bits */
409     int                             flag_bits = 0;
410     uint                            tmp_size;
411     byte *                          pdata0 = pdata;
412     const gx_device_color_saved *   psdc = psdc0;
413     int                             code;
414 
415     if (offset != 0)
416         return_error(gs_error_unregistered); /* Not implemented yet. */
417 
418     /* check if operand and saved colors are the same type */
419     if (psdc != 0 && psdc->type != pdevc->type)
420         psdc = 0;
421 
422     /* check for the information that must be transmitted */
423     if ( psdc == 0                                                      ||
424          pdevc->colors.binary.color[0] != psdc->colors.binary.b_color[0]  ) {
425         flag_bits |= dc_ht_binary_has_color0;
426         tmp_size = 0;
427         (void)gx_dc_write_color( pdevc->colors.binary.color[0],
428                                  dev,
429                                  pdata,
430                                  &tmp_size );
431         req_size += tmp_size;
432     }
433     if ( psdc == 0                                                      ||
434          pdevc->colors.binary.color[1] != psdc->colors.binary.b_color[1]  ) {
435         flag_bits |= dc_ht_binary_has_color1;
436         tmp_size = 0;
437         (void)gx_dc_write_color( pdevc->colors.binary.color[1],
438                                  dev,
439                                  pdata,
440                                  &tmp_size );
441         req_size += tmp_size;
442     }
443 
444     if ( psdc == 0                                                  ||
445          pdevc->colors.binary.b_level != psdc->colors.binary.b_level  ) {
446         flag_bits |= dc_ht_binary_has_level;
447         req_size += enc_u_sizew(pdevc->colors.binary.b_level);
448     }
449 
450     if ( psdc == 0                                                  ||
451          pdevc->colors.binary.b_index != psdc->colors.binary.b_index  ) {
452         flag_bits |= dc_ht_binary_has_index;
453         req_size += 1;
454     }
455 
456     /* check if there is anything to be done */
457     if (flag_bits == 0) {
458         *psize = 0;
459         return 1;
460     }
461 
462     /* check if sufficient space has been provided */
463     if (req_size > *psize) {
464         *psize = req_size;
465         return gs_error_rangecheck;
466     }
467 
468     /* write out the flag byte */
469     *pdata++ = (byte)flag_bits;
470 
471     /* write out such other parts of the device color as are required */
472     if ((flag_bits & dc_ht_binary_has_color0) != 0) {
473         tmp_size = req_size - (pdata - pdata0);
474         code = gx_dc_write_color( pdevc->colors.binary.color[0],
475                                   dev,
476                                   pdata,
477                                   &tmp_size );
478         if (code < 0)
479             return code;
480         pdata += tmp_size;
481     }
482     if ((flag_bits & dc_ht_binary_has_color1) != 0) {
483         tmp_size = req_size - (pdata - pdata0);
484         code = gx_dc_write_color( pdevc->colors.binary.color[1],
485                                   dev,
486                                   pdata,
487                                   &tmp_size );
488         if (code < 0)
489             return code;
490         pdata += tmp_size;
491     }
492     if ((flag_bits & dc_ht_binary_has_level) != 0)
493         enc_u_putw(pdevc->colors.binary.b_level, pdata);
494     if ((flag_bits & dc_ht_binary_has_index) != 0)
495         *pdata++ = pdevc->colors.binary.b_index;
496 
497     *psize = pdata - pdata0;
498     return 0;
499 }
500 
501 /*
502  * Reconstruct a binary halftone device color from its serial representation.
503  *
504  * Operands:
505  *
506  *  pdevc       pointer to the location in which to write the
507  *              reconstructed device color
508  *
509  *  pis         pointer to the current imager state (to access the
510  *              current halftone)
511  *
512  *  prior_devc  pointer to the current device color (this is provided
513  *              separately because the device color is not part of the
514  *              imager state)
515  *
516  *  dev         pointer to the current device, used to retrieve process
517  *              color model information
518  *
519  *  pdata       pointer to the buffer to be read
520  *
521  *  size        size of the buffer to be read; this should be large
522  *              enough to hold the entire color description
523  *
524  *  mem         pointer to the memory to be used for allocations
525  *              (ignored here)
526  *
527  * Returns:
528  *
529  *  # of bytes read if everthing OK, < 0 in the event of an error
530  */
531 static int
gx_dc_ht_binary_read(gx_device_color * pdevc,const gs_imager_state * pis,const gx_device_color * prior_devc,const gx_device * dev,int64_t offset,const byte * pdata,uint size,gs_memory_t * mem)532 gx_dc_ht_binary_read(
533     gx_device_color *       pdevc,
534     const gs_imager_state * pis,
535     const gx_device_color * prior_devc,
536     const gx_device *       dev,        /* ignored */
537     int64_t		    offset,
538     const byte *            pdata,
539     uint                    size,
540     gs_memory_t *           mem )       /* ignored */
541 {
542     gx_device_color         devc;
543     const byte *            pdata0 = pdata;
544     int                     code, flag_bits;
545 
546     if (offset != 0)
547         return_error(gs_error_unregistered); /* Not implemented yet. */
548 
549     /* if prior information is available, use it */
550     if (prior_devc != 0 && prior_devc->type == gx_dc_type_ht_binary)
551         devc = *prior_devc;
552     else
553         memset(&devc, 0, sizeof(devc));   /* clear pointers */
554     devc.type = gx_dc_type_ht_binary;
555 
556     /* the halftone is always taken from the imager state */
557     devc.colors.binary.b_ht = pis->dev_ht;
558 
559     /* cache is not porvided until the device color is used */
560     devc.colors.binary.b_tile = 0;
561 
562     /* verify the minimum amount of information */
563     if (size == 0)
564         return_error(gs_error_rangecheck);
565     size --;
566     flag_bits = *pdata++;
567 
568     /* read the other information provided */
569     if ((flag_bits & dc_ht_binary_has_color0) != 0) {
570         code = gx_dc_read_color( &devc.colors.binary.color[0],
571                                  dev,
572                                  pdata,
573                                  size );
574         if (code < 0)
575             return code;
576         size -= code;
577         pdata += code;
578     }
579     if ((flag_bits & dc_ht_binary_has_color1) != 0) {
580         code = gx_dc_read_color( &devc.colors.binary.color[1],
581                                  dev,
582                                  pdata,
583                                  size );
584         if (code < 0)
585             return code;
586         size -= code;
587         pdata += code;
588     }
589     if ((flag_bits & dc_ht_binary_has_level) != 0) {
590         const byte *    pdata_start = pdata;
591 
592         if (size < 1)
593             return_error(gs_error_rangecheck);
594         enc_u_getw(devc.colors.binary.b_level, pdata);
595         size -= pdata - pdata_start;
596     }
597     if ((flag_bits & dc_ht_binary_has_index) != 0) {
598         if (size == 0)
599             return_error(gs_error_rangecheck);
600         --size;
601         devc.colors.binary.b_index = *pdata++;
602     }
603 
604     if (pis->dev_ht == NULL)
605         return_error(gs_error_unregistered); /* Must not happen. */
606     /* set the phase as required (select value is arbitrary) */
607     color_set_phase_mod( &devc,
608                          pis->screen_phase[0].x,
609                          pis->screen_phase[0].y,
610                          pis->dev_ht->lcm_width,
611                          pis->dev_ht->lcm_height );
612 
613     /* everything looks good */
614     *pdevc = devc;
615     return pdata - pdata0;
616 }
617 
618 /*
619  * Get the nonzero components of a binary halftone. This is used to
620  * distinguish components that are given zero intensity due to halftoning
621  * from those for which the original color intensity was in fact zero.
622  *
623  * Since this device color type involves only a single halftone component,
624  * we can reasonably assume that b_level != 0. Hence, we need to check
625  * for components with identical intensities in color[0] and color[1].
626  */
627 int
gx_dc_ht_binary_get_nonzero_comps(const gx_device_color * pdevc,const gx_device * dev,gx_color_index * pcomp_bits)628 gx_dc_ht_binary_get_nonzero_comps(
629     const gx_device_color * pdevc,
630     const gx_device *       dev,
631     gx_color_index *        pcomp_bits )
632 {
633     int                     code;
634     gx_color_value          cvals_0[GX_DEVICE_COLOR_MAX_COMPONENTS],
635                             cvals_1[GX_DEVICE_COLOR_MAX_COMPONENTS];
636 
637     if ( (code = dev_proc(dev, decode_color)( (gx_device *)dev,
638                                               pdevc->colors.binary.color[0],
639                                               cvals_0 )) >= 0 &&
640          (code = dev_proc(dev, decode_color)( (gx_device *)dev,
641                                               pdevc->colors.binary.color[1],
642                                               cvals_1 )) >= 0   ) {
643         int     i, ncomps = dev->color_info.num_components;
644         int     mask = 0x1, comp_bits = 0;
645 
646         for (i = 0; i < ncomps; i++, mask <<= 1) {
647             if (cvals_0[i] != 0 || cvals_1[i] != 0)
648                 comp_bits |= mask;
649         }
650         *pcomp_bits = comp_bits;
651         code = 0;
652     }
653 
654     return code;
655 }
656 
657 /* Initialize the tile cache for a given screen. */
658 /* Cache as many different levels as will fit. */
659 void
gx_ht_init_cache(const gs_memory_t * mem,gx_ht_cache * pcache,const gx_ht_order * porder)660 gx_ht_init_cache(const gs_memory_t *mem, gx_ht_cache * pcache, const gx_ht_order * porder)
661 {
662     uint width = porder->width;
663     uint height = porder->height;
664     uint size = width * height + 1;
665     int width_unit =
666     (width <= ht_mask_bits / 2 ? ht_mask_bits / width * width :
667      width);
668     int height_unit = height;
669     uint raster = porder->raster;
670     uint tile_bytes = raster * height;
671     uint shift = porder->shift;
672     int num_cached;
673     int i;
674     byte *tbits = pcache->bits;
675 
676     /* Non-monotonic halftones may have more bits than size. */
677     if (porder->num_bits >= size)
678         size = porder->num_bits + 1;
679     /* Make sure num_cached is within bounds */
680     num_cached = pcache->bits_size / tile_bytes;
681     if (num_cached > size)
682         num_cached = size;
683     if (num_cached > pcache->num_tiles)
684         num_cached = pcache->num_tiles;
685     if (num_cached == size &&
686         tile_bytes * num_cached <= pcache->bits_size / 2
687         ) {
688         /*
689          * We can afford to replicate every tile in the cache,
690          * which will reduce breakage when tiling.  Since
691          * horizontal breakage is more expensive than vertical,
692          * and since wide shallow fills are more common than
693          * narrow deep fills, we replicate the tile horizontally.
694          * We do have to be careful not to replicate the tile
695          * to an absurdly large size, however.
696          */
697         uint rep_raster =
698         ((pcache->bits_size / num_cached) / height) &
699         ~(align_bitmap_mod - 1);
700         uint rep_count = rep_raster * 8 / width;
701 
702         /*
703          * There's no real value in replicating the tile
704          * beyond the point where the byte width of the replicated
705          * tile is a multiple of a long.
706          */
707         if (rep_count > sizeof(ulong) * 8)
708             rep_count = sizeof(ulong) * 8;
709         width_unit = width * rep_count;
710         raster = bitmap_raster(width_unit);
711         tile_bytes = raster * height;
712     }
713     pcache->base_id = gs_next_ids(mem, porder->num_levels + 1);
714     pcache->order = *porder;
715     /* The transfer function is irrelevant, and might become dangling. */
716     pcache->order.transfer = 0;
717     pcache->num_cached = num_cached;
718     pcache->levels_per_tile = (size + num_cached - 1) / num_cached;
719     pcache->tiles_fit = -1;
720     memset(tbits, 0, pcache->bits_size);
721     for (i = 0; i < num_cached; i++, tbits += tile_bytes) {
722         register gx_ht_tile *bt = &pcache->ht_tiles[i];
723 
724         bt->level = 0;
725         bt->index = i;
726         bt->tiles.data = tbits;
727         bt->tiles.raster = raster;
728         bt->tiles.size.x = width_unit;
729         bt->tiles.size.y = height_unit;
730         bt->tiles.rep_width = width;
731         bt->tiles.rep_height = height;
732         bt->tiles.shift = bt->tiles.rep_shift = shift;
733         bt->tiles.num_planes = 1;
734     }
735     pcache->render_ht = gx_render_ht_default;
736 }
737 
738 /*
739  * Compute and save the rendering of a given gray level
740  * with the current halftone.  The cache holds multiple tiles,
741  * where each tile covers a range of possible levels.
742  * We adjust the tile whose range includes the desired level incrementally;
743  * this saves a lot of time for the average image, where gray levels
744  * don't change abruptly.  Note that the "level" is the number of bits,
745  * not the index in the levels vector.
746  */
747 static int
render_ht(gx_ht_tile * pbt,int level,const gx_ht_order * porder,gx_bitmap_id new_id)748 render_ht(gx_ht_tile * pbt, int level /* [1..num_bits-1] */ ,
749           const gx_ht_order * porder, gx_bitmap_id new_id)
750 {
751     byte *data = pbt->tiles.data;
752     int code;
753 
754     if_debug7('H', "[H]Halftone cache slot 0x%lx: old=%d, new=%d, w=%d(%d), h=%d(%d):\n",
755               (ulong) data, pbt->level, level,
756               pbt->tiles.size.x, porder->width,
757               pbt->tiles.size.y, porder->num_bits / porder->width);
758 #ifdef DEBUG
759     if (level < 0 || level > porder->num_bits) {
760         lprintf3("Error in render_ht: level=%d, old level=%d, num_bits=%d\n",
761                  level, pbt->level, porder->num_bits);
762         return_error(gs_error_Fatal);
763     }
764 #endif
765     code = porder->procs->render(pbt, level, porder);
766     if (code < 0)
767         return code;
768     pbt->level = level;
769     pbt->tiles.id = new_id;
770     pbt->tiles.num_planes = 1;
771     /*
772      * Check whether we want to replicate the tile in the cache.
773      * Since we only do this when all the renderings will fit
774      * in the cache, we only do it once per level, and it doesn't
775      * have to be very efficient.
776      */
777         /****** TEST IS WRONG if width > rep_width but tile.raster ==
778          ****** order raster.
779          ******/
780     if (pbt->tiles.raster > porder->raster)
781         bits_replicate_horizontally(data, pbt->tiles.rep_width,
782                                     pbt->tiles.rep_height, porder->raster,
783                                     pbt->tiles.size.x, pbt->tiles.raster);
784     if (pbt->tiles.size.y > pbt->tiles.rep_height &&
785         pbt->tiles.shift == 0
786         )
787         bits_replicate_vertically(data, pbt->tiles.rep_height,
788                                   pbt->tiles.raster, pbt->tiles.size.y);
789 #ifdef DEBUG
790     if (gs_debug_c('H')) {
791         const byte *p = pbt->tiles.data;
792         int wb = pbt->tiles.raster;
793         const byte *ptr = p + wb * pbt->tiles.size.y;
794 
795         while (p < ptr) {
796             dprintf8(" %d%d%d%d%d%d%d%d",
797                      *p >> 7, (*p >> 6) & 1, (*p >> 5) & 1,
798                      (*p >> 4) & 1, (*p >> 3) & 1, (*p >> 2) & 1,
799                      (*p >> 1) & 1, *p & 1);
800             if ((++p - data) % wb == 0)
801                 dputc('\n');
802         }
803     }
804 #endif
805     return 0;
806 }
807