Line data Source code
1 : /*
2 : * Copyright (c) 1990-1997 Sam Leffler
3 : * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4 : *
5 : * Permission to use, copy, modify, distribute, and sell this software and
6 : * its documentation for any purpose is hereby granted without fee, provided
7 : * that (i) the above copyright notices and this permission notice appear in
8 : * all copies of the software and related documentation, and (ii) the names of
9 : * Sam Leffler and Silicon Graphics may not be used in any advertising or
10 : * publicity relating to the software without the specific, prior written
11 : * permission of Sam Leffler and Silicon Graphics.
12 : *
13 : * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14 : * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15 : * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16 : *
17 : * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18 : * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19 : * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20 : * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21 : * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22 : * OF THIS SOFTWARE.
23 : */
24 :
25 : #include "tiffiop.h"
26 : #ifdef CCITT_SUPPORT
27 : /*
28 : * TIFF Library.
29 : *
30 : * CCITT Group 3 (T.4) and Group 4 (T.6) Compression Support.
31 : *
32 : * This file contains support for decoding and encoding TIFF
33 : * compression algorithms 2, 3, 4, and 32771.
34 : *
35 : * Decoder support is derived, with permission, from the code
36 : * in Frank Cringle's viewfax program;
37 : * Copyright (C) 1990, 1995 Frank D. Cringle.
38 : */
39 : #include "tif_fax3.h"
40 : #define G3CODES
41 : #include "t4.h"
42 : #include <stdio.h>
43 :
44 : #ifndef EOF_REACHED_COUNT_THRESHOLD
45 : /* Arbitrary threshold to avoid corrupted single-strip files with extremely
46 : * large imageheight to cause apparently endless looping, such as in
47 : * https://gitlab.com/libtiff/libtiff/-/issues/583
48 : */
49 : #define EOF_REACHED_COUNT_THRESHOLD 8192
50 : #endif
51 :
52 : /*
53 : * Compression+decompression state blocks are
54 : * derived from this ``base state'' block.
55 : */
56 : typedef struct
57 : {
58 : int rw_mode; /* O_RDONLY for decode, else encode */
59 : int mode; /* operating mode */
60 : tmsize_t rowbytes; /* bytes in a decoded scanline */
61 : uint32_t rowpixels; /* pixels in a scanline */
62 :
63 : uint16_t cleanfaxdata; /* CleanFaxData tag */
64 : uint32_t badfaxrun; /* BadFaxRun tag */
65 : uint32_t badfaxlines; /* BadFaxLines tag */
66 : uint32_t groupoptions; /* Group 3/4 options tag */
67 :
68 : TIFFVGetMethod vgetparent; /* super-class method */
69 : TIFFVSetMethod vsetparent; /* super-class method */
70 : TIFFPrintMethod printdir; /* super-class method */
71 : } Fax3BaseState;
72 : #define Fax3State(tif) ((Fax3BaseState *)(tif)->tif_data)
73 :
74 : typedef enum
75 : {
76 : G3_1D,
77 : G3_2D
78 : } Ttag;
79 : typedef struct
80 : {
81 : Fax3BaseState b;
82 :
83 : /* Decoder state info */
84 : const unsigned char *bitmap; /* bit reversal table */
85 : uint32_t data; /* current i/o byte/word */
86 : int bit; /* current i/o bit in byte */
87 : int EOLcnt; /* count of EOL codes recognized */
88 : int eofReachedCount; /* number of times decode has been called with
89 : EOF already reached */
90 : int eolReachedCount; /* number of times decode has been called with
91 : EOL already reached */
92 : int unexpectedReachedCount; /* number of times decode has been called with
93 : "unexpedted" already reached */
94 : TIFFFaxFillFunc fill; /* fill routine */
95 : uint32_t *runs; /* b&w runs for current/previous row */
96 : uint32_t nruns; /* size of the refruns / curruns arrays */
97 : uint32_t *refruns; /* runs for reference line */
98 : uint32_t *curruns; /* runs for current line */
99 :
100 : /* Encoder state info */
101 : Ttag tag; /* encoding state */
102 : unsigned char *refline; /* reference line for 2d decoding */
103 : int k; /* #rows left that can be 2d encoded */
104 : int maxk; /* max #rows that can be 2d encoded */
105 :
106 : int line;
107 : } Fax3CodecState;
108 : #define DecoderState(tif) ((Fax3CodecState *)Fax3State(tif))
109 : #define EncoderState(tif) ((Fax3CodecState *)Fax3State(tif))
110 :
111 : #define is2DEncoding(sp) (sp->b.groupoptions & GROUP3OPT_2DENCODING)
112 : #define isAligned(p, t) ((((size_t)(p)) & (sizeof(t) - 1)) == 0)
113 :
114 : /*
115 : * Group 3 and Group 4 Decoding.
116 : */
117 :
118 : /*
119 : * These macros glue the TIFF library state to
120 : * the state expected by Frank's decoder.
121 : */
122 : #define DECLARE_STATE(tif, sp, mod) \
123 : static const char module[] = mod; \
124 : Fax3CodecState *sp = DecoderState(tif); \
125 : int a0; /* reference element */ \
126 : int lastx = sp->b.rowpixels; /* last element in row */ \
127 : uint32_t BitAcc; /* bit accumulator */ \
128 : int BitsAvail; /* # valid bits in BitAcc */ \
129 : int RunLength; /* length of current run */ \
130 : unsigned char *cp; /* next byte of input data */ \
131 : unsigned char *ep; /* end of input data */ \
132 : uint32_t *pa; /* place to stuff next run */ \
133 : uint32_t *thisrun; /* current row's run array */ \
134 : int EOLcnt; /* # EOL codes recognized */ \
135 : const unsigned char *bitmap = sp->bitmap; /* input data bit reverser */ \
136 : const TIFFFaxTabEnt *TabEnt
137 :
138 : #define DECLARE_STATE_2D(tif, sp, mod) \
139 : DECLARE_STATE(tif, sp, mod); \
140 : int b1; /* next change on prev line */ \
141 : uint32_t \
142 : *pb /* next run in reference line */ /* \
143 : * Load any state that may be \
144 : * changed during decoding. \
145 : */
146 : #define CACHE_STATE(tif, sp) \
147 : do \
148 : { \
149 : BitAcc = sp->data; \
150 : BitsAvail = sp->bit; \
151 : EOLcnt = sp->EOLcnt; \
152 : cp = (unsigned char *)tif->tif_rawcp; \
153 : ep = cp + tif->tif_rawcc; \
154 : } while (0)
155 : /*
156 : * Save state possibly changed during decoding.
157 : */
158 : #define UNCACHE_STATE(tif, sp) \
159 : do \
160 : { \
161 : sp->bit = BitsAvail; \
162 : sp->data = BitAcc; \
163 : sp->EOLcnt = EOLcnt; \
164 : tif->tif_rawcc -= (tmsize_t)((uint8_t *)cp - tif->tif_rawcp); \
165 : tif->tif_rawcp = (uint8_t *)cp; \
166 : } while (0)
167 :
168 : /*
169 : * Setup state for decoding a strip.
170 : */
171 13 : static int Fax3PreDecode(TIFF *tif, uint16_t s)
172 : {
173 13 : Fax3CodecState *sp = DecoderState(tif);
174 :
175 : (void)s;
176 13 : assert(sp != NULL);
177 13 : sp->bit = 0; /* force initial read */
178 13 : sp->data = 0;
179 13 : sp->EOLcnt = 0; /* force initial scan for EOL */
180 13 : sp->eofReachedCount = 0;
181 13 : sp->eolReachedCount = 0;
182 13 : sp->unexpectedReachedCount = 0;
183 : /*
184 : * Decoder assumes lsb-to-msb bit order. Note that we select
185 : * this here rather than in Fax3SetupState so that viewers can
186 : * hold the image open, fiddle with the FillOrder tag value,
187 : * and then re-decode the image. Otherwise they'd need to close
188 : * and open the image to get the state reset.
189 : */
190 13 : sp->bitmap =
191 13 : TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
192 13 : sp->curruns = sp->runs;
193 13 : if (sp->refruns)
194 : { /* init reference line to white */
195 11 : sp->refruns = sp->runs + sp->nruns;
196 11 : sp->refruns[0] = (uint32_t)sp->b.rowpixels;
197 11 : sp->refruns[1] = 0;
198 : }
199 13 : sp->line = 0;
200 13 : return (1);
201 : }
202 :
203 : /*
204 : * Routine for handling various errors/conditions.
205 : * Note how they are "glued into the decoder" by
206 : * overriding the definitions used by the decoder.
207 : */
208 :
209 0 : static void Fax3Unexpected(const char *module, TIFF *tif, uint32_t line,
210 : uint32_t a0)
211 : {
212 0 : TIFFErrorExtR(tif, module,
213 : "Bad code word at line %" PRIu32 " of %s %" PRIu32
214 : " (x %" PRIu32 ")",
215 0 : line, isTiled(tif) ? "tile" : "strip",
216 0 : (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
217 0 : }
218 : #define unexpected(table, a0) \
219 : do \
220 : { \
221 : Fax3Unexpected(module, tif, sp->line, a0); \
222 : ++sp->unexpectedReachedCount; \
223 : } while (0)
224 :
225 0 : static void Fax3Extension(const char *module, TIFF *tif, uint32_t line,
226 : uint32_t a0)
227 : {
228 0 : TIFFErrorExtR(tif, module,
229 : "Uncompressed data (not supported) at line %" PRIu32
230 : " of %s %" PRIu32 " (x %" PRIu32 ")",
231 0 : line, isTiled(tif) ? "tile" : "strip",
232 0 : (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
233 0 : }
234 : #define extension(a0) Fax3Extension(module, tif, sp->line, a0)
235 :
236 0 : static void Fax3BadLength(const char *module, TIFF *tif, uint32_t line,
237 : uint32_t a0, uint32_t lastx)
238 : {
239 0 : TIFFWarningExtR(tif, module,
240 : "%s at line %" PRIu32 " of %s %" PRIu32 " (got %" PRIu32
241 : ", expected %" PRIu32 ")",
242 : a0 < lastx ? "Premature EOL" : "Line length mismatch", line,
243 0 : isTiled(tif) ? "tile" : "strip",
244 0 : (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0,
245 : lastx);
246 0 : }
247 : #define badlength(a0, lastx) \
248 : do \
249 : { \
250 : Fax3BadLength(module, tif, sp->line, a0, lastx); \
251 : ++sp->eolReachedCount; \
252 : } while (0)
253 :
254 0 : static void Fax3PrematureEOF(const char *module, TIFF *tif, uint32_t line,
255 : uint32_t a0)
256 : {
257 0 : TIFFWarningExtR(tif, module,
258 : "Premature EOF at line %" PRIu32 " of %s %" PRIu32
259 : " (x %" PRIu32 ")",
260 0 : line, isTiled(tif) ? "tile" : "strip",
261 0 : (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
262 0 : }
263 : #define prematureEOF(a0) \
264 : do \
265 : { \
266 : Fax3PrematureEOF(module, tif, sp->line, a0); \
267 : ++sp->eofReachedCount; \
268 : } while (0)
269 :
270 0 : static void Fax3TryG3WithoutEOL(const char *module, TIFF *tif, uint32_t line,
271 : uint32_t a0)
272 : {
273 0 : TIFFWarningExtR(
274 : tif, module,
275 : "Try to decode (read) fax Group 3 data without EOL at line %" PRIu32
276 : " of %s %" PRIu32 " (x %" PRIu32 "). Please check result",
277 0 : line, isTiled(tif) ? "tile" : "strip",
278 0 : (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip), a0);
279 0 : }
280 : #define tryG3WithoutEOL(a0) \
281 : do \
282 : { \
283 : Fax3TryG3WithoutEOL(module, tif, sp->line, a0); \
284 : } while (0)
285 :
286 : #define Nop
287 :
288 21610 : static int CheckReachedCounters(TIFF *tif, const char *module,
289 : Fax3CodecState *sp)
290 : {
291 21610 : if (sp->eofReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
292 : {
293 0 : TIFFErrorExtR(tif, module,
294 : "End of file (EOF) has already been reached %d times "
295 : "within that %s.",
296 0 : sp->eofReachedCount, isTiled(tif) ? "tile" : "strip");
297 0 : return (-1);
298 : }
299 21610 : if (sp->eolReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
300 : {
301 0 : TIFFErrorExtR(tif, module,
302 : "Bad line length (EOL) has already been reached %d times "
303 : "within that %s",
304 0 : sp->eolReachedCount, isTiled(tif) ? "tile" : "strip");
305 0 : return (-1);
306 : }
307 21610 : if (sp->unexpectedReachedCount >= EOF_REACHED_COUNT_THRESHOLD)
308 : {
309 0 : TIFFErrorExtR(tif, module,
310 : "Bad code word (unexpected) has already been reached %d "
311 : "times within that %s",
312 : sp->unexpectedReachedCount,
313 0 : isTiled(tif) ? "tile" : "strip");
314 0 : return (-1);
315 : }
316 21610 : return (0);
317 : }
318 :
319 : /**
320 : * Decode the requested amount of G3 1D-encoded data.
321 : * @param buf destination buffer
322 : * @param occ available bytes in destination buffer
323 : * @param s number of planes (ignored)
324 : * @returns 1 for success, -1 in case of error
325 : */
326 1 : static int Fax3Decode1D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
327 : {
328 1 : DECLARE_STATE(tif, sp, "Fax3Decode1D");
329 : (void)s;
330 1 : if (occ % sp->b.rowbytes)
331 : {
332 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
333 0 : return (-1);
334 : }
335 1 : if (CheckReachedCounters(tif, module, sp))
336 0 : return (-1);
337 1 : RETRY_WITHOUT_EOL_1D:
338 1 : CACHE_STATE(tif, sp);
339 1 : thisrun = sp->curruns;
340 100 : while (occ > 0)
341 : {
342 99 : a0 = 0;
343 99 : RunLength = 0;
344 99 : pa = thisrun;
345 : #ifdef FAX3_DEBUG
346 : printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
347 : printf("-------------------- %" PRIu32 "\n", tif->tif_row);
348 : fflush(stdout);
349 : #endif
350 693 : SYNC_EOL(EOF1D, RETRY_WITHOUT_EOL_1D);
351 1323 : EXPAND1D(EOF1Da);
352 99 : (*sp->fill)(buf, thisrun, pa, lastx);
353 99 : buf += sp->b.rowbytes;
354 99 : occ -= sp->b.rowbytes;
355 99 : sp->line++;
356 99 : continue;
357 0 : EOF1D: /* premature EOF */
358 0 : CLEANUP_RUNS();
359 0 : EOF1Da: /* premature EOF */
360 0 : (*sp->fill)(buf, thisrun, pa, lastx);
361 0 : UNCACHE_STATE(tif, sp);
362 0 : return (-1);
363 : }
364 1 : UNCACHE_STATE(tif, sp);
365 1 : return (1);
366 : }
367 :
368 : #define SWAP(t, a, b) \
369 : { \
370 : t x; \
371 : x = (a); \
372 : (a) = (b); \
373 : (b) = x; \
374 : }
375 : /*
376 : * Decode the requested amount of G3 2D-encoded data.
377 : */
378 1 : static int Fax3Decode2D(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
379 : {
380 1 : DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
381 : int is1D; /* current line is 1d/2d-encoded */
382 : (void)s;
383 1 : if (occ % sp->b.rowbytes)
384 : {
385 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
386 0 : return (-1);
387 : }
388 1 : if (CheckReachedCounters(tif, module, sp))
389 0 : return (-1);
390 1 : RETRY_WITHOUT_EOL_2D:
391 1 : CACHE_STATE(tif, sp);
392 1025 : while (occ > 0)
393 : {
394 1024 : a0 = 0;
395 1024 : RunLength = 0;
396 1024 : pa = thisrun = sp->curruns;
397 : #ifdef FAX3_DEBUG
398 : printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d EOLcnt = %d", BitAcc,
399 : BitsAvail, EOLcnt);
400 : #endif
401 7168 : SYNC_EOL(EOF2D, RETRY_WITHOUT_EOL_2D);
402 1024 : NeedBits8(1, EOF2D);
403 1024 : is1D = GetBits(1); /* 1D/2D-encoding tag bit */
404 1024 : ClrBits(1);
405 : #ifdef FAX3_DEBUG
406 : printf(" %s\n-------------------- %" PRIu32 "\n", is1D ? "1D" : "2D",
407 : tif->tif_row);
408 : fflush(stdout);
409 : #endif
410 1024 : pb = sp->refruns;
411 1024 : b1 = *pb++;
412 1024 : if (is1D)
413 737 : EXPAND1D(EOF2Da);
414 : else
415 3072 : EXPAND2D(EOF2Da);
416 1024 : (*sp->fill)(buf, thisrun, pa, lastx);
417 1024 : if (pa < thisrun + sp->nruns)
418 : {
419 1024 : SETVALUE(0); /* imaginary change for reference */
420 : }
421 1024 : SWAP(uint32_t *, sp->curruns, sp->refruns);
422 1024 : buf += sp->b.rowbytes;
423 1024 : occ -= sp->b.rowbytes;
424 1024 : sp->line++;
425 1024 : continue;
426 0 : EOF2D: /* premature EOF */
427 0 : CLEANUP_RUNS();
428 0 : EOF2Da: /* premature EOF */
429 0 : (*sp->fill)(buf, thisrun, pa, lastx);
430 0 : UNCACHE_STATE(tif, sp);
431 0 : return (-1);
432 : }
433 1 : UNCACHE_STATE(tif, sp);
434 1 : return (1);
435 : }
436 : #undef SWAP
437 :
438 : #define FILL(n, cp) \
439 : for (int32_t ifill = 0; ifill < (n); ++ifill) \
440 : { \
441 : (cp)[ifill] = 0xff; \
442 : } \
443 : (cp) += (n);
444 :
445 : #define ZERO(n, cp) \
446 : for (int32_t izero = 0; izero < (n); ++izero) \
447 : { \
448 : (cp)[izero] = 0; \
449 : } \
450 : (cp) += (n);
451 :
452 : /*
453 : * Bit-fill a row according to the white/black
454 : * runs generated during G3/G4 decoding.
455 : */
456 23917 : void _TIFFFax3fillruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
457 : uint32_t lastx)
458 : {
459 : static const unsigned char _fillmasks[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0,
460 : 0xf8, 0xfc, 0xfe, 0xff};
461 : unsigned char *cp;
462 : uint32_t x, bx, run;
463 : int32_t n, nw;
464 : int64_t *lp;
465 :
466 23917 : if ((erun - runs) & 1)
467 991 : *erun++ = 0;
468 23917 : x = 0;
469 84444 : for (; runs < erun; runs += 2)
470 : {
471 60527 : run = runs[0];
472 60527 : if (x + run > lastx || run > lastx)
473 0 : run = runs[0] = (uint32_t)(lastx - x);
474 60527 : if (run)
475 : {
476 38491 : cp = buf + (x >> 3);
477 38491 : bx = x & 7;
478 38491 : if (run > 8 - bx)
479 : {
480 25749 : if (bx)
481 : { /* align to byte boundary */
482 21848 : *cp++ &= 0xff << (8 - bx);
483 21848 : run -= 8 - bx;
484 : }
485 25749 : if ((n = run >> 3) != 0)
486 : { /* multiple bytes to fill */
487 15572 : if ((n / sizeof(int64_t)) > 1)
488 : {
489 : /*
490 : * Align to int64_tword boundary and fill.
491 : */
492 2335 : for (; n && !isAligned(cp, int64_t); n--)
493 1140 : *cp++ = 0x00;
494 1195 : lp = (int64_t *)cp;
495 1195 : nw = (int32_t)(n / sizeof(int64_t));
496 1195 : n -= nw * sizeof(int64_t);
497 : do
498 : {
499 8396 : *lp++ = 0L;
500 8396 : } while (--nw);
501 1195 : cp = (unsigned char *)lp;
502 : }
503 56634 : ZERO(n, cp);
504 15572 : run &= 7;
505 : }
506 25749 : if (run)
507 23710 : cp[0] &= 0xff >> run;
508 : }
509 : else
510 12742 : cp[0] &= ~(_fillmasks[run] >> bx);
511 38491 : x += runs[0];
512 : }
513 60527 : run = runs[1];
514 60527 : if (x + run > lastx || run > lastx)
515 0 : run = runs[1] = lastx - x;
516 60527 : if (run)
517 : {
518 59536 : cp = buf + (x >> 3);
519 59536 : bx = x & 7;
520 59536 : if (run > 8 - bx)
521 : {
522 47609 : if (bx)
523 : { /* align to byte boundary */
524 23602 : *cp++ |= 0xff >> bx;
525 23602 : run -= 8 - bx;
526 : }
527 47609 : if ((n = run >> 3) != 0)
528 : { /* multiple bytes to fill */
529 41944 : if ((n / sizeof(int64_t)) > 1)
530 : {
531 : /*
532 : * Align to int64_t boundary and fill.
533 : */
534 54579 : for (; n && !isAligned(cp, int64_t); n--)
535 26493 : *cp++ = 0xff;
536 28086 : lp = (int64_t *)cp;
537 28086 : nw = (int32_t)(n / sizeof(int64_t));
538 28086 : n -= nw * sizeof(int64_t);
539 : do
540 : {
541 311441 : *lp++ = -1L;
542 311441 : } while (--nw);
543 28086 : cp = (unsigned char *)lp;
544 : }
545 226601 : FILL(n, cp);
546 41944 : run &= 7;
547 : }
548 : /* Explicit 0xff masking to make icc -check=conversions happy */
549 47609 : if (run)
550 22430 : cp[0] = (unsigned char)((cp[0] | (0xff00 >> run)) & 0xff);
551 : }
552 : else
553 11927 : cp[0] |= _fillmasks[run] >> bx;
554 59536 : x += runs[1];
555 : }
556 : }
557 23917 : assert(x == lastx);
558 23917 : }
559 : #undef ZERO
560 : #undef FILL
561 :
562 53 : static int Fax3FixupTags(TIFF *tif)
563 : {
564 : (void)tif;
565 53 : return (1);
566 : }
567 :
568 : /*
569 : * Setup G3/G4-related compression/decompression state
570 : * before data is processed. This routine is called once
571 : * per image -- it sets up different state based on whether
572 : * or not decoding or encoding is being done and whether
573 : * 1D- or 2D-encoded data is involved.
574 : */
575 22 : static int Fax3SetupState(TIFF *tif)
576 : {
577 : static const char module[] = "Fax3SetupState";
578 22 : TIFFDirectory *td = &tif->tif_dir;
579 22 : Fax3BaseState *sp = Fax3State(tif);
580 : int needsRefLine;
581 22 : Fax3CodecState *dsp = (Fax3CodecState *)Fax3State(tif);
582 : tmsize_t rowbytes;
583 : uint32_t rowpixels;
584 :
585 22 : if (td->td_bitspersample != 1)
586 : {
587 0 : TIFFErrorExtR(tif, module,
588 : "Bits/sample must be 1 for Group 3/4 encoding/decoding");
589 0 : return (0);
590 : }
591 22 : if (td->td_samplesperpixel != 1 &&
592 0 : td->td_planarconfig != PLANARCONFIG_SEPARATE)
593 : {
594 0 : TIFFErrorExtR(
595 : tif, module,
596 : "Samples/pixel shall be 1 for Group 3/4 encoding/decoding, "
597 : "or PlanarConfiguration must be set to Separate.");
598 0 : return 0;
599 : }
600 : /*
601 : * Calculate the scanline/tile widths.
602 : */
603 22 : if (isTiled(tif))
604 : {
605 0 : rowbytes = TIFFTileRowSize(tif);
606 0 : rowpixels = td->td_tilewidth;
607 : }
608 : else
609 : {
610 22 : rowbytes = TIFFScanlineSize(tif);
611 22 : rowpixels = td->td_imagewidth;
612 : }
613 22 : if ((int64_t)rowbytes < ((int64_t)rowpixels + 7) / 8)
614 : {
615 0 : TIFFErrorExtR(tif, module,
616 : "Inconsistent number of bytes per row : rowbytes=%" PRId64
617 : " rowpixels=%" PRIu32,
618 : (int64_t)rowbytes, rowpixels);
619 0 : return (0);
620 : }
621 22 : sp->rowbytes = rowbytes;
622 22 : sp->rowpixels = rowpixels;
623 : /*
624 : * Allocate any additional space required for decoding/encoding.
625 : */
626 43 : needsRefLine = ((sp->groupoptions & GROUP3OPT_2DENCODING) ||
627 21 : td->td_compression == COMPRESSION_CCITTFAX4);
628 :
629 : /*
630 : Assure that allocation computations do not overflow.
631 :
632 : TIFFroundup and TIFFSafeMultiply return zero on integer overflow
633 : */
634 22 : if (dsp->runs != NULL)
635 : {
636 0 : _TIFFfreeExt(tif, dsp->runs);
637 0 : dsp->runs = (uint32_t *)NULL;
638 : }
639 22 : dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
640 22 : if (needsRefLine)
641 : {
642 18 : dsp->nruns = TIFFSafeMultiply(uint32_t, dsp->nruns, 2);
643 : }
644 22 : if ((dsp->nruns == 0) || (TIFFSafeMultiply(uint32_t, dsp->nruns, 2) == 0))
645 : {
646 0 : TIFFErrorExtR(tif, tif->tif_name,
647 : "Row pixels integer overflow (rowpixels %" PRIu32 ")",
648 : rowpixels);
649 0 : return (0);
650 : }
651 22 : dsp->runs = (uint32_t *)_TIFFCheckMalloc(
652 22 : tif, TIFFSafeMultiply(uint32_t, dsp->nruns, 2), sizeof(uint32_t),
653 : "for Group 3/4 run arrays");
654 22 : if (dsp->runs == NULL)
655 0 : return (0);
656 0 : memset(dsp->runs, 0,
657 22 : TIFFSafeMultiply(uint32_t, dsp->nruns, 2) * sizeof(uint32_t));
658 22 : dsp->curruns = dsp->runs;
659 22 : if (needsRefLine)
660 18 : dsp->refruns = dsp->runs + dsp->nruns;
661 : else
662 4 : dsp->refruns = NULL;
663 22 : if (td->td_compression == COMPRESSION_CCITTFAX3 && is2DEncoding(dsp))
664 : { /* NB: default is 1D routine */
665 1 : tif->tif_decoderow = Fax3Decode2D;
666 1 : tif->tif_decodestrip = Fax3Decode2D;
667 1 : tif->tif_decodetile = Fax3Decode2D;
668 : }
669 :
670 22 : if (needsRefLine)
671 : { /* 2d encoding */
672 18 : Fax3CodecState *esp = EncoderState(tif);
673 : /*
674 : * 2d encoding requires a scanline
675 : * buffer for the ``reference line''; the
676 : * scanline against which delta encoding
677 : * is referenced. The reference line must
678 : * be initialized to be ``white'' (done elsewhere).
679 : */
680 18 : if (esp->refline != NULL)
681 : {
682 0 : _TIFFfreeExt(tif, esp->refline);
683 : }
684 18 : esp->refline = (unsigned char *)_TIFFmallocExt(tif, rowbytes);
685 18 : if (esp->refline == NULL)
686 : {
687 0 : TIFFErrorExtR(tif, module, "No space for Group 3/4 reference line");
688 0 : return (0);
689 : }
690 : }
691 : else /* 1d encoding */
692 4 : EncoderState(tif)->refline = NULL;
693 :
694 22 : return (1);
695 : }
696 :
697 : /*
698 : * CCITT Group 3 FAX Encoding.
699 : */
700 :
701 : #define Fax3FlushBits(tif, sp) \
702 : { \
703 : if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
704 : { \
705 : if (!TIFFFlushData1(tif)) \
706 : return 0; \
707 : } \
708 : *(tif)->tif_rawcp++ = (uint8_t)(sp)->data; \
709 : (tif)->tif_rawcc++; \
710 : (sp)->data = 0, (sp)->bit = 8; \
711 : }
712 : #define _FlushBits(tif) \
713 : { \
714 : if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
715 : { \
716 : if (!TIFFFlushData1(tif)) \
717 : return 0; \
718 : } \
719 : *(tif)->tif_rawcp++ = (uint8_t)data; \
720 : (tif)->tif_rawcc++; \
721 : data = 0, bit = 8; \
722 : }
723 : static const int _msbmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f,
724 : 0x1f, 0x3f, 0x7f, 0xff};
725 : #define _PutBits(tif, bits, length) \
726 : { \
727 : while (length > bit) \
728 : { \
729 : data |= bits >> (length - bit); \
730 : length -= bit; \
731 : _FlushBits(tif); \
732 : } \
733 : assert(length < 9); \
734 : data |= (bits & _msbmask[length]) << (bit - length); \
735 : bit -= length; \
736 : if (bit == 0) \
737 : _FlushBits(tif); \
738 : }
739 :
740 : /*
741 : * Write a variable-length bit-value to
742 : * the output stream. Values are
743 : * assumed to be at most 16 bits.
744 : */
745 43734 : static int Fax3PutBits(TIFF *tif, unsigned int bits, unsigned int length)
746 : {
747 43734 : Fax3CodecState *sp = EncoderState(tif);
748 43734 : unsigned int bit = sp->bit;
749 43734 : int data = sp->data;
750 :
751 50366 : _PutBits(tif, bits, length);
752 :
753 43734 : sp->data = data;
754 43734 : sp->bit = bit;
755 43734 : return 1;
756 : }
757 :
758 : /*
759 : * Write a code to the output stream.
760 : */
761 : #define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
762 :
763 : #ifdef FAX3_DEBUG
764 : #define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
765 : #define DEBUG_PRINT(what, len) \
766 : { \
767 : int t; \
768 : printf("%08" PRIX32 "/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), \
769 : len); \
770 : for (t = length - 1; t >= 0; t--) \
771 : putchar(code & (1 << t) ? '1' : '0'); \
772 : putchar('\n'); \
773 : }
774 : #endif
775 :
776 : /*
777 : * Write the sequence of codes that describes
778 : * the specified span of zero's or one's. The
779 : * appropriate table that holds the make-up and
780 : * terminating codes is supplied.
781 : */
782 13030 : static int putspan(TIFF *tif, int32_t span, const tableentry *tab)
783 : {
784 13030 : Fax3CodecState *sp = EncoderState(tif);
785 13030 : unsigned int bit = sp->bit;
786 13030 : int data = sp->data;
787 : unsigned int code, length;
788 :
789 13030 : while (span >= 2624)
790 : {
791 0 : const tableentry *te = &tab[63 + (2560 >> 6)];
792 0 : code = te->code;
793 0 : length = te->length;
794 : #ifdef FAX3_DEBUG
795 : DEBUG_PRINT("MakeUp", te->runlen);
796 : #endif
797 0 : _PutBits(tif, code, length);
798 0 : span -= te->runlen;
799 : }
800 13030 : if (span >= 64)
801 : {
802 418 : const tableentry *te = &tab[63 + (span >> 6)];
803 418 : assert(te->runlen == 64 * (span >> 6));
804 418 : code = te->code;
805 418 : length = te->length;
806 : #ifdef FAX3_DEBUG
807 : DEBUG_PRINT("MakeUp", te->runlen);
808 : #endif
809 969 : _PutBits(tif, code, length);
810 418 : span -= te->runlen;
811 : }
812 13030 : code = tab[span].code;
813 13030 : length = tab[span].length;
814 : #ifdef FAX3_DEBUG
815 : DEBUG_PRINT(" Term", tab[span].runlen);
816 : #endif
817 19233 : _PutBits(tif, code, length);
818 :
819 13030 : sp->data = data;
820 13030 : sp->bit = bit;
821 :
822 13030 : return 1;
823 : }
824 :
825 : /*
826 : * Write an EOL code to the output stream. The zero-fill
827 : * logic for byte-aligning encoded scanlines is handled
828 : * here. We also handle writing the tag bit for the next
829 : * scanline when doing 2d encoding.
830 : */
831 99 : static int Fax3PutEOL(TIFF *tif)
832 : {
833 99 : Fax3CodecState *sp = EncoderState(tif);
834 99 : unsigned int bit = sp->bit;
835 99 : int data = sp->data;
836 : unsigned int code, length, tparm;
837 :
838 99 : if (sp->b.groupoptions & GROUP3OPT_FILLBITS)
839 : {
840 : /*
841 : * Force bit alignment so EOL will terminate on
842 : * a byte boundary. That is, force the bit alignment
843 : * to 16-12 = 4 before putting out the EOL code.
844 : */
845 0 : int align = 8 - 4;
846 0 : if (align != sp->bit)
847 : {
848 0 : if (align > sp->bit)
849 0 : align = sp->bit + (8 - align);
850 : else
851 0 : align = sp->bit - align;
852 0 : tparm = align;
853 0 : _PutBits(tif, 0, tparm);
854 : }
855 : }
856 99 : code = EOL;
857 99 : length = 12;
858 99 : if (is2DEncoding(sp))
859 : {
860 0 : code = (code << 1) | (sp->tag == G3_1D);
861 0 : length++;
862 : }
863 242 : _PutBits(tif, code, length);
864 :
865 99 : sp->data = data;
866 99 : sp->bit = bit;
867 :
868 99 : return 1;
869 : }
870 :
871 : /*
872 : * Reset encoding state at the start of a strip.
873 : */
874 9 : static int Fax3PreEncode(TIFF *tif, uint16_t s)
875 : {
876 9 : Fax3CodecState *sp = EncoderState(tif);
877 :
878 : (void)s;
879 9 : assert(sp != NULL);
880 9 : sp->bit = 8;
881 9 : sp->data = 0;
882 9 : sp->tag = G3_1D;
883 : /*
884 : * This is necessary for Group 4; otherwise it isn't
885 : * needed because the first scanline of each strip ends
886 : * up being copied into the refline.
887 : */
888 9 : if (sp->refline)
889 7 : _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
890 9 : if (is2DEncoding(sp))
891 : {
892 0 : float res = tif->tif_dir.td_yresolution;
893 : /*
894 : * The CCITT spec says that when doing 2d encoding, you
895 : * should only do it on K consecutive scanlines, where K
896 : * depends on the resolution of the image being encoded
897 : * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory
898 : * code initializes td_yresolution to 0, this code will
899 : * select a K of 2 unless the YResolution tag is set
900 : * appropriately. (Note also that we fudge a little here
901 : * and use 150 lpi to avoid problems with units conversion.)
902 : */
903 0 : if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER)
904 0 : res *= 2.54f; /* convert to inches */
905 0 : sp->maxk = (res > 150 ? 4 : 2);
906 0 : sp->k = sp->maxk - 1;
907 : }
908 : else
909 9 : sp->k = sp->maxk = 0;
910 9 : sp->line = 0;
911 9 : return (1);
912 : }
913 :
914 : static const unsigned char zeroruns[256] = {
915 : 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
916 : 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
917 : 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
918 : 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
919 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
920 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
921 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
922 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
923 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
924 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
925 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
926 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
927 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
928 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
929 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
930 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
931 : };
932 : static const unsigned char oneruns[256] = {
933 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
934 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
935 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
936 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
937 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
938 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
939 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
940 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
941 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
942 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
943 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
944 : 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
945 : 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
946 : 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
947 : 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
948 : 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
949 : };
950 :
951 : /*
952 : * Find a span of ones or zeros using the supplied
953 : * table. The ``base'' of the bit string is supplied
954 : * along with the start+end bit indices.
955 : */
956 69633 : static inline int32_t find0span(unsigned char *bp, int32_t bs, int32_t be)
957 : {
958 69633 : int32_t bits = be - bs;
959 : int32_t n, span;
960 :
961 69633 : bp += bs >> 3;
962 : /*
963 : * Check partial byte on lhs.
964 : */
965 69633 : if (bits > 0 && (n = (bs & 7)) != 0)
966 : {
967 53657 : span = zeroruns[(*bp << n) & 0xff];
968 53657 : if (span > 8 - n) /* table value too generous */
969 29826 : span = 8 - n;
970 53657 : if (span > bits) /* constrain span to bit range */
971 359 : span = bits;
972 53657 : if (n + span < 8) /* doesn't extend to edge of byte */
973 24190 : return (span);
974 29467 : bits -= span;
975 29467 : bp++;
976 : }
977 : else
978 15976 : span = 0;
979 45443 : if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
980 : {
981 : int64_t *lp;
982 : /*
983 : * Align to int64_t boundary and check int64_t words.
984 : */
985 54272 : while (!isAligned(bp, int64_t))
986 : {
987 38361 : if (*bp != 0x00)
988 15909 : return (span + zeroruns[*bp]);
989 22452 : span += 8;
990 22452 : bits -= 8;
991 22452 : bp++;
992 : }
993 15911 : lp = (int64_t *)bp;
994 17290 : while ((bits >= (int32_t)(8 * sizeof(int64_t))) && (0 == *lp))
995 : {
996 1379 : span += 8 * sizeof(int64_t);
997 1379 : bits -= 8 * sizeof(int64_t);
998 1379 : lp++;
999 : }
1000 15911 : bp = (unsigned char *)lp;
1001 : }
1002 : /*
1003 : * Scan full bytes for all 0's.
1004 : */
1005 50893 : while (bits >= 8)
1006 : {
1007 48775 : if (*bp != 0x00) /* end of run */
1008 27416 : return (span + zeroruns[*bp]);
1009 21359 : span += 8;
1010 21359 : bits -= 8;
1011 21359 : bp++;
1012 : }
1013 : /*
1014 : * Check partial byte on rhs.
1015 : */
1016 2118 : if (bits > 0)
1017 : {
1018 2002 : n = zeroruns[*bp];
1019 2002 : span += (n > bits ? bits : n);
1020 : }
1021 2118 : return (span);
1022 : }
1023 :
1024 83357 : static inline int32_t find1span(unsigned char *bp, int32_t bs, int32_t be)
1025 : {
1026 83357 : int32_t bits = be - bs;
1027 : int32_t n, span;
1028 :
1029 83357 : bp += bs >> 3;
1030 : /*
1031 : * Check partial byte on lhs.
1032 : */
1033 83357 : if (bits > 0 && (n = (bs & 7)) != 0)
1034 : {
1035 53819 : span = oneruns[(*bp << n) & 0xff];
1036 53819 : if (span > 8 - n) /* table value too generous */
1037 0 : span = 8 - n;
1038 53819 : if (span > bits) /* constrain span to bit range */
1039 0 : span = bits;
1040 53819 : if (n + span < 8) /* doesn't extend to edge of byte */
1041 24458 : return (span);
1042 29361 : bits -= span;
1043 29361 : bp++;
1044 : }
1045 : else
1046 29538 : span = 0;
1047 58899 : if (bits >= (int32_t)(2 * 8 * sizeof(int64_t)))
1048 : {
1049 : int64_t *lp;
1050 : /*
1051 : * Align to int64_t boundary and check int64_t words.
1052 : */
1053 94760 : while (!isAligned(bp, int64_t))
1054 : {
1055 61078 : if (*bp != 0xff)
1056 11996 : return (span + oneruns[*bp]);
1057 49082 : span += 8;
1058 49082 : bits -= 8;
1059 49082 : bp++;
1060 : }
1061 33682 : lp = (int64_t *)bp;
1062 338421 : while ((bits >= (int32_t)(8 * sizeof(int64_t))) &&
1063 317978 : (~((uint64_t)0) == (uint64_t)*lp))
1064 : {
1065 304739 : span += 8 * sizeof(int64_t);
1066 304739 : bits -= 8 * sizeof(int64_t);
1067 304739 : lp++;
1068 : }
1069 33682 : bp = (unsigned char *)lp;
1070 : }
1071 : /*
1072 : * Scan full bytes for all 1's.
1073 : */
1074 206691 : while (bits >= 8)
1075 : {
1076 184031 : if (*bp != 0xff) /* end of run */
1077 24243 : return (span + oneruns[*bp]);
1078 159788 : span += 8;
1079 159788 : bits -= 8;
1080 159788 : bp++;
1081 : }
1082 : /*
1083 : * Check partial byte on rhs.
1084 : */
1085 22660 : if (bits > 0)
1086 : {
1087 888 : n = oneruns[*bp];
1088 888 : span += (n > bits ? bits : n);
1089 : }
1090 22660 : return (span);
1091 : }
1092 :
1093 : /*
1094 : * Return the offset of the next bit in the range
1095 : * [bs..be] that is different from the specified
1096 : * color. The end, be, is returned if no such bit
1097 : * exists.
1098 : */
1099 : #define finddiff(_cp, _bs, _be, _color) \
1100 : (_bs + (_color ? find1span(_cp, _bs, _be) : find0span(_cp, _bs, _be)))
1101 : /*
1102 : * Like finddiff, but also check the starting bit
1103 : * against the end in case start > end.
1104 : */
1105 : #define finddiff2(_cp, _bs, _be, _color) \
1106 : (_bs < _be ? finddiff(_cp, _bs, _be, _color) : _be)
1107 :
1108 : /*
1109 : * 1d-encode a row of pixels. The encoding is
1110 : * a sequence of all-white or all-black spans
1111 : * of pixels encoded with Huffman codes.
1112 : */
1113 198 : static int Fax3Encode1DRow(TIFF *tif, unsigned char *bp, uint32_t bits)
1114 : {
1115 198 : Fax3CodecState *sp = EncoderState(tif);
1116 : int32_t span;
1117 198 : uint32_t bs = 0;
1118 :
1119 : for (;;)
1120 : {
1121 2646 : span = find0span(bp, bs, bits); /* white span */
1122 2646 : if (!putspan(tif, span, TIFFFaxWhiteCodes))
1123 0 : return 0;
1124 2646 : bs += span;
1125 2646 : if (bs >= bits)
1126 52 : break;
1127 2594 : span = find1span(bp, bs, bits); /* black span */
1128 2594 : if (!putspan(tif, span, TIFFFaxBlackCodes))
1129 0 : return 0;
1130 2594 : bs += span;
1131 2594 : if (bs >= bits)
1132 146 : break;
1133 : }
1134 198 : if (sp->b.mode & (FAXMODE_BYTEALIGN | FAXMODE_WORDALIGN))
1135 : {
1136 99 : if (sp->bit != 8) /* byte-align */
1137 89 : Fax3FlushBits(tif, sp);
1138 99 : if ((sp->b.mode & FAXMODE_WORDALIGN) &&
1139 0 : !isAligned(tif->tif_rawcp, uint16_t))
1140 0 : Fax3FlushBits(tif, sp);
1141 : }
1142 198 : return (1);
1143 : }
1144 :
1145 : static const tableentry horizcode = {3, 0x1, 0}; /* 001 */
1146 : static const tableentry passcode = {4, 0x1, 0}; /* 0001 */
1147 : static const tableentry vcodes[7] = {
1148 : {7, 0x03, 0}, /* 0000 011 */
1149 : {6, 0x03, 0}, /* 0000 11 */
1150 : {3, 0x03, 0}, /* 011 */
1151 : {1, 0x1, 0}, /* 1 */
1152 : {3, 0x2, 0}, /* 010 */
1153 : {6, 0x02, 0}, /* 0000 10 */
1154 : {7, 0x02, 0} /* 0000 010 */
1155 : };
1156 :
1157 : /*
1158 : * 2d-encode a row of pixels. Consult the CCITT
1159 : * documentation for the algorithm.
1160 : */
1161 7897 : static int Fax3Encode2DRow(TIFF *tif, unsigned char *bp, unsigned char *rp,
1162 : uint32_t bits)
1163 : {
1164 : #define PIXEL(buf, ix) ((((buf)[(ix) >> 3]) >> (7 - ((ix)&7))) & 1)
1165 7897 : uint32_t a0 = 0;
1166 7897 : uint32_t a1 = (PIXEL(bp, 0) != 0 ? 0 : finddiff(bp, 0, bits, 0));
1167 7897 : uint32_t b1 = (PIXEL(rp, 0) != 0 ? 0 : finddiff(rp, 0, bits, 0));
1168 : uint32_t a2, b2;
1169 :
1170 : for (;;)
1171 : {
1172 43720 : b2 = finddiff2(rp, b1, bits, PIXEL(rp, b1));
1173 43720 : if (b2 >= a1)
1174 : {
1175 : /* Naive computation triggers
1176 : * -fsanitize=undefined,unsigned-integer-overflow */
1177 : /* although it is correct unless the difference between both is < 31
1178 : * bit */
1179 : /* int32_t d = b1 - a1; */
1180 36175 : int32_t d = (b1 >= a1 && b1 - a1 <= 3U) ? (int32_t)(b1 - a1)
1181 86693 : : (b1 < a1 && a1 - b1 <= 3U) ? -(int32_t)(a1 - b1)
1182 13042 : : 0x7FFFFFFF;
1183 40956 : if (!(-3 <= d && d <= 3))
1184 : { /* horizontal mode */
1185 3895 : a2 = finddiff2(bp, a1, bits, PIXEL(bp, a1));
1186 3895 : if (!putcode(tif, &horizcode))
1187 0 : return 0;
1188 3895 : if (a0 + a1 == 0 || PIXEL(bp, a0) == 0)
1189 : {
1190 1950 : if (!putspan(tif, a1 - a0, TIFFFaxWhiteCodes))
1191 0 : return 0;
1192 1950 : if (!putspan(tif, a2 - a1, TIFFFaxBlackCodes))
1193 0 : return 0;
1194 : }
1195 : else
1196 : {
1197 1945 : if (!putspan(tif, a1 - a0, TIFFFaxBlackCodes))
1198 0 : return 0;
1199 1945 : if (!putspan(tif, a2 - a1, TIFFFaxWhiteCodes))
1200 0 : return 0;
1201 : }
1202 3895 : a0 = a2;
1203 : }
1204 : else
1205 : { /* vertical mode */
1206 37061 : if (!putcode(tif, &vcodes[d + 3]))
1207 0 : return 0;
1208 37061 : a0 = a1;
1209 : }
1210 : }
1211 : else
1212 : { /* pass mode */
1213 2764 : if (!putcode(tif, &passcode))
1214 0 : return 0;
1215 2764 : a0 = b2;
1216 : }
1217 43720 : if (a0 >= bits)
1218 7897 : break;
1219 35823 : a1 = finddiff(bp, a0, bits, PIXEL(bp, a0));
1220 35823 : b1 = finddiff(rp, a0, bits, !PIXEL(bp, a0));
1221 35823 : b1 = finddiff(rp, b1, bits, PIXEL(bp, a0));
1222 : }
1223 7897 : return (1);
1224 : #undef PIXEL
1225 : }
1226 :
1227 : /*
1228 : * Encode a buffer of pixels.
1229 : */
1230 2 : static int Fax3Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1231 : {
1232 : static const char module[] = "Fax3Encode";
1233 2 : Fax3CodecState *sp = EncoderState(tif);
1234 : (void)s;
1235 2 : if (cc % sp->b.rowbytes)
1236 : {
1237 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1238 0 : return (0);
1239 : }
1240 200 : while (cc > 0)
1241 : {
1242 198 : if ((sp->b.mode & FAXMODE_NOEOL) == 0)
1243 : {
1244 99 : if (!Fax3PutEOL(tif))
1245 0 : return 0;
1246 : }
1247 198 : if (is2DEncoding(sp))
1248 : {
1249 0 : if (sp->tag == G3_1D)
1250 : {
1251 0 : if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1252 0 : return (0);
1253 0 : sp->tag = G3_2D;
1254 : }
1255 : else
1256 : {
1257 0 : if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1258 0 : return (0);
1259 0 : sp->k--;
1260 : }
1261 0 : if (sp->k == 0)
1262 : {
1263 0 : sp->tag = G3_1D;
1264 0 : sp->k = sp->maxk - 1;
1265 : }
1266 : else
1267 0 : _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1268 : }
1269 : else
1270 : {
1271 198 : if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
1272 0 : return (0);
1273 : }
1274 198 : bp += sp->b.rowbytes;
1275 198 : cc -= sp->b.rowbytes;
1276 : }
1277 2 : return (1);
1278 : }
1279 :
1280 2 : static int Fax3PostEncode(TIFF *tif)
1281 : {
1282 2 : Fax3CodecState *sp = EncoderState(tif);
1283 :
1284 2 : if (sp->bit != 8)
1285 1 : Fax3FlushBits(tif, sp);
1286 2 : return (1);
1287 : }
1288 :
1289 17 : static int _Fax3Close(TIFF *tif)
1290 : {
1291 17 : if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0 && tif->tif_rawcp)
1292 : {
1293 0 : Fax3CodecState *sp = EncoderState(tif);
1294 0 : unsigned int code = EOL;
1295 0 : unsigned int length = 12;
1296 : int i;
1297 :
1298 0 : if (is2DEncoding(sp))
1299 : {
1300 0 : code = (code << 1) | (sp->tag == G3_1D);
1301 0 : length++;
1302 : }
1303 0 : for (i = 0; i < 6; i++)
1304 0 : Fax3PutBits(tif, code, length);
1305 0 : Fax3FlushBits(tif, sp);
1306 : }
1307 17 : return 1;
1308 : }
1309 :
1310 17 : static void Fax3Close(TIFF *tif) { _Fax3Close(tif); }
1311 :
1312 70 : static void Fax3Cleanup(TIFF *tif)
1313 : {
1314 70 : Fax3CodecState *sp = DecoderState(tif);
1315 :
1316 70 : assert(sp != 0);
1317 :
1318 70 : tif->tif_tagmethods.vgetfield = sp->b.vgetparent;
1319 70 : tif->tif_tagmethods.vsetfield = sp->b.vsetparent;
1320 70 : tif->tif_tagmethods.printdir = sp->b.printdir;
1321 :
1322 70 : if (sp->runs)
1323 22 : _TIFFfreeExt(tif, sp->runs);
1324 70 : if (sp->refline)
1325 18 : _TIFFfreeExt(tif, sp->refline);
1326 :
1327 70 : _TIFFfreeExt(tif, tif->tif_data);
1328 70 : tif->tif_data = NULL;
1329 :
1330 70 : _TIFFSetDefaultCompressionState(tif);
1331 70 : }
1332 :
1333 : #define FIELD_BADFAXLINES (FIELD_CODEC + 0)
1334 : #define FIELD_CLEANFAXDATA (FIELD_CODEC + 1)
1335 : #define FIELD_BADFAXRUN (FIELD_CODEC + 2)
1336 :
1337 : #define FIELD_OPTIONS (FIELD_CODEC + 7)
1338 :
1339 : static const TIFFField faxFields[] = {
1340 : {TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO, FALSE,
1341 : FALSE, "FaxMode", NULL},
1342 : {TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, 0, TIFF_SETGET_OTHER, FIELD_PSEUDO,
1343 : FALSE, FALSE, "FaxFillFunc", NULL},
1344 : {TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1345 : FIELD_BADFAXLINES, TRUE, FALSE, "BadFaxLines", NULL},
1346 : {TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16,
1347 : FIELD_CLEANFAXDATA, TRUE, FALSE, "CleanFaxData", NULL},
1348 : {TIFFTAG_CONSECUTIVEBADFAXLINES, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1349 : FIELD_BADFAXRUN, TRUE, FALSE, "ConsecutiveBadFaxLines", NULL}};
1350 : static const TIFFField fax3Fields[] = {
1351 : {TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1352 : FIELD_OPTIONS, FALSE, FALSE, "Group3Options", NULL},
1353 : };
1354 : static const TIFFField fax4Fields[] = {
1355 : {TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32,
1356 : FIELD_OPTIONS, FALSE, FALSE, "Group4Options", NULL},
1357 : };
1358 :
1359 616 : static int Fax3VSetField(TIFF *tif, uint32_t tag, va_list ap)
1360 : {
1361 616 : Fax3BaseState *sp = Fax3State(tif);
1362 : const TIFFField *fip;
1363 :
1364 616 : assert(sp != 0);
1365 616 : assert(sp->vsetparent != 0);
1366 :
1367 616 : switch (tag)
1368 : {
1369 70 : case TIFFTAG_FAXMODE:
1370 70 : sp->mode = (int)va_arg(ap, int);
1371 70 : return 1; /* NB: pseudo tag */
1372 70 : case TIFFTAG_FAXFILLFUNC:
1373 70 : DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
1374 70 : return 1; /* NB: pseudo tag */
1375 2 : case TIFFTAG_GROUP3OPTIONS:
1376 : /* XXX: avoid reading options if compression mismatches. */
1377 2 : if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX3)
1378 2 : sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1379 2 : break;
1380 0 : case TIFFTAG_GROUP4OPTIONS:
1381 : /* XXX: avoid reading options if compression mismatches. */
1382 0 : if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1383 0 : sp->groupoptions = (uint32_t)va_arg(ap, uint32_t);
1384 0 : break;
1385 0 : case TIFFTAG_BADFAXLINES:
1386 0 : sp->badfaxlines = (uint32_t)va_arg(ap, uint32_t);
1387 0 : break;
1388 0 : case TIFFTAG_CLEANFAXDATA:
1389 0 : sp->cleanfaxdata = (uint16_t)va_arg(ap, uint16_vap);
1390 0 : break;
1391 0 : case TIFFTAG_CONSECUTIVEBADFAXLINES:
1392 0 : sp->badfaxrun = (uint32_t)va_arg(ap, uint32_t);
1393 0 : break;
1394 474 : default:
1395 474 : return (*sp->vsetparent)(tif, tag, ap);
1396 : }
1397 :
1398 2 : if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
1399 2 : TIFFSetFieldBit(tif, fip->field_bit);
1400 : else
1401 0 : return 0;
1402 :
1403 2 : tif->tif_flags |= TIFF_DIRTYDIRECT;
1404 2 : return 1;
1405 : }
1406 :
1407 741 : static int Fax3VGetField(TIFF *tif, uint32_t tag, va_list ap)
1408 : {
1409 741 : Fax3BaseState *sp = Fax3State(tif);
1410 :
1411 741 : assert(sp != 0);
1412 :
1413 741 : switch (tag)
1414 : {
1415 0 : case TIFFTAG_FAXMODE:
1416 0 : *va_arg(ap, int *) = sp->mode;
1417 0 : break;
1418 0 : case TIFFTAG_FAXFILLFUNC:
1419 0 : *va_arg(ap, TIFFFaxFillFunc *) = DecoderState(tif)->fill;
1420 0 : break;
1421 2 : case TIFFTAG_GROUP3OPTIONS:
1422 : case TIFFTAG_GROUP4OPTIONS:
1423 2 : *va_arg(ap, uint32_t *) = sp->groupoptions;
1424 2 : break;
1425 0 : case TIFFTAG_BADFAXLINES:
1426 0 : *va_arg(ap, uint32_t *) = sp->badfaxlines;
1427 0 : break;
1428 0 : case TIFFTAG_CLEANFAXDATA:
1429 0 : *va_arg(ap, uint16_t *) = sp->cleanfaxdata;
1430 0 : break;
1431 0 : case TIFFTAG_CONSECUTIVEBADFAXLINES:
1432 0 : *va_arg(ap, uint32_t *) = sp->badfaxrun;
1433 0 : break;
1434 739 : default:
1435 739 : return (*sp->vgetparent)(tif, tag, ap);
1436 : }
1437 2 : return (1);
1438 : }
1439 :
1440 0 : static void Fax3PrintDir(TIFF *tif, FILE *fd, long flags)
1441 : {
1442 0 : Fax3BaseState *sp = Fax3State(tif);
1443 :
1444 0 : assert(sp != 0);
1445 :
1446 : (void)flags;
1447 0 : if (TIFFFieldSet(tif, FIELD_OPTIONS))
1448 : {
1449 0 : const char *sep = " ";
1450 0 : if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
1451 : {
1452 0 : fprintf(fd, " Group 4 Options:");
1453 0 : if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED)
1454 0 : fprintf(fd, "%suncompressed data", sep);
1455 : }
1456 : else
1457 : {
1458 :
1459 0 : fprintf(fd, " Group 3 Options:");
1460 0 : if (sp->groupoptions & GROUP3OPT_2DENCODING)
1461 : {
1462 0 : fprintf(fd, "%s2-d encoding", sep);
1463 0 : sep = "+";
1464 : }
1465 0 : if (sp->groupoptions & GROUP3OPT_FILLBITS)
1466 : {
1467 0 : fprintf(fd, "%sEOL padding", sep);
1468 0 : sep = "+";
1469 : }
1470 0 : if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
1471 0 : fprintf(fd, "%suncompressed data", sep);
1472 : }
1473 0 : fprintf(fd, " (%" PRIu32 " = 0x%" PRIx32 ")\n", sp->groupoptions,
1474 : sp->groupoptions);
1475 : }
1476 0 : if (TIFFFieldSet(tif, FIELD_CLEANFAXDATA))
1477 : {
1478 0 : fprintf(fd, " Fax Data:");
1479 0 : switch (sp->cleanfaxdata)
1480 : {
1481 0 : case CLEANFAXDATA_CLEAN:
1482 0 : fprintf(fd, " clean");
1483 0 : break;
1484 0 : case CLEANFAXDATA_REGENERATED:
1485 0 : fprintf(fd, " receiver regenerated");
1486 0 : break;
1487 0 : case CLEANFAXDATA_UNCLEAN:
1488 0 : fprintf(fd, " uncorrected errors");
1489 0 : break;
1490 : }
1491 0 : fprintf(fd, " (%" PRIu16 " = 0x%" PRIx16 ")\n", sp->cleanfaxdata,
1492 0 : sp->cleanfaxdata);
1493 : }
1494 0 : if (TIFFFieldSet(tif, FIELD_BADFAXLINES))
1495 0 : fprintf(fd, " Bad Fax Lines: %" PRIu32 "\n", sp->badfaxlines);
1496 0 : if (TIFFFieldSet(tif, FIELD_BADFAXRUN))
1497 0 : fprintf(fd, " Consecutive Bad Fax Lines: %" PRIu32 "\n",
1498 : sp->badfaxrun);
1499 0 : if (sp->printdir)
1500 0 : (*sp->printdir)(tif, fd, flags);
1501 0 : }
1502 :
1503 70 : static int InitCCITTFax3(TIFF *tif)
1504 : {
1505 : static const char module[] = "InitCCITTFax3";
1506 : Fax3BaseState *sp;
1507 :
1508 : /*
1509 : * Merge codec-specific tag information.
1510 : */
1511 70 : if (!_TIFFMergeFields(tif, faxFields, TIFFArrayCount(faxFields)))
1512 : {
1513 0 : TIFFErrorExtR(tif, "InitCCITTFax3",
1514 : "Merging common CCITT Fax codec-specific tags failed");
1515 0 : return 0;
1516 : }
1517 :
1518 : /*
1519 : * Allocate state block so tag methods have storage to record values.
1520 : */
1521 70 : tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(Fax3CodecState));
1522 :
1523 70 : if (tif->tif_data == NULL)
1524 : {
1525 0 : TIFFErrorExtR(tif, module, "No space for state block");
1526 0 : return (0);
1527 : }
1528 70 : _TIFFmemset(tif->tif_data, 0, sizeof(Fax3CodecState));
1529 :
1530 70 : sp = Fax3State(tif);
1531 70 : sp->rw_mode = tif->tif_mode;
1532 :
1533 : /*
1534 : * Override parent get/set field methods.
1535 : */
1536 70 : sp->vgetparent = tif->tif_tagmethods.vgetfield;
1537 70 : tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
1538 70 : sp->vsetparent = tif->tif_tagmethods.vsetfield;
1539 70 : tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
1540 70 : sp->printdir = tif->tif_tagmethods.printdir;
1541 70 : tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
1542 70 : sp->groupoptions = 0;
1543 :
1544 70 : if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
1545 25 : tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
1546 70 : DecoderState(tif)->runs = NULL;
1547 70 : TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
1548 70 : EncoderState(tif)->refline = NULL;
1549 :
1550 : /*
1551 : * Install codec methods.
1552 : */
1553 70 : tif->tif_fixuptags = Fax3FixupTags;
1554 70 : tif->tif_setupdecode = Fax3SetupState;
1555 70 : tif->tif_predecode = Fax3PreDecode;
1556 70 : tif->tif_decoderow = Fax3Decode1D;
1557 70 : tif->tif_decodestrip = Fax3Decode1D;
1558 70 : tif->tif_decodetile = Fax3Decode1D;
1559 70 : tif->tif_setupencode = Fax3SetupState;
1560 70 : tif->tif_preencode = Fax3PreEncode;
1561 70 : tif->tif_postencode = Fax3PostEncode;
1562 70 : tif->tif_encoderow = Fax3Encode;
1563 70 : tif->tif_encodestrip = Fax3Encode;
1564 70 : tif->tif_encodetile = Fax3Encode;
1565 70 : tif->tif_close = Fax3Close;
1566 70 : tif->tif_cleanup = Fax3Cleanup;
1567 :
1568 70 : return (1);
1569 : }
1570 :
1571 9 : int TIFFInitCCITTFax3(TIFF *tif, int scheme)
1572 : {
1573 : (void)scheme;
1574 9 : if (InitCCITTFax3(tif))
1575 : {
1576 : /*
1577 : * Merge codec-specific tag information.
1578 : */
1579 9 : if (!_TIFFMergeFields(tif, fax3Fields, TIFFArrayCount(fax3Fields)))
1580 : {
1581 0 : TIFFErrorExtR(tif, "TIFFInitCCITTFax3",
1582 : "Merging CCITT Fax 3 codec-specific tags failed");
1583 0 : return 0;
1584 : }
1585 :
1586 : /*
1587 : * The default format is Class/F-style w/o RTC.
1588 : */
1589 9 : return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
1590 : }
1591 : else
1592 0 : return 01;
1593 : }
1594 :
1595 : /*
1596 : * CCITT Group 4 (T.6) Facsimile-compatible
1597 : * Compression Scheme Support.
1598 : */
1599 :
1600 : #define SWAP(t, a, b) \
1601 : { \
1602 : t x; \
1603 : x = (a); \
1604 : (a) = (b); \
1605 : (b) = x; \
1606 : }
1607 : /*
1608 : * Decode the requested amount of G4-encoded data.
1609 : */
1610 21607 : static int Fax4Decode(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1611 : {
1612 21607 : DECLARE_STATE_2D(tif, sp, "Fax4Decode");
1613 : (void)s;
1614 21607 : if (occ % sp->b.rowbytes)
1615 : {
1616 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1617 0 : return (-1);
1618 : }
1619 21607 : if (CheckReachedCounters(tif, module, sp))
1620 0 : return (-1);
1621 21607 : CACHE_STATE(tif, sp);
1622 21607 : int start = sp->line;
1623 44302 : while (occ > 0)
1624 : {
1625 22695 : a0 = 0;
1626 22695 : RunLength = 0;
1627 22695 : pa = thisrun = sp->curruns;
1628 22695 : pb = sp->refruns;
1629 22695 : b1 = *pb++;
1630 : #ifdef FAX3_DEBUG
1631 : printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1632 : printf("-------------------- %d\n", tif->tif_row);
1633 : fflush(stdout);
1634 : #endif
1635 151277 : EXPAND2D(EOFG4);
1636 22695 : if (EOLcnt)
1637 0 : goto EOFG4;
1638 22695 : if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1639 : {
1640 0 : TIFFErrorExtR(tif, module,
1641 : "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1642 : " bytes available, %d bits needed",
1643 : occ, lastx);
1644 0 : return -1;
1645 : }
1646 22695 : (*sp->fill)(buf, thisrun, pa, lastx);
1647 22695 : SETVALUE(0); /* imaginary change for reference */
1648 22695 : SWAP(uint32_t *, sp->curruns, sp->refruns);
1649 22695 : buf += sp->b.rowbytes;
1650 22695 : occ -= sp->b.rowbytes;
1651 22695 : sp->line++;
1652 22695 : continue;
1653 0 : EOFG4:
1654 0 : NeedBits16(13, BADG4);
1655 0 : BADG4:
1656 : #ifdef FAX3_DEBUG
1657 : if (GetBits(13) != 0x1001)
1658 : fputs("Bad EOFB\n", stderr);
1659 : #endif
1660 0 : ClrBits(13);
1661 0 : if (((lastx + 7) >> 3) > (int)occ) /* check for buffer overrun */
1662 : {
1663 0 : TIFFErrorExtR(tif, module,
1664 : "Buffer overrun detected : %" TIFF_SSIZE_FORMAT
1665 : " bytes available, %d bits needed",
1666 : occ, lastx);
1667 0 : return -1;
1668 : }
1669 0 : (*sp->fill)(buf, thisrun, pa, lastx);
1670 0 : UNCACHE_STATE(tif, sp);
1671 0 : return (sp->line != start
1672 : ? 1
1673 0 : : -1); /* don't error on badly-terminated strips */
1674 : }
1675 21607 : UNCACHE_STATE(tif, sp);
1676 21607 : return (1);
1677 : }
1678 : #undef SWAP
1679 :
1680 : /*
1681 : * Encode the requested amount of data.
1682 : */
1683 7206 : static int Fax4Encode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1684 : {
1685 : static const char module[] = "Fax4Encode";
1686 7206 : Fax3CodecState *sp = EncoderState(tif);
1687 : (void)s;
1688 7206 : if (cc % sp->b.rowbytes)
1689 : {
1690 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be written");
1691 0 : return (0);
1692 : }
1693 15103 : while (cc > 0)
1694 : {
1695 7897 : if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
1696 0 : return (0);
1697 7897 : _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
1698 7897 : bp += sp->b.rowbytes;
1699 7897 : cc -= sp->b.rowbytes;
1700 : }
1701 7206 : return (1);
1702 : }
1703 :
1704 7 : static int Fax4PostEncode(TIFF *tif)
1705 : {
1706 7 : Fax3CodecState *sp = EncoderState(tif);
1707 :
1708 : /* terminate strip w/ EOFB */
1709 7 : Fax3PutBits(tif, EOL, 12);
1710 7 : Fax3PutBits(tif, EOL, 12);
1711 7 : if (sp->bit != 8)
1712 7 : Fax3FlushBits(tif, sp);
1713 7 : return (1);
1714 : }
1715 :
1716 53 : int TIFFInitCCITTFax4(TIFF *tif, int scheme)
1717 : {
1718 : (void)scheme;
1719 53 : if (InitCCITTFax3(tif))
1720 : { /* reuse G3 support */
1721 : /*
1722 : * Merge codec-specific tag information.
1723 : */
1724 53 : if (!_TIFFMergeFields(tif, fax4Fields, TIFFArrayCount(fax4Fields)))
1725 : {
1726 0 : TIFFErrorExtR(tif, "TIFFInitCCITTFax4",
1727 : "Merging CCITT Fax 4 codec-specific tags failed");
1728 0 : return 0;
1729 : }
1730 :
1731 53 : tif->tif_decoderow = Fax4Decode;
1732 53 : tif->tif_decodestrip = Fax4Decode;
1733 53 : tif->tif_decodetile = Fax4Decode;
1734 53 : tif->tif_encoderow = Fax4Encode;
1735 53 : tif->tif_encodestrip = Fax4Encode;
1736 53 : tif->tif_encodetile = Fax4Encode;
1737 53 : tif->tif_postencode = Fax4PostEncode;
1738 : /*
1739 : * Suppress RTC at the end of each strip.
1740 : */
1741 53 : return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
1742 : }
1743 : else
1744 0 : return (0);
1745 : }
1746 :
1747 : /*
1748 : * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
1749 : * (Compression algorithms 2 and 32771)
1750 : */
1751 :
1752 : /*
1753 : * Decode the requested amount of RLE-encoded data.
1754 : */
1755 1 : static int Fax3DecodeRLE(TIFF *tif, uint8_t *buf, tmsize_t occ, uint16_t s)
1756 : {
1757 1 : DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
1758 1 : int mode = sp->b.mode;
1759 : (void)s;
1760 1 : if (occ % sp->b.rowbytes)
1761 : {
1762 0 : TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
1763 0 : return (-1);
1764 : }
1765 1 : if (CheckReachedCounters(tif, module, sp))
1766 0 : return (-1);
1767 1 : CACHE_STATE(tif, sp);
1768 1 : thisrun = sp->curruns;
1769 100 : while (occ > 0)
1770 : {
1771 99 : a0 = 0;
1772 99 : RunLength = 0;
1773 99 : pa = thisrun;
1774 : #ifdef FAX3_DEBUG
1775 : printf("\nBitAcc=%08" PRIX32 ", BitsAvail = %d\n", BitAcc, BitsAvail);
1776 : printf("-------------------- %" PRIu32 "\n", tif->tif_row);
1777 : fflush(stdout);
1778 : #endif
1779 1323 : EXPAND1D(EOFRLE);
1780 99 : (*sp->fill)(buf, thisrun, pa, lastx);
1781 : /*
1782 : * Cleanup at the end of the row.
1783 : */
1784 99 : if (mode & FAXMODE_BYTEALIGN)
1785 : {
1786 99 : int n = BitsAvail - (BitsAvail & ~7);
1787 99 : ClrBits(n);
1788 : }
1789 0 : else if (mode & FAXMODE_WORDALIGN)
1790 : {
1791 0 : int n = BitsAvail - (BitsAvail & ~15);
1792 0 : ClrBits(n);
1793 0 : if (BitsAvail == 0 && !isAligned(cp, uint16_t))
1794 0 : cp++;
1795 : }
1796 99 : buf += sp->b.rowbytes;
1797 99 : occ -= sp->b.rowbytes;
1798 99 : sp->line++;
1799 99 : continue;
1800 0 : EOFRLE: /* premature EOF */
1801 0 : (*sp->fill)(buf, thisrun, pa, lastx);
1802 0 : UNCACHE_STATE(tif, sp);
1803 0 : return (-1);
1804 : }
1805 1 : UNCACHE_STATE(tif, sp);
1806 1 : return (1);
1807 : }
1808 :
1809 8 : int TIFFInitCCITTRLE(TIFF *tif, int scheme)
1810 : {
1811 : (void)scheme;
1812 8 : if (InitCCITTFax3(tif))
1813 : { /* reuse G3 support */
1814 8 : tif->tif_decoderow = Fax3DecodeRLE;
1815 8 : tif->tif_decodestrip = Fax3DecodeRLE;
1816 8 : tif->tif_decodetile = Fax3DecodeRLE;
1817 : /*
1818 : * Suppress RTC+EOLs when encoding and byte-align data.
1819 : */
1820 8 : return TIFFSetField(tif, TIFFTAG_FAXMODE,
1821 : FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_BYTEALIGN);
1822 : }
1823 : else
1824 0 : return (0);
1825 : }
1826 :
1827 0 : int TIFFInitCCITTRLEW(TIFF *tif, int scheme)
1828 : {
1829 : (void)scheme;
1830 0 : if (InitCCITTFax3(tif))
1831 : { /* reuse G3 support */
1832 0 : tif->tif_decoderow = Fax3DecodeRLE;
1833 0 : tif->tif_decodestrip = Fax3DecodeRLE;
1834 0 : tif->tif_decodetile = Fax3DecodeRLE;
1835 : /*
1836 : * Suppress RTC+EOLs when encoding and word-align data.
1837 : */
1838 0 : return TIFFSetField(tif, TIFFTAG_FAXMODE,
1839 : FAXMODE_NORTC | FAXMODE_NOEOL | FAXMODE_WORDALIGN);
1840 : }
1841 : else
1842 0 : return (0);
1843 : }
1844 : #endif /* CCITT_SUPPORT */
|