/src/FreeImage/Source/LibTIFF/tif_fax3.c

https://bitbucket.org/cabalistic/ogredeps/ · C · 1626 lines · 1235 code · 112 blank · 279 comment · 212 complexity · eed115d889374fc6c108692da446a597 MD5 · raw file

  1. /* $Id: tif_fax3.c,v 1.37 2011/04/10 17:14:09 drolon Exp $ */
  2. /*
  3. * Copyright (c) 1990-1997 Sam Leffler
  4. * Copyright (c) 1991-1997 Silicon Graphics, Inc.
  5. *
  6. * Permission to use, copy, modify, distribute, and sell this software and
  7. * its documentation for any purpose is hereby granted without fee, provided
  8. * that (i) the above copyright notices and this permission notice appear in
  9. * all copies of the software and related documentation, and (ii) the names of
  10. * Sam Leffler and Silicon Graphics may not be used in any advertising or
  11. * publicity relating to the software without the specific, prior written
  12. * permission of Sam Leffler and Silicon Graphics.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  15. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  16. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  17. *
  18. * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  19. * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  20. * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  21. * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
  22. * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  23. * OF THIS SOFTWARE.
  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. * Compression+decompression state blocks are
  45. * derived from this ``base state'' block.
  46. */
  47. typedef struct {
  48. int rw_mode; /* O_RDONLY for decode, else encode */
  49. int mode; /* operating mode */
  50. uint32 rowbytes; /* bytes in a decoded scanline */
  51. uint32 rowpixels; /* pixels in a scanline */
  52. uint16 cleanfaxdata; /* CleanFaxData tag */
  53. uint32 badfaxrun; /* BadFaxRun tag */
  54. uint32 badfaxlines; /* BadFaxLines tag */
  55. uint32 groupoptions; /* Group 3/4 options tag */
  56. uint32 recvparams; /* encoded Class 2 session params */
  57. char* subaddress; /* subaddress string */
  58. uint32 recvtime; /* time spent receiving (secs) */
  59. char* faxdcs; /* Table 2/T.30 encoded session params */
  60. TIFFVGetMethod vgetparent; /* super-class method */
  61. TIFFVSetMethod vsetparent; /* super-class method */
  62. TIFFPrintMethod printdir; /* super-class method */
  63. } Fax3BaseState;
  64. #define Fax3State(tif) ((Fax3BaseState*) (tif)->tif_data)
  65. typedef enum { G3_1D, G3_2D } Ttag;
  66. typedef struct {
  67. Fax3BaseState b;
  68. /* Decoder state info */
  69. const unsigned char* bitmap; /* bit reversal table */
  70. uint32 data; /* current i/o byte/word */
  71. int bit; /* current i/o bit in byte */
  72. int EOLcnt; /* count of EOL codes recognized */
  73. TIFFFaxFillFunc fill; /* fill routine */
  74. uint32* runs; /* b&w runs for current/previous row */
  75. uint32* refruns; /* runs for reference line */
  76. uint32* curruns; /* runs for current line */
  77. /* Encoder state info */
  78. Ttag tag; /* encoding state */
  79. unsigned char* refline; /* reference line for 2d decoding */
  80. int k; /* #rows left that can be 2d encoded */
  81. int maxk; /* max #rows that can be 2d encoded */
  82. int line;
  83. } Fax3CodecState;
  84. #define DecoderState(tif) ((Fax3CodecState*) Fax3State(tif))
  85. #define EncoderState(tif) ((Fax3CodecState*) Fax3State(tif))
  86. #define is2DEncoding(sp) \
  87. (sp->b.groupoptions & GROUP3OPT_2DENCODING)
  88. #define isAligned(p,t) ((((unsigned long)(p)) & (sizeof (t)-1)) == 0)
  89. /*
  90. * Group 3 and Group 4 Decoding.
  91. */
  92. /*
  93. * These macros glue the TIFF library state to
  94. * the state expected by Frank's decoder.
  95. */
  96. #define DECLARE_STATE(tif, sp, mod) \
  97. static const char module[] = mod; \
  98. Fax3CodecState* sp = DecoderState(tif); \
  99. int a0; /* reference element */ \
  100. int lastx = sp->b.rowpixels; /* last element in row */ \
  101. uint32 BitAcc; /* bit accumulator */ \
  102. int BitsAvail; /* # valid bits in BitAcc */ \
  103. int RunLength; /* length of current run */ \
  104. unsigned char* cp; /* next byte of input data */ \
  105. unsigned char* ep; /* end of input data */ \
  106. uint32* pa; /* place to stuff next run */ \
  107. uint32* thisrun; /* current row's run array */ \
  108. int EOLcnt; /* # EOL codes recognized */ \
  109. const unsigned char* bitmap = sp->bitmap; /* input data bit reverser */ \
  110. const TIFFFaxTabEnt* TabEnt
  111. #define DECLARE_STATE_2D(tif, sp, mod) \
  112. DECLARE_STATE(tif, sp, mod); \
  113. int b1; /* next change on prev line */ \
  114. uint32* pb /* next run in reference line */\
  115. /*
  116. * Load any state that may be changed during decoding.
  117. */
  118. #define CACHE_STATE(tif, sp) do { \
  119. BitAcc = sp->data; \
  120. BitsAvail = sp->bit; \
  121. EOLcnt = sp->EOLcnt; \
  122. cp = (unsigned char*) tif->tif_rawcp; \
  123. ep = cp + tif->tif_rawcc; \
  124. } while (0)
  125. /*
  126. * Save state possibly changed during decoding.
  127. */
  128. #define UNCACHE_STATE(tif, sp) do { \
  129. sp->bit = BitsAvail; \
  130. sp->data = BitAcc; \
  131. sp->EOLcnt = EOLcnt; \
  132. tif->tif_rawcc -= (tidata_t) cp - tif->tif_rawcp; \
  133. tif->tif_rawcp = (tidata_t) cp; \
  134. } while (0)
  135. /*
  136. * Setup state for decoding a strip.
  137. */
  138. static int
  139. Fax3PreDecode(TIFF* tif, tsample_t s)
  140. {
  141. Fax3CodecState* sp = DecoderState(tif);
  142. (void) s;
  143. assert(sp != NULL);
  144. sp->bit = 0; /* force initial read */
  145. sp->data = 0;
  146. sp->EOLcnt = 0; /* force initial scan for EOL */
  147. /*
  148. * Decoder assumes lsb-to-msb bit order. Note that we select
  149. * this here rather than in Fax3SetupState so that viewers can
  150. * hold the image open, fiddle with the FillOrder tag value,
  151. * and then re-decode the image. Otherwise they'd need to close
  152. * and open the image to get the state reset.
  153. */
  154. sp->bitmap =
  155. TIFFGetBitRevTable(tif->tif_dir.td_fillorder != FILLORDER_LSB2MSB);
  156. if (sp->refruns) { /* init reference line to white */
  157. sp->refruns[0] = (uint32) sp->b.rowpixels;
  158. sp->refruns[1] = 0;
  159. }
  160. sp->line = 0;
  161. return (1);
  162. }
  163. /*
  164. * Routine for handling various errors/conditions.
  165. * Note how they are "glued into the decoder" by
  166. * overriding the definitions used by the decoder.
  167. */
  168. static void
  169. Fax3Unexpected(const char* module, TIFF* tif, uint32 line, uint32 a0)
  170. {
  171. TIFFErrorExt(tif->tif_clientdata, module, "%s: Bad code word at line %u of %s %u (x %u)",
  172. tif->tif_name, line, isTiled(tif) ? "tile" : "strip",
  173. (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip),
  174. a0);
  175. }
  176. #define unexpected(table, a0) Fax3Unexpected(module, tif, sp->line, a0)
  177. static void
  178. Fax3Extension(const char* module, TIFF* tif, uint32 line, uint32 a0)
  179. {
  180. TIFFErrorExt(tif->tif_clientdata, module,
  181. "%s: Uncompressed data (not supported) at line %u of %s %u (x %u)",
  182. tif->tif_name, line, isTiled(tif) ? "tile" : "strip",
  183. (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip),
  184. a0);
  185. }
  186. #define extension(a0) Fax3Extension(module, tif, sp->line, a0)
  187. static void
  188. Fax3BadLength(const char* module, TIFF* tif, uint32 line, uint32 a0, uint32 lastx)
  189. {
  190. TIFFWarningExt(tif->tif_clientdata, module, "%s: %s at line %u of %s %u (got %u, expected %u)",
  191. tif->tif_name,
  192. a0 < lastx ? "Premature EOL" : "Line length mismatch",
  193. line, isTiled(tif) ? "tile" : "strip",
  194. (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip),
  195. a0, lastx);
  196. }
  197. #define badlength(a0,lastx) Fax3BadLength(module, tif, sp->line, a0, lastx)
  198. static void
  199. Fax3PrematureEOF(const char* module, TIFF* tif, uint32 line, uint32 a0)
  200. {
  201. TIFFWarningExt(tif->tif_clientdata, module, "%s: Premature EOF at line %u of %s %u (x %u)",
  202. tif->tif_name,
  203. line, isTiled(tif) ? "tile" : "strip",
  204. (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip),
  205. a0);
  206. }
  207. #define prematureEOF(a0) Fax3PrematureEOF(module, tif, sp->line, a0)
  208. #define Nop
  209. /*
  210. * Decode the requested amount of G3 1D-encoded data.
  211. */
  212. static int
  213. Fax3Decode1D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  214. {
  215. DECLARE_STATE(tif, sp, "Fax3Decode1D");
  216. (void) s;
  217. CACHE_STATE(tif, sp);
  218. thisrun = sp->curruns;
  219. while ((long)occ > 0) {
  220. a0 = 0;
  221. RunLength = 0;
  222. pa = thisrun;
  223. #ifdef FAX3_DEBUG
  224. printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  225. printf("-------------------- %d\n", tif->tif_row);
  226. fflush(stdout);
  227. #endif
  228. SYNC_EOL(EOF1D);
  229. EXPAND1D(EOF1Da);
  230. (*sp->fill)(buf, thisrun, pa, lastx);
  231. buf += sp->b.rowbytes;
  232. occ -= sp->b.rowbytes;
  233. sp->line++;
  234. continue;
  235. EOF1D: /* premature EOF */
  236. CLEANUP_RUNS();
  237. EOF1Da: /* premature EOF */
  238. (*sp->fill)(buf, thisrun, pa, lastx);
  239. UNCACHE_STATE(tif, sp);
  240. return (-1);
  241. }
  242. UNCACHE_STATE(tif, sp);
  243. return (1);
  244. }
  245. #define SWAP(t,a,b) { t x; x = (a); (a) = (b); (b) = x; }
  246. /*
  247. * Decode the requested amount of G3 2D-encoded data.
  248. */
  249. static int
  250. Fax3Decode2D(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  251. {
  252. DECLARE_STATE_2D(tif, sp, "Fax3Decode2D");
  253. int is1D; /* current line is 1d/2d-encoded */
  254. (void) s;
  255. CACHE_STATE(tif, sp);
  256. while ((long)occ > 0) {
  257. a0 = 0;
  258. RunLength = 0;
  259. pa = thisrun = sp->curruns;
  260. #ifdef FAX3_DEBUG
  261. printf("\nBitAcc=%08X, BitsAvail = %d EOLcnt = %d",
  262. BitAcc, BitsAvail, EOLcnt);
  263. #endif
  264. SYNC_EOL(EOF2D);
  265. NeedBits8(1, EOF2D);
  266. is1D = GetBits(1); /* 1D/2D-encoding tag bit */
  267. ClrBits(1);
  268. #ifdef FAX3_DEBUG
  269. printf(" %s\n-------------------- %d\n",
  270. is1D ? "1D" : "2D", tif->tif_row);
  271. fflush(stdout);
  272. #endif
  273. pb = sp->refruns;
  274. b1 = *pb++;
  275. if (is1D)
  276. EXPAND1D(EOF2Da);
  277. else
  278. EXPAND2D(EOF2Da);
  279. (*sp->fill)(buf, thisrun, pa, lastx);
  280. SETVALUE(0); /* imaginary change for reference */
  281. SWAP(uint32*, sp->curruns, sp->refruns);
  282. buf += sp->b.rowbytes;
  283. occ -= sp->b.rowbytes;
  284. sp->line++;
  285. continue;
  286. EOF2D: /* premature EOF */
  287. CLEANUP_RUNS();
  288. EOF2Da: /* premature EOF */
  289. (*sp->fill)(buf, thisrun, pa, lastx);
  290. UNCACHE_STATE(tif, sp);
  291. return (-1);
  292. }
  293. UNCACHE_STATE(tif, sp);
  294. return (1);
  295. }
  296. #undef SWAP
  297. /*
  298. * The ZERO & FILL macros must handle spans < 2*sizeof(long) bytes.
  299. * For machines with 64-bit longs this is <16 bytes; otherwise
  300. * this is <8 bytes. We optimize the code here to reflect the
  301. * machine characteristics.
  302. */
  303. #if SIZEOF_LONG == 8
  304. # define FILL(n, cp) \
  305. switch (n) { \
  306. case 15:(cp)[14] = 0xff; case 14:(cp)[13] = 0xff; case 13: (cp)[12] = 0xff;\
  307. case 12:(cp)[11] = 0xff; case 11:(cp)[10] = 0xff; case 10: (cp)[9] = 0xff;\
  308. case 9: (cp)[8] = 0xff; case 8: (cp)[7] = 0xff; case 7: (cp)[6] = 0xff;\
  309. case 6: (cp)[5] = 0xff; case 5: (cp)[4] = 0xff; case 4: (cp)[3] = 0xff;\
  310. case 3: (cp)[2] = 0xff; case 2: (cp)[1] = 0xff; \
  311. case 1: (cp)[0] = 0xff; (cp) += (n); case 0: ; \
  312. }
  313. # define ZERO(n, cp) \
  314. switch (n) { \
  315. case 15:(cp)[14] = 0; case 14:(cp)[13] = 0; case 13: (cp)[12] = 0; \
  316. case 12:(cp)[11] = 0; case 11:(cp)[10] = 0; case 10: (cp)[9] = 0; \
  317. case 9: (cp)[8] = 0; case 8: (cp)[7] = 0; case 7: (cp)[6] = 0; \
  318. case 6: (cp)[5] = 0; case 5: (cp)[4] = 0; case 4: (cp)[3] = 0; \
  319. case 3: (cp)[2] = 0; case 2: (cp)[1] = 0; \
  320. case 1: (cp)[0] = 0; (cp) += (n); case 0: ; \
  321. }
  322. #else
  323. # define FILL(n, cp) \
  324. switch (n) { \
  325. case 7: (cp)[6] = 0xff; case 6: (cp)[5] = 0xff; case 5: (cp)[4] = 0xff; \
  326. case 4: (cp)[3] = 0xff; case 3: (cp)[2] = 0xff; case 2: (cp)[1] = 0xff; \
  327. case 1: (cp)[0] = 0xff; (cp) += (n); case 0: ; \
  328. }
  329. # define ZERO(n, cp) \
  330. switch (n) { \
  331. case 7: (cp)[6] = 0; case 6: (cp)[5] = 0; case 5: (cp)[4] = 0; \
  332. case 4: (cp)[3] = 0; case 3: (cp)[2] = 0; case 2: (cp)[1] = 0; \
  333. case 1: (cp)[0] = 0; (cp) += (n); case 0: ; \
  334. }
  335. #endif
  336. /*
  337. * Bit-fill a row according to the white/black
  338. * runs generated during G3/G4 decoding.
  339. */
  340. void
  341. _TIFFFax3fillruns(unsigned char* buf, uint32* runs, uint32* erun, uint32 lastx)
  342. {
  343. static const unsigned char _fillmasks[] =
  344. { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
  345. unsigned char* cp;
  346. uint32 x, bx, run;
  347. int32 n, nw;
  348. long* lp;
  349. if ((erun-runs)&1)
  350. *erun++ = 0;
  351. x = 0;
  352. for (; runs < erun; runs += 2) {
  353. run = runs[0];
  354. if (x+run > lastx || run > lastx )
  355. run = runs[0] = (uint32) (lastx - x);
  356. if (run) {
  357. cp = buf + (x>>3);
  358. bx = x&7;
  359. if (run > 8-bx) {
  360. if (bx) { /* align to byte boundary */
  361. *cp++ &= 0xff << (8-bx);
  362. run -= 8-bx;
  363. }
  364. if( (n = run >> 3) != 0 ) { /* multiple bytes to fill */
  365. if ((n/sizeof (long)) > 1) {
  366. /*
  367. * Align to longword boundary and fill.
  368. */
  369. for (; n && !isAligned(cp, long); n--)
  370. *cp++ = 0x00;
  371. lp = (long*) cp;
  372. nw = (int32)(n / sizeof (long));
  373. n -= nw * sizeof (long);
  374. do {
  375. *lp++ = 0L;
  376. } while (--nw);
  377. cp = (unsigned char*) lp;
  378. }
  379. ZERO(n, cp);
  380. run &= 7;
  381. }
  382. if (run)
  383. cp[0] &= 0xff >> run;
  384. } else
  385. cp[0] &= ~(_fillmasks[run]>>bx);
  386. x += runs[0];
  387. }
  388. run = runs[1];
  389. if (x+run > lastx || run > lastx )
  390. run = runs[1] = lastx - x;
  391. if (run) {
  392. cp = buf + (x>>3);
  393. bx = x&7;
  394. if (run > 8-bx) {
  395. if (bx) { /* align to byte boundary */
  396. *cp++ |= 0xff >> bx;
  397. run -= 8-bx;
  398. }
  399. if( (n = run>>3) != 0 ) { /* multiple bytes to fill */
  400. if ((n/sizeof (long)) > 1) {
  401. /*
  402. * Align to longword boundary and fill.
  403. */
  404. for (; n && !isAligned(cp, long); n--)
  405. *cp++ = 0xff;
  406. lp = (long*) cp;
  407. nw = (int32)(n / sizeof (long));
  408. n -= nw * sizeof (long);
  409. do {
  410. *lp++ = -1L;
  411. } while (--nw);
  412. cp = (unsigned char*) lp;
  413. }
  414. FILL(n, cp);
  415. run &= 7;
  416. }
  417. if (run)
  418. cp[0] |= 0xff00 >> run;
  419. } else
  420. cp[0] |= _fillmasks[run]>>bx;
  421. x += runs[1];
  422. }
  423. }
  424. assert(x == lastx);
  425. }
  426. #undef ZERO
  427. #undef FILL
  428. /*
  429. * Setup G3/G4-related compression/decompression state
  430. * before data is processed. This routine is called once
  431. * per image -- it sets up different state based on whether
  432. * or not decoding or encoding is being done and whether
  433. * 1D- or 2D-encoded data is involved.
  434. */
  435. static int
  436. Fax3SetupState(TIFF* tif)
  437. {
  438. TIFFDirectory* td = &tif->tif_dir;
  439. Fax3BaseState* sp = Fax3State(tif);
  440. int needsRefLine;
  441. Fax3CodecState* dsp = (Fax3CodecState*) Fax3State(tif);
  442. uint32 rowbytes, rowpixels, nruns;
  443. if (td->td_bitspersample != 1) {
  444. TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
  445. "Bits/sample must be 1 for Group 3/4 encoding/decoding");
  446. return (0);
  447. }
  448. /*
  449. * Calculate the scanline/tile widths.
  450. */
  451. if (isTiled(tif)) {
  452. rowbytes = TIFFTileRowSize(tif);
  453. rowpixels = td->td_tilewidth;
  454. } else {
  455. rowbytes = TIFFScanlineSize(tif);
  456. rowpixels = td->td_imagewidth;
  457. }
  458. sp->rowbytes = (uint32) rowbytes;
  459. sp->rowpixels = (uint32) rowpixels;
  460. /*
  461. * Allocate any additional space required for decoding/encoding.
  462. */
  463. needsRefLine = (
  464. (sp->groupoptions & GROUP3OPT_2DENCODING) ||
  465. td->td_compression == COMPRESSION_CCITTFAX4
  466. );
  467. /*
  468. Assure that allocation computations do not overflow.
  469. TIFFroundup and TIFFSafeMultiply return zero on integer overflow
  470. */
  471. dsp->runs=(uint32*) NULL;
  472. nruns = TIFFroundup(rowpixels,32);
  473. if (needsRefLine) {
  474. nruns = TIFFSafeMultiply(uint32,nruns,2);
  475. }
  476. if ((nruns == 0) || (TIFFSafeMultiply(uint32,nruns,2) == 0)) {
  477. TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
  478. "Row pixels integer overflow (rowpixels %u)",
  479. rowpixels);
  480. return (0);
  481. }
  482. dsp->runs = (uint32*) _TIFFCheckMalloc(tif,
  483. TIFFSafeMultiply(uint32,nruns,2),
  484. sizeof (uint32),
  485. "for Group 3/4 run arrays");
  486. if (dsp->runs == NULL)
  487. return (0);
  488. dsp->curruns = dsp->runs;
  489. if (needsRefLine)
  490. dsp->refruns = dsp->runs + nruns;
  491. else
  492. dsp->refruns = NULL;
  493. if (td->td_compression == COMPRESSION_CCITTFAX3
  494. && is2DEncoding(dsp)) { /* NB: default is 1D routine */
  495. tif->tif_decoderow = Fax3Decode2D;
  496. tif->tif_decodestrip = Fax3Decode2D;
  497. tif->tif_decodetile = Fax3Decode2D;
  498. }
  499. if (needsRefLine) { /* 2d encoding */
  500. Fax3CodecState* esp = EncoderState(tif);
  501. /*
  502. * 2d encoding requires a scanline
  503. * buffer for the ``reference line''; the
  504. * scanline against which delta encoding
  505. * is referenced. The reference line must
  506. * be initialized to be ``white'' (done elsewhere).
  507. */
  508. esp->refline = (unsigned char*) _TIFFmalloc(rowbytes);
  509. if (esp->refline == NULL) {
  510. TIFFErrorExt(tif->tif_clientdata, "Fax3SetupState",
  511. "%s: No space for Group 3/4 reference line",
  512. tif->tif_name);
  513. return (0);
  514. }
  515. } else /* 1d encoding */
  516. EncoderState(tif)->refline = NULL;
  517. return (1);
  518. }
  519. /*
  520. * CCITT Group 3 FAX Encoding.
  521. */
  522. #define Fax3FlushBits(tif, sp) { \
  523. if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
  524. (void) TIFFFlushData1(tif); \
  525. *(tif)->tif_rawcp++ = (tidataval_t) (sp)->data; \
  526. (tif)->tif_rawcc++; \
  527. (sp)->data = 0, (sp)->bit = 8; \
  528. }
  529. #define _FlushBits(tif) { \
  530. if ((tif)->tif_rawcc >= (tif)->tif_rawdatasize) \
  531. (void) TIFFFlushData1(tif); \
  532. *(tif)->tif_rawcp++ = (tidataval_t) data; \
  533. (tif)->tif_rawcc++; \
  534. data = 0, bit = 8; \
  535. }
  536. static const int _msbmask[9] =
  537. { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
  538. #define _PutBits(tif, bits, length) { \
  539. while (length > bit) { \
  540. data |= bits >> (length - bit); \
  541. length -= bit; \
  542. _FlushBits(tif); \
  543. } \
  544. data |= (bits & _msbmask[length]) << (bit - length); \
  545. bit -= length; \
  546. if (bit == 0) \
  547. _FlushBits(tif); \
  548. }
  549. /*
  550. * Write a variable-length bit-value to
  551. * the output stream. Values are
  552. * assumed to be at most 16 bits.
  553. */
  554. static void
  555. Fax3PutBits(TIFF* tif, unsigned int bits, unsigned int length)
  556. {
  557. Fax3CodecState* sp = EncoderState(tif);
  558. unsigned int bit = sp->bit;
  559. int data = sp->data;
  560. _PutBits(tif, bits, length);
  561. sp->data = data;
  562. sp->bit = bit;
  563. }
  564. /*
  565. * Write a code to the output stream.
  566. */
  567. #define putcode(tif, te) Fax3PutBits(tif, (te)->code, (te)->length)
  568. #ifdef FAX3_DEBUG
  569. #define DEBUG_COLOR(w) (tab == TIFFFaxWhiteCodes ? w "W" : w "B")
  570. #define DEBUG_PRINT(what,len) { \
  571. int t; \
  572. printf("%08X/%-2d: %s%5d\t", data, bit, DEBUG_COLOR(what), len); \
  573. for (t = length-1; t >= 0; t--) \
  574. putchar(code & (1<<t) ? '1' : '0'); \
  575. putchar('\n'); \
  576. }
  577. #endif
  578. /*
  579. * Write the sequence of codes that describes
  580. * the specified span of zero's or one's. The
  581. * appropriate table that holds the make-up and
  582. * terminating codes is supplied.
  583. */
  584. static void
  585. putspan(TIFF* tif, int32 span, const tableentry* tab)
  586. {
  587. Fax3CodecState* sp = EncoderState(tif);
  588. unsigned int bit = sp->bit;
  589. int data = sp->data;
  590. unsigned int code, length;
  591. while (span >= 2624) {
  592. const tableentry* te = &tab[63 + (2560>>6)];
  593. code = te->code, length = te->length;
  594. #ifdef FAX3_DEBUG
  595. DEBUG_PRINT("MakeUp", te->runlen);
  596. #endif
  597. _PutBits(tif, code, length);
  598. span -= te->runlen;
  599. }
  600. if (span >= 64) {
  601. const tableentry* te = &tab[63 + (span>>6)];
  602. assert(te->runlen == 64*(span>>6));
  603. code = te->code, length = te->length;
  604. #ifdef FAX3_DEBUG
  605. DEBUG_PRINT("MakeUp", te->runlen);
  606. #endif
  607. _PutBits(tif, code, length);
  608. span -= te->runlen;
  609. }
  610. code = tab[span].code, length = tab[span].length;
  611. #ifdef FAX3_DEBUG
  612. DEBUG_PRINT(" Term", tab[span].runlen);
  613. #endif
  614. _PutBits(tif, code, length);
  615. sp->data = data;
  616. sp->bit = bit;
  617. }
  618. /*
  619. * Write an EOL code to the output stream. The zero-fill
  620. * logic for byte-aligning encoded scanlines is handled
  621. * here. We also handle writing the tag bit for the next
  622. * scanline when doing 2d encoding.
  623. */
  624. static void
  625. Fax3PutEOL(TIFF* tif)
  626. {
  627. Fax3CodecState* sp = EncoderState(tif);
  628. unsigned int bit = sp->bit;
  629. int data = sp->data;
  630. unsigned int code, length, tparm;
  631. if (sp->b.groupoptions & GROUP3OPT_FILLBITS) {
  632. /*
  633. * Force bit alignment so EOL will terminate on
  634. * a byte boundary. That is, force the bit alignment
  635. * to 16-12 = 4 before putting out the EOL code.
  636. */
  637. int align = 8 - 4;
  638. if (align != sp->bit) {
  639. if (align > sp->bit)
  640. align = sp->bit + (8 - align);
  641. else
  642. align = sp->bit - align;
  643. code = 0;
  644. tparm=align;
  645. _PutBits(tif, 0, tparm);
  646. }
  647. }
  648. code = EOL, length = 12;
  649. if (is2DEncoding(sp))
  650. code = (code<<1) | (sp->tag == G3_1D), length++;
  651. _PutBits(tif, code, length);
  652. sp->data = data;
  653. sp->bit = bit;
  654. }
  655. /*
  656. * Reset encoding state at the start of a strip.
  657. */
  658. static int
  659. Fax3PreEncode(TIFF* tif, tsample_t s)
  660. {
  661. Fax3CodecState* sp = EncoderState(tif);
  662. (void) s;
  663. assert(sp != NULL);
  664. sp->bit = 8;
  665. sp->data = 0;
  666. sp->tag = G3_1D;
  667. /*
  668. * This is necessary for Group 4; otherwise it isn't
  669. * needed because the first scanline of each strip ends
  670. * up being copied into the refline.
  671. */
  672. if (sp->refline)
  673. _TIFFmemset(sp->refline, 0x00, sp->b.rowbytes);
  674. if (is2DEncoding(sp)) {
  675. float res = tif->tif_dir.td_yresolution;
  676. /*
  677. * The CCITT spec says that when doing 2d encoding, you
  678. * should only do it on K consecutive scanlines, where K
  679. * depends on the resolution of the image being encoded
  680. * (2 for <= 200 lpi, 4 for > 200 lpi). Since the directory
  681. * code initializes td_yresolution to 0, this code will
  682. * select a K of 2 unless the YResolution tag is set
  683. * appropriately. (Note also that we fudge a little here
  684. * and use 150 lpi to avoid problems with units conversion.)
  685. */
  686. if (tif->tif_dir.td_resolutionunit == RESUNIT_CENTIMETER)
  687. res *= 2.54f; /* convert to inches */
  688. sp->maxk = (res > 150 ? 4 : 2);
  689. sp->k = sp->maxk-1;
  690. } else
  691. sp->k = sp->maxk = 0;
  692. sp->line = 0;
  693. return (1);
  694. }
  695. static const unsigned char zeroruns[256] = {
  696. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, /* 0x00 - 0x0f */
  697. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x10 - 0x1f */
  698. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x20 - 0x2f */
  699. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x30 - 0x3f */
  700. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 - 0x4f */
  701. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x50 - 0x5f */
  702. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 - 0x6f */
  703. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x70 - 0x7f */
  704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
  705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
  706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
  707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
  708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
  709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
  710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
  711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xf0 - 0xff */
  712. };
  713. static const unsigned char oneruns[256] = {
  714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 - 0x0f */
  715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
  716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
  717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
  718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
  719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
  720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6f */
  721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
  722. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x80 - 0x8f */
  723. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x90 - 0x9f */
  724. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xa0 - 0xaf */
  725. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xb0 - 0xbf */
  726. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 - 0xcf */
  727. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 - 0xdf */
  728. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 - 0xef */
  729. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, /* 0xf0 - 0xff */
  730. };
  731. /*
  732. * On certain systems it pays to inline
  733. * the routines that find pixel spans.
  734. */
  735. #ifdef VAXC
  736. static int32 find0span(unsigned char*, int32, int32);
  737. static int32 find1span(unsigned char*, int32, int32);
  738. #pragma inline(find0span,find1span)
  739. #endif
  740. /*
  741. * Find a span of ones or zeros using the supplied
  742. * table. The ``base'' of the bit string is supplied
  743. * along with the start+end bit indices.
  744. */
  745. static int32
  746. find0span(unsigned char* bp, int32 bs, int32 be)
  747. {
  748. int32 bits = be - bs;
  749. int32 n, span;
  750. bp += bs>>3;
  751. /*
  752. * Check partial byte on lhs.
  753. */
  754. if (bits > 0 && (n = (bs & 7))) {
  755. span = zeroruns[(*bp << n) & 0xff];
  756. if (span > 8-n) /* table value too generous */
  757. span = 8-n;
  758. if (span > bits) /* constrain span to bit range */
  759. span = bits;
  760. if (n+span < 8) /* doesn't extend to edge of byte */
  761. return (span);
  762. bits -= span;
  763. bp++;
  764. } else
  765. span = 0;
  766. if (bits >= (int32)(2 * 8 * sizeof(long))) {
  767. long* lp;
  768. /*
  769. * Align to longword boundary and check longwords.
  770. */
  771. while (!isAligned(bp, long)) {
  772. if (*bp != 0x00)
  773. return (span + zeroruns[*bp]);
  774. span += 8, bits -= 8;
  775. bp++;
  776. }
  777. lp = (long*) bp;
  778. while ((bits >= (int32)(8 * sizeof(long))) && (0 == *lp)) {
  779. span += 8*sizeof (long), bits -= 8*sizeof (long);
  780. lp++;
  781. }
  782. bp = (unsigned char*) lp;
  783. }
  784. /*
  785. * Scan full bytes for all 0's.
  786. */
  787. while (bits >= 8) {
  788. if (*bp != 0x00) /* end of run */
  789. return (span + zeroruns[*bp]);
  790. span += 8, bits -= 8;
  791. bp++;
  792. }
  793. /*
  794. * Check partial byte on rhs.
  795. */
  796. if (bits > 0) {
  797. n = zeroruns[*bp];
  798. span += (n > bits ? bits : n);
  799. }
  800. return (span);
  801. }
  802. static int32
  803. find1span(unsigned char* bp, int32 bs, int32 be)
  804. {
  805. int32 bits = be - bs;
  806. int32 n, span;
  807. bp += bs>>3;
  808. /*
  809. * Check partial byte on lhs.
  810. */
  811. if (bits > 0 && (n = (bs & 7))) {
  812. span = oneruns[(*bp << n) & 0xff];
  813. if (span > 8-n) /* table value too generous */
  814. span = 8-n;
  815. if (span > bits) /* constrain span to bit range */
  816. span = bits;
  817. if (n+span < 8) /* doesn't extend to edge of byte */
  818. return (span);
  819. bits -= span;
  820. bp++;
  821. } else
  822. span = 0;
  823. if (bits >= (int32)(2 * 8 * sizeof(long))) {
  824. long* lp;
  825. /*
  826. * Align to longword boundary and check longwords.
  827. */
  828. while (!isAligned(bp, long)) {
  829. if (*bp != 0xff)
  830. return (span + oneruns[*bp]);
  831. span += 8, bits -= 8;
  832. bp++;
  833. }
  834. lp = (long*) bp;
  835. while ((bits >= (int32)(8 * sizeof(long))) && (~0 == *lp)) {
  836. span += 8*sizeof (long), bits -= 8*sizeof (long);
  837. lp++;
  838. }
  839. bp = (unsigned char*) lp;
  840. }
  841. /*
  842. * Scan full bytes for all 1's.
  843. */
  844. while (bits >= 8) {
  845. if (*bp != 0xff) /* end of run */
  846. return (span + oneruns[*bp]);
  847. span += 8, bits -= 8;
  848. bp++;
  849. }
  850. /*
  851. * Check partial byte on rhs.
  852. */
  853. if (bits > 0) {
  854. n = oneruns[*bp];
  855. span += (n > bits ? bits : n);
  856. }
  857. return (span);
  858. }
  859. /*
  860. * Return the offset of the next bit in the range
  861. * [bs..be] that is different from the specified
  862. * color. The end, be, is returned if no such bit
  863. * exists.
  864. */
  865. #define finddiff(_cp, _bs, _be, _color) \
  866. (_bs + (_color ? find1span(_cp,_bs,_be) : find0span(_cp,_bs,_be)))
  867. /*
  868. * Like finddiff, but also check the starting bit
  869. * against the end in case start > end.
  870. */
  871. #define finddiff2(_cp, _bs, _be, _color) \
  872. (_bs < _be ? finddiff(_cp,_bs,_be,_color) : _be)
  873. /*
  874. * 1d-encode a row of pixels. The encoding is
  875. * a sequence of all-white or all-black spans
  876. * of pixels encoded with Huffman codes.
  877. */
  878. static int
  879. Fax3Encode1DRow(TIFF* tif, unsigned char* bp, uint32 bits)
  880. {
  881. Fax3CodecState* sp = EncoderState(tif);
  882. int32 span;
  883. uint32 bs = 0;
  884. for (;;) {
  885. span = find0span(bp, bs, bits); /* white span */
  886. putspan(tif, span, TIFFFaxWhiteCodes);
  887. bs += span;
  888. if (bs >= bits)
  889. break;
  890. span = find1span(bp, bs, bits); /* black span */
  891. putspan(tif, span, TIFFFaxBlackCodes);
  892. bs += span;
  893. if (bs >= bits)
  894. break;
  895. }
  896. if (sp->b.mode & (FAXMODE_BYTEALIGN|FAXMODE_WORDALIGN)) {
  897. if (sp->bit != 8) /* byte-align */
  898. Fax3FlushBits(tif, sp);
  899. if ((sp->b.mode&FAXMODE_WORDALIGN) &&
  900. !isAligned(tif->tif_rawcp, uint16))
  901. Fax3FlushBits(tif, sp);
  902. }
  903. return (1);
  904. }
  905. static const tableentry horizcode =
  906. { 3, 0x1, 0 }; /* 001 */
  907. static const tableentry passcode =
  908. { 4, 0x1, 0 }; /* 0001 */
  909. static const tableentry vcodes[7] = {
  910. { 7, 0x03, 0 }, /* 0000 011 */
  911. { 6, 0x03, 0 }, /* 0000 11 */
  912. { 3, 0x03, 0 }, /* 011 */
  913. { 1, 0x1, 0 }, /* 1 */
  914. { 3, 0x2, 0 }, /* 010 */
  915. { 6, 0x02, 0 }, /* 0000 10 */
  916. { 7, 0x02, 0 } /* 0000 010 */
  917. };
  918. /*
  919. * 2d-encode a row of pixels. Consult the CCITT
  920. * documentation for the algorithm.
  921. */
  922. static int
  923. Fax3Encode2DRow(TIFF* tif, unsigned char* bp, unsigned char* rp, uint32 bits)
  924. {
  925. #define PIXEL(buf,ix) ((((buf)[(ix)>>3]) >> (7-((ix)&7))) & 1)
  926. uint32 a0 = 0;
  927. uint32 a1 = (PIXEL(bp, 0) != 0 ? 0 : finddiff(bp, 0, bits, 0));
  928. uint32 b1 = (PIXEL(rp, 0) != 0 ? 0 : finddiff(rp, 0, bits, 0));
  929. uint32 a2, b2;
  930. for (;;) {
  931. b2 = finddiff2(rp, b1, bits, PIXEL(rp,b1));
  932. if (b2 >= a1) {
  933. int32 d = b1 - a1;
  934. if (!(-3 <= d && d <= 3)) { /* horizontal mode */
  935. a2 = finddiff2(bp, a1, bits, PIXEL(bp,a1));
  936. putcode(tif, &horizcode);
  937. if (a0+a1 == 0 || PIXEL(bp, a0) == 0) {
  938. putspan(tif, a1-a0, TIFFFaxWhiteCodes);
  939. putspan(tif, a2-a1, TIFFFaxBlackCodes);
  940. } else {
  941. putspan(tif, a1-a0, TIFFFaxBlackCodes);
  942. putspan(tif, a2-a1, TIFFFaxWhiteCodes);
  943. }
  944. a0 = a2;
  945. } else { /* vertical mode */
  946. putcode(tif, &vcodes[d+3]);
  947. a0 = a1;
  948. }
  949. } else { /* pass mode */
  950. putcode(tif, &passcode);
  951. a0 = b2;
  952. }
  953. if (a0 >= bits)
  954. break;
  955. a1 = finddiff(bp, a0, bits, PIXEL(bp,a0));
  956. b1 = finddiff(rp, a0, bits, !PIXEL(bp,a0));
  957. b1 = finddiff(rp, b1, bits, PIXEL(bp,a0));
  958. }
  959. return (1);
  960. #undef PIXEL
  961. }
  962. /*
  963. * Encode a buffer of pixels.
  964. */
  965. static int
  966. Fax3Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
  967. {
  968. Fax3CodecState* sp = EncoderState(tif);
  969. (void) s;
  970. while ((long)cc > 0) {
  971. if ((sp->b.mode & FAXMODE_NOEOL) == 0)
  972. Fax3PutEOL(tif);
  973. if (is2DEncoding(sp)) {
  974. if (sp->tag == G3_1D) {
  975. if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
  976. return (0);
  977. sp->tag = G3_2D;
  978. } else {
  979. if (!Fax3Encode2DRow(tif, bp, sp->refline,
  980. sp->b.rowpixels))
  981. return (0);
  982. sp->k--;
  983. }
  984. if (sp->k == 0) {
  985. sp->tag = G3_1D;
  986. sp->k = sp->maxk-1;
  987. } else
  988. _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
  989. } else {
  990. if (!Fax3Encode1DRow(tif, bp, sp->b.rowpixels))
  991. return (0);
  992. }
  993. bp += sp->b.rowbytes;
  994. cc -= sp->b.rowbytes;
  995. }
  996. return (1);
  997. }
  998. static int
  999. Fax3PostEncode(TIFF* tif)
  1000. {
  1001. Fax3CodecState* sp = EncoderState(tif);
  1002. if (sp->bit != 8)
  1003. Fax3FlushBits(tif, sp);
  1004. return (1);
  1005. }
  1006. static void
  1007. Fax3Close(TIFF* tif)
  1008. {
  1009. if ((Fax3State(tif)->mode & FAXMODE_NORTC) == 0) {
  1010. Fax3CodecState* sp = EncoderState(tif);
  1011. unsigned int code = EOL;
  1012. unsigned int length = 12;
  1013. int i;
  1014. if (is2DEncoding(sp))
  1015. code = (code<<1) | (sp->tag == G3_1D), length++;
  1016. for (i = 0; i < 6; i++)
  1017. Fax3PutBits(tif, code, length);
  1018. Fax3FlushBits(tif, sp);
  1019. }
  1020. }
  1021. static void
  1022. Fax3Cleanup(TIFF* tif)
  1023. {
  1024. Fax3CodecState* sp = DecoderState(tif);
  1025. assert(sp != 0);
  1026. tif->tif_tagmethods.vgetfield = sp->b.vgetparent;
  1027. tif->tif_tagmethods.vsetfield = sp->b.vsetparent;
  1028. tif->tif_tagmethods.printdir = sp->b.printdir;
  1029. if (sp->runs)
  1030. _TIFFfree(sp->runs);
  1031. if (sp->refline)
  1032. _TIFFfree(sp->refline);
  1033. if (Fax3State(tif)->subaddress)
  1034. _TIFFfree(Fax3State(tif)->subaddress);
  1035. if (Fax3State(tif)->faxdcs)
  1036. _TIFFfree(Fax3State(tif)->faxdcs);
  1037. _TIFFfree(tif->tif_data);
  1038. tif->tif_data = NULL;
  1039. _TIFFSetDefaultCompressionState(tif);
  1040. }
  1041. #define FIELD_BADFAXLINES (FIELD_CODEC+0)
  1042. #define FIELD_CLEANFAXDATA (FIELD_CODEC+1)
  1043. #define FIELD_BADFAXRUN (FIELD_CODEC+2)
  1044. #define FIELD_RECVPARAMS (FIELD_CODEC+3)
  1045. #define FIELD_SUBADDRESS (FIELD_CODEC+4)
  1046. #define FIELD_RECVTIME (FIELD_CODEC+5)
  1047. #define FIELD_FAXDCS (FIELD_CODEC+6)
  1048. #define FIELD_OPTIONS (FIELD_CODEC+7)
  1049. static const TIFFFieldInfo faxFieldInfo[] = {
  1050. { TIFFTAG_FAXMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
  1051. FALSE, FALSE, "FaxMode" },
  1052. { TIFFTAG_FAXFILLFUNC, 0, 0, TIFF_ANY, FIELD_PSEUDO,
  1053. FALSE, FALSE, "FaxFillFunc" },
  1054. { TIFFTAG_BADFAXLINES, 1, 1, TIFF_LONG, FIELD_BADFAXLINES,
  1055. TRUE, FALSE, "BadFaxLines" },
  1056. { TIFFTAG_BADFAXLINES, 1, 1, TIFF_SHORT, FIELD_BADFAXLINES,
  1057. TRUE, FALSE, "BadFaxLines" },
  1058. { TIFFTAG_CLEANFAXDATA, 1, 1, TIFF_SHORT, FIELD_CLEANFAXDATA,
  1059. TRUE, FALSE, "CleanFaxData" },
  1060. { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_LONG, FIELD_BADFAXRUN,
  1061. TRUE, FALSE, "ConsecutiveBadFaxLines" },
  1062. { TIFFTAG_CONSECUTIVEBADFAXLINES,1,1, TIFF_SHORT, FIELD_BADFAXRUN,
  1063. TRUE, FALSE, "ConsecutiveBadFaxLines" },
  1064. { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
  1065. TRUE, FALSE, "FaxRecvParams" },
  1066. { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
  1067. TRUE, FALSE, "FaxSubAddress" },
  1068. { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
  1069. TRUE, FALSE, "FaxRecvTime" },
  1070. { TIFFTAG_FAXDCS, -1,-1, TIFF_ASCII, FIELD_FAXDCS,
  1071. TRUE, FALSE, "FaxDcs" },
  1072. };
  1073. static const TIFFFieldInfo fax3FieldInfo[] = {
  1074. { TIFFTAG_GROUP3OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS,
  1075. FALSE, FALSE, "Group3Options" },
  1076. };
  1077. static const TIFFFieldInfo fax4FieldInfo[] = {
  1078. { TIFFTAG_GROUP4OPTIONS, 1, 1, TIFF_LONG, FIELD_OPTIONS,
  1079. FALSE, FALSE, "Group4Options" },
  1080. };
  1081. #define N(a) (sizeof (a) / sizeof (a[0]))
  1082. static int
  1083. Fax3VSetField(TIFF* tif, ttag_t tag, va_list ap)
  1084. {
  1085. Fax3BaseState* sp = Fax3State(tif);
  1086. const TIFFFieldInfo* fip;
  1087. assert(sp != 0);
  1088. assert(sp->vsetparent != 0);
  1089. switch (tag) {
  1090. case TIFFTAG_FAXMODE:
  1091. sp->mode = va_arg(ap, int);
  1092. return 1; /* NB: pseudo tag */
  1093. case TIFFTAG_FAXFILLFUNC:
  1094. DecoderState(tif)->fill = va_arg(ap, TIFFFaxFillFunc);
  1095. return 1; /* NB: pseudo tag */
  1096. case TIFFTAG_GROUP3OPTIONS:
  1097. /* XXX: avoid reading options if compression mismatches. */
  1098. if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX3)
  1099. sp->groupoptions = va_arg(ap, uint32);
  1100. break;
  1101. case TIFFTAG_GROUP4OPTIONS:
  1102. /* XXX: avoid reading options if compression mismatches. */
  1103. if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4)
  1104. sp->groupoptions = va_arg(ap, uint32);
  1105. break;
  1106. case TIFFTAG_BADFAXLINES:
  1107. sp->badfaxlines = va_arg(ap, uint32);
  1108. break;
  1109. case TIFFTAG_CLEANFAXDATA:
  1110. sp->cleanfaxdata = (uint16) va_arg(ap, int);
  1111. break;
  1112. case TIFFTAG_CONSECUTIVEBADFAXLINES:
  1113. sp->badfaxrun = va_arg(ap, uint32);
  1114. break;
  1115. case TIFFTAG_FAXRECVPARAMS:
  1116. sp->recvparams = va_arg(ap, uint32);
  1117. break;
  1118. case TIFFTAG_FAXSUBADDRESS:
  1119. _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
  1120. break;
  1121. case TIFFTAG_FAXRECVTIME:
  1122. sp->recvtime = va_arg(ap, uint32);
  1123. break;
  1124. case TIFFTAG_FAXDCS:
  1125. _TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
  1126. break;
  1127. default:
  1128. return (*sp->vsetparent)(tif, tag, ap);
  1129. }
  1130. if ((fip = _TIFFFieldWithTag(tif, tag)))
  1131. TIFFSetFieldBit(tif, fip->field_bit);
  1132. else
  1133. return 0;
  1134. tif->tif_flags |= TIFF_DIRTYDIRECT;
  1135. return 1;
  1136. }
  1137. static int
  1138. Fax3VGetField(TIFF* tif, ttag_t tag, va_list ap)
  1139. {
  1140. Fax3BaseState* sp = Fax3State(tif);
  1141. assert(sp != 0);
  1142. switch (tag) {
  1143. case TIFFTAG_FAXMODE:
  1144. *va_arg(ap, int*) = sp->mode;
  1145. break;
  1146. case TIFFTAG_FAXFILLFUNC:
  1147. *va_arg(ap, TIFFFaxFillFunc*) = DecoderState(tif)->fill;
  1148. break;
  1149. case TIFFTAG_GROUP3OPTIONS:
  1150. case TIFFTAG_GROUP4OPTIONS:
  1151. *va_arg(ap, uint32*) = sp->groupoptions;
  1152. break;
  1153. case TIFFTAG_BADFAXLINES:
  1154. *va_arg(ap, uint32*) = sp->badfaxlines;
  1155. break;
  1156. case TIFFTAG_CLEANFAXDATA:
  1157. *va_arg(ap, uint16*) = sp->cleanfaxdata;
  1158. break;
  1159. case TIFFTAG_CONSECUTIVEBADFAXLINES:
  1160. *va_arg(ap, uint32*) = sp->badfaxrun;
  1161. break;
  1162. case TIFFTAG_FAXRECVPARAMS:
  1163. *va_arg(ap, uint32*) = sp->recvparams;
  1164. break;
  1165. case TIFFTAG_FAXSUBADDRESS:
  1166. *va_arg(ap, char**) = sp->subaddress;
  1167. break;
  1168. case TIFFTAG_FAXRECVTIME:
  1169. *va_arg(ap, uint32*) = sp->recvtime;
  1170. break;
  1171. case TIFFTAG_FAXDCS:
  1172. *va_arg(ap, char**) = sp->faxdcs;
  1173. break;
  1174. default:
  1175. return (*sp->vgetparent)(tif, tag, ap);
  1176. }
  1177. return (1);
  1178. }
  1179. static void
  1180. Fax3PrintDir(TIFF* tif, FILE* fd, long flags)
  1181. {
  1182. Fax3BaseState* sp = Fax3State(tif);
  1183. assert(sp != 0);
  1184. (void) flags;
  1185. if (TIFFFieldSet(tif,FIELD_OPTIONS)) {
  1186. const char* sep = " ";
  1187. if (tif->tif_dir.td_compression == COMPRESSION_CCITTFAX4) {
  1188. fprintf(fd, " Group 4 Options:");
  1189. if (sp->groupoptions & GROUP4OPT_UNCOMPRESSED)
  1190. fprintf(fd, "%suncompressed data", sep);
  1191. } else {
  1192. fprintf(fd, " Group 3 Options:");
  1193. if (sp->groupoptions & GROUP3OPT_2DENCODING)
  1194. fprintf(fd, "%s2-d encoding", sep), sep = "+";
  1195. if (sp->groupoptions & GROUP3OPT_FILLBITS)
  1196. fprintf(fd, "%sEOL padding", sep), sep = "+";
  1197. if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
  1198. fprintf(fd, "%suncompressed data", sep);
  1199. }
  1200. fprintf(fd, " (%lu = 0x%lx)\n",
  1201. (unsigned long) sp->groupoptions,
  1202. (unsigned long) sp->groupoptions);
  1203. }
  1204. if (TIFFFieldSet(tif,FIELD_CLEANFAXDATA)) {
  1205. fprintf(fd, " Fax Data:");
  1206. switch (sp->cleanfaxdata) {
  1207. case CLEANFAXDATA_CLEAN:
  1208. fprintf(fd, " clean");
  1209. break;
  1210. case CLEANFAXDATA_REGENERATED:
  1211. fprintf(fd, " receiver regenerated");
  1212. break;
  1213. case CLEANFAXDATA_UNCLEAN:
  1214. fprintf(fd, " uncorrected errors");
  1215. break;
  1216. }
  1217. fprintf(fd, " (%u = 0x%x)\n",
  1218. sp->cleanfaxdata, sp->cleanfaxdata);
  1219. }
  1220. if (TIFFFieldSet(tif,FIELD_BADFAXLINES))
  1221. fprintf(fd, " Bad Fax Lines: %lu\n",
  1222. (unsigned long) sp->badfaxlines);
  1223. if (TIFFFieldSet(tif,FIELD_BADFAXRUN))
  1224. fprintf(fd, " Consecutive Bad Fax Lines: %lu\n",
  1225. (unsigned long) sp->badfaxrun);
  1226. if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
  1227. fprintf(fd, " Fax Receive Parameters: %08lx\n",
  1228. (unsigned long) sp->recvparams);
  1229. if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
  1230. fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress);
  1231. if (TIFFFieldSet(tif,FIELD_RECVTIME))
  1232. fprintf(fd, " Fax Receive Time: %lu secs\n",
  1233. (unsigned long) sp->recvtime);
  1234. if (TIFFFieldSet(tif,FIELD_FAXDCS))
  1235. fprintf(fd, " Fax DCS: %s\n", sp->faxdcs);
  1236. }
  1237. static int
  1238. InitCCITTFax3(TIFF* tif)
  1239. {
  1240. Fax3BaseState* sp;
  1241. /*
  1242. * Merge codec-specific tag information.
  1243. */
  1244. if (!_TIFFMergeFieldInfo(tif, faxFieldInfo, N(faxFieldInfo))) {
  1245. TIFFErrorExt(tif->tif_clientdata, "InitCCITTFax3",
  1246. "Merging common CCITT Fax codec-specific tags failed");
  1247. return 0;
  1248. }
  1249. /*
  1250. * Allocate state block so tag methods have storage to record values.
  1251. */
  1252. tif->tif_data = (tidata_t)
  1253. _TIFFmalloc(sizeof (Fax3CodecState));
  1254. if (tif->tif_data == NULL) {
  1255. TIFFErrorExt(tif->tif_clientdata, "TIFFInitCCITTFax3",
  1256. "%s: No space for state block", tif->tif_name);
  1257. return (0);
  1258. }
  1259. sp = Fax3State(tif);
  1260. sp->rw_mode = tif->tif_mode;
  1261. /*
  1262. * Override parent get/set field methods.
  1263. */
  1264. sp->vgetparent = tif->tif_tagmethods.vgetfield;
  1265. tif->tif_tagmethods.vgetfield = Fax3VGetField; /* hook for codec tags */
  1266. sp->vsetparent = tif->tif_tagmethods.vsetfield;
  1267. tif->tif_tagmethods.vsetfield = Fax3VSetField; /* hook for codec tags */
  1268. sp->printdir = tif->tif_tagmethods.printdir;
  1269. tif->tif_tagmethods.printdir = Fax3PrintDir; /* hook for codec tags */
  1270. sp->groupoptions = 0;
  1271. sp->recvparams = 0;
  1272. sp->subaddress = NULL;
  1273. sp->faxdcs = NULL;
  1274. if (sp->rw_mode == O_RDONLY) /* FIXME: improve for in place update */
  1275. tif->tif_flags |= TIFF_NOBITREV; /* decoder does bit reversal */
  1276. DecoderState(tif)->runs = NULL;
  1277. TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, _TIFFFax3fillruns);
  1278. EncoderState(tif)->refline = NULL;
  1279. /*
  1280. * Install codec methods.
  1281. */
  1282. tif->tif_setupdecode = Fax3SetupState;
  1283. tif->tif_predecode = Fax3PreDecode;
  1284. tif->tif_decoderow = Fax3Decode1D;
  1285. tif->tif_decodestrip = Fax3Decode1D;
  1286. tif->tif_decodetile = Fax3Decode1D;
  1287. tif->tif_setupencode = Fax3SetupState;
  1288. tif->tif_preencode = Fax3PreEncode;
  1289. tif->tif_postencode = Fax3PostEncode;
  1290. tif->tif_encoderow = Fax3Encode;
  1291. tif->tif_encodestrip = Fax3Encode;
  1292. tif->tif_encodetile = Fax3Encode;
  1293. tif->tif_close = Fax3Close;
  1294. tif->tif_cleanup = Fax3Cleanup;
  1295. return (1);
  1296. }
  1297. int
  1298. TIFFInitCCITTFax3(TIFF* tif, int scheme)
  1299. {
  1300. (void) scheme;
  1301. if (InitCCITTFax3(tif)) {
  1302. /*
  1303. * Merge codec-specific tag information.
  1304. */
  1305. if (!_TIFFMergeFieldInfo(tif, fax3FieldInfo, N(fax3FieldInfo))) {
  1306. TIFFErrorExt(tif->tif_clientdata, "TIFFInitCCITTFax3",
  1307. "Merging CCITT Fax 3 codec-specific tags failed");
  1308. return 0;
  1309. }
  1310. /*
  1311. * The default format is Class/F-style w/o RTC.
  1312. */
  1313. return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_CLASSF);
  1314. } else
  1315. return 01;
  1316. }
  1317. /*
  1318. * CCITT Group 4 (T.6) Facsimile-compatible
  1319. * Compression Scheme Support.
  1320. */
  1321. #define SWAP(t,a,b) { t x; x = (a); (a) = (b); (b) = x; }
  1322. /*
  1323. * Decode the requested amount of G4-encoded data.
  1324. */
  1325. static int
  1326. Fax4Decode(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  1327. {
  1328. DECLARE_STATE_2D(tif, sp, "Fax4Decode");
  1329. (void) s;
  1330. CACHE_STATE(tif, sp);
  1331. while ((long)occ > 0) {
  1332. a0 = 0;
  1333. RunLength = 0;
  1334. pa = thisrun = sp->curruns;
  1335. pb = sp->refruns;
  1336. b1 = *pb++;
  1337. #ifdef FAX3_DEBUG
  1338. printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  1339. printf("-------------------- %d\n", tif->tif_row);
  1340. fflush(stdout);
  1341. #endif
  1342. EXPAND2D(EOFG4);
  1343. if (EOLcnt)
  1344. goto EOFG4;
  1345. (*sp->fill)(buf, thisrun, pa, lastx);
  1346. SETVALUE(0); /* imaginary change for reference */
  1347. SWAP(uint32*, sp->curruns, sp->refruns);
  1348. buf += sp->b.rowbytes;
  1349. occ -= sp->b.rowbytes;
  1350. sp->line++;
  1351. continue;
  1352. EOFG4:
  1353. NeedBits16( 13, BADG4 );
  1354. BADG4:
  1355. #ifdef FAX3_DEBUG
  1356. if( GetBits(13) != 0x1001 )
  1357. fputs( "Bad EOFB\n", stderr );
  1358. #endif
  1359. ClrBits( 13 );
  1360. (*sp->fill)(buf, thisrun, pa, lastx);
  1361. UNCACHE_STATE(tif, sp);
  1362. return ( sp->line ? 1 : -1); /* don't error on badly-terminated strips */
  1363. }
  1364. UNCACHE_STATE(tif, sp);
  1365. return (1);
  1366. }
  1367. #undef SWAP
  1368. /*
  1369. * Encode the requested amount of data.
  1370. */
  1371. static int
  1372. Fax4Encode(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s)
  1373. {
  1374. Fax3CodecState *sp = EncoderState(tif);
  1375. (void) s;
  1376. while ((long)cc > 0) {
  1377. if (!Fax3Encode2DRow(tif, bp, sp->refline, sp->b.rowpixels))
  1378. return (0);
  1379. _TIFFmemcpy(sp->refline, bp, sp->b.rowbytes);
  1380. bp += sp->b.rowbytes;
  1381. cc -= sp->b.rowbytes;
  1382. }
  1383. return (1);
  1384. }
  1385. static int
  1386. Fax4PostEncode(TIFF* tif)
  1387. {
  1388. Fax3CodecState *sp = EncoderState(tif);
  1389. /* terminate strip w/ EOFB */
  1390. Fax3PutBits(tif, EOL, 12);
  1391. Fax3PutBits(tif, EOL, 12);
  1392. if (sp->bit != 8)
  1393. Fax3FlushBits(tif, sp);
  1394. return (1);
  1395. }
  1396. int
  1397. TIFFInitCCITTFax4(TIFF* tif, int scheme)
  1398. {
  1399. (void) scheme;
  1400. if (InitCCITTFax3(tif)) { /* reuse G3 support */
  1401. /*
  1402. * Merge codec-specific tag information.
  1403. */
  1404. if (!_TIFFMergeFieldInfo(tif, fax4FieldInfo, N(fax4FieldInfo))) {
  1405. TIFFErrorExt(tif->tif_clientdata, "TIFFInitCCITTFax4",
  1406. "Merging CCITT Fax 4 codec-specific tags failed");
  1407. return 0;
  1408. }
  1409. tif->tif_decoderow = Fax4Decode;
  1410. tif->tif_decodestrip = Fax4Decode;
  1411. tif->tif_decodetile = Fax4Decode;
  1412. tif->tif_encoderow = Fax4Encode;
  1413. tif->tif_encodestrip = Fax4Encode;
  1414. tif->tif_encodetile = Fax4Encode;
  1415. tif->tif_postencode = Fax4PostEncode;
  1416. /*
  1417. * Suppress RTC at the end of each strip.
  1418. */
  1419. return TIFFSetField(tif, TIFFTAG_FAXMODE, FAXMODE_NORTC);
  1420. } else
  1421. return (0);
  1422. }
  1423. /*
  1424. * CCITT Group 3 1-D Modified Huffman RLE Compression Support.
  1425. * (Compression algorithms 2 and 32771)
  1426. */
  1427. /*
  1428. * Decode the requested amount of RLE-encoded data.
  1429. */
  1430. static int
  1431. Fax3DecodeRLE(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
  1432. {
  1433. DECLARE_STATE(tif, sp, "Fax3DecodeRLE");
  1434. int mode = sp->b.mode;
  1435. (void) s;
  1436. CACHE_STATE(tif, sp);
  1437. thisrun = sp->curruns;
  1438. while ((long)occ > 0) {
  1439. a0 = 0;
  1440. RunLength = 0;
  1441. pa = thisrun;
  1442. #ifdef FAX3_DEBUG
  1443. printf("\nBitAcc=%08X, BitsAvail = %d\n", BitAcc, BitsAvail);
  1444. printf("-------------------- %d\n", tif->tif_row);
  1445. fflush(stdout);
  1446. #endif
  1447. EXPAND1D(EOFRLE);
  1448. (*sp->fill)(buf, thisrun, pa, lastx);
  1449. /*
  1450. * Cleanup at the end of the row.
  1451. */
  1452. if (mode & FAXMODE_BYTEALIGN) {
  1453. int n = BitsAvail - (BitsAvail &~ 7);
  1454. ClrBits(n);
  1455. } else if (mode & FAXMODE_WORDALIGN) {
  1456. int n = BitsAvail - (BitsAvail &~ 15);
  1457. ClrBits(n);
  1458. if (BitsAvail == 0 && !isAligned(cp, uint16))
  1459. cp++;
  1460. }
  1461. buf += sp->b.rowbytes;
  1462. occ -= sp->b.rowbytes;
  1463. sp->line++;
  1464. continue;
  1465. EOFRLE: /* premature EOF */
  1466. (*sp->fill)(buf, thisrun, pa, lastx);
  1467. UNCACHE_STATE(tif, sp);
  1468. return (-1);
  1469. }
  1470. UNCACHE_STATE(tif, sp);
  1471. return (1);
  1472. }
  1473. int
  1474. TIFFInitCCITTRLE(TIFF* tif, int scheme)
  1475. {
  1476. (void) scheme;
  1477. if (InitCCITTFax3(tif)) { /* reuse G3 support */
  1478. tif->tif_decoderow = Fax3DecodeRLE;
  1479. tif->tif_decodestrip = Fax3DecodeRLE;
  1480. tif->tif_decodetile = Fax3DecodeRLE;
  1481. /*
  1482. * Suppress RTC+EOLs when encoding and byte-align data.
  1483. */
  1484. return TIFFSetField(tif, TIFFTAG_FAXMODE,
  1485. FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_BYTEALIGN);
  1486. } else
  1487. return (0);
  1488. }
  1489. int
  1490. TIFFInitCCITTRLEW(TIFF* tif, int scheme)
  1491. {
  1492. (void) scheme;
  1493. if (InitCCITTFax3(tif)) { /* reuse G3 support */
  1494. tif->tif_decoderow = Fax3DecodeRLE;
  1495. tif->tif_decodestrip = Fax3DecodeRLE;
  1496. tif->tif_decodetile = Fax3DecodeRLE;
  1497. /*
  1498. * Suppress RTC+EOLs when encoding and word-align data.
  1499. */
  1500. return TIFFSetField(tif, TIFFTAG_FAXMODE,
  1501. FAXMODE_NORTC|FAXMODE_NOEOL|FAXMODE_WORDALIGN);
  1502. } else
  1503. return (0);
  1504. }
  1505. #endif /* CCITT_SUPPORT */
  1506. /* vim: set ts=8 sts=8 sw=8 noet: */
  1507. /*
  1508. * Local Variables:
  1509. * mode: c
  1510. * c-basic-offset: 8
  1511. * fill-column: 78
  1512. * End:
  1513. */