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