Debian Codegraph @

converter/pbm/pbmtog3.c

raw
1 /* pbmtog3.c - read a PBM image and produce a Group 3 FAX file
2
3 For specifications for Group 3 (G3) fax MH coding see ITU-T T.4:
4 Standardization of Group 3 facsimile terminals for document transmission
5 https://www.itu.int/rec/T-REC-T.4/en
6
7 This program generates only MH.
8 */
9
10
11 #include <assert.h>
12
13 #include "pm_c_util.h"
14 #include "shhopt.h"
15 #include "mallocvar.h"
16 #include "bitreverse.h"
17 #include "intcode.h"
18 #include "g3.h"
19 #include "g3ttable.h"
20 #include "g3prefab.h"
21 #include "pbm.h"
22
23 enum G3eol {EOL, ALIGN8, ALIGN16, NO_EOL, NO_RTC, NO_EOLRTC};
24
25 struct OutStream;
26
27 struct OutStream {
28 FILE * fp;
29 struct BitString buffer;
30 bool reverseBits; /* Reverse bit order */
31 enum G3eol eolAlign; /* Omit EOL and/or RTC; align EOL to 8/16 bits */
32 void * data; /* Reserved for future expansion */
33 };
34
35
36
37 struct CmdlineInfo {
38 /* All the information the user supplied in the command line,
39 in a form easy for the program to use.
40 */
41 const char * inputFileName;
42 unsigned int reversebits;
43 enum G3eol align;
44 unsigned int desiredWidth;
45 unsigned int verbose;
46 };
47
48
49
50 static void
51 parseCommandLine(int argc, const char ** const argv,
52 struct CmdlineInfo * const cmdlineP) {
53 /*----------------------------------------------------------------------------
54 Note that the file spec array we return is stored in the storage that
55 was passed to us as the argv array.
56 -----------------------------------------------------------------------------*/
57 optEntry * option_def;
58 /* Instructions to OptParseOptions2 on how to parse our options. */
59 optStruct3 opt;
60 unsigned int option_def_index;
61
62 unsigned int nofixedwidth;
63 unsigned int align8, align16;
64
65 MALLOCARRAY_NOFAIL(option_def, 100);
66
67 option_def_index = 0; /* incremented by OPTENTRY */
68 OPTENT3(0, "reversebits", OPT_FLAG, NULL, &cmdlineP->reversebits,
69 0);
70 OPTENT3(0, "nofixedwidth", OPT_FLAG, NULL, &nofixedwidth,
71 0);
72 OPTENT3(0, "align8", OPT_FLAG, NULL, &align8,
73 0);
74 OPTENT3(0, "align16", OPT_FLAG, NULL, &align16,
75 0);
76 OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose,
77 0);
78
79 /* TODO
80 Explicit fixed widths: -A4 -B4 -A3
81 */
82
83 opt.opt_table = option_def;
84 opt.short_allowed = false; /* We have no short (old-fashioned) options */
85 opt.allowNegNum = true; /* We may have parms that are negative numbers */
86
87 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
88 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
89
90 free(option_def);
91
92 if (align8) {
93 if (align16)
94 pm_error("You can't specify both -align8 and -align16");
95 else
96 cmdlineP->align = ALIGN8;
97 } else if (align16)
98 cmdlineP->align = ALIGN16;
99 else
100 cmdlineP->align = EOL;
101
102 if (nofixedwidth)
103 cmdlineP->desiredWidth = 0;
104 else
105 cmdlineP->desiredWidth = 1728;
106
107 if (argc-1 == 0)
108 cmdlineP->inputFileName = "-";
109 else if (argc-1 != 1)
110 pm_error("Program takes zero or one argument (filename). You "
111 "specified %d", argc-1);
112 else
113 cmdlineP->inputFileName = argv[1];
114 }
115
116
117
118 static void
119 reversebuffer(unsigned char * const p,
120 unsigned int const n) {
121
122 unsigned int i;
123
124 for (i = 0; i < n; ++i)
125 p[i] = bitreverse[p[i]];
126 }
127
128
129
130 static void
131 flushBuffer(struct OutStream * const outP) {
132 /*----------------------------------------------------------------------------
133 Flush the contents of the bit buffer
134 -----------------------------------------------------------------------------*/
135 struct BitString const buffer = outP->buffer;
136
137 assert (buffer.bitCount <= 32);
138
139 if (buffer.bitCount > 0) {
140 unsigned int const fullBuffer = sizeof(buffer.intBuffer) * 8;
141 unsigned int const bytesToWrite = (buffer.bitCount+7)/8;
142 bigend32 outbytes;
143 size_t rc;
144
145 outbytes = pm_bigendFromUint32(
146 buffer.intBuffer << (fullBuffer - buffer.bitCount));
147 if (outP->reverseBits)
148 reversebuffer((unsigned char *)&outbytes, bytesToWrite);
149 rc = fwrite((unsigned char *)&outbytes, 1, bytesToWrite, outP->fp);
150 if (rc != bytesToWrite)
151 pm_error("Output error");
152 }
153 }
154
155
156
157 #if 1==0
158 static void
159 putbitsDump(struct OutStream * const outP,
160 struct BitString const newBits) {
161 /*----------------------------------------------------------------------------
162 Print the content of the bit put request, in human readable text form
163 For debugging. Also good for studying how the coding scheme works.
164
165 By default the compiler ignores this function.
166 To turn on, remove the "#if" - "#endif" lines enclosing the function and
167 edit the output function name in putbits().
168 -----------------------------------------------------------------------------*/
169 unsigned int const bitCount = newBits.bitCount;
170
171 unsigned int i;
172 char charBuff[128];
173
174 assert (bitCount >= 0 && bitCount < 32);
175 assert (sizeof(newBits.intBuffer) + 2 < 128);
176
177 for (i = 0; i < bitCount; ++i) {
178 unsigned int const n = bitCount - i - 1;
179 charBuff[i] = ((newBits.intBuffer >> n) & 0x01) + '0';
180 }
181
182 charBuff[bitCount] = '\n';
183 charBuff[bitCount+1] = '\0';
184 fwrite(charBuff, 1, bitCount+1, outP->fp);
185 }
186 #endif
187
188
189
190 static void
191 putbitsBinary(struct OutStream * const outP,
192 struct BitString const newBits) {
193 /*----------------------------------------------------------------------------
194 Push the bits 'newBits' onto the right end of output buffer
195 out.buffer (moving the bits already in the buffer left).
196
197 Flush the buffer to stdout as necessary to make room.
198
199 'newBits' must be shorter than a whole word.
200
201 N.B. the definition of struct BitString requires upper bits to be zero.
202 -----------------------------------------------------------------------------*/
203 unsigned int const fullBuffer = sizeof(outP->buffer.intBuffer) * 8;
204 unsigned int const spaceLeft = fullBuffer - outP->buffer.bitCount;
205 /* Number of bits of unused space (at the high end) in buffer */
206
207 assert(newBits.bitCount < fullBuffer);
208 assert(newBits.intBuffer >> newBits.bitCount == 0);
209
210 if (spaceLeft > newBits.bitCount) {
211 /* New bits fit with bits to spare */
212 outP->buffer.intBuffer =
213 outP->buffer.intBuffer << newBits.bitCount | newBits.intBuffer;
214 outP->buffer.bitCount += newBits.bitCount;
215 } else {
216 /* New bits fill buffer. We'll have to flush the buffer to stdout
217 and put the rest of the bits in the new buffer.
218 */
219 unsigned int const nextBufBitCount = newBits.bitCount - spaceLeft;
220 unsigned int const bitMask = ((1<<nextBufBitCount) - 1);
221
222 outP->buffer.intBuffer = ( (outP->buffer.intBuffer << spaceLeft)
223 | (newBits.intBuffer >> nextBufBitCount));
224 outP->buffer.bitCount = fullBuffer;
225 flushBuffer(outP);
226
227 outP->buffer.intBuffer = newBits.intBuffer & bitMask;
228 outP->buffer.bitCount = nextBufBitCount;
229 }
230 }
231
232
233
234 static void
235 initOutStream(struct OutStream * const outP,
236 bool const reverseBits,
237 enum G3eol const eolAlign) {
238
239 outP->buffer.intBuffer = 0;
240 outP->buffer.bitCount = 0;
241 outP->reverseBits = reverseBits;
242 outP->fp = stdout;
243 outP->eolAlign = eolAlign;
244 }
245
246
247
248 static struct BitString
249 tableEntryToBitString(G3TableEntry const tableEntry) {
250
251 struct BitString retval;
252
253 retval.intBuffer = tableEntry.code;
254 retval.bitCount = tableEntry.length;
255
256 return retval;
257 }
258
259
260
261 static void
262 putbits(struct OutStream * const outP,
263 struct BitString const newBits) {
264
265 putbitsBinary(outP, newBits);
266 /* Change to putbitsDump() for human readable output */
267 }
268
269
270
271 static void
272 putcodeShort(struct OutStream * const outP,
273 bit const color,
274 unsigned int const runLength) {
275
276 /* Note that this requires g3ttable_table to be aligned white entry, black
277 entry, white, black, etc.
278 */
279 unsigned int index = runLength * 2 + color;
280 putbits(outP, tableEntryToBitString(g3ttable_table[index]));
281 }
282
283
284
285 static void
286 putcodeLong(struct OutStream * const outP,
287 bit const color,
288 unsigned int const runLength) {
289 /*----------------------------------------------------------------------------
290 Output Make-up code and Terminating code at once.
291
292 For run lengths which require both: length 64 and above
293
294 The codes are combined here to avoid calculations in putbits()
295
296 Terminating code is max 12 bits, Make-up code is max 13 bits.
297 (See g3ttable_table, g3ttable_mtable entries in g3ttable.h)
298
299 Also reduces object code size when putcode is compiled inline.
300 -----------------------------------------------------------------------------*/
301 unsigned int const loIndex = runLength % 64 * 2 + color;
302 unsigned int const hiIndex = runLength / 64 * 2 + color;
303 unsigned int const loLength = g3ttable_table[loIndex].length;
304 unsigned int const hiLength = g3ttable_mtable[hiIndex].length;
305
306 struct BitString combinedCode;
307
308 combinedCode.intBuffer = g3ttable_mtable[hiIndex].code << loLength |
309 g3ttable_table[loIndex].code;
310 combinedCode.bitCount = hiLength + loLength;
311
312 putbits(outP, combinedCode);
313 }
314
315
316
317 static void
318 putcodeExtra(struct OutStream * const outP,
319 int const color,
320 int const runLength) {
321 /*----------------------------------------------------------------------------
322 Lengths over 2560. This is rare.
323 According to the standard, the mark-up code for 2560 can be issued as
324 many times as necessary without terminal codes.
325 --------------------------------------------------------------------------*/
326 G3TableEntry const markUp2560 = g3ttable_mtable[2560/64*2];
327 /* Same code for black and white */
328
329 unsigned int remainingLen;
330
331 for (remainingLen = runLength; remainingLen > 2560; remainingLen -= 2560)
332 putbits(outP, tableEntryToBitString(markUp2560));
333 /* after the above: 0 < remainingLen <= 2560 */
334
335 if (remainingLen >= 64)
336 putcodeLong(outP, color, remainingLen);
337 else
338 putcodeShort(outP, color, remainingLen);
339 }
340
341
342
343 static void
344 putspan(struct OutStream * const outP,
345 bit const color,
346 unsigned int const runLength) {
347
348 if (runLength < 64)
349 putcodeShort(outP, color, runLength);
350 else if (runLength < 2560)
351 putcodeLong (outP, color, runLength);
352 else /* runLength > 2560 : rare */
353 putcodeExtra(outP, color, runLength);
354 }
355
356
357
358 static void
359 puteol(struct OutStream * const outP) {
360
361 switch (outP->eolAlign) {
362 case EOL: {
363 struct BitString const eol = { 1, 12 };
364
365 putbits(outP, eol);
366 } break;
367 case ALIGN8: case ALIGN16: {
368 unsigned int const bitCount = outP->buffer.bitCount;
369 unsigned int const fillbits =
370 (outP->eolAlign == ALIGN8) ? (44 - bitCount) % 8
371 : (52 - bitCount) % 16;
372
373 struct BitString eol;
374
375 eol.bitCount = 12 + fillbits; eol.intBuffer = 1;
376 putbits(outP, eol);
377 } break;
378 case NO_EOL: case NO_EOLRTC:
379 break;
380 case NO_RTC:
381 pm_error("INTERNAL ERROR: no-RTC EOL treatment not implemented");
382 break;
383 }
384 }
385
386
387
388 static void
389 putrtc(struct OutStream * const outP) {
390
391 switch (outP->eolAlign) {
392 case NO_RTC: case NO_EOLRTC:
393 break;
394 default:
395 puteol(outP); puteol(outP); puteol(outP);
396 puteol(outP); puteol(outP); puteol(outP);
397 }
398 }
399
400
401
402 static void
403 readOffSideMargins(unsigned char * const bitrow,
404 unsigned int const colChars,
405 unsigned int * const firstNonWhiteCharP,
406 unsigned int * const lastNonWhiteCharP,
407 bool * const blankRowP) {
408 /*----------------------------------------------------------------------------
409 Determine the white margins on the left and right side of a row.
410 This is an enhancement: convertRowToG3() works without this.
411 -----------------------------------------------------------------------------*/
412 unsigned int charCnt;
413 unsigned int firstChar;
414 unsigned int lastChar;
415 bool blankRow;
416
417 assert(colChars > 0);
418
419 for (charCnt = 0; charCnt < colChars && bitrow[charCnt] == 0; ++charCnt);
420
421 if (charCnt >= colChars) {
422 /* Reached end of bitrow with no black pixels encountered */
423 firstChar = lastChar = 0;
424 blankRow = true;
425 } else {
426 /* There is at least one black pixel in the row */
427 firstChar = charCnt;
428 blankRow = false;
429
430 charCnt = colChars - 1;
431
432 while (bitrow[charCnt--] == 0x00)
433 ;
434 lastChar = charCnt + 1;
435 }
436
437 *firstNonWhiteCharP = firstChar;
438 *lastNonWhiteCharP = lastChar;
439 *blankRowP = blankRow;
440 }
441
442
443
444 static void
445 setBlockBitsInFinalChar(unsigned char * const finalByteP,
446 unsigned int const cols) {
447 /*----------------------------------------------------------------------------
448 If the char in the row is fractional, set it up so that the don't care
449 bits are the opposite color of the last valid pixel.
450 ----------------------------------------------------------------------------*/
451 unsigned char const finalByte = *finalByteP;
452 unsigned int const silentBitCnt = 8 - cols % 8;
453 bit const rowEndColor = (finalByte >> silentBitCnt) & 0x01;
454
455 if (rowEndColor == PBM_WHITE) {
456 unsigned char const blackMask = (0x01 << silentBitCnt) - 1;
457
458 *finalByteP = finalByte | blackMask;
459 }
460 /* No adjustment required if the row ends with a black pixel.
461 pbm_cleanrowend_packed() takes care of this.
462 */
463 }
464
465
466
467 static void
468 trimFinalChar(struct OutStream * const outP,
469 bit const color,
470 int const carryLength,
471 int const existingCols,
472 int const desiredWidth) {
473 /*---------------------------------------------------------------------------
474 If the carry value from the last char in the row represents a valid
475 sequence, output it.
476
477 (1) If input row width is not a whole multiple of 8 and -nofixwidth
478 was specified, the final carry value represents inactive bits
479 at the row end. Emit no code. See setBlockBitsInFinalChar().
480
481 (2) If there is white margin on the right side, the final carry value
482 is valid. We add to it the margin width. Right-side margin may
483 be added in main() to a narrow input image, detected in the
484 input row by readOffSideMargins() or both. The same treatment
485 applies regardless of the nature of the right-side margin.
486 ----------------------------------------------------------------------------*/
487 if (existingCols == desiredWidth) {
488 if (existingCols % 8 == 0)
489 putspan(outP, color, carryLength); /* Code up to byte boundary */
490 /* Emit nothing if existingCols is not a whole multiple of 8 */
491 } else if (existingCols < desiredWidth) {
492 if (color == 0) { /* Last bit sequence in final char: white */
493 unsigned int const totalLength =
494 carryLength + (desiredWidth - existingCols);
495 putspan(outP, 0, totalLength);
496 } else { /* Black */
497 unsigned int const padLength = desiredWidth - existingCols;
498 putspan(outP, 1, carryLength);
499 putspan(outP, 0, padLength);
500 }
501 }
502 }
503
504
505
506 static void
507 convertRowToG3(struct OutStream * const outP,
508 unsigned char * const bitrow,
509 unsigned int const existingCols,
510 unsigned int const desiredWidth) {
511 /*----------------------------------------------------------------------------
512 Table based Huffman coding
513
514 Normally Huffman code encoders count sequences of ones and zeros
515 and convert them to binary codes as they terminate. This program
516 recognizes chains of pixels and converts them directly, reading
517 prefabricated code chains from an indexed table.
518
519 For example the 8-bit sequence 01100110 translates to
520 Huffman code: 000111 11 0111 11 000111.
521
522 In reality things are more complicated. The leftmost 0 (MSB) may be
523 part of a longer sequence starting in the adjacent byte or perhaps
524 spanning several bytes. Likewise for the rightmost 0.
525
526 So we first remove the sequence on the left side and compare its
527 color with the leftmost pixel of the adjacent byte and emit either
528 one code for a single sequence if they agree or two if they disagree.
529 Next the composite code for the central part (in the above example
530 110011 -> 11 0111 11) is emitted. Finally we save the length and
531 color of the sequence on the right end as carry-over for the next
532 byte cycle. Some 8-bit input sequences (00000000, 01111111,
533 00111111, etc.) have no central part: these are special cases.
534 ---------------------------------------------------------------------------*/
535 unsigned int const colChars = pbm_packed_bytes(existingCols);
536
537 unsigned int charCnt;
538 unsigned int firstActiveChar;
539 unsigned int lastActiveChar;
540 bool blankRow;
541 bit borderColor;
542
543 borderColor = PBM_WHITE; /* initial value */
544
545 if (existingCols == desiredWidth && (desiredWidth % 8) > 0)
546 setBlockBitsInFinalChar(&bitrow[colChars-1], desiredWidth);
547
548 readOffSideMargins(bitrow, colChars,
549 &firstActiveChar, &lastActiveChar, &blankRow);
550
551 if (blankRow)
552 putspan(outP, PBM_WHITE, desiredWidth);
553 else {
554 unsigned int carryLength;
555
556 for (charCnt = firstActiveChar, carryLength = firstActiveChar * 8;
557 charCnt <=lastActiveChar;
558 ++charCnt) {
559
560 unsigned char const byte = bitrow[charCnt];
561 bit const rColor = !borderColor;
562
563 if (byte == borderColor * 0xFF) {
564 carryLength += 8;
565 } else if (byte == (unsigned char) ~(borderColor * 0xFF)) {
566 putspan(outP, borderColor, carryLength);
567 carryLength = 8;
568 borderColor = rColor;
569 } else {
570 struct PrefabCode const code = g3prefab_code[byte];
571 unsigned int const activeLength =
572 8 - code.leadBits - code.trailBits;
573
574 if (borderColor == (byte >> 7)) {
575 putspan(outP, borderColor, carryLength + code.leadBits);
576 } else {
577 putspan(outP, borderColor, carryLength);
578 putcodeShort(outP, rColor, code.leadBits);
579 }
580 if (activeLength > 0)
581 putbits(outP, code.activeBits);
582
583 borderColor = byte & 0x01;
584 carryLength = code.trailBits;
585 }
586 }
587 trimFinalChar(outP, borderColor, carryLength,
588 (lastActiveChar + 1) * 8, desiredWidth);
589 }
590 puteol(outP);
591 }
592
593
594
595 int
596 main(int argc,
597 const char * argv[]) {
598
599 struct CmdlineInfo cmdline;
600 FILE * ifP;
601 unsigned char * bitrow;
602 /* This is the bits of the current row, as read from the input and
603 modified various ways at various points in the program. It has
604 a word of zero padding on the high (right) end for the convenience
605 of code that accesses this buffer in word-size bites.
606 */
607
608 int rows;
609 int cols;
610 int format;
611 unsigned int existingCols;
612 unsigned int desiredWidth;
613 unsigned int row;
614 struct OutStream out;
615
616 pm_proginit(&argc, argv);
617
618 parseCommandLine(argc, argv, &cmdline);
619
620 ifP = pm_openr(cmdline.inputFileName);
621
622 pbm_readpbminit(ifP, &cols, &rows, &format);
623
624 if (cmdline.desiredWidth == 0)
625 desiredWidth = existingCols = cols;
626 else {
627 if (cmdline.desiredWidth < cols)
628 existingCols = desiredWidth = cmdline.desiredWidth;
629 else {
630 existingCols = pbm_packed_bytes(cols) * 8;
631 desiredWidth = cmdline.desiredWidth;
632 }
633 }
634
635 MALLOCARRAY(bitrow, pbm_packed_bytes(cols) + sizeof(uint32_t));
636
637 if (!bitrow)
638 pm_error("Failed to allocate a row buffer for %u columns", cols);
639
640 initOutStream(&out, cmdline.reversebits, cmdline.align);
641
642 puteol(&out);
643
644 for (row = 0; row < rows; ++row) {
645 pbm_readpbmrow_packed(ifP, bitrow, cols, format);
646 pbm_cleanrowend_packed(bitrow, cols);
647 convertRowToG3(&out, bitrow, existingCols, desiredWidth);
648 }
649
650 pbm_freerow_packed(bitrow);
651 putrtc(&out);
652 flushBuffer(&out);
653 pm_close(ifP);
654
655 return 0;
656 }
657
658
659