summaryrefslogtreecommitdiff
blob: 942ac69f3879b51e21ebc1af88196ef092e062f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
/* Copyright (C) 2001-2019 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  1305 Grant Avenue - Suite 200, Novato,
   CA 94945, U.S.A., +1(415)492-9861, for further information.
*/


/* Command list writing utilities. */

#include "memory_.h"
#include "string_.h"
#include "gx.h"
#include "gp.h"
#include "gpcheck.h"
#include "gserrors.h"
#include "gxdevice.h"
#include "gxdevmem.h"		/* must precede gxcldev.h */
#include "gxcldev.h"
#include "gxclpath.h"
#include "gsparams.h"

#include "valgrind.h"

/* ---------------- Statistics ---------------- */

#ifdef DEBUG
const char *const cmd_op_names[16] =
{cmd_op_name_strings};
static const char *const cmd_misc_op_names[16] =
{cmd_misc_op_name_strings};
static const char *const cmd_misc2_op_names[16] =
{cmd_misc2_op_name_strings};
static const char *const cmd_segment_op_names[16] =
{cmd_segment_op_name_strings};
static const char *const cmd_path_op_names[16] =
{cmd_path_op_name_strings};
const char *const *const cmd_sub_op_names[16] =
{cmd_misc_op_names, 0, 0, 0, 0, 0, 0, 0,
 0, 0, 0, 0,
 0, cmd_misc2_op_names, cmd_segment_op_names, cmd_path_op_names
};
#ifndef GS_THREADSAFE
struct stats_cmd_s {
    ulong op_counts[256];
    ulong op_sizes[256];
    ulong tile_reset, tile_found, tile_added;
    ulong same_band, other_band;
} stats_cmd;
extern ulong stats_cmd_diffs[5];	/* in gxclpath.c */
int
cmd_count_op(int op, uint size,const gs_memory_t *mem)
{
    stats_cmd.op_counts[op]++;
    stats_cmd.op_sizes[op] += size;
    if (gs_debug_c('L')) {
        const char *const *sub = cmd_sub_op_names[op >> 4];

        if (sub)
            dmlprintf2(mem, ", %s(%u)\n", sub[op & 0xf], size);
        else
            dmlprintf3(mem, ", %s %d(%u)\n", cmd_op_names[op >> 4], op & 0xf,
                      size);
        dmflush(mem);
    }
    return op;
}
void
cmd_uncount_op(int op, uint size)
{
    stats_cmd.op_counts[op]--;
    stats_cmd.op_sizes[op] -= size;
}
#endif
#endif

/* Print statistics. */
#if defined(DEBUG) && !defined(GS_THREADSAFE)
void
cmd_print_stats(const gs_memory_t *mem)
{
    int ci, cj;

    dmlprintf3(mem, "[l]counts: reset = %lu, found = %lu, added = %lu\n",
              stats_cmd.tile_reset, stats_cmd.tile_found,
              stats_cmd.tile_added);
    dmlprintf5(mem, "     diff 2.5 = %lu, 3 = %lu, 4 = %lu, 2 = %lu, >4 = %lu\n",
              stats_cmd_diffs[0], stats_cmd_diffs[1], stats_cmd_diffs[2],
              stats_cmd_diffs[3], stats_cmd_diffs[4]);
    dmlprintf2(mem, "     same_band = %lu, other_band = %lu\n",
              stats_cmd.same_band, stats_cmd.other_band);
    for (ci = 0; ci < 0x100; ci += 0x10) {
        const char *const *sub = cmd_sub_op_names[ci >> 4];

        if (sub != 0) {
            dmlprintf1(mem, "[l]  %s =", cmd_op_names[ci >> 4]);
            for (cj = ci; cj < ci + 0x10; cj += 2)
                dmprintf6(mem, "\n\t%s = %lu(%lu), %s = %lu(%lu)",
                         sub[cj - ci],
                         stats_cmd.op_counts[cj], stats_cmd.op_sizes[cj],
                         sub[cj - ci + 1],
                   stats_cmd.op_counts[cj + 1], stats_cmd.op_sizes[cj + 1]);
        } else {
            ulong tcounts = 0, tsizes = 0;

            for (cj = ci; cj < ci + 0x10; cj++)
                tcounts += stats_cmd.op_counts[cj],
                    tsizes += stats_cmd.op_sizes[cj];
            dmlprintf3(mem, "[l]  %s (%lu,%lu) =\n\t",
                      cmd_op_names[ci >> 4], tcounts, tsizes);
            for (cj = ci; cj < ci + 0x10; cj++)
                if (stats_cmd.op_counts[cj] == 0)
                    dmputs(mem, " -");
                else
                    dmprintf2(mem, " %lu(%lu)", stats_cmd.op_counts[cj],
                             stats_cmd.op_sizes[cj]);
        }
        dmputs(mem, "\n");
    }
}
#endif /* DEBUG */

/* ---------------- Writing utilities ---------------- */

/* Update the 'trans_bbox' in the states for bands affected by the given rectangle */
/* The caller has determined the the PDF 1.4 transparency will actuall be needed   */
/* for the given rectangle (conservatively). This will allow some bands that only  */
/* paint to the page level with full opacity to skip the pdf14 compositor during   */
/* rendering/reading and thus run faster and with less memory for those bands.     */
void
clist_update_trans_bbox(gx_device_clist_writer *cldev, gs_int_rect *bbox)
{
    int p_y, q_y;
    int band, first_band, last_band;

    first_band = max(0, bbox->p.y / cldev->page_band_height);
    p_y = bbox->p.y - (first_band * cldev->page_band_height);
    last_band = min((cldev->nbands - 1), bbox->q.y / cldev->page_band_height);

    for (band=first_band; band <= last_band; band++) {
        if (cldev->states[band].color_usage.trans_bbox.p.y > p_y)
            cldev->states[band].color_usage.trans_bbox.p.y = p_y;
        if (cldev->states[band].color_usage.trans_bbox.p.x > bbox->p.x)
            cldev->states[band].color_usage.trans_bbox.p.x = bbox->p.x;
        p_y = 0;	/* will be top of next band */
        q_y = (band == last_band) ? bbox->q.y - (last_band * cldev->page_band_height) :
                                      cldev->page_band_height - 1;
        if (cldev->states[band].color_usage.trans_bbox.q.y < q_y)
            cldev->states[band].color_usage.trans_bbox.q.y = q_y;
        if (cldev->states[band].color_usage.trans_bbox.q.x < bbox->q.x)
            cldev->states[band].color_usage.trans_bbox.q.x = bbox->q.x;
    }
}

/* Write the commands for one band or band range. */
static int	/* ret 0 all ok, -ve error code, or +1 ok w/low-mem warning */
cmd_write_band(gx_device_clist_writer * cldev, int band_min, int band_max,
               cmd_list * pcl, byte cmd_end)
{
    const cmd_prefix *cp = pcl->head;
    int code_b = 0;
    int code_c = 0;

    if (cp != 0 || cmd_end != cmd_opv_end_run) {
        clist_file_ptr cfile = cldev->page_cfile;
        clist_file_ptr bfile = cldev->page_bfile;
        cmd_block cb;
        byte end = cmd_count_op(cmd_end, 1, cldev->memory);

        if (cfile == 0 || bfile == 0)
            return_error(gs_error_ioerror);
        cb.band_min = band_min;
        cb.band_max = band_max;
        cb.pos = cldev->page_info.io_procs->ftell(cfile);
        if_debug3m('l', cldev->memory, "[l]writing for bands (%d,%d) at %ld\n",
                  band_min, band_max, (long)cb.pos);
        cldev->page_info.io_procs->fwrite_chars(&cb, sizeof(cb), bfile);
        if (cp != 0) {
            pcl->tail->next = 0;	/* terminate the list */
            for (; cp != 0; cp = cp->next) {
#ifdef DEBUG
                if ((const byte *)cp < cldev->cbuf ||
                    (const byte *)cp >= cldev->cend ||
                    cp->size > cldev->cend - (const byte *)cp
                    ) {
                    mlprintf1(cldev->memory, "cmd_write_band error at 0x%lx\n", (ulong) cp);
                    return_error(gs_error_Fatal);
                }
#endif
                if_debug2m('L', cldev->memory, "[L]Wrote cmd id=%ld at %ld\n",
                           cp->id, (long)cldev->page_info.io_procs->ftell(cfile));
                cldev->page_info.io_procs->fwrite_chars(cp + 1, cp->size, cfile);
            }
            pcl->head = pcl->tail = 0;
        }
        cldev->page_info.io_procs->fwrite_chars(&end, 1, cfile);
        process_interrupts(cldev->memory);
        code_b = cldev->page_info.io_procs->ferror_code(bfile);
        code_c = cldev->page_info.io_procs->ferror_code(cfile);
        if (code_b < 0)
            return_error(code_b);
        if (code_c < 0)
            return_error(code_c);
    }
    return code_b | code_c;
}

/* Write out a pseudo-band block of data, using the specific pseudo_band_offset */
int
cmd_write_pseudo_band(gx_device_clist_writer * cldev, unsigned char *pbuf, int data_size, int pseudo_band_offset)
{

    /* Data is written out maxband + pseudo_band_offset */

    int band = cldev->band_range_max + pseudo_band_offset;
    clist_file_ptr cfile = cldev->page_cfile;
    clist_file_ptr bfile = cldev->page_bfile;
    cmd_block cb;
    int code_b, code_c;

    if (cfile == 0 || bfile == 0)
        return_error(gs_error_ioerror);

    /* Set up the command block information that
       is stored in the bfile. */

    cb.band_min = band;
    cb.band_max = band;
    cb.pos = cldev->page_info.io_procs->ftell(cfile);

    if_debug2m('l', cldev->memory, "[l]writing pseudo band %d cb pos %ld\n",
                  band, (long)cb.pos);

    cldev->page_info.io_procs->fwrite_chars(&cb, sizeof(cb), bfile);

    /* Now store the information in the cfile */
    if_debug2m('l', cldev->memory, "[l]writing %d bytes into cfile at %ld\n",
            data_size, (long)cldev->page_info.io_procs->ftell(cfile));

    cldev->page_info.io_procs->fwrite_chars(pbuf, data_size, cfile);

    process_interrupts(cldev->memory);
    code_b = cldev->page_info.io_procs->ferror_code(bfile);
    code_c = cldev->page_info.io_procs->ferror_code(cfile);

    if (code_b < 0)
        return_error(code_b);
    if (code_c < 0)
        return_error(code_c);

    return code_b | code_c;
}

/* Write out the buffered commands, and reset the buffer. */
int	/* ret 0 all-ok, -ve error code, or +1 ok w/low-mem warning */
cmd_write_buffer(gx_device_clist_writer * cldev, byte cmd_end)
{
    int nbands = cldev->nbands;
    gx_clist_state *pcls;
    int band;
    int code = cmd_write_band(cldev, cldev->band_range_min,
                              cldev->band_range_max,
                              &cldev->band_range_list,
                              cmd_opv_end_run);

    int warning = code;

    for (band = 0, pcls = cldev->states;
         code >= 0 && band < nbands; band++, pcls++
         ) {
        code = cmd_write_band(cldev, band, band, &pcls->list, cmd_end);
        warning |= code;
    }
    /* If an error occurred, finish cleaning up the pointers. */
    for (; band < nbands; band++, pcls++)
        pcls->list.head = pcls->list.tail = 0;
    cldev->cnext = cldev->cbuf;
#ifdef HAVE_VALGRIND
    VALGRIND_MAKE_MEM_UNDEFINED(cldev->cbuf, cldev->cend - cldev->cbuf);
#endif
    cldev->ccl = 0;
#if defined(DEBUG) && !defined(GS_THREADSAFE)
    if (gs_debug_c('l'))
        cmd_print_stats(cldev->memory);
#endif
    return_check_interrupt(cldev->memory, code != 0 ? code : warning);
}

/*
 * Add a command to the appropriate band list, and allocate space for its
 * data.  Return the pointer to the data area.  If an error or (low-memory
 * warning) occurs, set cldev->error_code and return 0.
 */
#define cmd_headroom (sizeof(cmd_prefix) + ARCH_ALIGN_PTR_MOD)
byte *
cmd_put_list_op(gx_device_clist_writer * cldev, cmd_list * pcl, uint size)
{
    byte *dp = cldev->cnext;

    CMD_CHECK_LAST_OP_BLOCK_DEFINED(cldev);

    if (size + cmd_headroom > cldev->cend - dp) {
        if ((cldev->error_code =
             cmd_write_buffer(cldev, cmd_opv_end_run)) != 0 ||
            (size + cmd_headroom > cldev->cend - cldev->cnext)) {
            return 0;
        }
        else
            return cmd_put_list_op(cldev, pcl, size);
    }
    if (cldev->ccl == pcl) {	/* We're adding another command for the same band. */
        /* Tack it onto the end of the previous one. */
        cmd_count_add1(stats_cmd.same_band);
#ifdef DEBUG
        if (pcl->tail->size > dp - (byte *) (pcl->tail + 1)) {
            lprintf1("cmd_put_list_op error at 0x%lx\n", (ulong) pcl->tail);
        }
#endif
        if_debug2m('L', cldev->memory, ", to id=%ld , offset=%ld",
                   pcl->tail->id, (long)pcl->tail->size);
        pcl->tail->size += size;
    } else {
        /* Skip to an appropriate alignment boundary. */
        /* (We assume the command buffer itself is aligned.) */
        cmd_prefix *cp = (cmd_prefix *)
            (dp + ((cldev->cbuf - dp) & (ARCH_ALIGN_PTR_MOD - 1)));

        cmd_count_add1(stats_cmd.other_band);
        dp = (byte *) (cp + 1);
        if (pcl->tail != 0) {
#ifdef DEBUG
            if (pcl->tail < pcl->head ||
                pcl->tail->size > dp - (byte *) (pcl->tail + 1)
                ) {
                lprintf1("cmd_put_list_op error at 0x%lx\n",
                         (ulong) pcl->tail);
            }
#endif
            pcl->tail->next = cp;
        } else
            pcl->head = cp;
        pcl->tail = cp;
        cldev->ccl = pcl;
        cp->size = size;
        cp->id = cldev->ins_count;
        if_debug1m('L', cldev->memory, ", id=%ld ", cldev->ins_count);
        cldev->ins_count++;
    }
    cldev->cnext = dp + size;
    return dp;
}

/* Request a space in the buffer.
   Writes out the buffer if necessary.
   Returns the size of available space. */
int
cmd_get_buffer_space(gx_device_clist_writer * cldev, gx_clist_state * pcls, uint size)
{
    CMD_CHECK_LAST_OP_BLOCK_DEFINED(cldev);

    if (size + cmd_headroom > cldev->cend - cldev->cnext) {
        cldev->error_code = cmd_write_buffer(cldev, cmd_opv_end_run);
        if (cldev->error_code < 0) {
            return cldev->error_code;
        }
    }
    return cldev->cend - cldev->cnext - cmd_headroom;
}

#ifdef DEBUG
byte *
cmd_put_op(gx_device_clist_writer * cldev, gx_clist_state * pcls, uint size)
{
    if_debug3m('L', cldev->memory, "[L]band %d: size=%u, left=%u",
               (int)(pcls - cldev->states),
               size, 0);
    return cmd_put_list_op(cldev, &pcls->list, size);
}
#endif

/* Add a command for a range of bands. */
byte *
cmd_put_range_op(gx_device_clist_writer * cldev, int band_min, int band_max,
                 uint size)
{
    CMD_CHECK_LAST_OP_BLOCK_DEFINED(cldev);

    if_debug4m('L', cldev->memory, "[L]band range(%d,%d): size=%u, left=%u",
               band_min, band_max, size, 0);
    if (cldev->ccl != 0 &&
        (cldev->ccl != &cldev->band_range_list ||
         band_min != cldev->band_range_min ||
         band_max != cldev->band_range_max)
        ) {
        if ((cldev->error_code = cmd_write_buffer(cldev, cmd_opv_end_run)) != 0) {
            return 0;
        }
        cldev->band_range_min = band_min;
        cldev->band_range_max = band_max;
    }
    return cmd_put_list_op(cldev, &cldev->band_range_list, size);
}

/* Write a variable-size positive integer. */
int
cmd_size_w(register uint w)
{
    register int size = 1;

    while (w > 0x7f)
        w >>= 7, size++;
    return size;
}
byte *
cmd_put_w(register uint w, register byte * dp)
{
    while (w > 0x7f)
        *dp++ = w | 0x80, w >>= 7;
    *dp = w;
    return dp + 1;
}
/* Write a variable-size positive fractional. */
int
cmd_size_frac31(register frac31 w)
{
    register int size = 1;
    register uint32_t v = w;

    while (v & 0x01FFFFFF)
        v <<= 7, size++;
    return size;
}
byte *
cmd_put_frac31(register frac31 w, register byte * dp)
{
    register uint32_t v = w;

    while (v & 0x01FFFFFF)
        *dp++ = (v >> 24) | 1, v <<= 7;
    *dp = (v >> 24);
    return dp + 1;
}

/*
 * This next two arrays are used for the 'delta' mode of placing a color
 * in the clist.  These arrays are indexed by the number of bytes in the
 * color value (the depth).
 *
 * Delta values are calculated by subtracting the old value for the color
 * from the desired new value.  Then each byte of the differenece is
 * examined.  For most bytes, if the difference fits into 4 bits (signed)
 * then those bits are packed into the clist along with an opcode.  If
 * the size of the color (the depth) is an odd number of bytes then instead
 * of four bits per byte, extra bits are used for the upper three bytes
 * of the color.  In this case, five bits are used for the first byte,
 * six bits for the second byte, and five bits for third byte.  This
 * maximizes the chance that the 'delta' mode can be used for placing
 * colors in the clist.
 */
/*
 * Depending upon the compiler and user choices, the size of a gx_color_index
 * may be 4 to 8 bytes.  We will define table entries for up to 8 bytes.
 * This macro is being used to prevent compiler warnings if gx_color_index is
 * only 4 bytes.
 */
#define tab_entry(x) ((x) & (~((gx_color_index) 0)))

const gx_color_index cmd_delta_offsets[] = {
        tab_entry(0),
        tab_entry(0),
        tab_entry(0x0808),
        tab_entry(0x102010),
        tab_entry(0x08080808)
#if ARCH_SIZEOF_GX_COLOR_INDEX > 4
        ,
        tab_entry(0x1020100808),
        tab_entry(0x080808080808),
        tab_entry(0x10201008080808),
        tab_entry(0x0808080808080808)
#endif
        };

static const gx_color_index cmd_delta_masks[] = {
        tab_entry(0),
        tab_entry(0),
        tab_entry(0x0f0f),
        tab_entry(0x1f3f1f),
        tab_entry(0x0f0f0f0f)
#if ARCH_SIZEOF_GX_COLOR_INDEX > 4
        ,
        tab_entry(0x1f3f1f0f0f),
        tab_entry(0x0f0f0f0f0f0f),
        tab_entry(0x1f3f1f0f0f0f0f),
        tab_entry(0x0f0f0f0f0f0f0f0f)
#endif
        };

#undef tab_entry

/*
 * There are currently only four different color "types" that can be placed
 * into the clist.  These are called "color0", "color1", and "tile_color0",
 * and "tile_color1".  There are separate command codes for color0 versus
 * color1, both for the full value and delta commands - see cmd_put_color.
 * Tile colors are preceded by a cmd_opv_set_tile_color command.
 */
const clist_select_color_t
    clist_select_color0 = {cmd_op_set_color0, cmd_opv_delta_color0, 0},
    clist_select_color1 = {cmd_op_set_color1, cmd_opv_delta_color1, 0},
    clist_select_tile_color0 = {cmd_op_set_color0, cmd_opv_delta_color0, 1},
    clist_select_tile_color1 = {cmd_op_set_color1, cmd_opv_delta_color1, 1};

/*
 * This routine is used to place a color into the clist.  Colors, in the
 * clist, can be specified either as by a full value or by a "delta" value.
 *
 * See the comments before cmd_delta_offsets[] for a description of the
 * 'delta' mode.  The delta mode may allow for a smaller command in the clist.
 *
 * For the full value mode, values are sent as a cmd code plus n bytes of
 * data.  To minimize the number of bytes, a count is made of any low order
 * bytes which are zero.  This count is packed into the low order 4 bits
 * of the cmd code.  The data for these bytes are not sent.
 *
 * The gx_no_color_index value is treated as a special case.  This is done
 * because it is both a commonly sent value and because it may require
 * more bytes then the other color values.
 *
 * Parameters:
 *   cldev - Pointer to clist device
 *   pcls - Pointer to clist state
 *   select - Descriptor record for type of color being sent.  See comments
 *       by clist_select_color_t.
 *   color - The new color value.
 *   pcolor - Pointer to previous color value.  (If the color value is the
 *       same as the previous value then nothing is placed into the clist.)
 *
 * Returns:
 *   Error code
 *   clist and pcls and cldev may be updated.
 */
int
cmd_put_color(gx_device_clist_writer * cldev, gx_clist_state * pcls,
              const clist_select_color_t * select,
              gx_color_index color, gx_color_index * pcolor)
{
    byte * dp;		/* This is manipulated by the set_cmd_put_op macro */
    gx_color_index diff = color - *pcolor;
    byte op, op_delta;
    int code;

    if (diff == 0)
        return 0;

    /* If this is a tile color then send tile color type */
    if (select->tile_color) {
        code = set_cmd_put_op(&dp, cldev, pcls, cmd_opv_set_tile_color, 1);
        if (code < 0)
            return code;
    }
    op = select->set_op;
    op_delta = select->delta_op;
    if (color == gx_no_color_index) {
        /*
         * We must handle this specially, because it may take more
         * bytes than the color depth.
         */
        code = set_cmd_put_op(&dp, cldev, pcls, op + cmd_no_color_index, 1);
        if (code < 0)
            return code;
    } else {
        /* Check if the "delta" mode command can be used. */
        /* clist_color_info may be different than target device due to
         * transparency group during clist writing phase */
        int depth = (cldev->clist_color_info.depth <= sizeof(gx_color_index)*8 ?
                     cldev->clist_color_info.depth : sizeof(gx_color_index)*8);
        int num_bytes = (depth + 7) >> 3;
        int delta_bytes = (num_bytes + 1) / 2;
        gx_color_index delta_offset = cmd_delta_offsets[num_bytes];
        gx_color_index delta_mask = cmd_delta_masks[num_bytes];
        gx_color_index delta = (diff + delta_offset) & delta_mask;
        bool use_delta = (color == (*pcolor + delta - delta_offset));
        int bytes_dropped = 0;
        gx_color_index data = color;

        /*
         * If we use the full value mode, we do not send low order bytes
         * which are zero. Determine how many low order bytes are zero.
         */
        if (color == 0) {
            bytes_dropped = num_bytes;
        }
        else  {
            while ((data & 0xff) == 0) {
                bytes_dropped++;
                data >>= 8;
            }
        }
        /* Now send one of the two command forms */
        if (use_delta && delta_bytes < (num_bytes - bytes_dropped)) {
            code = set_cmd_put_op(&dp, cldev, pcls,
                                        op_delta, delta_bytes + 1);
            if (code < 0)
                return code;
            /*
             * If we have an odd number of bytes then use extra bits for
             * the high order three bytes of the color.
             */
            if ((num_bytes >= 3) && (num_bytes & 1)) {
                data = delta >> ((num_bytes - 3) * 8);
                dp[delta_bytes--] = (byte)(((data >> 13) & 0xf8) + ((data >> 11) & 0x07));
                dp[delta_bytes--] = (byte)(((data >> 3) & 0xe0) + (data & 0x1f));
            }
            for(; delta_bytes>0; delta_bytes--) {
                dp[delta_bytes] = (byte)((delta >> 4) + delta);
                delta >>= 16;
            }
        }
        else {
            num_bytes -= bytes_dropped;
            code = set_cmd_put_op(&dp, cldev, pcls,
                                (byte)(op + bytes_dropped), num_bytes + 1);
            if (code < 0)
                return code;
            for(; num_bytes>0; num_bytes--) {
                dp[num_bytes] = (byte)data;
                data >>= 8;
            }
        }
    }
    *pcolor = color;
    return 0;
}

/* Put out a command to set the tile colors. */
int
cmd_set_tile_colors(gx_device_clist_writer * cldev, gx_clist_state * pcls,
                    gx_color_index color0, gx_color_index color1)
{
    int code = 0;

    if (color0 != pcls->tile_colors[0]) {
        code = cmd_put_color(cldev, pcls,
                             &clist_select_tile_color0,
                             color0, &pcls->tile_colors[0]);
        if (code != 0)
            return code;
    }
    if (color1 != pcls->tile_colors[1])
        code = cmd_put_color(cldev, pcls,
                             &clist_select_tile_color1,
                             color1, &pcls->tile_colors[1]);
    return code;
}

/* Put out a command to set the tile phase. */
int
cmd_set_tile_phase_generic(gx_device_clist_writer * cldev, gx_clist_state * pcls,
                   int px, int py, bool all_bands)
{
    int pcsize;
    byte *dp;
    int code;

    pcsize = 1 + cmd_size2w(px, py);
    if (all_bands)
        code = set_cmd_put_all_op(&dp, cldev, (byte)cmd_opv_set_tile_phase, pcsize);
    else
        code = set_cmd_put_op(&dp, cldev, pcls, (byte)cmd_opv_set_tile_phase, pcsize);
    if (code < 0)
        return code;
    ++dp;
    pcls->tile_phase.x = px;
    pcls->tile_phase.y = py;
    cmd_putxy(pcls->tile_phase, &dp);
    return 0;
}

int
cmd_set_tile_phase(gx_device_clist_writer * cldev, gx_clist_state * pcls,
                   int px, int py)
{
    return cmd_set_tile_phase_generic(cldev, pcls, px, py, false);
}

/* Write a command to enable or disable the logical operation. */
int
cmd_put_enable_lop(gx_device_clist_writer * cldev, gx_clist_state * pcls,
                   int enable)
{
    byte *dp;
    int code = set_cmd_put_op(&dp, cldev, pcls,
                              (byte)(enable ? cmd_opv_enable_lop :
                                     cmd_opv_disable_lop),
                              1);

    if (code < 0)
        return code;
    pcls->lop_enabled = enable;
    return 0;
}

/* Write a command to enable or disable clipping. */
/* This routine is only called if the path extensions are included. */
int
cmd_put_enable_clip(gx_device_clist_writer * cldev, gx_clist_state * pcls,
                    int enable)
{
    byte *dp;
    int code = set_cmd_put_op(&dp, cldev, pcls,
                              (byte)(enable ? cmd_opv_enable_clip :
                                     cmd_opv_disable_clip),
                              1);

    if (code < 0)
        return code;
    pcls->clip_enabled = enable;
    return 0;
}

/* Write a command to set the logical operation. */
int
cmd_set_lop(gx_device_clist_writer * cldev, gx_clist_state * pcls,
            gs_logical_operation_t lop)
{
    byte *dp;
    uint lop_msb = lop >> 6;
    int code = set_cmd_put_op(&dp, cldev, pcls,
                              cmd_opv_set_misc, 2 + cmd_size_w(lop_msb));

    if (code < 0)
        return code;
    dp[1] = cmd_set_misc_lop + (lop & 0x3f);
    cmd_put_w(lop_msb, dp + 2);
    pcls->lop = lop;
    return 0;
}

/* Disable (if default) or enable the logical operation, setting it if */
/* needed. */
int
cmd_update_lop(gx_device_clist_writer *cldev, gx_clist_state *pcls,
               gs_logical_operation_t lop)
{
    int code;

    if (lop == lop_default)
        return cmd_disable_lop(cldev, pcls);
    code = cmd_set_lop(cldev, pcls, lop);
    if (code < 0)
        return code;
    return cmd_enable_lop(cldev, pcls);
}

/* Write a parameter list */
int	/* ret 0 all ok, -ve error */
cmd_put_params(gx_device_clist_writer *cldev,
               gs_param_list *param_list) /* NB open for READ */
{
    byte *dp;
    int code;
    byte local_buf[512];	/* arbitrary */
    int param_length;

    /* Get serialized list's length + try to get it into local var if it fits. */
    param_length = code =
        gs_param_list_serialize(param_list, local_buf, sizeof(local_buf));
    if (param_length > 0) {
        /* Get cmd buffer space for serialized */
        code = set_cmd_put_all_op(&dp, cldev, cmd_opv_extend,
                                  2 + sizeof(unsigned) + param_length);
        if (code < 0)
            return code;

        /* write param list to cmd list: needs to all fit in cmd buffer */
        if_debug1m('l', cldev->memory, "[l]put_params, length=%d\n", param_length);
        dp[1] = cmd_opv_ext_put_params;
        dp += 2;
        memcpy(dp, &param_length, sizeof(unsigned));
        dp += sizeof(unsigned);
        if (param_length > sizeof(local_buf)) {
            int old_param_length = param_length;

            param_length = code =
                gs_param_list_serialize(param_list, dp, old_param_length);
            if (param_length >= 0)
                code = (old_param_length != param_length ?
                        gs_note_error(gs_error_unknownerror) : 0);
            if (code < 0) {
                /* error serializing: back out by writing a 0-length parm list */
                memset(dp - sizeof(unsigned), 0, sizeof(unsigned));
                cmd_shorten_list_op(cldev, &cldev->band_range_list,
                                    old_param_length);
            }
        } else
            memcpy(dp, local_buf, param_length);	    /* did this when computing length */
    }
    return code;
}

/* Initialize CCITTFax filters. */
static void
clist_cf_init(stream_CF_state *ss, int width)
{
    ss->K = -1;
    ss->Columns = width;
#if 0 /* Disabled due to a crash with ppmraw -r216 c327.bin :
         the decoding filter overruns in 1 byte.
       */
    ss->EndOfBlock = false;
#else
    ss->EndOfBlock = true;
#endif
    ss->BlackIs1 = true;
    ss->DecodedByteAlign = align_bitmap_mod;
}
void
clist_cfe_init(stream_CFE_state *ss, int width, gs_memory_t *mem)
{
    s_init_state((stream_state *)ss, &s_CFE_template, mem);
    s_CFE_set_defaults_inline(ss);
    clist_cf_init((stream_CF_state *)ss, width);
    s_CFE_template.init((stream_state *)(ss));
}
void
clist_cfd_init(stream_CFD_state *ss, int width, int height, gs_memory_t *mem)
{
    s_init_state((stream_state *)ss, &s_CFD_template, mem);
    s_CFD_template.set_defaults((stream_state *)ss);
    clist_cf_init((stream_CF_state *)ss, width);
    ss->Rows = height;
    s_CFD_template.init((stream_state *)(ss));
}

/* Initialize RunLength filters. */
void
clist_rle_init(stream_RLE_state *ss)
{
    s_init_state((stream_state *)ss, &s_RLE_template, (gs_memory_t *)0);
    ss->templat->set_defaults((stream_state *)ss);
    ss->templat->init((stream_state *)ss);
}
void
clist_rld_init(stream_RLD_state *ss)
{
    s_init_state((stream_state *)ss, &s_RLD_template, (gs_memory_t *)0);
    ss->templat->set_defaults((stream_state *)ss);
    ss->templat->init((stream_state *)ss);
}

/* Read a transformation matrix. */
const byte *
cmd_read_matrix(gs_matrix * pmat, const byte * cbp)
{
    stream s;

    s_init(&s, NULL);
    sread_string(&s, cbp, 1 + sizeof(*pmat));
    sget_matrix(&s, pmat);
    return cbp + stell(&s);
}