tif_fax3.c 61 KB

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