Debian Codegraph @

converter/pbm/g3topbm.c

raw
1 /*===========================================================================
2 g3topbm
3 =============================================================================
4
5 This program reads a Group 3 FAX file and produces a PBM image.
6
7 Bryan Henderson wrote this on August 5, 2004 and contributed it to
8 the public domain.
9
10 This program is designed to be a drop-in replacement for the program
11 of the same name that was distributed with Pbmplus and Netpbm since
12 1989, written by Paul Haeberli <[email protected]>.
13
14 Bryan used ideas on processing G3 data from Haeberli's code, but did
15 not use any of the code.
16
17 Others have modified the program since Bryan's initial work, each
18 contributing their work to the public domain.
19 ===========================================================================*/
20
21 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
22 #define _BSD_SOURCE /* Make nstring.h define strcaseeq() */
23
24 #include <assert.h>
25
26 #include "pm_c_util.h"
27 #include "pbm.h"
28 #include "shhopt.h"
29 #include "nstring.h"
30 #include "mallocvar.h"
31 #include "g3.h"
32 #include "g3ttable.h"
33 #include "bitreverse.h"
34 #include "bitarith.h"
35
36 #define LEFTBITS pm_byteLeftBits
37 #define RIGHTBITS pm_byteRightBits
38
39 #define MAXCOLS 10800
40 #define MAXROWS 14400 /* this allows up to two pages of image */
41
42 #define WHASHA 3510
43 #define WHASHB 1178
44
45 #define BHASHA 293
46 #define BHASHB 2695
47
48 #define HASHSIZE 1021
49
50 #define MAXFILLBITS (5 * 9600)
51
52 /*
53 Fill bits are for flow control. This was important when DRAM was
54 expensive and fax machines came with small buffers.
55
56 If data arrives too quickly it may overflow the buffer of the
57 receiving device. On sending devices transmission time of compressed
58 data representing a single row can be shorter than the time required
59 to scan and encode. The CCITT standard allows sending devices to
60 insert fill bits to put communication on hold in these cases.
61
62 By the CCITT standard, the maximum transmission time for one row is:
63
64 100 - 400 pixels/inch 13 seconds
65 (standard mode: 200 pixels/inch)
66 600 pixels/inch 19 seconds
67 1200 pixels/inch 37 seconds
68
69 If one row is not received within the above limits, the receiving
70 machine must disconnect the line.
71
72 The receiver may be less patient. It may opt to disconnect if one row
73 is not received within 5 seconds.
74 */
75
76 struct CmdlineInfo {
77 /* All the information the user supplied in the command line,
78 in a form easy for the program to use.
79 */
80 const char * inputFilespec; /* Filespec of input file */
81 unsigned int reversebits;
82 unsigned int kludge;
83 unsigned int stretch;
84 unsigned int stop_error;
85 unsigned int expectedLineSize;
86 unsigned int correctlong;
87 };
88
89
90
91 static void
92 parseCommandLine(int argc, const char ** const argv,
93 struct CmdlineInfo * const cmdlineP) {
94 /*----------------------------------------------------------------------------
95 Note that the file spec array we return is stored in the storage that
96 was passed to us as the argv array.
97 -----------------------------------------------------------------------------*/
98 optEntry * option_def; /* malloc'ed */
99 optStruct3 opt;
100
101 unsigned int option_def_index;
102
103 unsigned int widthSpec, paper_sizeSpec;
104 const char * paperSize;
105
106 MALLOCARRAY_NOFAIL(option_def, 100);
107
108 option_def_index = 0; /* incremented by OPTENTRY */
109 OPTENT3(0, "reversebits", OPT_FLAG, NULL, &cmdlineP->reversebits,
110 0);
111 OPTENT3(0, "kludge", OPT_FLAG, NULL, &cmdlineP->kludge,
112 0);
113 OPTENT3(0, "stretch", OPT_FLAG, NULL, &cmdlineP->stretch,
114 0);
115 OPTENT3(0, "stop_error", OPT_FLAG, NULL, &cmdlineP->stop_error,
116 0);
117 OPTENT3(0, "width", OPT_UINT, &cmdlineP->expectedLineSize,
118 &widthSpec, 0);
119 OPTENT3(0, "paper_size", OPT_STRING, &paperSize,
120 &paper_sizeSpec, 0);
121 OPTENT3(0, "correctlong", OPT_FLAG, NULL, &cmdlineP->correctlong,
122 0);
123
124 opt.opt_table = option_def;
125 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
126 opt.allowNegNum = FALSE; /* We may have parms that are negative numbers */
127
128 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
129 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
130
131 if (widthSpec && paper_sizeSpec)
132 pm_error("You can't specify both -width and -paper_size");
133
134 if (widthSpec) {
135 if (cmdlineP->expectedLineSize < 1)
136 pm_error("-width must be at least 1");
137 } else if (paper_sizeSpec) {
138 if (strcaseeq(paperSize, "A6"))
139 cmdlineP->expectedLineSize = 864;
140 else if (strcaseeq(paperSize, "A5"))
141 cmdlineP->expectedLineSize = 1216;
142 else if (strcaseeq(paperSize, "A4"))
143 cmdlineP->expectedLineSize = 1728;
144 else if (strcaseeq(paperSize, "B4"))
145 cmdlineP->expectedLineSize = 2048;
146 else if (strcaseeq(paperSize, "A3"))
147 cmdlineP->expectedLineSize = 2432;
148 else
149 pm_error("Unrecognized value for -paper_size '%s'. "
150 "We recognize only A3, A4, A5, A6, and B4.",
151 paperSize);
152 } else
153 cmdlineP->expectedLineSize = 0;
154
155 if (argc-1 == 0)
156 cmdlineP->inputFilespec = "-";
157 else if (argc-1 != 1)
158 pm_error("Program takes zero or one argument (filename). You "
159 "specified %d", argc-1);
160 else
161 cmdlineP->inputFilespec = argv[1];
162 }
163
164
165
166 typedef struct {
167 const G3TableEntry * whash[HASHSIZE];
168 const G3TableEntry * bhash[HASHSIZE];
169 } BwHash;
170
171 struct BitStream {
172
173 FILE * fileP;
174 bool reversebits;
175 int shdata;
176 /* 8-bit buffer for rawgetbit(). */
177 unsigned int shbit;
178 /* single bit mask for the bit of 'shdata' that is next in the stream.
179 zero when 'shdata' is empty.
180 */
181 unsigned int zeroBitCount;
182 /* Number of consecutive zero bits the stream has seen. Note that
183 because an EOL mark ends in a one bit, this starts over for each
184 line.
185 */
186 };
187
188
189
190 static void
191 readBit(struct BitStream * const bitStreamP,
192 unsigned int * const bitP,
193 const char ** const errorP) {
194 /*----------------------------------------------------------------------------
195 Return the next raw bit from the G3 input stream.
196
197 Do not call this outside of the bit stream object; Caller is responsible
198 for maintaining object state.
199 -----------------------------------------------------------------------------*/
200 *errorP = NULL; /* initial assumption */
201
202 if ((bitStreamP->shbit & 0xff) == 0) {
203 bitStreamP->shdata = getc(bitStreamP->fileP);
204 if (bitStreamP->shdata == EOF)
205 pm_asprintf(errorP, "EOF or error reading file");
206 else {
207 bitStreamP->shbit = 0x80;
208 if ( bitStreamP->reversebits )
209 bitStreamP->shdata = bitreverse[ bitStreamP->shdata ];
210 }
211 }
212
213 if (bitStreamP->shdata & bitStreamP->shbit)
214 *bitP = 1;
215 else
216 *bitP = 0;
217
218 bitStreamP->shbit >>= 1;
219 }
220
221
222
223 static void
224 readBitAndDetectEol(struct BitStream * const bitStreamP,
225 unsigned int * const bitP,
226 bool * const eolP,
227 const char ** const errorP) {
228 /*----------------------------------------------------------------------------
229 Same as readBit(), but iff the bit read is the final bit of an EOL
230 mark, return *eolP == TRUE.
231
232 An EOL mark is 11 zero bits followed by a one.
233 -----------------------------------------------------------------------------*/
234 readBit(bitStreamP, bitP, errorP);
235 if (!*errorP) {
236 bool eol;
237
238 eol = FALSE; /* initial assumption */
239 if (*bitP == 0)
240 ++bitStreamP->zeroBitCount;
241 else {
242 if (bitStreamP->zeroBitCount >= 11)
243 eol = TRUE;
244 bitStreamP->zeroBitCount = 0;
245 }
246 *eolP = eol;
247 }
248 }
249
250
251
252 static void
253 initBitStream(struct BitStream * const bitStreamP,
254 FILE * const fileP,
255 bool const reversebits) {
256
257 bitStreamP->fileP = fileP;
258 bitStreamP->reversebits = reversebits;
259 bitStreamP->shbit = 0x00;
260 bitStreamP->zeroBitCount = 0;
261 }
262
263
264
265 static void
266 skipToNextLine(struct BitStream * const bitStreamP) {
267
268 bool eol;
269 const char * error;
270
271 eol = FALSE;
272 error = NULL;
273
274 while (!eol && !error) {
275 unsigned int bit;
276
277 readBitAndDetectEol(bitStreamP, &bit, &eol, &error);
278 }
279 }
280
281
282
283 static void
284 addtohash(const G3TableEntry ** const hash,
285 const G3TableEntry * const table,
286 unsigned int const n,
287 int const a,
288 int const b) {
289
290 unsigned int i;
291
292 for (i = 0; i < n; ++i) {
293 const G3TableEntry * const teP = &table[i*2];
294 unsigned int const pos =
295 ((teP->length + a) * (teP->code + b)) % HASHSIZE;
296 if (hash[pos])
297 pm_error("internal error: addtohash fatal hash collision");
298 hash[pos] = teP;
299 }
300 }
301
302
303
304 static const G3TableEntry *
305 hashfind(const G3TableEntry * const * const hash,
306 unsigned int const length,
307 int const code,
308 int const a,
309 int const b) {
310
311 unsigned int const pos = ((length + a) * (code + b)) % HASHSIZE;
312 const G3TableEntry * const teP = hash[pos];
313
314 return ((teP && teP->length == length && teP->code == code) ? teP : NULL);
315 }
316
317
318
319 static BwHash *
320 newBwHash() {
321
322 BwHash * bwHashP;
323
324 MALLOCVAR(bwHashP);
325
326 if (!bwHashP)
327 pm_error("Unable to allocate memory for hashes");
328 else {
329 unsigned int i;
330 /* Initialize */
331 for (i = 0; i < HASHSIZE; ++i)
332 bwHashP->whash[i] = bwHashP->bhash[i] = NULL;
333
334 addtohash(bwHashP->whash, &g3ttable_table [0], 64, WHASHA, WHASHB);
335 addtohash(bwHashP->whash, &g3ttable_mtable[2], 40, WHASHA, WHASHB);
336
337 addtohash(bwHashP->bhash, &g3ttable_table [1], 64, BHASHA, BHASHB);
338 addtohash(bwHashP->bhash, &g3ttable_mtable[3], 40, BHASHA, BHASHB);
339 }
340 return bwHashP;
341 }
342
343
344
345 static void
346 freeBwHash(BwHash * const bwHashP) {
347
348 free(bwHashP);
349 }
350
351
352
353 static void
354 makeRowWhite(unsigned char * const packedBitrow,
355 unsigned int const cols) {
356
357 unsigned int colByte;
358 for (colByte = 0; colByte < pbm_packed_bytes(cols); ++colByte)
359 packedBitrow[colByte] = PBM_WHITE * 0xff;
360 }
361
362
363
364 static const G3TableEntry *
365 g3code(unsigned int const curcode,
366 unsigned int const curlen,
367 bit const color,
368 const BwHash * const bwHashP) {
369 /*----------------------------------------------------------------------------
370 Return the position in the code tables mtable and ttable of the
371 G3 code which is the 'curlen' bits long with value 'curcode'.
372
373 Note that it is the _position_ in the table that determines the meaning
374 of the code. The contents of the table entry do not.
375 -----------------------------------------------------------------------------*/
376 const G3TableEntry * retval;
377
378 switch (color) {
379 case PBM_WHITE:
380 if (curlen < 4)
381 retval = NULL;
382 else
383 retval = hashfind(bwHashP->whash, curlen, curcode, WHASHA, WHASHB);
384 break;
385 case PBM_BLACK:
386 if (curlen < 2)
387 retval = NULL;
388 else
389 retval = hashfind(bwHashP->bhash, curlen, curcode, BHASHA, BHASHB);
390 break;
391 default:
392 pm_error("INTERNAL ERROR: color is not black or white");
393 }
394 return retval;
395 }
396
397
398
399 static void
400 writeBlackBitSpan(unsigned char * const packedBitrow,
401 int const cols,
402 int const offset) {
403 /*----------------------------------------------------------------------------
404 Write black (="1") bits into packedBitrow[], starting at 'offset',
405 length 'cols'.
406 -----------------------------------------------------------------------------*/
407 unsigned char * const dest = & packedBitrow[offset/8];
408 unsigned int const rs = offset % 8;
409 unsigned int const trs = (cols + rs) % 8;
410 unsigned int const colBytes = pbm_packed_bytes(cols + rs);
411 unsigned int const last = colBytes - 1;
412
413 unsigned char const origHead = dest[0];
414 unsigned char const origEnd = 0x00;
415
416 unsigned int i;
417
418 for( i = 0; i < colBytes; ++i)
419 dest[i] = PBM_BLACK * 0xff;
420
421 if (rs > 0)
422 dest[0] = LEFTBITS(origHead, rs) | RIGHTBITS(dest[0], 8-rs);
423
424 if (trs > 0)
425 dest[last] = LEFTBITS(dest[last], trs) | RIGHTBITS(origEnd, 8-trs);
426 }
427
428
429
430 enum g3tableId {TERMWHITE, TERMBLACK, MKUPWHITE, MKUPBLACK};
431
432 static void
433 processG3Code(const G3TableEntry * const teP,
434 unsigned char * const packedBitrow,
435 unsigned int * const colP,
436 bit * const colorP,
437 unsigned int * const countP) {
438 /*----------------------------------------------------------------------------
439 'teP' is a pointer into the mtable/ttable. Note that the thing it points
440 to is irrelevant to us; it is only the position in the table that
441 matters.
442 -----------------------------------------------------------------------------*/
443 enum g3tableId const teId =
444 (teP > g3ttable_mtable ? 2 : 0) + (teP - g3ttable_table) % 2;
445
446 unsigned int teCount;
447
448 switch(teId) {
449 case TERMWHITE: teCount = (teP - g3ttable_table ) / 2; break;
450 case TERMBLACK: teCount = (teP - g3ttable_table - 1) / 2; break;
451 case MKUPWHITE: teCount = (teP - g3ttable_mtable ) / 2 * 64; break;
452 case MKUPBLACK: teCount = (teP - g3ttable_mtable - 1) / 2 * 64; break;
453 }
454
455 switch (teId) {
456 case TERMWHITE:
457 case TERMBLACK: {
458 unsigned int totalRunLength;
459 unsigned int col;
460
461 col = *colP;
462 totalRunLength = MIN(*countP + teCount, MAXCOLS - col);
463
464 if (totalRunLength > 0) {
465 if (*colorP == PBM_BLACK)
466 writeBlackBitSpan(packedBitrow, totalRunLength, col);
467 /* else : Row was initialized to white, so we just skip */
468 col += totalRunLength;
469 }
470 *colorP = !*colorP;
471 *countP = 0;
472 *colP = col;
473 } break;
474 case MKUPWHITE:
475 case MKUPBLACK:
476 *countP += teCount;
477 break;
478 default:
479 pm_error("Can't happen");
480 }
481 }
482
483
484
485 static void
486 formatBadCodeException(const char ** const exceptionP,
487 unsigned int const col,
488 unsigned int const curlen,
489 unsigned int const curcode) {
490
491 pm_asprintf(exceptionP,
492 "bad code word at Column %u. "
493 "No prefix of the %u bits 0x%x matches any recognized "
494 "code word and no code words longer than 13 bits are "
495 "defined. ",
496 col, curlen, curcode);
497 }
498
499
500
501 static void
502 readFaxRow(struct BitStream * const bitStreamP,
503 unsigned char * const packedBitrow,
504 BwHash * const bwHashP,
505 unsigned int * const lineLengthP,
506 const char ** const exceptionP,
507 const char ** const errorP) {
508 /*----------------------------------------------------------------------------
509 Read one line of G3 fax from the bit stream *bitStreamP into
510 packedBitrow[]. Return the length of the line, in pixels, as *lineLengthP.
511
512 If there's a problem with the line, return as much of it as we can,
513 advance the input stream past the next EOL mark, and put a text
514 description of the problem in newly malloc'ed storage at
515 *exceptionP. If there's no problem, return *exceptionP = NULL.
516
517 We guarantee that we make progress through the input stream.
518
519 Iff there is an error, return a text description of it in newly
520 malloc'ed storage at *errorP and all other specified behavior
521 (including return values) is unspecified.
522 -----------------------------------------------------------------------------*/
523 unsigned int col;
524 unsigned int curlen;
525 /* Number of bits we've read so far for the code we're currently
526 reading
527 */
528 unsigned int fillbits;
529 /* Number of consecutive 0 bits. Can precede EOL codes */
530 unsigned int curcode;
531 /* What we've assembled so far of the code we're currently reading */
532 unsigned int count;
533 /* Number of consecutive pixels of the same color */
534 bit currentColor;
535 /* The color of the current run of pixels */
536 bool done;
537
538 makeRowWhite(packedBitrow, MAXCOLS); /* initialize row */
539
540 col = 0;
541 curlen = 0;
542 curcode = 0;
543 fillbits = 0;
544 currentColor = PBM_WHITE;
545 count = 0;
546 *exceptionP = NULL;
547 *errorP = NULL;
548 done = FALSE;
549
550 while (!done) {
551 if (col >= MAXCOLS) {
552 pm_asprintf(exceptionP, "Line is too long for this program to "
553 "handle -- longer than %u columns", MAXCOLS);
554 done = TRUE;
555 } else {
556 unsigned int bit;
557 bool eol;
558 const char * error;
559
560 readBitAndDetectEol(bitStreamP, &bit, &eol, &error);
561 if (error) {
562 if (col > 0)
563 /* We got at least some of the row, so it's only an
564 exception, not a fatal error.
565 */
566 *exceptionP = error;
567 else
568 *errorP = error;
569 done = TRUE;
570 } else if (eol)
571 done = TRUE;
572 else {
573 curcode = (curcode << 1) | bit;
574 ++curlen;
575
576 if (curlen > 11 && curcode == 0x00) {
577 if (++fillbits > MAXFILLBITS)
578 pm_error("Encountered %u consecutive fill bits. "
579 "Aborting", fillbits);
580 } else if (curlen - fillbits > 13) {
581 formatBadCodeException(exceptionP, col, curlen, curcode);
582 done = TRUE;
583 } else if (curcode != 0) {
584 const G3TableEntry * const teP =
585 g3code(curcode, curlen, currentColor, bwHashP);
586 /* Address of structure that describes the
587 current G3 code. Null means 'curcode' isn't
588 a G3 code yet (probably just the beginning of one)
589 */
590 if (teP) {
591 processG3Code(teP, packedBitrow,
592 &col, &currentColor, &count);
593
594 curcode = 0;
595 curlen = 0;
596 }
597 }
598 }
599 }
600 }
601 if (*exceptionP)
602 skipToNextLine(bitStreamP);
603
604 *lineLengthP = col;
605 }
606
607
608
609 static void
610 freeBits(unsigned char ** const packedBits,
611 unsigned int const rows,
612 bool const stretched) {
613
614 unsigned int row;
615
616 for (row = 0; row < rows; ++row) {
617 if (stretched && row % 2 == 1) {
618 /* This is just a pointer to the previous row; don't want to
619 free it twice.
620 */
621 } else
622 pbm_freerow_packed(packedBits[row]);
623 }
624 free(packedBits);
625 }
626
627
628
629 static void
630 handleRowException(const char * const exception,
631 const char * const error,
632 unsigned int const row,
633 bool const tolerateErrors) {
634
635
636 if (exception) {
637 if (tolerateErrors)
638 pm_message("Problem reading Row %u. Skipping rest of row. %s",
639 row, exception);
640 else
641 pm_error("Problem reading Row %u. Aborting. %s", row, exception);
642 pm_strfree(exception);
643 }
644
645 if (error) {
646 if (tolerateErrors)
647 pm_message("Unable to read Row %u. Skipping rest of image. %s",
648 row, error);
649 else
650 pm_error("Unable to read Row %u. Aborting. %s", row, error);
651 pm_strfree(error);
652 }
653 }
654
655
656
657 typedef struct {
658 unsigned int expectedLineSize;
659 /* The size that lines are supposed to be. Zero means we're happy
660 with any size.
661 */
662 unsigned int maxLineSize;
663 /* The maximum line size we have seen so far, or zero if we have
664 not seen any lines yet.
665 */
666 bool warned;
667 /* We have warned the user that he has a line length problem */
668
669 bool tolerateErrors;
670 /* Try to continue when we detect a line size error, as opposed to
671 aborting the program.
672 */
673 unsigned int lineSizeCt[MAXCOLS+1];
674 /* Histogram of line sizes in image -- lineSizeCt[i] is the number
675 of lines we've seen of size i.
676 */
677 } LineSizeAnalyzer;
678
679
680
681 static void
682 initializeLineSizeAnalyzer(LineSizeAnalyzer * const analyzerP,
683 unsigned int const expectedLineSize,
684 bool const tolerateErrors) {
685
686 analyzerP->expectedLineSize = expectedLineSize;
687 analyzerP->tolerateErrors = tolerateErrors;
688
689 analyzerP->maxLineSize = 0;
690 analyzerP->warned = FALSE;
691
692 {
693 unsigned int i;
694
695 for (i = 0; i < MAXCOLS; ++i)
696 analyzerP->lineSizeCt[i] = 0;
697 }
698 }
699
700
701
702 static void
703 analyzeLineSize(LineSizeAnalyzer * const analyzerP,
704 unsigned int const thisLineSize) {
705
706 const char * error;
707
708 if (analyzerP->expectedLineSize &&
709 thisLineSize != analyzerP->expectedLineSize)
710 pm_asprintf(&error, "Image contains a line of %u pixels. "
711 "You specified lines should be %u pixels.",
712 thisLineSize, analyzerP->expectedLineSize);
713 else {
714 if (analyzerP->maxLineSize && thisLineSize != analyzerP->maxLineSize)
715 pm_asprintf(&error, "There are at least two different "
716 "line lengths in this image, "
717 "%u pixels and %u pixels. "
718 "This is a violation of the G3 standard. ",
719 thisLineSize, analyzerP->maxLineSize);
720 else
721 error = NULL;
722 }
723
724 if (error) {
725 if (analyzerP->tolerateErrors) {
726 if (!analyzerP->warned) {
727 pm_message("Warning: %s.", error);
728 analyzerP->warned = TRUE;
729 }
730 } else
731 pm_error("%s", error);
732
733 pm_strfree(error);
734 }
735 analyzerP->maxLineSize = MAX(thisLineSize, analyzerP->maxLineSize);
736
737 assert(thisLineSize <= MAXCOLS);
738 ++analyzerP->lineSizeCt[thisLineSize];
739 }
740
741
742
743 static unsigned int
744 imageLineSize(const LineSizeAnalyzer * const lineSizeAnalyzerP,
745 bool const mustCorrectLongLine) {
746 /*----------------------------------------------------------------------------
747 The width of the fax in pixels, based on the analysis of the image
748 *lineSizeAnalyzerP.
749
750 Zero if the fax contains no lines.
751 -----------------------------------------------------------------------------*/
752 unsigned int retval;
753
754 if (mustCorrectLongLine) {
755 /* Assume that long lines are actually concatenation of two
756 lines because the EOL code that was supposed to separate them
757 got lost.
758
759 Assume the most common line length in the image is the correct line
760 length for the image and that other line lengths are due to
761 corruption
762 */
763 unsigned int modeSoFar;
764 unsigned int i;
765
766 for (i = 0, modeSoFar = 0; i <= MAXCOLS; ++i) {
767 if (lineSizeAnalyzerP->lineSizeCt[i] > modeSoFar)
768 modeSoFar = i;
769 }
770 retval = modeSoFar;
771 } else {
772 retval = lineSizeAnalyzerP->maxLineSize;
773 }
774 return retval;
775 }
776
777
778
779 /* An empty line means EOF. An ancient comment in the code said there
780 is supposed to be 6 EOL marks in a row to indicate EOF, but the code
781 checked for 3 and considered 2 in a row just to mean a zero length
782 line. Starting in Netpbm 10.24 (August 2004), we assume there is
783 no valid reason to have an empty line and recognize EOF as any
784 empty line. Alternatively, we could read off and ignore two empty
785 lines without a 3rd.
786 */
787
788 static void
789 readFax(struct BitStream * const bitStreamP,
790 bool const stretch,
791 unsigned int const expectedLineSize,
792 bool const mustTolerateErrors,
793 bool const mustCorrectLongLine,
794 BwHash * const bwHashP,
795 unsigned char *** const packedBitsP,
796 unsigned int * const colsP,
797 unsigned int * const rowsP) {
798
799 LineSizeAnalyzer lineSizeAnalyzer;
800 unsigned char ** packedBits;
801 const char * error;
802 bool eof;
803 unsigned int row;
804
805 MALLOCARRAY_NOFAIL(packedBits, MAXROWS);
806
807 initializeLineSizeAnalyzer(&lineSizeAnalyzer,
808 expectedLineSize, mustTolerateErrors);
809
810 eof = FALSE;
811 error = NULL;
812 row = 0;
813
814 while (!eof && !error) {
815 unsigned int lineSize;
816
817 if (row >= MAXROWS)
818 pm_asprintf(&error, "Image is too tall. This program can "
819 "handle at most %u rows", MAXROWS);
820 else {
821 const char * exception;
822
823 packedBits[row] = pbm_allocrow_packed(MAXCOLS);
824 readFaxRow(bitStreamP, packedBits[row], bwHashP,
825 &lineSize, &exception, &error);
826
827 handleRowException(exception, error, row, mustTolerateErrors);
828
829 if (!error) {
830 if (lineSize == 0) {
831 /* EOF. See explanation above */
832 eof = TRUE;
833 } else {
834 analyzeLineSize(&lineSizeAnalyzer, lineSize);
835
836 if (stretch) {
837 ++row;
838 if (row >= MAXROWS)
839 pm_asprintf(&error, "Image is too tall. This "
840 "program can handle at most %u rows "
841 "after stretching", MAXROWS);
842 else
843 packedBits[row] = packedBits[row-1];
844 }
845 ++row;
846 }
847 }
848 }
849 }
850 *rowsP = row;
851 *colsP = imageLineSize(&lineSizeAnalyzer, mustCorrectLongLine);
852
853 *packedBitsP = packedBits;
854 }
855
856
857
858 int
859 main(int argc, const char * argv[]) {
860
861 struct CmdlineInfo cmdline;
862 FILE * ifP;
863 struct BitStream bitStream;
864 unsigned int rows, cols;
865 unsigned char ** packedBits;
866 BwHash * bwHashP;
867
868 pm_proginit(&argc, argv);
869
870 parseCommandLine(argc, argv, &cmdline);
871
872 ifP = pm_openr(cmdline.inputFilespec);
873
874 initBitStream(&bitStream, ifP, cmdline.reversebits);
875
876 if (cmdline.kludge) {
877 /* Skip extra lines to get in sync. */
878 skipToNextLine(&bitStream);
879 skipToNextLine(&bitStream);
880 skipToNextLine(&bitStream);
881 }
882 skipToNextLine(&bitStream);
883
884 bwHashP = newBwHash();
885
886 readFax(&bitStream, cmdline.stretch, cmdline.expectedLineSize,
887 !cmdline.stop_error, !!cmdline.correctlong, bwHashP,
888 &packedBits, &cols, &rows);
889
890 pm_close(ifP);
891
892 if (cols > 0 && rows > 0) {
893 unsigned int row;
894 pbm_writepbminit(stdout, cols, rows, 0);
895 for (row = 0; row < rows; ++row)
896 pbm_writepbmrow_packed(stdout, packedBits[row], cols, 0);
897 } else
898 pm_error("No image data in input");
899
900 pm_close(stdout);
901
902 freeBits(packedBits, rows, cmdline.stretch);
903
904 freeBwHash(bwHashP);
905
906 return 0;
907 }
908
909
910