Coverage Report

Created: 2026-08-08 08:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/base/scfd.c
Line
Count
Source
1
/* Copyright (C) 2001-2025 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
75.9M
#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
1.29M
{
45
1.29M
    stream_CFD_state *const ss = (stream_CFD_state *) st;
46
47
1.29M
    s_CFD_set_defaults_inline(ss);
48
1.29M
}
49
50
/* Initialize CCITTFaxDecode filter */
51
static int
52
s_CFD_init(stream_state * st)
53
1.29M
{
54
1.29M
    stream_CFD_state *const ss = (stream_CFD_state *) st;
55
1.29M
    int raster = ss->raster =
56
1.29M
        ROUND_UP((ss->Columns + 7) >> 3, ss->DecodedByteAlign);
57
1.29M
    byte white = (ss->BlackIs1 ? 0 : 0xff);
58
59
1.29M
    if (raster < 0)
60
1
        return ERRC;
61
62
1.29M
    if (ss->Columns <= 0)
63
0
        return ERRC;
64
65
1.29M
    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
1.29M
    ss->lbufstart = gs_alloc_bytes(st->memory, raster + CFD_BUFFER_SLOP * (size_t)2, "CFD lbuf");
69
1.29M
    ss->lprev = 0;
70
1.29M
    if (ss->lbufstart == 0)
71
0
        return ERRC;   /****** WRONG ******/
72
1.29M
    ss->lbuf = ss->lbufstart + CFD_BUFFER_SLOP;
73
1.29M
    memset(ss->lbufstart, 0xaa, CFD_BUFFER_SLOP);
74
1.29M
    memset(ss->lbuf, white, raster);
75
1.29M
    memset(ss->lbuf + raster, 0xaa, CFD_BUFFER_SLOP);  /* for Valgrind */
76
1.29M
    if (ss->K != 0) {
77
1.29M
        ss->lprevstart = gs_alloc_bytes(st->memory, raster + CFD_BUFFER_SLOP * (size_t)2, "CFD lprev");
78
1.29M
        if (ss->lprevstart == 0)
79
0
            return ERRC; /****** WRONG ******/
80
1.29M
        ss->lprev = ss->lprevstart + CFD_BUFFER_SLOP;
81
        /* Clear the initial reference line for 2-D encoding. */
82
1.29M
        memset(ss->lprev, white, raster);
83
        /* Ensure that the scan of the reference line will stop. */
84
1.29M
        memset(ss->lprev + raster, 0xaa, CFD_BUFFER_SLOP);
85
1.29M
        memset(ss->lprevstart, 0xaa, CFD_BUFFER_SLOP);
86
1.29M
    }
87
1.29M
    ss->k_left = min(ss->K, 0);
88
1.29M
    ss->run_color = 0;
89
1.29M
    ss->damaged_rows = 0;
90
1.29M
    ss->skipping_damage = false;
91
1.29M
    ss->cbit = 0;
92
1.29M
    ss->uncomp_run = 0;
93
1.29M
    ss->rows_left = (ss->Rows <= 0 || ss->EndOfBlock ? -1 : ss->Rows);
94
1.29M
    ss->row = 0;
95
1.29M
    ss->rpos = ss->wpos = -1;
96
1.29M
    ss->eol_count = 0;
97
1.29M
    ss->invert = white;
98
1.29M
    ss->min_left = 1;
99
1.29M
    return 0;
100
1.29M
}
101
102
/* Release the filter. */
103
static void
104
s_CFD_release(stream_state * st)
105
1.29M
{
106
1.29M
    stream_CFD_state *const ss = (stream_CFD_state *) st;
107
108
1.29M
    gs_free_object(st->memory, ss->lprevstart, "CFD lprev(close)");
109
1.29M
    gs_free_object(st->memory, ss->lbufstart, "CFD lbuf(close)");
110
1.29M
}
111
112
/* Declare the variables that hold the state. */
113
#define cfd_declare_state\
114
130M
        hcd_declare_state;\
115
130M
        register byte *q;\
116
130M
        int qbit
117
/* Load the state from the stream. */
118
#define cfd_load_state()\
119
222M
        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
222M
        hcd_store_state(),\
124
82.3M
        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
1.01M
#define avail_bits(n) hcd_bits_available(n)
131
253M
#define ensure_bits(n, outl) hcd_ensure_bits(n, outl)
132
273M
#define peek_bits(n) hcd_peek_bits(n)
133
1.01M
#define peek_var_bits(n) hcd_peek_var_bits(n)
134
227M
#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
1.01M
#  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
20.7M
{
146
20.7M
    cfd_declare_state;
147
20.7M
    const cfd_node *np;
148
20.7M
    int clen;
149
20.7M
    cfd_load_state();
150
151
20.7M
    HCD_ENSURE_BITS_ELSE(initial_bits) {
152
        /* We might still have enough bits for the specific code. */
153
776
        if (bits_left < min_bits)
154
235
            goto outl;
155
541
        np = &decode[hcd_peek_bits_left() << (initial_bits - bits_left)];
156
541
        if ((clen = np->code_length) > bits_left)
157
293
            goto outl;
158
248
        goto locl;
159
541
    }
160
20.7M
    np = &decode[peek_bits(initial_bits)];
161
20.7M
    if ((clen = np->code_length) > initial_bits) {
162
1.01M
            IF_DEBUG(uint init_bits = peek_bits(initial_bits));
163
1.01M
            if (!avail_bits(clen)) goto outl;
164
1.01M
            clen -= initial_bits;
165
1.01M
            skip_bits(initial_bits);
166
1.01M
            ensure_bits(clen, outl);                /* can't goto outl */
167
1.01M
            np = &decode[np->run_length + peek_var_bits(clen)];
168
1.01M
            if_debug4('W', "%s xcode=0x%x,%d rlen=%d\n", str,
169
1.01M
                      (init_bits << np->code_length) +
170
1.01M
                        peek_var_bits(np->code_length),
171
1.01M
                      initial_bits + np->code_length,
172
1.01M
                      np->run_length);
173
1.01M
            skip_bits(np->code_length);
174
19.7M
    } else {
175
19.7M
locl:
176
19.7M
       if_debug4('W', "%s code=0x%x,%d rlen=%d\n", str,
177
19.7M
                      peek_var_bits(clen), clen, np->run_length);
178
19.7M
       skip_bits(clen);
179
19.7M
    }
180
20.7M
    *runlen = np->run_length;
181
182
20.7M
    cfd_store_state();
183
20.7M
    return(0);
184
559
outl:
185
559
    cfd_store_state();
186
559
    return(-1);
187
20.7M
}
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
5.96M
{
194
5.96M
    cfd_declare_state;
195
5.96M
    cfd_load_state();
196
5.96M
    (void)rlimit;
197
198
5.96M
    if ( (qbit -= rlen) < 0 )
199
4.51M
    {
200
4.51M
        q -= qbit >> 3, qbit &= 7;
201
4.51M
        if ( rlen >= 64 ) {
202
198k
            cfd_store_state();
203
198k
            return(-1);
204
198k
        }
205
4.51M
    }
206
5.96M
    cfd_store_state();
207
5.77M
    return(0);
208
5.96M
}
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
65.4M
{
217
65.4M
    byte *qlim = ss->lbuf + ss->raster + CFD_BUFFER_SLOP;
218
65.4M
    cfd_declare_state;
219
65.4M
    cfd_load_state();
220
65.4M
    (void)rlimit;
221
222
65.4M
    if (q >= qlim || q < ss->lbufstart) {
223
0
        return(-1);
224
0
    }
225
226
65.4M
    if ( (*rlen) > qbit )
227
41.1M
    {
228
41.1M
        if (q + ((*rlen - qbit) >> 3) > qlim) {
229
5
            return(-1);
230
5
        }
231
232
41.1M
        if (q >= ss->lbuf) {
233
39.9M
          *q++ ^= (1 << qbit) - 1;
234
39.9M
        }
235
1.13M
        else {
236
1.13M
            q++;
237
1.13M
        }
238
41.1M
        (*rlen) -= qbit;
239
240
41.1M
        if (q + ((*rlen) >> 3) >= qlim) {
241
11
            return(-1);
242
11
        }
243
244
41.1M
        switch ( (*rlen) >> 3 )
245
41.1M
        {
246
286k
          case 7:         /* original rlen possibly >= 64 */
247
286k
                  if ( (*rlen) + qbit >= 64 ) {
248
171k
                    goto d;
249
171k
                  }
250
114k
                  *q++ = black_byte;
251
332k
          case 6: *q++ = black_byte;
252
587k
          case 5: *q++ = black_byte;
253
1.01M
          case 4: *q++ = black_byte;
254
1.84M
          case 3: *q++ = black_byte;
255
4.34M
          case 2: *q++ = black_byte;
256
11.1M
          case 1: *q = black_byte;
257
11.1M
              (*rlen) &= 7;
258
11.1M
              if ( !(*rlen) ) {
259
1.96M
                  qbit = 0;
260
1.96M
                  break;
261
1.96M
              }
262
9.22M
              q++;
263
38.5M
          case 0:                 /* know rlen != 0 */
264
38.5M
              qbit = 8 - (*rlen);
265
38.5M
              *q ^= 0xff << qbit;
266
38.5M
              break;
267
452k
          default:        /* original rlen >= 64 */
268
623k
d:            memset(q, black_byte, (*rlen) >> 3);
269
623k
              q += (*rlen) >> 3;
270
623k
              (*rlen) &= 7;
271
623k
              if ( !(*rlen) ) {
272
84.5k
                qbit = 0;
273
84.5k
                q--;
274
84.5k
              }
275
539k
              else {
276
539k
                qbit = 8 - (*rlen);
277
539k
                *q ^= 0xff << qbit;
278
539k
              }
279
623k
              cfd_store_state();
280
623k
              return(-1);
281
41.1M
          }
282
41.1M
    }
283
24.3M
    else {
284
24.3M
            qbit -= (*rlen),
285
24.3M
            *q ^= ((1 << (*rlen)) - 1) << qbit;
286
287
24.3M
    }
288
65.4M
    cfd_store_state();
289
64.8M
    return(0);
290
65.4M
}
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
1.33M
{
302
1.33M
    stream_CFD_state *const ss = (stream_CFD_state *) st;
303
1.33M
    int wstop = ss->raster - 1;
304
1.33M
    int eol_count = ss->eol_count;
305
1.33M
    int k_left = ss->k_left;
306
1.33M
    int rows_left = ss->rows_left;
307
1.33M
    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
1.33M
    ss->lbuf = ss->lbufstart + CFD_BUFFER_SLOP;
317
1.33M
    ss->lprev = ss->lprevstart + CFD_BUFFER_SLOP;
318
319
39.9M
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
39.9M
    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
39.9M
    if (ss->wpos == wstop && ss->cbit <= (-ss->Columns & 7) &&
370
38.6M
        (k_left == 0 ? !(ss->run_color & ~1) : ss->run_color == 0)
371
39.9M
        ) {     /* 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
38.6M
        if (ss->rpos < ss->wpos) {
375
38.6M
            stream_cursor_read cr;
376
377
38.6M
            cr.ptr = ss->lbuf + ss->rpos;
378
38.6M
            cr.limit = ss->lbuf + ss->wpos;
379
38.6M
            status = stream_move(&cr, pw);
380
38.6M
            ss->rpos = cr.ptr - ss->lbuf;
381
38.6M
            if (status)
382
31.0k
                goto out;
383
38.6M
        }
384
38.5M
        ss->row++;
385
38.5M
        if (rows_left > 0 && --rows_left == 0)
386
190
            goto ck_eol;  /* handle EOD if it is present */
387
38.5M
        if (ss->K != 0) {
388
38.5M
            byte *prev_bits = ss->lprev;
389
38.5M
            byte *prev_start = ss->lprevstart;
390
391
38.5M
            ss->lprev = ss->lbuf;
392
38.5M
            ss->lprevstart = ss->lbufstart;
393
38.5M
            ss->lbuf = prev_bits;
394
38.5M
            ss->lbufstart = prev_start;
395
38.5M
            if (ss->K > 0)
396
1.93k
                k_left = (k_left == 0 ? ss->K : k_left) - 1;
397
38.5M
        }
398
38.5M
        ss->rpos = ss->wpos = -1;
399
38.5M
        ss->eol_count = eol_count = 0;
400
38.5M
        ss->cbit = 0;
401
38.5M
        ss->invert = (ss->BlackIs1 ? 0 : 0xff);
402
38.5M
        memset(ss->lbuf, ss->invert, wstop + 1);
403
38.5M
        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
38.5M
        if (ss->EncodedByteAlign && !ss->EndOfLine)
410
0
            ss->bits_left &= ~7;
411
38.5M
    }
412
    /* If we're between scan lines, scan for EOLs. */
413
39.8M
    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
39.8M
ck_eol:
420
41.1M
        while ((status = cf_decode_eol(ss, pr)) > 0) {
421
2.61M
            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
2.61M
            if (ss->K > 0) {
425
2.17k
                hcd_declare_state;
426
2.17k
                hcd_load_state();
427
2.17k
                ensure_bits(1, out); /* can't fail */
428
2.17k
                k_left = (peek_bits(1) ? 0 : 1);
429
2.17k
                skip_bits(1);
430
2.17k
                hcd_store_state();
431
2.17k
            }
432
2.61M
            ++eol_count;
433
2.61M
            if (eol_count == (ss->K < 0 ? 2 : 6)) {
434
1.29M
                status = EOFC;
435
1.29M
                goto out;
436
1.29M
            }
437
2.61M
        }
438
38.5M
        if (rows_left == 0) {
439
189
            status = EOFC;
440
189
            goto out;
441
189
        }
442
38.5M
        if (status == 0)  /* input empty while scanning EOLs */
443
2.01k
            goto out;
444
38.5M
        switch (eol_count) {
445
38.5M
            case 0:
446
38.5M
                if (ss->EndOfLine) { /* EOL is required, but none is present. */
447
0
                    status = ERRC;
448
0
                    goto check;
449
0
                }
450
38.5M
            case 1:
451
38.5M
                break;
452
3
            default:
453
3
                status = ERRC;
454
3
                goto check;
455
38.5M
        }
456
38.5M
    }
457
    /* Now decode actual data. */
458
38.5M
    if (k_left < 0) {
459
38.5M
        if_debug0m('w', ss->memory, "[w2]new row\n");
460
38.5M
        status = cf_decode_2d(ss, pr);
461
38.5M
    } else if (k_left == 0) {
462
19.9k
        if_debug0m('w', ss->memory, "[w1]new row\n");
463
19.9k
        status = cf_decode_1d(ss, pr);
464
19.9k
    } else {
465
1.88k
        if_debug1m('w', ss->memory, "[w1]new 2-D row, k_left=%d\n", k_left);
466
1.88k
        status = cf_decode_2d(ss, pr);
467
1.88k
    }
468
38.5M
    if_debug3m('w', ss->memory, "[w]CFD status = %d, wpos = %d, cbit = %d\n",
469
38.5M
               status, ss->wpos, ss->cbit);
470
38.5M
  check:switch (status) {
471
38.5M
        case 1:   /* output full */
472
38.5M
            goto top;
473
1.36k
        case ERRC:
474
            /* Check for special handling of damaged rows. */
475
1.36k
            if (ss->damaged_rows >= ss->DamagedRowsBeforeError ||
476
0
                !(ss->EndOfLine && ss->K >= 0)
477
1.36k
                )
478
1.36k
                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
754
        default:
489
754
            ss->damaged_rows = 0; /* finished a good row */
490
38.5M
    }
491
1.33M
  out:ss->k_left = k_left;
492
1.33M
    ss->rows_left = rows_left;
493
1.33M
    ss->eol_count = eol_count;
494
1.33M
    if (ss->ErrsAsEOD && status < 0)
495
0
        return EOFC;
496
1.33M
    return status;
497
1.33M
}
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
41.1M
{
512
41.1M
    hcd_declare_state;
513
41.1M
    int zeros;
514
41.1M
    int look_ahead;
515
516
41.1M
    hcd_load_state();
517
90.8M
    for (zeros = 0; zeros < run_eol_code_length - 1; zeros++) {
518
88.2M
        ensure_bits(1, out);
519
88.2M
        if (peek_bits(1))
520
38.5M
            return -(zeros + 1);
521
49.6M
        skip_bits(1);
522
49.6M
    }
523
    /* We definitely have an EOL.  Skip further zero bits. */
524
2.61M
    look_ahead = (ss->K > 0 ? 2 : 1);
525
2.61M
    for (;;) {
526
2.61M
        ensure_bits(look_ahead, back);
527
2.61M
        if (peek_bits(1))
528
2.61M
            break;
529
127
        skip_bits(1);
530
127
    }
531
2.61M
    skip_bits(1);
532
2.61M
    hcd_store_state();
533
2.61M
    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
2.01k
  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
19.9k
{
550
19.9k
    cfd_declare_state;
551
19.9k
    byte black_byte = (ss->BlackIs1 ? 0xff : 0);
552
19.9k
    int end_bit = -ss->Columns & 7;
553
19.9k
    byte *stop = ss->lbuf - 1 + ss->raster;
554
19.9k
    int run_color = ss->run_color;
555
19.9k
    int status;
556
19.9k
    int bcnt;
557
19.9k
    (void)rlimit;
558
559
19.9k
    cfd_load_state();
560
19.9k
    if_debug1m('w', ss->memory, "[w1]entry run_color = %d\n", ss->run_color);
561
19.9k
    if (run_color > 0)
562
116
        goto db;
563
19.8k
    else
564
19.8k
        goto dw;
565
856k
#define q_at_stop() (q >= stop && (qbit <= end_bit || q > stop))
566
419k
    while (1)
567
419k
    {
568
419k
        run_color = 0;
569
419k
        if (q_at_stop())
570
3.24k
            goto done;
571
572
436k
  dw:   /* Decode a white run. */
573
559k
        do {
574
559k
            cfd_store_state();
575
559k
            status = get_run(ss, pr, cf_white_decode, cfd_white_initial_bits,
576
559k
                             cfd_white_min_bits, &bcnt, "[w1]white");
577
559k
            cfd_load_state();
578
559k
            if (status < 0) {
579
                /* We already set run_color to 0 or -1. */
580
230
                status = 0;
581
230
                goto out;
582
230
            }
583
584
558k
            if (bcnt < 0) {   /* exceptional situation */
585
24
                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
24
                    default:
599
24
                        status = ERRC;
600
24
                        goto out;
601
24
                }
602
24
            }
603
604
558k
            cfd_store_state();
605
558k
            status = skip_data(ss, pr, bcnt);
606
558k
            cfd_load_state();
607
558k
            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
122k
                run_color = -1;
611
122k
            }
612
558k
        } while (status < 0);
613
614
436k
        if (q_at_stop()) {
615
16.2k
            run_color = 0;    /* not inside a run */
616
19.5k
  done:
617
19.5k
            if (q > stop || qbit < end_bit)
618
164
                status = ERRC;
619
19.3k
            else
620
19.3k
                status = 1;
621
19.5k
            break;
622
16.2k
        }
623
419k
        run_color = 1;
624
625
420k
  db:   /* Decode a black run. */
626
420k
        do {
627
420k
            cfd_store_state();
628
420k
            status = get_run(ss, pr, cf_black_decode, cfd_black_initial_bits,
629
420k
                             cfd_black_min_bits, &bcnt, "[w1]black");
630
420k
            cfd_load_state();
631
420k
            if (status < 0) {
632
                /* We already set run_color to 1 or 2. */
633
116
                status = 0;
634
116
                goto out;
635
116
            }
636
637
420k
            if (bcnt < 0) {  /* All exceptional codes are invalid here. */
638
                /****** WRONG, uncompressed IS ALLOWED ******/
639
29
                status = ERRC;
640
29
                goto out;
641
29
            }
642
643
            /* Invert bits designated by black run. */
644
420k
            cfd_store_state();
645
420k
            status = invert_data(ss, pr, &bcnt, black_byte);
646
420k
            cfd_load_state();
647
420k
            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
409
                run_color = 2;
651
409
            }
652
420k
        } while (status < 0);
653
420k
    }
654
655
19.9k
out:
656
19.9k
    cfd_store_state();
657
19.9k
    ss->run_color = run_color;
658
19.9k
    if_debug1m('w', ss->memory, "[w1]exit run_color = %d\n", run_color);
659
19.9k
    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
38.5M
{
666
38.5M
    cfd_declare_state;
667
38.5M
    byte invert_white = (ss->BlackIs1 ? 0 : 0xff);
668
38.5M
    byte black_byte = ~invert_white;
669
38.5M
    byte invert = ss->invert;
670
38.5M
    int end_count = -ss->Columns & 7;
671
38.5M
    uint raster = ss->raster;
672
38.5M
    byte *q0 = ss->lbuf;
673
38.5M
    byte *prev_q01 = ss->lprev + 1;
674
38.5M
    byte *endptr = q0 - 1 + raster;
675
38.5M
    int init_count = raster << 3;
676
38.5M
    register int count;
677
38.5M
    int rlen;
678
38.5M
    int status;
679
680
38.5M
    cfd_load_state();
681
38.5M
    count = ((endptr - q) << 3) + qbit;
682
38.5M
    endptr[1] = 0xa0;   /* a byte with some 0s and some 1s, */
683
    /* to ensure run scan will stop */
684
38.5M
    if_debug1m('W', ss->memory, "[w2]raster=%d\n", raster);
685
38.5M
    switch (ss->run_color) {
686
9
        case -2:
687
9
            ss->run_color = 0;
688
9
            goto hww;
689
42
        case -1:
690
42
            ss->run_color = 0;
691
42
            goto hbw;
692
36
        case 1:
693
36
            ss->run_color = 0;
694
36
            goto hwb;
695
13
        case 2:
696
13
            ss->run_color = 0;
697
13
            goto hbb;
698
            /*case 0: */
699
38.5M
    }
700
701
    /* top of decode loop */
702
200M
    while (1)
703
200M
    {
704
200M
        if (count <= end_count) {
705
38.5M
            status = (count < end_count ? ERRC : 1);
706
38.5M
            goto out;
707
38.5M
        }
708
        /* If invert == invert_white, white and black have their */
709
        /* correct meanings; if invert == ~invert_white, */
710
        /* black and white are interchanged. */
711
200M
        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
162M
        ensure_bits(3, out3);
729
302M
#define vertical_0 (countof(cf2_run_vertical) / 2)
730
162M
        switch (peek_bits(3)) {
731
118M
        default /*4..7*/ :  /* vertical(0) */
732
118M
            if (0) {
733
297
 out3:
734
                /* Unless it's a 1-bit "vertical 0" code, exit. */
735
297
                if (!(bits_left > 0 && peek_bits(1)))
736
177
                    goto out0;
737
297
            }
738
118M
            skip_bits(1);
739
118M
            rlen = vertical_0;
740
118M
            break;
741
15.6M
        case 2:   /* vertical(+1) */
742
15.6M
            skip_bits(3);
743
15.6M
            rlen = vertical_0 + 1;
744
15.6M
            break;
745
13.2M
        case 3:   /* vertical(-1) */
746
13.2M
            skip_bits(3);
747
13.2M
            rlen = vertical_0 - 1;
748
13.2M
            break;
749
5.33M
        case 1:   /* horizontal */
750
5.33M
            skip_bits(3);
751
5.33M
            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
3.30M
  hww:
756
3.34M
                do {
757
3.34M
                    cfd_store_state();
758
3.34M
                    status = get_run(ss, pr, cf_white_decode,
759
3.34M
                                     cfd_white_initial_bits,
760
3.34M
                                     cfd_white_min_bits, &rlen, " white");
761
3.34M
                    cfd_load_state();
762
3.34M
                    if (status < 0) {
763
17
                        ss->run_color = -2;
764
17
                        goto out0;
765
17
                    }
766
767
3.34M
                    if ((count -= rlen) < end_count) {
768
96
                        status = ERRC;
769
96
                        goto out;
770
96
                    }
771
3.34M
                    if (rlen < 0) goto rlen_lt_zero;
772
773
3.34M
                    cfd_store_state();
774
3.34M
                    status = skip_data(ss, pr, rlen);
775
3.34M
                    cfd_load_state();
776
3.34M
                } while (status < 0);
777
778
                /* Handle the second half of a white-black horizontal code. */
779
3.30M
  hwb:
780
3.34M
                do {
781
3.34M
                    cfd_store_state();
782
3.34M
                    status = get_run(ss, pr, cf_black_decode,
783
3.34M
                                     cfd_black_initial_bits,
784
3.34M
                                     cfd_black_min_bits, &rlen, " black");
785
3.34M
                    cfd_load_state();
786
3.34M
                    if (status < 0){
787
43
                        ss->run_color = 1;
788
43
                        goto out0;
789
43
                    }
790
791
3.34M
                    if ((count -= rlen) < end_count) {
792
58
                        status = ERRC;
793
58
                        goto out;
794
58
                    }
795
3.34M
                    if (rlen < 0) goto rlen_lt_zero;
796
797
3.34M
                    cfd_store_state();
798
3.34M
                    status = invert_data(ss, pr, &rlen, black_byte);
799
3.34M
                    cfd_load_state();
800
3.34M
                } while (status < 0);
801
3.30M
            } else {
802
                /* Black, then white. */
803
2.02M
  hbb:
804
2.04M
                do {
805
2.04M
                    cfd_store_state();
806
2.04M
                    status = get_run(ss, pr, cf_black_decode,
807
2.04M
                                     cfd_black_initial_bits,
808
2.04M
                                     cfd_black_min_bits, &rlen, " black");
809
2.04M
                    cfd_load_state();
810
2.04M
                    if (status < 0) {
811
13
                        ss->run_color = 2;
812
13
                        goto out0;
813
13
                    }
814
815
2.04M
                    if ((count -= rlen) < end_count) {
816
83
                        status = ERRC;
817
83
                        goto out;
818
83
                    }
819
2.04M
                    if (rlen < 0) goto rlen_lt_zero;
820
821
2.04M
                    cfd_store_state();
822
2.04M
                    status = invert_data(ss, pr, &rlen, black_byte);
823
2.04M
                    cfd_load_state();
824
2.04M
                }
825
2.04M
                while (status < 0);
826
827
                /* Handle the second half of a black-white horizontal code. */
828
2.02M
  hbw:
829
2.06M
                do {
830
2.06M
                    cfd_store_state();
831
2.06M
                    status = get_run(ss, pr, cf_white_decode,
832
2.06M
                                     cfd_white_initial_bits,
833
2.06M
                                     cfd_white_min_bits, &rlen, " white");
834
2.06M
                    cfd_load_state();
835
2.06M
                    if (status < 0) {
836
43
                        ss->run_color = -1;
837
43
                        goto out0;
838
43
                    }
839
840
2.06M
                    if ((count -= rlen) < end_count) {
841
220
                        status = ERRC;
842
220
                        goto out;
843
220
                    }
844
2.06M
                    if (rlen < 0) goto rlen_lt_zero;
845
846
2.06M
                    cfd_store_state();
847
2.06M
                    status = skip_data(ss, pr, rlen);
848
2.06M
                    cfd_load_state();
849
2.06M
                } while (status < 0);
850
2.02M
            }
851
5.33M
            continue; /* jump back to top of decode loop */
852
8.98M
        case 0:   /* everything else */
853
8.98M
            cfd_store_state();
854
8.98M
            status = get_run(ss, pr, cf_2d_decode, cfd_2d_initial_bits,
855
8.98M
                             cfd_2d_min_bits, &rlen, "[w2]");
856
8.98M
            cfd_load_state();
857
8.98M
            if (status < 0) {
858
97
                goto out0;
859
97
            }
860
861
            /* rlen may be run2_pass, run_uncompressed, or */
862
            /* 0..countof(cf2_run_vertical)-1. */
863
8.98M
            if (rlen < 0) {
864
2.24M
rlen_lt_zero:
865
2.24M
                switch (rlen) {
866
2.24M
                case run2_pass:
867
2.24M
                    break;
868
9
                case run_uncompressed:
869
9
                {
870
9
                    int which;
871
872
9
                    cfd_store_state();
873
9
                    which = cf_decode_uncompressed(ss, pr);
874
9
                    if (which < 0) {
875
9
                        status = which;
876
9
                        goto out;
877
9
                    }
878
9
                    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
9
                }
883
197
                default:  /* run_error, run_zeros */
884
197
                    status = ERRC;
885
197
                    goto out;
886
2.24M
                }
887
2.24M
            }
888
162M
        }
889
        /* Interpreting the run requires scanning the */
890
        /* previous ('reference') line. */
891
156M
        {
892
156M
            int prev_count = count;
893
156M
            byte prev_data;
894
156M
            int dlen;
895
156M
            static const byte count_bit[8] =
896
156M
                                   {0x80, 1, 2, 4, 8, 0x10, 0x20, 0x40};
897
156M
            byte *prev_q = prev_q01 + (q - q0);
898
156M
            int plen;
899
900
156M
            if (!(count & 7))
901
50.6M
                prev_q++;   /* because of skip macros */
902
156M
            prev_data = prev_q[-1] ^ invert;
903
            /* Find the b1 transition. */
904
156M
            if ((prev_data & count_bit[prev_count & 7]) &&
905
19.7M
                (prev_count < init_count || invert != invert_white)
906
156M
                ) {     /* Look for changing white first. */
907
18.6M
                if_debug1m('W', ss->memory, " data=0x%x", prev_data);
908
18.6M
                skip_black_pixels(prev_data, prev_q,
909
18.6M
                                  prev_count, invert, plen);
910
18.6M
                if (prev_count < end_count)    /* overshot */
911
5.64k
                    prev_count = end_count;
912
18.6M
                if_debug1m('W', ss->memory, " b1 other=%d", prev_count);
913
18.6M
            }
914
156M
            if (prev_count != end_count) {
915
156M
                if_debug1m('W', ss->memory, " data=0x%x", prev_data);
916
156M
                skip_white_pixels(prev_data, prev_q,
917
156M
                                  prev_count, invert, plen);
918
156M
                if (prev_count < end_count)    /* overshot */
919
207k
                    prev_count = end_count;
920
156M
                if_debug1m('W', ss->memory, " b1 same=%d", prev_count);
921
156M
            }
922
            /* b1 = prev_count; */
923
156M
            if (rlen == run2_pass) { /* Pass mode.  Find b2. */
924
2.24M
                if (prev_count != end_count) {
925
2.24M
                    if_debug1m('W', ss->memory, " data=0x%x", prev_data);
926
2.24M
                    skip_black_pixels(prev_data, prev_q,
927
2.24M
                                      prev_count, invert, plen);
928
2.24M
                    if (prev_count < end_count)  /* overshot */
929
95
                        prev_count = end_count;
930
2.24M
                }
931
                /* b2 = prev_count; */
932
2.24M
                if_debug2m('W', ss->memory, " b2=%d, pass %d\n",
933
2.24M
                           prev_count, count - prev_count);
934
154M
            } else {   /* Vertical coding. */
935
                /* Remember that count counts *down*. */
936
154M
                prev_count += rlen - vertical_0; /* a1 */
937
154M
                if_debug2m('W', ss->memory, " vertical %d -> %d\n",
938
154M
                           (int)(rlen - vertical_0), prev_count);
939
154M
            }
940
            /* Now either invert or skip from count */
941
            /* to prev_count, and reset count. */
942
156M
            if (invert == invert_white) { /* Skip data bits. */
943
97.0M
                q = endptr - (prev_count >> 3);
944
97.0M
                qbit = prev_count & 7;
945
97.0M
            } else {   /* Invert data bits. */
946
59.6M
                dlen = count - prev_count;
947
948
59.6M
                cfd_store_state();
949
59.6M
                (void)invert_data(ss, pr, &dlen, black_byte);
950
59.6M
                cfd_load_state();
951
59.6M
            }
952
156M
            count = prev_count;
953
156M
            if (rlen >= 0)    /* vertical mode */
954
154M
                invert = ~invert; /* polarity changes */
955
156M
        }
956
        /* jump back to top of decode loop */
957
156M
    }
958
959
390
  out0:status = 0;
960
    /* falls through */
961
38.5M
  out:cfd_store_state();
962
38.5M
    ss->invert = invert;
963
    /* Ignore an error (missing EOFB/RTC when EndOfBlock == true) */
964
    /* if we have finished all rows. */
965
38.5M
    if (status == ERRC && ss->Rows > 0 && ss->row > ss->Rows)
966
18
        status = EOFC;
967
38.5M
    return status;
968
390
}
969
970
#if 1       /*************** */
971
static int
972
cf_decode_uncompressed(stream_CFD_state * ss, stream_cursor_read * pr)
973
9
{
974
9
    return ERRC;
975
9
}
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
};