Coverage Report

Created: 2025-06-10 07:06

/src/ghostpdl/base/scfd.c
Line
Count
Source (jump to first uncovered line)
1
/* Copyright (C) 2001-2023 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.,  39 Mesa Street, Suite 108A, San Francisco,
13
   CA 94129, USA, for further information.
14
*/
15
16
17
/* CCITTFax decoding filter */
18
#include "stdio_.h"   /* includes std.h */
19
#include "memory_.h"
20
#include "gdebug.h"
21
#include "strimpl.h"
22
#include "scf.h"
23
#include "scfx.h"
24
25
/* ------ CCITTFaxDecode ------ */
26
27
private_st_CFD_state();
28
29
6.76M
#define CFD_BUFFER_SLOP 4
30
31
static inline int
32
get_run(stream_CFD_state *ss, stream_cursor_read *pr, const cfd_node decode[],
33
    int initial_bits, int min_bits, int *runlen, const char *str);
34
35
static inline int
36
invert_data(stream_CFD_state *ss, stream_cursor_read *pr, int *rlen, byte black_byte);
37
38
static inline int
39
skip_data(stream_CFD_state *ss, stream_cursor_read *pr, int rlen);
40
41
/* Set default parameter values. */
42
static void
43
s_CFD_set_defaults(register stream_state * st)
44
114k
{
45
114k
    stream_CFD_state *const ss = (stream_CFD_state *) st;
46
47
114k
    s_CFD_set_defaults_inline(ss);
48
114k
}
49
50
/* Initialize CCITTFaxDecode filter */
51
static int
52
s_CFD_init(stream_state * st)
53
114k
{
54
114k
    stream_CFD_state *const ss = (stream_CFD_state *) st;
55
114k
    int raster = ss->raster =
56
114k
        ROUND_UP((ss->Columns + 7) >> 3, ss->DecodedByteAlign);
57
114k
    byte white = (ss->BlackIs1 ? 0 : 0xff);
58
59
114k
    if (raster < 0)
60
0
        return ERRC;
61
62
114k
    if (ss->Columns <= 0)
63
0
        return ERRC;
64
65
114k
    s_hcd_init_inline(ss);
66
    /* Because skip_white_pixels can look as many as 4 bytes ahead, */
67
    /* we need to allow 4 extra bytes at the end of the row buffers. */
68
114k
    ss->lbufstart = gs_alloc_bytes(st->memory, raster + CFD_BUFFER_SLOP * 2, "CFD lbuf");
69
114k
    ss->lprev = 0;
70
114k
    if (ss->lbufstart == 0)
71
0
        return ERRC;   /****** WRONG ******/
72
114k
    ss->lbuf = ss->lbufstart + CFD_BUFFER_SLOP;
73
114k
    memset(ss->lbufstart, 0xaa, CFD_BUFFER_SLOP);
74
114k
    memset(ss->lbuf, white, raster);
75
114k
    memset(ss->lbuf + raster, 0xaa, CFD_BUFFER_SLOP);  /* for Valgrind */
76
114k
    if (ss->K != 0) {
77
114k
        ss->lprevstart = gs_alloc_bytes(st->memory, raster + CFD_BUFFER_SLOP * 2, "CFD lprev");
78
114k
        if (ss->lprevstart == 0)
79
0
            return ERRC; /****** WRONG ******/
80
114k
        ss->lprev = ss->lprevstart + CFD_BUFFER_SLOP;
81
        /* Clear the initial reference line for 2-D encoding. */
82
114k
        memset(ss->lprev, white, raster);
83
        /* Ensure that the scan of the reference line will stop. */
84
114k
        memset(ss->lprev + raster, 0xaa, CFD_BUFFER_SLOP);
85
114k
        memset(ss->lprevstart, 0xaa, CFD_BUFFER_SLOP);
86
114k
    }
87
114k
    ss->k_left = min(ss->K, 0);
88
114k
    ss->run_color = 0;
89
114k
    ss->damaged_rows = 0;
90
114k
    ss->skipping_damage = false;
91
114k
    ss->cbit = 0;
92
114k
    ss->uncomp_run = 0;
93
114k
    ss->rows_left = (ss->Rows <= 0 || ss->EndOfBlock ? -1 : ss->Rows);
94
114k
    ss->row = 0;
95
114k
    ss->rpos = ss->wpos = -1;
96
114k
    ss->eol_count = 0;
97
114k
    ss->invert = white;
98
114k
    ss->min_left = 1;
99
114k
    return 0;
100
114k
}
101
102
/* Release the filter. */
103
static void
104
s_CFD_release(stream_state * st)
105
114k
{
106
114k
    stream_CFD_state *const ss = (stream_CFD_state *) st;
107
108
114k
    gs_free_object(st->memory, ss->lprevstart, "CFD lprev(close)");
109
114k
    gs_free_object(st->memory, ss->lbufstart, "CFD lbuf(close)");
110
114k
}
111
112
/* Declare the variables that hold the state. */
113
#define cfd_declare_state\
114
11.7M
        hcd_declare_state;\
115
11.7M
        register byte *q;\
116
11.7M
        int qbit
117
/* Load the state from the stream. */
118
#define cfd_load_state()\
119
19.9M
        hcd_load_state(),\
120
0
        q = ss->lbuf + ss->wpos, qbit = ss->cbit
121
/* Store the state back in the stream. */
122
#define cfd_store_state()\
123
19.9M
        hcd_store_state(),\
124
7.29M
        ss->wpos = q - ss->lbuf, ss->cbit = qbit
125
126
/* Macros to get blocks of bits from the input stream. */
127
/* Invariants: 0 <= bits_left <= bits_size; */
128
/* bits [bits_left-1..0] contain valid data. */
129
130
74.9k
#define avail_bits(n) hcd_bits_available(n)
131
22.8M
#define ensure_bits(n, outl) hcd_ensure_bits(n, outl)
132
24.6M
#define peek_bits(n) hcd_peek_bits(n)
133
74.9k
#define peek_var_bits(n) hcd_peek_var_bits(n)
134
20.3M
#define skip_bits(n) hcd_skip_bits(n)
135
136
/* Get a run from the stream. */
137
#ifdef DEBUG
138
#  define IF_DEBUG(expr) expr
139
#else
140
74.9k
#  define IF_DEBUG(expr) DO_NOTHING
141
#endif
142
143
static inline int get_run(stream_CFD_state *ss, stream_cursor_read *pr, const cfd_node decode[],
144
           int initial_bits, int min_bits, int *runlen, const char *str)
145
1.88M
{
146
1.88M
    cfd_declare_state;
147
1.88M
    const cfd_node *np;
148
1.88M
    int clen;
149
1.88M
    cfd_load_state();
150
151
1.88M
    HCD_ENSURE_BITS_ELSE(initial_bits) {
152
        /* We might still have enough bits for the specific code. */
153
70
        if (bits_left < min_bits)
154
18
            goto outl;
155
52
        np = &decode[hcd_peek_bits_left() << (initial_bits - bits_left)];
156
52
        if ((clen = np->code_length) > bits_left)
157
23
            goto outl;
158
29
        goto locl;
159
52
    }
160
1.88M
    np = &decode[peek_bits(initial_bits)];
161
1.88M
    if ((clen = np->code_length) > initial_bits) {
162
74.9k
            IF_DEBUG(uint init_bits = peek_bits(initial_bits));
163
74.9k
            if (!avail_bits(clen)) goto outl;
164
74.9k
            clen -= initial_bits;
165
74.9k
            skip_bits(initial_bits);
166
74.9k
            ensure_bits(clen, outl);                /* can't goto outl */
167
74.9k
            np = &decode[np->run_length + peek_var_bits(clen)];
168
74.9k
            if_debug4('W', "%s xcode=0x%x,%d rlen=%d\n", str,
169
74.9k
                      (init_bits << np->code_length) +
170
74.9k
                        peek_var_bits(np->code_length),
171
74.9k
                      initial_bits + np->code_length,
172
74.9k
                      np->run_length);
173
74.9k
            skip_bits(np->code_length);
174
1.81M
    } else {
175
1.81M
locl:
176
1.81M
       if_debug4('W', "%s code=0x%x,%d rlen=%d\n", str,
177
1.81M
                      peek_var_bits(clen), clen, np->run_length);
178
1.81M
       skip_bits(clen);
179
1.81M
    }
180
1.88M
    *runlen = np->run_length;
181
182
1.88M
    cfd_store_state();
183
1.88M
    return(0);
184
41
outl:
185
41
    cfd_store_state();
186
41
    return(-1);
187
1.88M
}
188
189
190
/* Skip data bits for a white run. */
191
/* rlen is either less than 64, or a multiple of 64. */
192
static inline int skip_data(stream_CFD_state *ss, stream_cursor_read *pr, int rlen)
193
508k
{
194
508k
    cfd_declare_state;
195
508k
    cfd_load_state();
196
508k
    (void)rlimit;
197
198
508k
    if ( (qbit -= rlen) < 0 )
199
359k
    {
200
359k
        q -= qbit >> 3, qbit &= 7;
201
359k
        if ( rlen >= 64 ) {
202
5.43k
            cfd_store_state();
203
5.43k
            return(-1);
204
5.43k
        }
205
359k
    }
206
508k
    cfd_store_state();
207
502k
    return(0);
208
508k
}
209
210
211
/* Invert data bits for a black run. */
212
/* If rlen >= 64, execute makeup_action: this is to handle */
213
/* makeup codes efficiently, since these are always a multiple of 64. */
214
215
static inline int invert_data(stream_CFD_state *ss, stream_cursor_read *pr, int *rlen, byte black_byte)
216
5.84M
{
217
5.84M
    byte *qlim = ss->lbuf + ss->raster + CFD_BUFFER_SLOP;
218
5.84M
    cfd_declare_state;
219
5.84M
    cfd_load_state();
220
5.84M
    (void)rlimit;
221
222
5.84M
    if (q >= qlim || q < ss->lbufstart) {
223
0
        return(-1);
224
0
    }
225
226
5.84M
    if ( (*rlen) > qbit )
227
3.78M
    {
228
3.78M
        if (q + ((*rlen - qbit) >> 3) > qlim) {
229
0
            return(-1);
230
0
        }
231
232
3.78M
        if (q >= ss->lbuf) {
233
3.68M
          *q++ ^= (1 << qbit) - 1;
234
3.68M
        }
235
99.9k
        else {
236
99.9k
            q++;
237
99.9k
        }
238
3.78M
        (*rlen) -= qbit;
239
240
3.78M
        if (q + ((*rlen) >> 3) >= qlim) {
241
0
            return(-1);
242
0
        }
243
244
3.78M
        switch ( (*rlen) >> 3 )
245
3.78M
        {
246
43.6k
          case 7:         /* original rlen possibly >= 64 */
247
43.6k
                  if ( (*rlen) + qbit >= 64 ) {
248
11.5k
                    goto d;
249
11.5k
                  }
250
32.0k
                  *q++ = black_byte;
251
61.4k
          case 6: *q++ = black_byte;
252
83.2k
          case 5: *q++ = black_byte;
253
117k
          case 4: *q++ = black_byte;
254
186k
          case 3: *q++ = black_byte;
255
374k
          case 2: *q++ = black_byte;
256
1.05M
          case 1: *q = black_byte;
257
1.05M
              (*rlen) &= 7;
258
1.05M
              if ( !(*rlen) ) {
259
188k
                  qbit = 0;
260
188k
                  break;
261
188k
              }
262
868k
              q++;
263
3.52M
          case 0:                 /* know rlen != 0 */
264
3.52M
              qbit = 8 - (*rlen);
265
3.52M
              *q ^= 0xff << qbit;
266
3.52M
              break;
267
60.6k
          default:        /* original rlen >= 64 */
268
72.1k
d:            memset(q, black_byte, (*rlen) >> 3);
269
72.1k
              q += (*rlen) >> 3;
270
72.1k
              (*rlen) &= 7;
271
72.1k
              if ( !(*rlen) ) {
272
10.7k
                qbit = 0;
273
10.7k
                q--;
274
10.7k
              }
275
61.4k
              else {
276
61.4k
                qbit = 8 - (*rlen);
277
61.4k
                *q ^= 0xff << qbit;
278
61.4k
              }
279
72.1k
              cfd_store_state();
280
72.1k
              return(-1);
281
3.78M
          }
282
3.78M
    }
283
2.06M
    else {
284
2.06M
            qbit -= (*rlen),
285
2.06M
            *q ^= ((1 << (*rlen)) - 1) << qbit;
286
287
2.06M
    }
288
5.84M
    cfd_store_state();
289
5.77M
    return(0);
290
5.84M
}
291
292
293
/* Buffer refill for CCITTFaxDecode filter */
294
static int cf_decode_eol(stream_CFD_state *, stream_cursor_read *);
295
static int cf_decode_1d(stream_CFD_state *, stream_cursor_read *);
296
static int cf_decode_2d(stream_CFD_state *, stream_cursor_read *);
297
static int cf_decode_uncompressed(stream_CFD_state *, stream_cursor_read *);
298
static int
299
s_CFD_process(stream_state * st, stream_cursor_read * pr,
300
              stream_cursor_write * pw, bool last)
301
115k
{
302
115k
    stream_CFD_state *const ss = (stream_CFD_state *) st;
303
115k
    int wstop = ss->raster - 1;
304
115k
    int eol_count = ss->eol_count;
305
115k
    int k_left = ss->k_left;
306
115k
    int rows_left = ss->rows_left;
307
115k
    int status = 0;
308
309
#ifdef DEBUG
310
    const byte *rstart = pr->ptr;
311
    const byte *wstart = pw->ptr;
312
313
#endif
314
315
    /* Update the pointers we actually use, in case GC moved the buffer */
316
115k
    ss->lbuf = ss->lbufstart + CFD_BUFFER_SLOP;
317
115k
    ss->lprev = ss->lprevstart + CFD_BUFFER_SLOP;
318
319
3.61M
top:
320
#ifdef DEBUG
321
    {
322
        hcd_declare_state;
323
        hcd_load_state();
324
        (void)rlimit;
325
        if_debug8m('w', ss->memory,
326
                   "[w]CFD_process top: eol_count=%d, k_left=%d, rows_left=%d\n"
327
                   "    bits="PRI_INTPTR", bits_left=%d, read %u, wrote %u%s\n",
328
                   eol_count, k_left, rows_left,
329
                   (intptr_t) bits, bits_left,
330
                   (uint) (p - rstart), (uint) (pw->ptr - wstart),
331
                   (ss->skipping_damage ? ", skipping damage" : ""));
332
    }
333
#endif
334
3.61M
    if (ss->skipping_damage) { /* Skip until we reach an EOL. */
335
0
        hcd_declare_state;
336
0
        int skip;
337
0
        (void)rlimit;
338
339
0
        status = 0;
340
0
        do {
341
0
            switch ((skip = cf_decode_eol(ss, pr))) {
342
0
                default:  /* not EOL */
343
0
                    hcd_load_state();
344
0
                    skip_bits(-skip);
345
0
                    hcd_store_state();
346
0
                    continue;
347
0
                case 0: /* need more input */
348
0
                    goto out;
349
0
                case 1: /* EOL */
350
0
                    {   /* Back up over the EOL. */
351
0
                        hcd_load_state();
352
0
                        bits_left += run_eol_code_length;
353
0
                        hcd_store_state();
354
0
                    }
355
0
                    ss->skipping_damage = false;
356
0
            }
357
0
        }
358
0
        while (ss->skipping_damage);
359
0
        ss->damaged_rows++;
360
0
    }
361
    /*
362
     * Check for a completed input scan line.  This isn't quite as
363
     * simple as it seems, because we could have run out of input data
364
     * between a makeup code and a 0-length termination code, or in a
365
     * 2-D line before a final horizontal code with a 0-length second
366
     * run.  There's probably a way to think about this situation that
367
     * doesn't require a special check, but I haven't found it yet.
368
     */
369
3.61M
    if (ss->wpos == wstop && ss->cbit <= (-ss->Columns & 7) &&
370
3.61M
        (k_left == 0 ? !(ss->run_color & ~1) : ss->run_color == 0)
371
3.61M
        ) {     /* Check for completed data to be copied to the client. */
372
        /* (We could avoid the extra copy step for 1-D, but */
373
        /* it's simpler not to, and it doesn't cost much.) */
374
3.50M
        if (ss->rpos < ss->wpos) {
375
3.50M
            stream_cursor_read cr;
376
377
3.50M
            cr.ptr = ss->lbuf + ss->rpos;
378
3.50M
            cr.limit = ss->lbuf + ss->wpos;
379
3.50M
            status = stream_move(&cr, pw);
380
3.50M
            ss->rpos = cr.ptr - ss->lbuf;
381
3.50M
            if (status)
382
328
                goto out;
383
3.50M
        }
384
3.50M
        ss->row++;
385
3.50M
        if (rows_left > 0 && --rows_left == 0)
386
10
            goto ck_eol;  /* handle EOD if it is present */
387
3.50M
        if (ss->K != 0) {
388
3.50M
            byte *prev_bits = ss->lprev;
389
3.50M
            byte *prev_start = ss->lprevstart;
390
391
3.50M
            ss->lprev = ss->lbuf;
392
3.50M
            ss->lprevstart = ss->lbufstart;
393
3.50M
            ss->lbuf = prev_bits;
394
3.50M
            ss->lbufstart = prev_start;
395
3.50M
            if (ss->K > 0)
396
51
                k_left = (k_left == 0 ? ss->K : k_left) - 1;
397
3.50M
        }
398
3.50M
        ss->rpos = ss->wpos = -1;
399
3.50M
        ss->eol_count = eol_count = 0;
400
3.50M
        ss->cbit = 0;
401
3.50M
        ss->invert = (ss->BlackIs1 ? 0 : 0xff);
402
3.50M
        memset(ss->lbuf, ss->invert, wstop + 1);
403
3.50M
        ss->run_color = 0;
404
        /*
405
         * If EndOfLine is true, we want to include the byte padding
406
         * in the string of initial zeros in the EOL.  If EndOfLine
407
         * is false, we aren't sure what we should do....
408
         */
409
3.50M
        if (ss->EncodedByteAlign && !ss->EndOfLine)
410
0
            ss->bits_left &= ~7;
411
3.50M
    }
412
    /* If we're between scan lines, scan for EOLs. */
413
3.61M
    if (ss->wpos < 0) {
414
            /*
415
             * According to Adobe, the decoder should always check for
416
             * the EOD sequence, regardless of EndOfBlock: the Red Book's
417
             * documentation of EndOfBlock is wrong.
418
             */
419
3.61M
ck_eol:
420
3.73M
        while ((status = cf_decode_eol(ss, pr)) > 0) {
421
229k
            if_debug0m('w', ss->memory, "[w]EOL\n");
422
            /* If we are in a Group 3 mixed regime, */
423
            /* check the next bit for 1- vs. 2-D. */
424
229k
            if (ss->K > 0) {
425
58
                hcd_declare_state;
426
58
                hcd_load_state();
427
58
                ensure_bits(1, out); /* can't fail */
428
58
                k_left = (peek_bits(1) ? 0 : 1);
429
58
                skip_bits(1);
430
58
                hcd_store_state();
431
58
            }
432
229k
            ++eol_count;
433
229k
            if (eol_count == (ss->K < 0 ? 2 : 6)) {
434
114k
                status = EOFC;
435
114k
                goto out;
436
114k
            }
437
229k
        }
438
3.50M
        if (rows_left == 0) {
439
10
            status = EOFC;
440
10
            goto out;
441
10
        }
442
3.50M
        if (status == 0)  /* input empty while scanning EOLs */
443
84
            goto out;
444
3.50M
        switch (eol_count) {
445
3.50M
            case 0:
446
3.50M
                if (ss->EndOfLine) { /* EOL is required, but none is present. */
447
0
                    status = ERRC;
448
0
                    goto check;
449
0
                }
450
3.50M
            case 1:
451
3.50M
                break;
452
0
            default:
453
0
                status = ERRC;
454
0
                goto check;
455
3.50M
        }
456
3.50M
    }
457
    /* Now decode actual data. */
458
3.50M
    if (k_left < 0) {
459
3.50M
        if_debug0m('w', ss->memory, "[w2]new row\n");
460
3.50M
        status = cf_decode_2d(ss, pr);
461
3.50M
    } else if (k_left == 0) {
462
244
        if_debug0m('w', ss->memory, "[w1]new row\n");
463
244
        status = cf_decode_1d(ss, pr);
464
244
    } else {
465
50
        if_debug1m('w', ss->memory, "[w1]new 2-D row, k_left=%d\n", k_left);
466
50
        status = cf_decode_2d(ss, pr);
467
50
    }
468
3.50M
    if_debug3m('w', ss->memory, "[w]CFD status = %d, wpos = %d, cbit = %d\n",
469
3.50M
               status, ss->wpos, ss->cbit);
470
3.50M
  check:switch (status) {
471
3.50M
        case 1:   /* output full */
472
3.50M
            goto top;
473
45
        case ERRC:
474
            /* Check for special handling of damaged rows. */
475
45
            if (ss->damaged_rows >= ss->DamagedRowsBeforeError ||
476
45
                !(ss->EndOfLine && ss->K >= 0)
477
45
                )
478
45
                break;
479
            /* Substitute undamaged data if appropriate. */
480
            /****** NOT IMPLEMENTED YET ******/
481
0
            {
482
0
                ss->wpos = wstop;
483
0
                ss->cbit = -ss->Columns & 7;
484
0
                ss->run_color = 0;
485
0
            }
486
0
            ss->skipping_damage = true;
487
0
            goto top;
488
78
        default:
489
78
            ss->damaged_rows = 0; /* finished a good row */
490
3.50M
    }
491
115k
  out:ss->k_left = k_left;
492
115k
    ss->rows_left = rows_left;
493
115k
    ss->eol_count = eol_count;
494
115k
    if (ss->ErrsAsEOD && status < 0)
495
0
        return EOFC;
496
115k
    return status;
497
115k
}
498
499
/*
500
 * Decode a leading EOL, if any.
501
 * If an EOL is present, skip over it and return 1;
502
 * if no EOL is present, read no input and return -N, where N is the
503
 * number of initial bits that can be skipped in the search for an EOL;
504
 * if more input is needed, return 0.
505
 * Note that if we detected an EOL, we know that we can back up over it;
506
 * if we detected an N-bit non-EOL, we know that at least N bits of data
507
 * are available in the buffer.
508
 */
509
static int
510
cf_decode_eol(stream_CFD_state * ss, stream_cursor_read * pr)
511
3.73M
{
512
3.73M
    hcd_declare_state;
513
3.73M
    int zeros;
514
3.73M
    int look_ahead;
515
516
3.73M
    hcd_load_state();
517
8.13M
    for (zeros = 0; zeros < run_eol_code_length - 1; zeros++) {
518
7.91M
        ensure_bits(1, out);
519
7.90M
        if (peek_bits(1))
520
3.50M
            return -(zeros + 1);
521
4.40M
        skip_bits(1);
522
4.40M
    }
523
    /* We definitely have an EOL.  Skip further zero bits. */
524
229k
    look_ahead = (ss->K > 0 ? 2 : 1);
525
229k
    for (;;) {
526
229k
        ensure_bits(look_ahead, back);
527
229k
        if (peek_bits(1))
528
229k
            break;
529
0
        skip_bits(1);
530
0
    }
531
229k
    skip_bits(1);
532
229k
    hcd_store_state();
533
229k
    return 1;
534
0
  back:     /*
535
                                 * We ran out of data while skipping zeros.
536
                                 * We know we are at a byte boundary, and have just skipped
537
                                 * at least run_eol_code_length - 1 zeros.  However,
538
                                 * bits_left may be 1 if look_ahead == 2.
539
                                 */
540
0
    bits &= (1 << bits_left) - 1;
541
0
    bits_left += run_eol_code_length - 1;
542
0
    hcd_store_state();
543
84
  out:return 0;
544
0
}
545
546
/* Decode a 1-D scan line. */
547
static int
548
cf_decode_1d(stream_CFD_state * ss, stream_cursor_read * pr)
549
244
{
550
244
    cfd_declare_state;
551
244
    byte black_byte = (ss->BlackIs1 ? 0xff : 0);
552
244
    int end_bit = -ss->Columns & 7;
553
244
    byte *stop = ss->lbuf - 1 + ss->raster;
554
244
    int run_color = ss->run_color;
555
244
    int status;
556
244
    int bcnt;
557
244
    (void)rlimit;
558
559
244
    cfd_load_state();
560
244
    if_debug1m('w', ss->memory, "[w1]entry run_color = %d\n", ss->run_color);
561
244
    if (run_color > 0)
562
0
        goto db;
563
244
    else
564
244
        goto dw;
565
2.91k
#define q_at_stop() (q >= stop && (qbit <= end_bit || q > stop))
566
1.45k
    while (1)
567
1.45k
    {
568
1.45k
        run_color = 0;
569
1.45k
        if (q_at_stop())
570
238
            goto done;
571
572
1.45k
  dw:   /* Decode a white run. */
573
1.49k
        do {
574
1.49k
            cfd_store_state();
575
1.49k
            status = get_run(ss, pr, cf_white_decode, cfd_white_initial_bits,
576
1.49k
                             cfd_white_min_bits, &bcnt, "[w1]white");
577
1.49k
            cfd_load_state();
578
1.49k
            if (status < 0) {
579
                /* We already set run_color to 0 or -1. */
580
0
                status = 0;
581
0
                goto out;
582
0
            }
583
584
1.49k
            if (bcnt < 0) {   /* exceptional situation */
585
0
                switch (bcnt) {
586
0
                    case run_uncompressed: /* Uncompressed data. */
587
0
                        cfd_store_state();
588
0
                        bcnt = cf_decode_uncompressed(ss, pr);
589
0
                        if (bcnt < 0)
590
0
                            return bcnt;
591
0
                        cfd_load_state();
592
0
                        if (bcnt)
593
0
                            goto db;
594
0
                        else
595
0
                            continue; /* Restart decoding white */
596
                        /*case run_error: */
597
                        /*case run_zeros: *//* Premature end-of-line. */
598
0
                    default:
599
0
                        status = ERRC;
600
0
                        goto out;
601
0
                }
602
0
            }
603
604
1.49k
            cfd_store_state();
605
1.49k
            status = skip_data(ss, pr, bcnt);
606
1.49k
            cfd_load_state();
607
1.49k
            if (status < 0) {
608
                /* If we run out of data after a makeup code, */
609
                /* note that we are still processing a white run. */
610
37
                run_color = -1;
611
37
            }
612
1.49k
        } while (status < 0);
613
614
1.45k
        if (q_at_stop()) {
615
6
            run_color = 0;    /* not inside a run */
616
244
  done:
617
244
            if (q > stop || qbit < end_bit)
618
6
                status = ERRC;
619
238
            else
620
238
                status = 1;
621
244
            break;
622
6
        }
623
1.45k
        run_color = 1;
624
625
1.45k
  db:   /* Decode a black run. */
626
1.47k
        do {
627
1.47k
            cfd_store_state();
628
1.47k
            status = get_run(ss, pr, cf_black_decode, cfd_black_initial_bits,
629
1.47k
                             cfd_black_min_bits, &bcnt, "[w1]black");
630
1.47k
            cfd_load_state();
631
1.47k
            if (status < 0) {
632
                /* We already set run_color to 1 or 2. */
633
0
                status = 0;
634
0
                goto out;
635
0
            }
636
637
1.47k
            if (bcnt < 0) {  /* All exceptional codes are invalid here. */
638
                /****** WRONG, uncompressed IS ALLOWED ******/
639
0
                status = ERRC;
640
0
                goto out;
641
0
            }
642
643
            /* Invert bits designated by black run. */
644
1.47k
            cfd_store_state();
645
1.47k
            status = invert_data(ss, pr, &bcnt, black_byte);
646
1.47k
            cfd_load_state();
647
1.47k
            if (status < 0) {
648
                /* If we run out of data after a makeup code, */
649
                /* note that we are still processing a black run. */
650
22
                run_color = 2;
651
22
            }
652
1.47k
        } while (status < 0);
653
1.45k
    }
654
655
244
out:
656
244
    cfd_store_state();
657
244
    ss->run_color = run_color;
658
244
    if_debug1m('w', ss->memory, "[w1]exit run_color = %d\n", run_color);
659
244
    return status;
660
0
}
661
662
/* Decode a 2-D scan line. */
663
static int
664
cf_decode_2d(stream_CFD_state * ss, stream_cursor_read * pr)
665
3.50M
{
666
3.50M
    cfd_declare_state;
667
3.50M
    byte invert_white = (ss->BlackIs1 ? 0 : 0xff);
668
3.50M
    byte black_byte = ~invert_white;
669
3.50M
    byte invert = ss->invert;
670
3.50M
    int end_count = -ss->Columns & 7;
671
3.50M
    uint raster = ss->raster;
672
3.50M
    byte *q0 = ss->lbuf;
673
3.50M
    byte *prev_q01 = ss->lprev + 1;
674
3.50M
    byte *endptr = q0 - 1 + raster;
675
3.50M
    int init_count = raster << 3;
676
3.50M
    register int count;
677
3.50M
    int rlen;
678
3.50M
    int status;
679
680
3.50M
    cfd_load_state();
681
3.50M
    count = ((endptr - q) << 3) + qbit;
682
3.50M
    endptr[1] = 0xa0;   /* a byte with some 0s and some 1s, */
683
    /* to ensure run scan will stop */
684
3.50M
    if_debug1m('W', ss->memory, "[w2]raster=%d\n", raster);
685
3.50M
    switch (ss->run_color) {
686
6
        case -2:
687
6
            ss->run_color = 0;
688
6
            goto hww;
689
10
        case -1:
690
10
            ss->run_color = 0;
691
10
            goto hbw;
692
10
        case 1:
693
10
            ss->run_color = 0;
694
10
            goto hwb;
695
0
        case 2:
696
0
            ss->run_color = 0;
697
0
            goto hbb;
698
            /*case 0: */
699
3.50M
    }
700
701
    /* top of decode loop */
702
18.0M
    while (1)
703
18.0M
    {
704
18.0M
        if (count <= end_count) {
705
3.50M
            status = (count < end_count ? ERRC : 1);
706
3.50M
            goto out;
707
3.50M
        }
708
        /* If invert == invert_white, white and black have their */
709
        /* correct meanings; if invert == ~invert_white, */
710
        /* black and white are interchanged. */
711
18.0M
        if_debug1m('W', ss->memory, "[w2]%4d:\n", count);
712
#ifdef DEBUG
713
        /* Check the invariant between q, qbit, and count. */
714
        {
715
            int pcount = (endptr - q) * 8 + qbit;
716
717
            if (pcount != count)
718
                dmlprintf2(ss->memory, "[w2]Error: count=%d pcount=%d\n",
719
                           count, pcount);
720
        }
721
#endif
722
        /*
723
         * We could just use get_run here, but we can do better.  However,
724
         * we must be careful to handle the case where the very last codes
725
         * in the input stream are 1-bit "vertical 0" codes: we can't just
726
         * use ensure_bits(3, ...) and go to get more data if it fails.
727
         */
728
14.5M
        ensure_bits(3, out3);
729
27.0M
#define vertical_0 (countof(cf2_run_vertical) / 2)
730
14.5M
        switch (peek_bits(3)) {
731
10.7M
        default /*4..7*/ :  /* vertical(0) */
732
10.7M
            if (0) {
733
49
 out3:
734
                /* Unless it's a 1-bit "vertical 0" code, exit. */
735
49
                if (!(bits_left > 0 && peek_bits(1)))
736
36
                    goto out0;
737
49
            }
738
10.7M
            skip_bits(1);
739
10.7M
            rlen = vertical_0;
740
10.7M
            break;
741
1.32M
        case 2:   /* vertical(+1) */
742
1.32M
            skip_bits(3);
743
1.32M
            rlen = vertical_0 + 1;
744
1.32M
            break;
745
1.15M
        case 3:   /* vertical(-1) */
746
1.15M
            skip_bits(3);
747
1.15M
            rlen = vertical_0 - 1;
748
1.15M
            break;
749
501k
        case 1:   /* horizontal */
750
501k
            skip_bits(3);
751
501k
            if (invert == invert_white) {
752
                /* We handle horizontal decoding here, so that we can
753
                 * branch back into it if we run out of input data. */
754
                /* White, then black. */
755
303k
  hww:
756
305k
                do {
757
305k
                    cfd_store_state();
758
305k
                    status = get_run(ss, pr, cf_white_decode,
759
305k
                                     cfd_white_initial_bits,
760
305k
                                     cfd_white_min_bits, &rlen, " white");
761
305k
                    cfd_load_state();
762
305k
                    if (status < 0) {
763
6
                        ss->run_color = -2;
764
6
                        goto out0;
765
6
                    }
766
767
305k
                    if ((count -= rlen) < end_count) {
768
3
                        status = ERRC;
769
3
                        goto out;
770
3
                    }
771
305k
                    if (rlen < 0) goto rlen_lt_zero;
772
773
305k
                    cfd_store_state();
774
305k
                    status = skip_data(ss, pr, rlen);
775
305k
                    cfd_load_state();
776
305k
                } while (status < 0);
777
778
                /* Handle the second half of a white-black horizontal code. */
779
303k
  hwb:
780
305k
                do {
781
305k
                    cfd_store_state();
782
305k
                    status = get_run(ss, pr, cf_black_decode,
783
305k
                                     cfd_black_initial_bits,
784
305k
                                     cfd_black_min_bits, &rlen, " black");
785
305k
                    cfd_load_state();
786
305k
                    if (status < 0){
787
10
                        ss->run_color = 1;
788
10
                        goto out0;
789
10
                    }
790
791
305k
                    if ((count -= rlen) < end_count) {
792
7
                        status = ERRC;
793
7
                        goto out;
794
7
                    }
795
305k
                    if (rlen < 0) goto rlen_lt_zero;
796
797
305k
                    cfd_store_state();
798
305k
                    status = invert_data(ss, pr, &rlen, black_byte);
799
305k
                    cfd_load_state();
800
305k
                } while (status < 0);
801
303k
            } else {
802
                /* Black, then white. */
803
197k
  hbb:
804
200k
                do {
805
200k
                    cfd_store_state();
806
200k
                    status = get_run(ss, pr, cf_black_decode,
807
200k
                                     cfd_black_initial_bits,
808
200k
                                     cfd_black_min_bits, &rlen, " black");
809
200k
                    cfd_load_state();
810
200k
                    if (status < 0) {
811
0
                        ss->run_color = 2;
812
0
                        goto out0;
813
0
                    }
814
815
200k
                    if ((count -= rlen) < end_count) {
816
2
                        status = ERRC;
817
2
                        goto out;
818
2
                    }
819
200k
                    if (rlen < 0) goto rlen_lt_zero;
820
821
200k
                    cfd_store_state();
822
200k
                    status = invert_data(ss, pr, &rlen, black_byte);
823
200k
                    cfd_load_state();
824
200k
                }
825
200k
                while (status < 0);
826
827
                /* Handle the second half of a black-white horizontal code. */
828
197k
  hbw:
829
200k
                do {
830
200k
                    cfd_store_state();
831
200k
                    status = get_run(ss, pr, cf_white_decode,
832
200k
                                     cfd_white_initial_bits,
833
200k
                                     cfd_white_min_bits, &rlen, " white");
834
200k
                    cfd_load_state();
835
200k
                    if (status < 0) {
836
10
                        ss->run_color = -1;
837
10
                        goto out0;
838
10
                    }
839
840
200k
                    if ((count -= rlen) < end_count) {
841
8
                        status = ERRC;
842
8
                        goto out;
843
8
                    }
844
200k
                    if (rlen < 0) goto rlen_lt_zero;
845
846
200k
                    cfd_store_state();
847
200k
                    status = skip_data(ss, pr, rlen);
848
200k
                    cfd_load_state();
849
200k
                } while (status < 0);
850
197k
            }
851
501k
            continue; /* jump back to top of decode loop */
852
871k
        case 0:   /* everything else */
853
871k
            cfd_store_state();
854
871k
            status = get_run(ss, pr, cf_2d_decode, cfd_2d_initial_bits,
855
871k
                             cfd_2d_min_bits, &rlen, "[w2]");
856
871k
            cfd_load_state();
857
871k
            if (status < 0) {
858
15
                goto out0;
859
15
            }
860
861
            /* rlen may be run2_pass, run_uncompressed, or */
862
            /* 0..countof(cf2_run_vertical)-1. */
863
871k
            if (rlen < 0) {
864
227k
rlen_lt_zero:
865
227k
                switch (rlen) {
866
227k
                case run2_pass:
867
227k
                    break;
868
0
                case run_uncompressed:
869
0
                {
870
0
                    int which;
871
872
0
                    cfd_store_state();
873
0
                    which = cf_decode_uncompressed(ss, pr);
874
0
                    if (which < 0) {
875
0
                        status = which;
876
0
                        goto out;
877
0
                    }
878
0
                    cfd_load_state();
879
/****** ADJUST count ******/
880
0
                    invert = (which ? ~invert_white : invert_white);
881
0
                    continue; /* jump back to top of decode loop */
882
0
                }
883
9
                default:  /* run_error, run_zeros */
884
9
                    status = ERRC;
885
9
                    goto out;
886
227k
                }
887
227k
            }
888
14.5M
        }
889
        /* Interpreting the run requires scanning the */
890
        /* previous ('reference') line. */
891
14.0M
        {
892
14.0M
            int prev_count = count;
893
14.0M
            byte prev_data;
894
14.0M
            int dlen;
895
14.0M
            static const byte count_bit[8] =
896
14.0M
                                   {0x80, 1, 2, 4, 8, 0x10, 0x20, 0x40};
897
14.0M
            byte *prev_q = prev_q01 + (q - q0);
898
14.0M
            int plen;
899
900
14.0M
            if (!(count & 7))
901
4.58M
                prev_q++;   /* because of skip macros */
902
14.0M
            prev_data = prev_q[-1] ^ invert;
903
            /* Find the b1 transition. */
904
14.0M
            if ((prev_data & count_bit[prev_count & 7]) &&
905
14.0M
                (prev_count < init_count || invert != invert_white)
906
14.0M
                ) {     /* Look for changing white first. */
907
1.61M
                if_debug1m('W', ss->memory, " data=0x%x", prev_data);
908
1.61M
                skip_black_pixels(prev_data, prev_q,
909
1.61M
                                  prev_count, invert, plen);
910
1.61M
                if (prev_count < end_count)    /* overshot */
911
627
                    prev_count = end_count;
912
1.61M
                if_debug1m('W', ss->memory, " b1 other=%d", prev_count);
913
1.61M
            }
914
14.0M
            if (prev_count != end_count) {
915
14.0M
                if_debug1m('W', ss->memory, " data=0x%x", prev_data);
916
14.0M
                skip_white_pixels(prev_data, prev_q,
917
14.0M
                                  prev_count, invert, plen);
918
14.0M
                if (prev_count < end_count)    /* overshot */
919
5.88k
                    prev_count = end_count;
920
14.0M
                if_debug1m('W', ss->memory, " b1 same=%d", prev_count);
921
14.0M
            }
922
            /* b1 = prev_count; */
923
14.0M
            if (rlen == run2_pass) { /* Pass mode.  Find b2. */
924
227k
                if (prev_count != end_count) {
925
227k
                    if_debug1m('W', ss->memory, " data=0x%x", prev_data);
926
227k
                    skip_black_pixels(prev_data, prev_q,
927
227k
                                      prev_count, invert, plen);
928
227k
                    if (prev_count < end_count)  /* overshot */
929
6
                        prev_count = end_count;
930
227k
                }
931
                /* b2 = prev_count; */
932
227k
                if_debug2m('W', ss->memory, " b2=%d, pass %d\n",
933
227k
                           prev_count, count - prev_count);
934
13.8M
            } else {   /* Vertical coding. */
935
                /* Remember that count counts *down*. */
936
13.8M
                prev_count += rlen - vertical_0; /* a1 */
937
13.8M
                if_debug2m('W', ss->memory, " vertical %d -> %d\n",
938
13.8M
                           (int)(rlen - vertical_0), prev_count);
939
13.8M
            }
940
            /* Now either invert or skip from count */
941
            /* to prev_count, and reset count. */
942
14.0M
            if (invert == invert_white) { /* Skip data bits. */
943
8.74M
                q = endptr - (prev_count >> 3);
944
8.74M
                qbit = prev_count & 7;
945
8.74M
            } else {   /* Invert data bits. */
946
5.34M
                dlen = count - prev_count;
947
948
5.34M
                cfd_store_state();
949
5.34M
                (void)invert_data(ss, pr, &dlen, black_byte);
950
5.34M
                cfd_load_state();
951
5.34M
            }
952
14.0M
            count = prev_count;
953
14.0M
            if (rlen >= 0)    /* vertical mode */
954
13.8M
                invert = ~invert; /* polarity changes */
955
14.0M
        }
956
        /* jump back to top of decode loop */
957
14.0M
    }
958
959
77
  out0:status = 0;
960
    /* falls through */
961
3.50M
  out:cfd_store_state();
962
3.50M
    ss->invert = invert;
963
    /* Ignore an error (missing EOFB/RTC when EndOfBlock == true) */
964
    /* if we have finished all rows. */
965
3.50M
    if (status == ERRC && ss->Rows > 0 && ss->row > ss->Rows)
966
1
        status = EOFC;
967
3.50M
    return status;
968
77
}
969
970
#if 1       /*************** */
971
static int
972
cf_decode_uncompressed(stream_CFD_state * ss, stream_cursor_read * pr)
973
0
{
974
0
    return ERRC;
975
0
}
976
#else /*************** */
977
978
/* Decode uncompressed data. */
979
/* (Not tested: no sample data available!) */
980
/****** DOESN'T CHECK FOR OVERFLOWING SCAN LINE ******/
981
static int
982
cf_decode_uncompressed(stream * s)
983
{
984
    cfd_declare_state;
985
    const cfd_node *np;
986
    int clen, rlen;
987
988
    cfd_load_state();
989
    while (1) {
990
        ensure_bits(cfd_uncompressed_initial_bits, NOOUT);
991
        np = &cf_uncompressed_decode[peek_bits(cfd_uncompressed_initial_bits)];
992
        clen = np->code_length;
993
        rlen = np->run_length;
994
        if (clen > cfd_uncompressed_initial_bits) { /* Must be an exit code. */
995
            break;
996
        }
997
        if (rlen == cfd_uncompressed_initial_bits) {  /* Longest representable white run */
998
            if_debug1m('W', s->memory, "[wu]%d\n", rlen);
999
            if ((qbit -= cfd_uncompressed_initial_bits) < 0)
1000
                qbit += 8, q++;
1001
        } else {
1002
            if_debug1m('W', s->memory, "[wu]%d+1\n", rlen);
1003
            if (qbit -= rlen < 0)
1004
                qbit += 8, q++;
1005
            *q ^= 1 << qbit;
1006
        }
1007
        skip_bits(clen);
1008
    }
1009
    clen -= cfd_uncompressed_initial_bits;
1010
    skip_bits(cfd_uncompressed_initial_bits);
1011
    ensure_bits(clen, NOOUT);
1012
    np = &cf_uncompressed_decode[rlen + peek_var_bits(clen)];
1013
    rlen = np->run_length;
1014
    skip_bits(np->code_length);
1015
    if_debug1m('w', s->memory, "[wu]exit %d\n", rlen);
1016
    if (rlen >= 0) {    /* Valid exit code, rlen = 2 * run length + next polarity */
1017
        if ((qbit -= rlen >> 1) < 0)
1018
            qbit += 8, q++;
1019
        rlen &= 1;
1020
    }
1021
  out:        /******* WRONG ******/
1022
    cfd_store_state();
1023
    return rlen;
1024
}
1025
1026
#endif /*************** */
1027
1028
/* Stream template */
1029
const stream_template s_CFD_template =
1030
{&st_CFD_state, s_CFD_init, s_CFD_process, 1, 1, s_CFD_release,
1031
 s_CFD_set_defaults
1032
};